fabaccess-bffh/src/modules/shelly.rs

61 lines
1.7 KiB
Rust
Raw Normal View History

2020-09-14 10:37:51 +02:00
use slog::Logger;
2020-09-15 14:31:10 +02:00
use crate::config::Settings;
use crate::error::Result;
2020-11-17 12:09:45 +01:00
use crate::db::machine::Status;
use std::pin::Pin;
use futures::prelude::*;
2020-09-18 12:34:18 +02:00
use futures::channel::mpsc;
2020-12-09 11:14:45 +01:00
use futures::future::BoxFuture;
use futures::ready;
2020-09-18 12:34:18 +02:00
use futures::task::{Poll, Context, Waker, Spawn, FutureObj};
2020-09-17 21:12:30 +02:00
use futures::StreamExt;
2020-09-17 15:34:35 +02:00
use futures_signals::signal::Signal;
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()));
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 {
Status::InUse(_, _) => "on",
_ => "off",
};
let msg = mqtt::Message::new(topic, pl, 0);
let f = self.client.publish(msg).map(|_| ());
return Box::pin(f);
}
}