diff --git a/src/light.rs b/src/light.rs index 20df390..5c7ba7d 100644 --- a/src/light.rs +++ b/src/light.rs @@ -32,51 +32,58 @@ pub enum Value { } impl Value { - pub fn new(label: &str, value: Vec) -> Option { - 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) -> Option { + 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) { + 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) -> Option { - 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) -> Option { - if value.len() == 2 { - Some(i16::from_ne_bytes([value[0], value[1]])) - } else { - None - } -} - pub struct Command { pub lightname: String, pub command: Value, diff --git a/src/mqtt_updates.rs b/src/mqtt_updates.rs index 905df92..6a95524 100644 --- a/src/mqtt_updates.rs +++ b/src/mqtt_updates.rs @@ -89,7 +89,7 @@ impl MqttUpdates { ), QoS::AtLeastOnce, true, - value, + value.into_bytes(), ) { warn!("{}", err); }