lifx-mqtt-bridge/src/mqtt_commands.rs

61 lines
1.9 KiB
Rust
Raw Normal View History

2019-01-16 21:46:12 +00:00
use crate::light::{Command, Value};
use regex::Regex;
use rumqtt;
use rumqtt::{Notification, Publish, Receiver};
pub struct MqttCommands {
notifications: Receiver<Notification>,
commands: crossbeam_channel::Sender<Command>,
}
impl MqttCommands {
pub fn new(
notifications: Receiver<Notification>,
commands: crossbeam_channel::Sender<Command>,
) -> 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();
}
}