handle device offline

This commit is contained in:
Robin Appelman 2020-12-26 22:51:19 +01:00
commit ff085e85ed

View file

@ -88,44 +88,50 @@ async fn mqtt_client(config: &Config, device_states: DeviceStates) -> Result<()>
while let Some(message) = stream.next().await { while let Some(message) = stream.next().await {
let message = message?; let message = message?;
println!( let payload = std::str::from_utf8(message.payload.as_ref()).unwrap_or_default();
"{} {}", println!("{} {}", message.topic, payload);
message.topic,
std::str::from_utf8(message.payload.as_ref()).unwrap_or_default()
);
let topic = Topic::from(message.topic.as_str()); let topic = Topic::from(message.topic.as_str());
match topic { match topic {
Topic::LWT(device) => { Topic::LWT(device) => {
// on discovery, ask the device for it's ip and name match payload {
let send_client = client.clone(); "Online" => {
tokio::task::spawn(async move { println!("Discovered {}", device.hostname);
if let Err(e) = send_client // on discovery, ask the device for it's ip and name
.publish( let send_client = client.clone();
device.get_topic("cmnd", "IPADDRESS"), tokio::task::spawn(async move {
QoS::AtMostOnce, if let Err(e) = send_client
false, .publish(
"", device.get_topic("cmnd", "IPADDRESS"),
) QoS::AtLeastOnce,
.await false,
{ "",
eprintln!("Failed to ask for power state: {:#}", e); )
.await
{
eprintln!("Failed to ask for device IP: {:#}", e);
}
if let Err(e) = send_client
.publish(
device.get_topic("cmnd", "DeviceName"),
QoS::AtLeastOnce,
false,
"",
)
.await
{
eprintln!("Failed to ask for device name: {:#}", e);
}
});
} }
if let Err(e) = send_client "Offline" => {
.publish( println!("Removing {}", device.hostname);
device.get_topic("cmnd", "DeviceName"), device_states.remove(&device.hostname);
QoS::AtMostOnce,
false,
"",
)
.await
{
eprintln!("Failed to ask for device name: {:#}", e);
} }
}); _ => {}
}
} }
Topic::Result(device) => { Topic::Result(device) => {
let payload = std::str::from_utf8(message.payload.as_ref()).unwrap_or_default();
if let Ok(json) = json::parse(payload) { if let Ok(json) = json::parse(payload) {
let mut device_state = device_states.entry(device.hostname).or_default(); let mut device_state = device_states.entry(device.hostname).or_default();
device_state.update(json); device_state.update(json);