embassy_ha/
binary_state.rs1use core::str::FromStr;
2
3use crate::constants;
4
5#[derive(Debug)]
6pub struct InvalidBinaryState;
7
8impl core::fmt::Display for InvalidBinaryState {
9 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
10 f.write_str("invalid binary state, allowed values are 'ON' and 'OFF' (case insensitive)")
11 }
12}
13
14impl core::error::Error for InvalidBinaryState {}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum BinaryState {
18 On,
19 Off,
20}
21
22impl BinaryState {
23 pub fn as_str(&self) -> &'static str {
24 match self {
25 Self::On => constants::HA_SWITCH_STATE_ON,
26 Self::Off => constants::HA_SWITCH_STATE_OFF,
27 }
28 }
29
30 pub fn flip(self) -> Self {
31 match self {
32 Self::On => Self::Off,
33 Self::Off => Self::On,
34 }
35 }
36}
37
38impl core::fmt::Display for BinaryState {
39 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
40 f.write_str(self.as_str())
41 }
42}
43
44impl FromStr for BinaryState {
45 type Err = InvalidBinaryState;
46
47 fn from_str(s: &str) -> Result<Self, Self::Err> {
48 if s.eq_ignore_ascii_case(constants::HA_SWITCH_STATE_ON) {
49 return Ok(Self::On);
50 }
51 if s.eq_ignore_ascii_case(constants::HA_SWITCH_STATE_OFF) {
52 return Ok(Self::Off);
53 }
54 Err(InvalidBinaryState)
55 }
56}
57
58impl TryFrom<&[u8]> for BinaryState {
59 type Error = InvalidBinaryState;
60
61 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
62 let string = str::from_utf8(value).map_err(|_| InvalidBinaryState)?;
63 string.parse()
64 }
65}