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
75
76
77
78
79
80
81
82
83
|
use crate::{BinaryState, Entity, EntityCommonConfig, EntityConfig, constants};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum BinarySensorClass {
#[default]
Generic,
Battery,
BatteryCharging,
Connectivity,
Door,
GarageDoor,
Motion,
Occupancy,
Opening,
Plug,
Power,
Presence,
Problem,
Smoke,
Window,
}
#[derive(Debug, Default)]
pub struct BinarySensorConfig {
pub common: EntityCommonConfig,
pub class: BinarySensorClass,
}
impl BinarySensorConfig {
pub(crate) fn populate(&self, config: &mut EntityConfig) {
self.common.populate(config);
config.domain = constants::HA_DOMAIN_BINARY_SENSOR;
config.device_class = match self.class {
BinarySensorClass::Generic => None,
BinarySensorClass::Battery => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_BATTERY),
BinarySensorClass::BatteryCharging => {
Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_BATTERY_CHARGING)
}
BinarySensorClass::Connectivity => {
Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_CONNECTIVITY)
}
BinarySensorClass::Door => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_DOOR),
BinarySensorClass::GarageDoor => {
Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_GARAGE_DOOR)
}
BinarySensorClass::Motion => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_MOTION),
BinarySensorClass::Occupancy => {
Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_OCCUPANCY)
}
BinarySensorClass::Opening => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_OPENING),
BinarySensorClass::Plug => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_PLUG),
BinarySensorClass::Power => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_POWER),
BinarySensorClass::Presence => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_PRESENCE),
BinarySensorClass::Problem => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_PROBLEM),
BinarySensorClass::Smoke => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_SMOKE),
BinarySensorClass::Window => Some(constants::HA_DEVICE_CLASS_BINARY_SENSOR_WINDOW),
};
}
}
pub struct BinarySensor<'a>(Entity<'a>);
impl<'a> BinarySensor<'a> {
pub(crate) fn new(entity: Entity<'a>) -> Self {
Self(entity)
}
pub fn set(&mut self, state: BinaryState) {
self.0.publish(state.as_str().as_bytes());
}
pub fn value(&self) -> Option<BinaryState> {
self.0
.with_data(|data| BinaryState::try_from(data.publish_value.as_slice()))
.ok()
}
pub fn toggle(&mut self) -> BinaryState {
let new_state = self.value().unwrap_or(BinaryState::Off).flip();
self.set(new_state);
new_state
}
}
|