Browse Source

Send all mqtt data as strings

master
Lara 2 years ago
parent
commit
8843e4f531
  1. 81
      src/light.rs
  2. 2
      src/mqtt_updates.rs

81
src/light.rs

@ -32,51 +32,58 @@ pub enum Value {
}
impl Value {
pub fn new(label: &str, value: Vec<u8>) -> Option<Self> {
match label {
POWER => Some(Value::Power(
String::from_utf8(value.clone())
.or_else(|x| {
warn!("{:#?}: {}", value, x);
Err(x)
})
.ok()?,
)),
BRIGHTNESS => Some(Value::Brightness(vec_to_f32(value)?)),
HUE => Some(Value::Hue(vec_to_f32(value)?)),
SATURATION => Some(Value::Saturation(vec_to_f32(value)?)),
KELVIN => Some(Value::Kelvin(vec_to_i16(value)?)),
_ => unimplemented!(),
pub fn new(label: &str, value_vec: Vec<u8>) -> Option<Self> {
match String::from_utf8(value_vec) {
Ok(value) => match label {
POWER => Some(Value::Power(value)),
BRIGHTNESS => {
if let Ok(val) = value.parse() {
Some(Value::Brightness(val))
} else {
None
}
}
HUE => {
if let Ok(val) = value.parse() {
Some(Value::Hue(val))
} else {
None
}
}
SATURATION => {
if let Ok(val) = value.parse() {
Some(Value::Saturation(val))
} else {
None
}
}
KELVIN => {
if let Ok(val) = value.parse() {
Some(Value::Kelvin(val))
} else {
None
}
}
_ => unimplemented!(),
},
Err(x) => {
warn!("{}", x);
None
}
}
}
pub fn unravel(self) -> (&'static str, Vec<u8>) {
pub fn unravel(self) -> (&'static str, String) {
match self {
Value::Power(val) => (POWER, val.into_bytes()),
Value::Brightness(val) => (BRIGHTNESS, (val as u32).to_ne_bytes().to_vec()),
Value::Hue(val) => (HUE, (val as u32).to_ne_bytes().to_vec()),
Value::Saturation(val) => (SATURATION, (val as u32).to_ne_bytes().to_vec()),
Value::Kelvin(val) => (KELVIN, (val as u32).to_ne_bytes().to_vec()),
Value::Power(val) => (POWER, val),
Value::Brightness(val) => (BRIGHTNESS, format!("{}", val)),
Value::Hue(val) => (HUE, format!("{}", val)),
Value::Saturation(val) => (SATURATION, format!("{}", val)),
Value::Kelvin(val) => (KELVIN, format!("{}", val)),
}
}
}
fn vec_to_f32(value: Vec<u8>) -> Option<f32> {
if value.len() == 4 {
Some(u32::from_ne_bytes([value[0], value[1], value[2], value[3]]) as f32)
} else {
None
}
}
fn vec_to_i16(value: Vec<u8>) -> Option<i16> {
if value.len() == 2 {
Some(i16::from_ne_bytes([value[0], value[1]]))
} else {
None
}
}
pub struct Command {
pub lightname: String,
pub command: Value,

2
src/mqtt_updates.rs

@ -89,7 +89,7 @@ impl MqttUpdates {
),
QoS::AtLeastOnce,
true,
value,
value.into_bytes(),
) {
warn!("{}", err);
}

Loading…
Cancel
Save