fabaccess-bffh/src/modules/shelly.rs

54 lines
1.5 KiB
Rust
Raw Normal View History

2020-09-14 10:37:51 +02:00
use slog::Logger;
2020-11-17 12:09:45 +01:00
use crate::db::machine::Status;
use futures::prelude::*;
2020-12-09 11:14:45 +01:00
use futures::future::BoxFuture;
2020-09-14 10:37:51 +02:00
2020-12-09 11:14:45 +01:00
use crate::actor::Actuator;
use crate::db::machine::MachineState;
use paho_mqtt as mqtt;
2020-09-14 10:37:51 +02:00
2020-12-09 11:14:45 +01:00
/// An actuator for a Shellie connected listening on one MQTT broker
///
/// This actuator will toggle the shellie with the given `name`.
/// If you need to toggle shellies on multiple brokers you need multiple instanced of this
/// actuator with different clients.
2020-12-14 11:02:46 +01:00
pub struct Shelly {
2020-12-09 11:14:45 +01:00
log: Logger,
name: String,
client: mqtt::AsyncClient,
}
impl Shelly {
pub fn new(log_view: &Logger, name: String, client: mqtt::AsyncClient) -> Self {
let log = log_view.new(o!("shelly_name" => name.clone()));
2020-12-14 12:39:01 +01:00
debug!(log, "Starting shelly module for {}", &name);
2020-12-09 11:14:45 +01:00
Shelly { log, name, client, }
}
/// Set the name to a new one. This changes the shelly that will be activated
pub fn set_name(&mut self, new_name: String) {
let log = self.log.new(o!("shelly_name" => new_name.clone()));
self.name = new_name;
self.log = log;
}
}
impl Actuator for Shelly {
fn apply(&mut self, state: MachineState) -> BoxFuture<'static, ()> {
info!(self.log, "Machine Status changed: {:?}", state);
let topic = format!("shellies/{}/relay/0/command", self.name);
let pl = match state.state {
2021-01-20 12:55:15 +01:00
Status::InUse(_) => "on",
2020-12-09 11:14:45 +01:00
_ => "off",
};
let msg = mqtt::Message::new(topic, pl, 0);
let f = self.client.publish(msg).map(|_| ());
return Box::pin(f);
}
}