Send all mqtt data as strings

This commit is contained in:
Lara 2019-02-17 15:36:47 +01:00
parent 940db5e20f
commit 8843e4f531
2 changed files with 45 additions and 38 deletions

View File

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

View File

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