use crate::light::{Command, Value}; use regex::Regex; use rumqtt; use rumqtt::{Notification, Publish, Receiver}; pub struct MqttCommands { notifications: Receiver, commands: crossbeam_channel::Sender, } impl MqttCommands { pub fn new( notifications: Receiver, commands: crossbeam_channel::Sender, ) -> Self { MqttCommands { notifications, commands, } } pub fn listen(&self) { loop { match self.notifications.recv() { Ok(notification) => { println!("MQTT notification received: {:#?}", notification); match notification { Notification::Publish(data) => self.handle_publish(data), Notification::PubAck(_) => {} Notification::PubRec(_) => {} Notification::PubRel(_) => {} Notification::PubComp(_) => {} Notification::SubAck(_) => {} Notification::None => {} } } Err(recv_error) => { println!("MQTT channel closed: {}", recv_error); } } } } fn handle_publish(&self, data: Publish) { lazy_static! { static ref matchStr: String = format!(r"^{}/(\w+)/command/(\w+)$", crate::MQTT_ID); static ref RE: Regex = Regex::new(&matchStr).unwrap(); } let mut matching = RE.find_iter(&data.topic_name); let lamp = matching.next().unwrap().as_str(); let command = matching.next().unwrap().as_str(); self.commands .send(Command { lampname: lamp.to_owned(), command: Value::new(command, data.payload.to_vec()), }) .unwrap(); } }