aboutsummaryrefslogtreecommitdiff
path: root/examples/sensor.rs
blob: 69bd87a20d30eaf2abb473cb980dc4f1bd5b60c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
mod common;

use common::AsyncTcp;
use embassy_executor::{Executor, Spawner};
use embassy_time::Timer;
use static_cell::StaticCell;

static RESOURCES: StaticCell<embassy_ha::DeviceResources> = StaticCell::new();

#[embassy_executor::task]
async fn main_task(spawner: Spawner) {
    let mut stream = AsyncTcp::connect(std::env!("MQTT_ADDRESS"));

    let mut device = embassy_ha::Device::new(
        RESOURCES.init(Default::default()),
        embassy_ha::DeviceConfig {
            device_id: "example-device-id",
            device_name: "Example Device Name",
            manufacturer: "Example Device Manufacturer",
            model: "Example Device Model",
        },
    );

    let temperature_sensor = device.create_sensor(
        "random-temperature-sensor-id",
        embassy_ha::SensorConfig {
            common: embassy_ha::EntityCommonConfig {
                name: Some("Random Temperature Sensor"),
                ..Default::default()
            },
            class: embassy_ha::SensorClass::Temperature,
            state_class: embassy_ha::StateClass::Measurement,
            unit: Some(embassy_ha::constants::HA_UNIT_TEMPERATURE_CELSIUS),
            suggested_display_precision: Some(1),
        },
    );

    let humidity_sensor = device.create_sensor(
        "random-humidity-sensor-id",
        embassy_ha::SensorConfig {
            common: embassy_ha::EntityCommonConfig {
                name: Some("Random Humidity Sensor"),
                ..Default::default()
            },
            class: embassy_ha::SensorClass::Humidity,
            state_class: embassy_ha::StateClass::Measurement,
            unit: Some(embassy_ha::constants::HA_UNIT_PERCENTAGE),
            suggested_display_precision: Some(0),
        },
    );

    spawner.must_spawn(random_temperature_task(temperature_sensor));
    spawner.must_spawn(random_humidity_task(humidity_sensor));

    device.run(&mut stream).await.unwrap();
}

#[embassy_executor::task]
async fn random_temperature_task(mut sensor: embassy_ha::Sensor<'static>) {
    loop {
        sensor.publish(rand::random_range(0.0..50.0));
        Timer::after_secs(1).await;
    }
}

#[embassy_executor::task]
async fn random_humidity_task(mut sensor: embassy_ha::Sensor<'static>) {
    loop {
        sensor.publish(rand::random_range(0.0..100.0));
        Timer::after_secs(1).await;
    }
}

example_main!();