aboutsummaryrefslogtreecommitdiff
path: root/src/entity_switch.rs
diff options
context:
space:
mode:
authordiogo464 <[email protected]>2025-12-05 12:17:01 +0000
committerdiogo464 <[email protected]>2025-12-05 12:17:01 +0000
commit0c86da392af50c7588b087c3f72602e8368af65e (patch)
tree894cd2f353298b83a56cde06eafd7b1e366aa6b3 /src/entity_switch.rs
parent1d2ee64d0ec917a2c2b66f8d58e1f37dd174a89d (diff)
reworked entity creation
Diffstat (limited to 'src/entity_switch.rs')
-rw-r--r--src/entity_switch.rs59
1 files changed, 59 insertions, 0 deletions
diff --git a/src/entity_switch.rs b/src/entity_switch.rs
new file mode 100644
index 0000000..4d2efdb
--- /dev/null
+++ b/src/entity_switch.rs
@@ -0,0 +1,59 @@
1use crate::{BinaryState, Entity, EntityCommonConfig, EntityConfig, constants};
2
3#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
4pub enum SwitchClass {
5 #[default]
6 Generic,
7 Outlet,
8 Switch,
9}
10
11#[derive(Debug, Default)]
12pub struct SwitchConfig {
13 pub common: EntityCommonConfig,
14 pub class: SwitchClass,
15}
16
17impl SwitchConfig {
18 pub(crate) fn populate(&self, config: &mut EntityConfig) {
19 self.common.populate(config);
20 config.domain = constants::HA_DOMAIN_SWITCH;
21 config.device_class = match self.class {
22 SwitchClass::Generic => None,
23 SwitchClass::Outlet => Some(constants::HA_DEVICE_CLASS_SWITCH_OUTLET),
24 SwitchClass::Switch => Some(constants::HA_DEVICE_CLASS_SWITCH_SWITCH),
25 };
26 }
27}
28
29pub struct Switch<'a>(Entity<'a>);
30
31impl<'a> Switch<'a> {
32 pub(crate) fn new(entity: Entity<'a>) -> Self {
33 Self(entity)
34 }
35
36 pub fn state(&self) -> Option<BinaryState> {
37 self.0
38 .with_data(|data| BinaryState::try_from(data.command_value.as_slice()).ok())
39 }
40
41 pub fn toggle(&mut self) -> BinaryState {
42 let new_state = self.state().unwrap_or(BinaryState::Off).flip();
43 self.set(new_state);
44 new_state
45 }
46
47 pub fn set(&mut self, state: BinaryState) {
48 self.0.publish(state.as_str().as_bytes());
49 }
50
51 pub async fn wait(&mut self) -> BinaryState {
52 loop {
53 self.0.wait_command().await;
54 if let Some(state) = self.state() {
55 return state;
56 }
57 }
58 }
59}