new mqtt topic

This commit is contained in:
Robin Appelman 2021-03-23 20:12:50 +01:00
commit d985f32a4c
3 changed files with 5 additions and 7 deletions

View file

@ -4,13 +4,12 @@ use std::str::FromStr;
#[derive(Debug, Eq, PartialEq, Clone, Hash)] #[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub struct Device { pub struct Device {
pub topic: String,
pub hostname: String, pub hostname: String,
} }
impl Device { impl Device {
pub fn get_topic(&self, prefix: &str, command: &str) -> String { pub fn get_topic(&self, prefix: &str, command: &str) -> String {
format!("{}/{}/{}/{}", prefix, self.topic, self.hostname, command) format!("{}/{}/{}", prefix, self.hostname, command)
} }
} }

View file

@ -7,8 +7,8 @@ pub async fn mqtt_stream(
mqtt_options: MqttOptions, mqtt_options: MqttOptions,
) -> Result<(AsyncClient, impl Stream<Item = Result<Publish>>)> { ) -> Result<(AsyncClient, impl Stream<Item = Result<Publish>>)> {
let (client, event_loop) = AsyncClient::new(mqtt_options, 10); let (client, event_loop) = AsyncClient::new(mqtt_options, 10);
client.subscribe("tele/+/+/LWT", QoS::AtMostOnce).await?; client.subscribe("tele/+/LWT", QoS::AtMostOnce).await?;
client.subscribe("stat/+/+/RESULT", QoS::AtMostOnce).await?; client.subscribe("stat/+/RESULT", QoS::AtMostOnce).await?;
let stream = event_loop_to_stream(event_loop).filter_map(|event| match event { let stream = event_loop_to_stream(event_loop).filter_map(|event| match event {
Ok(Event::Incoming(Packet::Publish(message))) => Some(Ok(message)), Ok(Event::Incoming(Packet::Publish(message))) => Some(Ok(message)),

View file

@ -12,11 +12,10 @@ pub enum Topic {
impl From<&str> for Topic { impl From<&str> for Topic {
fn from(raw: &str) -> Self { fn from(raw: &str) -> Self {
let mut parts = raw.split('/'); let mut parts = raw.split('/');
if let (Some(prefix), Some(topic), Some(hostname), Some(cmd)) = if let (Some(prefix), Some(hostname), Some(cmd)) =
(parts.next(), parts.next(), parts.next(), parts.next()) (parts.next(), parts.next(), parts.next())
{ {
let device = Device { let device = Device {
topic: topic.to_string(),
hostname: hostname.to_string(), hostname: hostname.to_string(),
}; };
match (prefix, cmd) { match (prefix, cmd) {