restructure and error logging

This commit is contained in:
Robin Appelman 2020-11-20 23:24:13 +01:00
commit 7b8786919c
7 changed files with 527 additions and 217 deletions

31
src/mqtt.rs Normal file
View file

@ -0,0 +1,31 @@
use async_stream::try_stream;
use color_eyre::Result;
use rumqttc::{AsyncClient, Event, EventLoop, MqttOptions, Packet, Publish, QoS};
use tokio::stream::{Stream, StreamExt};
pub async fn mqtt_stream(
mqtt_options: MqttOptions,
) -> Result<(AsyncClient, impl Stream<Item = Result<Publish>>)> {
let (client, event_loop) = AsyncClient::new(mqtt_options, 10);
client.subscribe("tele/+/+/LWT", QoS::AtMostOnce).await?;
client.subscribe("stat/+/+/POWER", QoS::AtMostOnce).await?;
client.subscribe("tele/+/+/SENSOR", QoS::AtMostOnce).await?;
client.subscribe("stat/+/+/RESULT", QoS::AtMostOnce).await?;
let stream = event_loop_to_stream(event_loop).filter_map(|event| match event {
Ok(Event::Incoming(Packet::Publish(message))) => Some(Ok(message)),
Ok(_) => None,
Err(e) => Some(Err(e)),
});
Ok((client, stream))
}
fn event_loop_to_stream(mut event_loop: EventLoop) -> impl Stream<Item = Result<Event>> {
try_stream! {
loop {
let event = event_loop.poll().await?;
yield event;
}
}
}