Reorganized project

This commit is contained in:
2024-12-08 00:15:03 +01:00
parent 42f391cde6
commit 8877b24e84
36 changed files with 505 additions and 797 deletions

View File

@@ -0,0 +1,260 @@
use std::sync::Arc;
use async_trait::async_trait;
use automation_lib::config::{InfoConfig, MqttDeviceConfig};
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt;
use automation_lib::messages::{AirFilterFanState, AirFilterState, SetAirFilterFanState};
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use google_home::device::Name;
use google_home::errors::ErrorCode;
use google_home::traits::{
AvailableSpeeds, FanSpeed, HumiditySetting, OnOff, Speed, SpeedValue, TemperatureSetting,
TemperatureUnit,
};
use google_home::types::Type;
use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, error, trace, warn};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
#[device_config(flatten)]
pub info: InfoConfig,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
#[derive(Debug, Clone)]
pub struct AirFilter {
config: Config,
state: Arc<RwLock<AirFilterState>>,
}
impl AirFilter {
async fn set_speed(&self, state: AirFilterFanState) {
let message = SetAirFilterFanState::new(state);
let topic = format!("{}/set", self.config.mqtt.topic);
// TODO: Handle potential errors here
self.config
.client
.publish(
&topic,
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(),
)
.await
.map_err(|err| warn!("Failed to update state on {topic}: {err}"))
.ok();
}
async fn state(&self) -> RwLockReadGuard<AirFilterState> {
self.state.read().await
}
async fn state_mut(&self) -> RwLockWriteGuard<AirFilterState> {
self.state.write().await
}
}
#[async_trait]
impl LuaDeviceCreate for AirFilter {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.info.identifier(), "Setting up AirFilter");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
let state = AirFilterState {
state: AirFilterFanState::Off,
humidity: 0.0,
temperature: 0.0,
};
let state = Arc::new(RwLock::new(state));
Ok(Self { config, state })
}
}
impl Device for AirFilter {
fn get_id(&self) -> String {
self.config.info.identifier()
}
}
#[async_trait]
impl OnMqtt for AirFilter {
async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
return;
}
let state = match AirFilterState::try_from(message) {
Ok(state) => state,
Err(err) => {
error!(id = Device::get_id(self), "Failed to parse message: {err}");
return;
}
};
if state == *self.state().await {
return;
}
debug!(id = Device::get_id(self), "Updating state to {state:?}");
*self.state_mut().await = state;
}
}
impl google_home::Device for AirFilter {
fn get_device_type(&self) -> Type {
Type::AirPurifier
}
fn get_device_name(&self) -> Name {
Name::new(&self.config.info.name)
}
fn get_id(&self) -> String {
Device::get_id(self)
}
fn is_online(&self) -> bool {
true
}
fn get_room_hint(&self) -> Option<&str> {
self.config.info.room.as_deref()
}
fn will_report_state(&self) -> bool {
false
}
}
#[async_trait]
impl OnOff for AirFilter {
async fn on(&self) -> Result<bool, ErrorCode> {
Ok(self.state().await.state != AirFilterFanState::Off)
}
async fn set_on(&self, on: bool) -> Result<(), ErrorCode> {
debug!("Turning on air filter: {on}");
if on {
self.set_speed(AirFilterFanState::High).await;
} else {
self.set_speed(AirFilterFanState::Off).await;
}
Ok(())
}
}
#[async_trait]
impl FanSpeed for AirFilter {
fn available_fan_speeds(&self) -> AvailableSpeeds {
AvailableSpeeds {
speeds: vec![
Speed {
speed_name: "off".into(),
speed_values: vec![SpeedValue {
speed_synonym: vec!["Off".into()],
lang: "en".into(),
}],
},
Speed {
speed_name: "low".into(),
speed_values: vec![SpeedValue {
speed_synonym: vec!["Low".into()],
lang: "en".into(),
}],
},
Speed {
speed_name: "medium".into(),
speed_values: vec![SpeedValue {
speed_synonym: vec!["Medium".into()],
lang: "en".into(),
}],
},
Speed {
speed_name: "high".into(),
speed_values: vec![SpeedValue {
speed_synonym: vec!["High".into()],
lang: "en".into(),
}],
},
],
ordered: true,
}
}
async fn current_fan_speed_setting(&self) -> Result<String, ErrorCode> {
let speed = match self.state().await.state {
AirFilterFanState::Off => "off",
AirFilterFanState::Low => "low",
AirFilterFanState::Medium => "medium",
AirFilterFanState::High => "high",
};
Ok(speed.into())
}
async fn set_fan_speed(&self, fan_speed: String) -> Result<(), ErrorCode> {
let fan_speed = fan_speed.as_str();
let state = if fan_speed == "off" {
AirFilterFanState::Off
} else if fan_speed == "low" {
AirFilterFanState::Low
} else if fan_speed == "medium" {
AirFilterFanState::Medium
} else if fan_speed == "high" {
AirFilterFanState::High
} else {
return Err(google_home::errors::DeviceError::TransientError.into());
};
self.set_speed(state).await;
Ok(())
}
}
#[async_trait]
impl HumiditySetting for AirFilter {
fn query_only_humidity_setting(&self) -> Option<bool> {
Some(true)
}
async fn humidity_ambient_percent(&self) -> Result<isize, ErrorCode> {
Ok(self.state().await.humidity.round() as isize)
}
}
#[async_trait]
impl TemperatureSetting for AirFilter {
fn query_only_temperature_control(&self) -> Option<bool> {
Some(true)
}
#[allow(non_snake_case)]
fn temperatureUnitForUX(&self) -> TemperatureUnit {
TemperatureUnit::Celsius
}
async fn temperature_ambient_celsius(&self) -> f32 {
// HACK: Round to one decimal place
(10.0 * self.state().await.temperature).round() / 10.0
}
}

View File

@@ -0,0 +1,183 @@
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use automation_lib::action_callback::ActionCallback;
use automation_lib::config::MqttDeviceConfig;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::error::DeviceConfigError;
use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::messages::{ContactMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient;
use automation_lib::presence::DEFAULT_PRESENCE;
use automation_macro::LuaDeviceConfig;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tokio::task::JoinHandle;
use tracing::{debug, error, trace, warn};
// NOTE: If we add more presence devices we might need to move this out of here
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct PresenceDeviceConfig {
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(with(Duration::from_secs))]
pub timeout: Duration,
}
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
pub identifier: String,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(from_lua, default)]
pub presence: Option<PresenceDeviceConfig>,
#[device_config(from_lua, default)]
pub callback: ActionCallback<bool>,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
#[derive(Debug)]
struct State {
overall_presence: bool,
is_closed: bool,
handle: Option<JoinHandle<()>>,
}
#[derive(Debug, Clone)]
pub struct ContactSensor {
config: Config,
state: Arc<RwLock<State>>,
}
impl ContactSensor {
async fn state(&self) -> RwLockReadGuard<State> {
self.state.read().await
}
async fn state_mut(&self) -> RwLockWriteGuard<State> {
self.state.write().await
}
}
#[async_trait]
impl LuaDeviceCreate for ContactSensor {
type Config = Config;
type Error = DeviceConfigError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.identifier, "Setting up ContactSensor");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
let state = State {
overall_presence: DEFAULT_PRESENCE,
is_closed: true,
handle: None,
};
let state = Arc::new(RwLock::new(state));
Ok(Self { config, state })
}
}
impl Device for ContactSensor {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
#[async_trait]
impl OnPresence for ContactSensor {
async fn on_presence(&self, presence: bool) {
self.state_mut().await.overall_presence = presence;
}
}
#[async_trait]
impl OnMqtt for ContactSensor {
async fn on_mqtt(&self, message: rumqttc::Publish) {
if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
return;
}
let is_closed = match ContactMessage::try_from(message) {
Ok(state) => state.is_closed(),
Err(err) => {
error!(id = self.get_id(), "Failed to parse message: {err}");
return;
}
};
if is_closed == self.state().await.is_closed {
return;
}
self.config.callback.call(!is_closed).await;
debug!(id = self.get_id(), "Updating state to {is_closed}");
self.state_mut().await.is_closed = is_closed;
// Check if this contact sensor works as a presence device
// If not we are done here
let presence = match &self.config.presence {
Some(presence) => presence.clone(),
None => return,
};
if !is_closed {
// Activate presence and stop any timeout once we open the door
if let Some(handle) = self.state_mut().await.handle.take() {
handle.abort();
}
// Only use the door as an presence sensor if there the current presence is set false
// This is to prevent the house from being marked as present for however long the
// timeout is set when leaving the house
if !self.state().await.overall_presence {
self.config
.client
.publish(
&presence.mqtt.topic,
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&PresenceMessage::new(true)).unwrap(),
)
.await
.map_err(|err| {
warn!(
"Failed to publish presence on {}: {err}",
presence.mqtt.topic
)
})
.ok();
}
} else {
// Once the door is closed again we start a timeout for removing the presence
let device = self.clone();
self.state_mut().await.handle = Some(tokio::spawn(async move {
debug!(
id = device.get_id(),
"Starting timeout ({:?}) for contact sensor...", presence.timeout
);
tokio::time::sleep(presence.timeout).await;
debug!(id = device.get_id(), "Removing door device!");
device
.config
.client
.publish(&presence.mqtt.topic, rumqttc::QoS::AtLeastOnce, false, "")
.await
.map_err(|err| {
warn!(
"Failed to publish presence on {}: {err}",
presence.mqtt.topic
)
})
.ok();
}));
}
}
}

View File

@@ -0,0 +1,89 @@
use std::convert::Infallible;
use async_trait::async_trait;
use automation_lib::config::MqttDeviceConfig;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence};
use automation_lib::messages::{DarknessMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use tracing::{trace, warn};
#[derive(Debug, LuaDeviceConfig, Clone)]
pub struct Config {
pub identifier: String,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
#[derive(Debug, Clone)]
pub struct DebugBridge {
config: Config,
}
#[async_trait]
impl LuaDeviceCreate for DebugBridge {
type Config = Config;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.identifier, "Setting up DebugBridge");
Ok(Self { config })
}
}
impl Device for DebugBridge {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
#[async_trait]
impl OnPresence for DebugBridge {
async fn on_presence(&self, presence: bool) {
let message = PresenceMessage::new(presence);
let topic = format!("{}/presence", self.config.mqtt.topic);
self.config
.client
.publish(
topic,
rumqttc::QoS::AtLeastOnce,
true,
serde_json::to_string(&message).expect("Serialization should not fail"),
)
.await
.map_err(|err| {
warn!(
"Failed to update presence on {}/presence: {err}",
self.config.mqtt.topic
)
})
.ok();
}
}
#[async_trait]
impl OnDarkness for DebugBridge {
async fn on_darkness(&self, dark: bool) {
let message = DarknessMessage::new(dark);
let topic = format!("{}/darkness", self.config.mqtt.topic);
self.config
.client
.publish(
topic,
rumqttc::QoS::AtLeastOnce,
true,
serde_json::to_string(&message).unwrap(),
)
.await
.map_err(|err| {
warn!(
"Failed to update presence on {}/presence: {err}",
self.config.mqtt.topic
)
})
.ok();
}
}

View File

@@ -0,0 +1,106 @@
use std::convert::Infallible;
use std::net::SocketAddr;
use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence};
use automation_macro::LuaDeviceConfig;
use serde::{Deserialize, Serialize};
use tracing::{error, trace, warn};
#[derive(Debug)]
pub enum Flag {
Presence,
Darkness,
}
#[derive(Debug, Clone, Deserialize)]
pub struct FlagIDs {
presence: isize,
darkness: isize,
}
#[derive(Debug, LuaDeviceConfig, Clone)]
pub struct Config {
pub identifier: String,
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
pub addr: SocketAddr,
pub login: String,
pub flags: FlagIDs,
}
#[derive(Debug, Clone)]
pub struct HueBridge {
config: Config,
}
#[derive(Debug, Serialize)]
struct FlagMessage {
flag: bool,
}
#[async_trait]
impl LuaDeviceCreate for HueBridge {
type Config = Config;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Infallible> {
trace!(id = config.identifier, "Setting up HueBridge");
Ok(Self { config })
}
}
impl HueBridge {
pub async fn set_flag(&self, flag: Flag, value: bool) {
let flag_id = match flag {
Flag::Presence => self.config.flags.presence,
Flag::Darkness => self.config.flags.darkness,
};
let url = format!(
"http://{}/api/{}/sensors/{flag_id}/state",
self.config.addr, self.config.login
);
trace!(?flag, flag_id, value, "Sending request to change flag");
let res = reqwest::Client::new()
.put(url)
.json(&FlagMessage { flag: value })
.send()
.await;
match res {
Ok(res) => {
let status = res.status();
if !status.is_success() {
warn!(flag_id, "Status code is not success: {status}");
}
}
Err(err) => {
error!(flag_id, "Error: {err}");
}
}
}
}
impl Device for HueBridge {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
#[async_trait]
impl OnPresence for HueBridge {
async fn on_presence(&self, presence: bool) {
trace!("Bridging presence to hue");
self.set_flag(Flag::Presence, presence).await;
}
}
#[async_trait]
impl OnDarkness for HueBridge {
async fn on_darkness(&self, dark: bool) {
trace!("Bridging darkness to hue");
self.set_flag(Flag::Darkness, dark).await;
}
}

View File

@@ -0,0 +1,209 @@
use std::net::SocketAddr;
use anyhow::Result;
use async_trait::async_trait;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use google_home::errors::ErrorCode;
use google_home::traits::OnOff;
use tracing::{error, trace, warn};
use super::{Device, LuaDeviceCreate};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
pub identifier: String,
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
pub addr: SocketAddr,
pub login: String,
pub group_id: isize,
pub scene_id: String,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
#[derive(Debug, Clone)]
pub struct HueGroup {
config: Config,
}
// Couple of helper function to get the correct urls
#[async_trait]
impl LuaDeviceCreate for HueGroup {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.identifier, "Setting up AudioSetup");
Ok(Self { config })
}
}
impl HueGroup {
fn url_base(&self) -> String {
format!("http://{}/api/{}", self.config.addr, self.config.login)
}
fn url_set_action(&self) -> String {
format!("{}/groups/{}/action", self.url_base(), self.config.group_id)
}
fn url_get_state(&self) -> String {
format!("{}/groups/{}", self.url_base(), self.config.group_id)
}
}
impl Device for HueGroup {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
#[async_trait]
impl OnOff for HueGroup {
async fn set_on(&self, on: bool) -> Result<(), ErrorCode> {
let message = if on {
message::Action::scene(self.config.scene_id.clone())
} else {
message::Action::on(false)
};
let res = reqwest::Client::new()
.put(self.url_set_action())
.json(&message)
.send()
.await;
match res {
Ok(res) => {
let status = res.status();
if !status.is_success() {
warn!(id = self.get_id(), "Status code is not success: {status}");
}
}
Err(err) => error!(id = self.get_id(), "Error: {err}"),
}
Ok(())
}
async fn on(&self) -> Result<bool, ErrorCode> {
let res = reqwest::Client::new()
.get(self.url_get_state())
.send()
.await;
match res {
Ok(res) => {
let status = res.status();
if !status.is_success() {
warn!(id = self.get_id(), "Status code is not success: {status}");
}
let on = match res.json::<message::Info>().await {
Ok(info) => info.any_on(),
Err(err) => {
error!(id = self.get_id(), "Failed to parse message: {err}");
// TODO: Error code
return Ok(false);
}
};
return Ok(on);
}
Err(err) => error!(id = self.get_id(), "Error: {err}"),
}
Ok(false)
}
}
mod message {
use std::time::Duration;
use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Action {
#[serde(skip_serializing_if = "Option::is_none")]
on: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
scene: Option<String>,
}
impl Action {
pub fn on(on: bool) -> Self {
Self {
on: Some(on),
scene: None,
}
}
pub fn scene(scene: String) -> Self {
Self {
on: None,
scene: Some(scene),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct State {
all_on: bool,
any_on: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Info {
state: State,
}
impl Info {
pub fn any_on(&self) -> bool {
self.state.any_on
}
// pub fn all_on(&self) -> bool {
// self.state.all_on
// }
}
#[derive(Debug)]
pub struct Timeout {
timeout: Option<Duration>,
}
impl Timeout {
pub fn new(timeout: Option<Duration>) -> Self {
Self { timeout }
}
}
impl Serialize for Timeout {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let len = if self.timeout.is_some() { 2 } else { 1 };
let mut state = serializer.serialize_struct("TimerMessage", len)?;
if self.timeout.is_some() {
state.serialize_field("status", "enabled")?;
} else {
state.serialize_field("status", "disabled")?;
}
if let Some(timeout) = self.timeout {
let seconds = timeout.as_secs() % 60;
let minutes = (timeout.as_secs() / 60) % 60;
let hours = timeout.as_secs() / 3600;
let time = format!("PT{hours:<02}:{minutes:<02}:{seconds:<02}");
state.serialize_field("localtime", &time)?;
};
state.end()
}
}
}

View File

@@ -0,0 +1,83 @@
use async_trait::async_trait;
use automation_lib::action_callback::ActionCallback;
use automation_lib::config::{InfoConfig, MqttDeviceConfig};
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use rumqttc::{matches, Publish};
use tracing::{debug, trace, warn};
use zigbee2mqtt_types::vendors::philips::Zigbee929003017102;
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
#[device_config(flatten)]
pub info: InfoConfig,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
#[device_config(from_lua, default)]
pub left_callback: ActionCallback<()>,
#[device_config(from_lua, default)]
pub right_callback: ActionCallback<()>,
}
#[derive(Debug, Clone)]
pub struct HueSwitch {
config: Config,
}
impl Device for HueSwitch {
fn get_id(&self) -> String {
self.config.info.identifier()
}
}
#[async_trait]
impl LuaDeviceCreate for HueSwitch {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.info.identifier(), "Setting up HueSwitch");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self { config })
}
}
#[async_trait]
impl OnMqtt for HueSwitch {
async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the deviec itself or from a remote
if matches(&message.topic, &self.config.mqtt.topic) {
let action = match serde_json::from_slice::<Zigbee929003017102>(&message.payload) {
Ok(message) => message.action,
Err(err) => {
warn!(id = Device::get_id(self), "Failed to parse message: {err}");
return;
}
};
debug!(id = Device::get_id(self), "Remote action = {:?}", action);
match action {
zigbee2mqtt_types::vendors::philips::Zigbee929003017102Action::Leftpress => {
self.config.left_callback.call(()).await
}
zigbee2mqtt_types::vendors::philips::Zigbee929003017102Action::Rightpress => {
self.config.right_callback.call(()).await
}
_ => {}
}
}
}
}

View File

@@ -0,0 +1,188 @@
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use automation_lib::action_callback::ActionCallback;
use automation_lib::config::{InfoConfig, MqttDeviceConfig};
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::messages::OnOffMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use google_home::device;
use google_home::errors::ErrorCode;
use google_home::traits::{self, OnOff};
use google_home::types::Type;
use rumqttc::{matches, Publish};
use serde::Deserialize;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, error, trace, warn};
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Copy)]
pub enum OutletType {
Outlet,
Kettle,
Charger,
Light,
}
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
#[device_config(flatten)]
pub info: InfoConfig,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(default(OutletType::Outlet))]
pub outlet_type: OutletType,
#[device_config(from_lua, default)]
pub callback: ActionCallback<(IkeaOutlet, bool)>,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
#[derive(Debug, Default)]
pub struct State {
last_known_state: bool,
}
#[derive(Debug, Clone)]
pub struct IkeaOutlet {
config: Config,
state: Arc<RwLock<State>>,
}
impl IkeaOutlet {
async fn state(&self) -> RwLockReadGuard<State> {
self.state.read().await
}
async fn state_mut(&self) -> RwLockWriteGuard<State> {
self.state.write().await
}
}
#[async_trait]
impl LuaDeviceCreate for IkeaOutlet {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.info.identifier(), "Setting up IkeaOutlet");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self {
config,
state: Default::default(),
})
}
}
impl Device for IkeaOutlet {
fn get_id(&self) -> String {
self.config.info.identifier()
}
}
#[async_trait]
impl OnMqtt for IkeaOutlet {
async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the deviec itself or from a remote
if matches(&message.topic, &self.config.mqtt.topic) {
// Update the internal state based on what the device has reported
let state = match OnOffMessage::try_from(message) {
Ok(state) => state.state(),
Err(err) => {
error!(id = Device::get_id(self), "Failed to parse message: {err}");
return;
}
};
// No need to do anything if the state has not changed
if state == self.state().await.last_known_state {
return;
}
self.config.callback.call((self.clone(), state)).await;
debug!(id = Device::get_id(self), "Updating state to {state}");
self.state_mut().await.last_known_state = state;
}
}
}
#[async_trait]
impl OnPresence for IkeaOutlet {
async fn on_presence(&self, presence: bool) {
// Turn off the outlet when we leave the house (Not if it is a battery charger)
if !presence && self.config.outlet_type != OutletType::Charger {
debug!(id = Device::get_id(self), "Turning device off");
self.set_on(false).await.ok();
}
}
}
impl google_home::Device for IkeaOutlet {
fn get_device_type(&self) -> Type {
match self.config.outlet_type {
OutletType::Outlet => Type::Outlet,
OutletType::Kettle => Type::Kettle,
OutletType::Light => Type::Light, // Find a better device type for this, ideally would like to use charger, but that needs more work
OutletType::Charger => Type::Outlet, // Find a better device type for this, ideally would like to use charger, but that needs more work
}
}
fn get_device_name(&self) -> device::Name {
device::Name::new(&self.config.info.name)
}
fn get_id(&self) -> String {
Device::get_id(self)
}
fn is_online(&self) -> bool {
true
}
fn get_room_hint(&self) -> Option<&str> {
self.config.info.room.as_deref()
}
fn will_report_state(&self) -> bool {
// TODO: Implement state reporting
false
}
}
#[async_trait]
impl traits::OnOff for IkeaOutlet {
async fn on(&self) -> Result<bool, ErrorCode> {
Ok(self.state().await.last_known_state)
}
async fn set_on(&self, on: bool) -> Result<(), ErrorCode> {
let message = OnOffMessage::new(on);
let topic = format!("{}/set", self.config.mqtt.topic);
// TODO: Handle potential errors here
self.config
.client
.publish(
&topic,
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(),
)
.await
.map_err(|err| warn!("Failed to update state on {topic}: {err}"))
.ok();
Ok(())
}
}

View File

@@ -0,0 +1,91 @@
use automation_lib::action_callback::ActionCallback;
use automation_lib::config::{InfoConfig, MqttDeviceConfig};
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt;
use automation_lib::messages::{RemoteAction, RemoteMessage};
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use axum::async_trait;
use rumqttc::{matches, Publish};
use tracing::{debug, error, trace};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
#[device_config(flatten)]
pub info: InfoConfig,
#[device_config(default)]
pub single_button: bool,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
#[device_config(from_lua)]
pub callback: ActionCallback<bool>,
}
#[derive(Debug, Clone)]
pub struct IkeaRemote {
config: Config,
}
impl Device for IkeaRemote {
fn get_id(&self) -> String {
self.config.info.identifier()
}
}
#[async_trait]
impl LuaDeviceCreate for IkeaRemote {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.info.identifier(), "Setting up IkeaRemote");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self { config })
}
}
#[async_trait]
impl OnMqtt for IkeaRemote {
async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the deviec itself or from a remote
if matches(&message.topic, &self.config.mqtt.topic) {
let action = match RemoteMessage::try_from(message) {
Ok(message) => message.action(),
Err(err) => {
error!(id = Device::get_id(self), "Failed to parse message: {err}");
return;
}
};
debug!(id = Device::get_id(self), "Remote action = {:?}", action);
let on = if self.config.single_button {
match action {
RemoteAction::On => Some(true),
RemoteAction::BrightnessMoveUp => Some(false),
_ => None,
}
} else {
match action {
RemoteAction::On => Some(true),
RemoteAction::Off => Some(false),
_ => None,
}
};
if let Some(on) = on {
self.config.callback.call(on).await;
}
}
}
}

View File

@@ -0,0 +1,287 @@
use std::convert::Infallible;
use std::net::SocketAddr;
use std::str::Utf8Error;
use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnPresence;
use automation_macro::LuaDeviceConfig;
use bytes::{Buf, BufMut};
use google_home::errors::{self, DeviceError};
use google_home::traits::OnOff;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tracing::{debug, trace};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
pub identifier: String,
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 9999)))]
pub addr: SocketAddr,
}
#[derive(Debug, Clone)]
pub struct KasaOutlet {
config: Config,
}
#[async_trait]
impl LuaDeviceCreate for KasaOutlet {
type Config = Config;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.identifier, "Setting up KasaOutlet");
Ok(Self { config })
}
}
impl Device for KasaOutlet {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
#[derive(Debug, Serialize)]
struct RequestRelayState {
state: isize,
}
#[derive(Debug, Serialize)]
struct RequestSysinfo;
#[derive(Debug, Serialize)]
struct RequestSystem {
#[serde(skip_serializing_if = "Option::is_none")]
get_sysinfo: Option<RequestSysinfo>,
#[serde(skip_serializing_if = "Option::is_none")]
set_relay_state: Option<RequestRelayState>,
}
#[derive(Debug, Serialize)]
struct Request {
system: RequestSystem,
}
impl Request {
fn get_sysinfo() -> Self {
Self {
system: RequestSystem {
get_sysinfo: Some(RequestSysinfo {}),
set_relay_state: None,
},
}
}
fn set_relay_state(on: bool) -> Self {
Self {
system: RequestSystem {
get_sysinfo: None,
set_relay_state: Some(RequestRelayState {
state: if on { 1 } else { 0 },
}),
},
}
}
fn encrypt(&self) -> bytes::Bytes {
let data: bytes::Bytes = serde_json::to_string(self).unwrap().into();
let mut key: u8 = 171;
let mut encrypted = bytes::BytesMut::with_capacity(data.len() + 4);
encrypted.put_u32(data.len() as u32);
for c in data {
key ^= c;
encrypted.put_u8(key);
}
encrypted.freeze()
}
}
#[derive(Debug, Deserialize)]
struct ErrorCode {
err_code: isize,
}
impl ErrorCode {
fn ok(&self) -> Result<(), ResponseError> {
if self.err_code != 0 {
Err(ResponseError::ErrorCode(self.err_code))
} else {
Ok(())
}
}
}
#[derive(Debug, Deserialize)]
struct ResponseSetRelayState {
#[serde(flatten)]
err_code: ErrorCode,
}
#[derive(Debug, Deserialize)]
struct ResponseGetSysinfo {
#[serde(flatten)]
err_code: ErrorCode,
relay_state: isize,
}
#[derive(Debug, Deserialize)]
struct ResponseSystem {
set_relay_state: Option<ResponseSetRelayState>,
get_sysinfo: Option<ResponseGetSysinfo>,
}
#[derive(Debug, Deserialize)]
struct Response {
system: ResponseSystem,
}
// TODO: Improve this error
#[derive(Debug, Error)]
enum ResponseError {
#[error("Expected a minimum data length of 4")]
ToShort,
#[error("No sysinfo found in response")]
SysinfoNotFound,
#[error("No relay_state not found in response")]
RelayStateNotFound,
#[error("Error code: {0}")]
ErrorCode(isize),
#[error(transparent)]
Other(#[from] Box<dyn std::error::Error>),
}
impl From<Utf8Error> for ResponseError {
fn from(err: Utf8Error) -> Self {
ResponseError::Other(err.into())
}
}
impl From<serde_json::Error> for ResponseError {
fn from(err: serde_json::Error) -> Self {
ResponseError::Other(err.into())
}
}
impl Response {
fn get_current_relay_state(&self) -> Result<bool, ResponseError> {
if let Some(sysinfo) = &self.system.get_sysinfo {
return sysinfo.err_code.ok().map(|_| sysinfo.relay_state == 1);
}
Err(ResponseError::SysinfoNotFound)
}
fn check_set_relay_success(&self) -> Result<(), ResponseError> {
if let Some(set_relay_state) = &self.system.set_relay_state {
return set_relay_state.err_code.ok();
}
Err(ResponseError::RelayStateNotFound)
}
fn decrypt(mut data: bytes::Bytes) -> Result<Self, ResponseError> {
let mut key: u8 = 171;
if data.len() < 4 {
return Err(ResponseError::ToShort);
}
let length = data.get_u32();
let mut decrypted = bytes::BytesMut::with_capacity(length as usize);
for c in data {
decrypted.put_u8(key ^ c);
key = c;
}
let decrypted = std::str::from_utf8(&decrypted)?;
Ok(serde_json::from_str(decrypted)?)
}
}
#[async_trait]
impl OnOff for KasaOutlet {
async fn on(&self) -> Result<bool, errors::ErrorCode> {
let mut stream = TcpStream::connect(self.config.addr)
.await
.or::<DeviceError>(Err(DeviceError::DeviceOffline))?;
let body = Request::get_sysinfo().encrypt();
stream
.write_all(&body)
.await
.and(stream.flush().await)
.or::<DeviceError>(Err(DeviceError::TransientError))?;
let mut received = Vec::new();
let mut rx_bytes = [0; 1024];
loop {
let read = stream
.read(&mut rx_bytes)
.await
.or::<errors::ErrorCode>(Err(DeviceError::TransientError.into()))?;
received.extend_from_slice(&rx_bytes[..read]);
if read < rx_bytes.len() {
break;
}
}
let resp = Response::decrypt(received.into())
.or::<errors::ErrorCode>(Err(DeviceError::TransientError.into()))?;
resp.get_current_relay_state()
.or(Err(DeviceError::TransientError.into()))
}
async fn set_on(&self, on: bool) -> Result<(), errors::ErrorCode> {
let mut stream = TcpStream::connect(self.config.addr)
.await
.or::<DeviceError>(Err(DeviceError::DeviceOffline))?;
let body = Request::set_relay_state(on).encrypt();
stream
.write_all(&body)
.await
.and(stream.flush().await)
.or::<DeviceError>(Err(DeviceError::TransientError))?;
let mut received = Vec::new();
let mut rx_bytes = [0; 1024];
loop {
let read = match stream.read(&mut rx_bytes).await {
Ok(read) => read,
Err(_) => return Err(DeviceError::TransientError.into()),
};
received.extend_from_slice(&rx_bytes[..read]);
if read < rx_bytes.len() {
break;
}
}
let resp = Response::decrypt(received.into())
.or::<errors::ErrorCode>(Err(DeviceError::TransientError.into()))?;
resp.check_set_relay_success()
.or(Err(DeviceError::TransientError.into()))
}
}
#[async_trait]
impl OnPresence for KasaOutlet {
async fn on_presence(&self, presence: bool) {
if !presence {
debug!(id = Device::get_id(self), "Turning device off");
self.set_on(false).await.ok();
}
}
}

View File

@@ -0,0 +1,110 @@
mod air_filter;
mod contact_sensor;
mod debug_bridge;
mod hue_bridge;
mod hue_group;
mod hue_switch;
mod ikea_outlet;
mod ikea_remote;
mod kasa_outlet;
mod light_sensor;
mod wake_on_lan;
mod washer;
use std::ops::Deref;
use automation_cast::Cast;
use automation_lib::device::{Device, LuaDeviceCreate};
pub use self::air_filter::AirFilter;
pub use self::contact_sensor::ContactSensor;
pub use self::debug_bridge::DebugBridge;
pub use self::hue_bridge::HueBridge;
pub use self::hue_group::HueGroup;
pub use self::hue_switch::HueSwitch;
pub use self::ikea_outlet::IkeaOutlet;
pub use self::ikea_remote::IkeaRemote;
pub use self::kasa_outlet::KasaOutlet;
pub use self::light_sensor::LightSensor;
pub use self::wake_on_lan::WakeOnLAN;
pub use self::washer::Washer;
macro_rules! register_device {
($lua:expr, $device:ty) => {
$lua.globals()
.set(stringify!($device), $lua.create_proxy::<$device>()?)?;
};
}
macro_rules! impl_device {
($device:ty) => {
impl mlua::UserData for $device {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_function("new", |_lua, config| async {
let device: $device = LuaDeviceCreate::create(config)
.await
.map_err(mlua::ExternalError::into_lua_err)?;
Ok(device)
});
methods.add_method("__box", |_lua, this, _: ()| {
let b: Box<dyn Device> = Box::new(this.clone());
Ok(b)
});
methods.add_async_method("get_id", |_lua, this, _: ()| async move { Ok(this.get_id()) });
if impls::impls!($device: google_home::traits::OnOff) {
methods.add_async_method("set_on", |_lua, this, on: bool| async move {
(this.deref().cast() as Option<&dyn google_home::traits::OnOff>)
.expect("Cast should be valid")
.set_on(on)
.await
.unwrap();
Ok(())
});
methods.add_async_method("is_on", |_lua, this, _: ()| async move {
Ok((this.deref().cast() as Option<&dyn google_home::traits::OnOff>)
.expect("Cast should be valid")
.on()
.await
.unwrap())
});
}
}
}
};
}
impl_device!(AirFilter);
impl_device!(ContactSensor);
impl_device!(DebugBridge);
impl_device!(HueBridge);
impl_device!(HueGroup);
impl_device!(HueSwitch);
impl_device!(IkeaOutlet);
impl_device!(IkeaRemote);
impl_device!(KasaOutlet);
impl_device!(LightSensor);
impl_device!(WakeOnLAN);
impl_device!(Washer);
pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
register_device!(lua, AirFilter);
register_device!(lua, ContactSensor);
register_device!(lua, DebugBridge);
register_device!(lua, HueBridge);
register_device!(lua, HueGroup);
register_device!(lua, HueSwitch);
register_device!(lua, IkeaOutlet);
register_device!(lua, IkeaRemote);
register_device!(lua, KasaOutlet);
register_device!(lua, LightSensor);
register_device!(lua, WakeOnLAN);
register_device!(lua, Washer);
Ok(())
}

View File

@@ -0,0 +1,118 @@
use std::sync::Arc;
use async_trait::async_trait;
use automation_lib::config::MqttDeviceConfig;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{self, Event, EventChannel, OnMqtt};
use automation_lib::messages::BrightnessMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, trace, warn};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
pub identifier: String,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
pub min: isize,
pub max: isize,
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
const DEFAULT: bool = false;
#[derive(Debug)]
pub struct State {
is_dark: bool,
}
#[derive(Debug, Clone)]
pub struct LightSensor {
config: Config,
state: Arc<RwLock<State>>,
}
impl LightSensor {
async fn state(&self) -> RwLockReadGuard<State> {
self.state.read().await
}
async fn state_mut(&self) -> RwLockWriteGuard<State> {
self.state.write().await
}
}
#[async_trait]
impl LuaDeviceCreate for LightSensor {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.identifier, "Setting up LightSensor");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
let state = State { is_dark: DEFAULT };
let state = Arc::new(RwLock::new(state));
Ok(Self { config, state })
}
}
impl Device for LightSensor {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
#[async_trait]
impl OnMqtt for LightSensor {
async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
return;
}
let illuminance = match BrightnessMessage::try_from(message) {
Ok(state) => state.illuminance(),
Err(err) => {
warn!("Failed to parse message: {err}");
return;
}
};
debug!("Illuminance: {illuminance}");
let is_dark = if illuminance <= self.config.min {
trace!("It is dark");
true
} else if illuminance >= self.config.max {
trace!("It is light");
false
} else {
let is_dark = self.state().await.is_dark;
trace!(
"In between min ({}) and max ({}) value, keeping current state: {}",
self.config.min,
self.config.max,
is_dark
);
is_dark
};
if is_dark != self.state().await.is_dark {
debug!("Dark state has changed: {is_dark}");
self.state_mut().await.is_dark = is_dark;
if self.config.tx.send(Event::Darkness(is_dark)).await.is_err() {
warn!("There are no receivers on the event channel");
}
}
}
}

View File

@@ -0,0 +1,144 @@
use std::net::Ipv4Addr;
use async_trait::async_trait;
use automation_lib::config::{InfoConfig, MqttDeviceConfig};
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt;
use automation_lib::messages::ActivateMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use eui48::MacAddress;
use google_home::device;
use google_home::errors::ErrorCode;
use google_home::traits::{self, Scene};
use google_home::types::Type;
use rumqttc::Publish;
use tracing::{debug, error, trace};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
#[device_config(flatten)]
pub info: InfoConfig,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
pub mac_address: MacAddress,
#[device_config(default(Ipv4Addr::new(255, 255, 255, 255)))]
pub broadcast_ip: Ipv4Addr,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
#[derive(Debug, Clone)]
pub struct WakeOnLAN {
config: Config,
}
#[async_trait]
impl LuaDeviceCreate for WakeOnLAN {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.info.identifier(), "Setting up WakeOnLAN");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self { config })
}
}
impl Device for WakeOnLAN {
fn get_id(&self) -> String {
self.config.info.identifier()
}
}
#[async_trait]
impl OnMqtt for WakeOnLAN {
async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
return;
}
let activate = match ActivateMessage::try_from(message) {
Ok(message) => message.activate(),
Err(err) => {
error!(id = Device::get_id(self), "Failed to parse message: {err}");
return;
}
};
self.set_active(activate).await.ok();
}
}
impl google_home::Device for WakeOnLAN {
fn get_device_type(&self) -> Type {
Type::Scene
}
fn get_device_name(&self) -> device::Name {
let mut name = device::Name::new(&self.config.info.name);
name.add_default_name("Computer");
name
}
fn get_id(&self) -> String {
Device::get_id(self)
}
fn is_online(&self) -> bool {
true
}
fn get_room_hint(&self) -> Option<&str> {
self.config.info.room.as_deref()
}
}
#[async_trait]
impl traits::Scene for WakeOnLAN {
async fn set_active(&self, deactivate: bool) -> Result<(), ErrorCode> {
if deactivate {
debug!(
id = Device::get_id(self),
"Trying to deactivate computer, this is not currently supported"
);
// We do not support deactivating this scene
Err(ErrorCode::DeviceError(
google_home::errors::DeviceError::ActionNotAvailable,
))
} else {
debug!(
id = Device::get_id(self),
"Activating Computer: {} (Sending to {})",
self.config.mac_address,
self.config.broadcast_ip
);
let wol = wakey::WolPacket::from_bytes(&self.config.mac_address.to_array()).map_err(
|err| {
error!(id = Device::get_id(self), "invalid mac address: {err}");
google_home::errors::DeviceError::TransientError
},
)?;
wol.send_magic_to(
(Ipv4Addr::new(0, 0, 0, 0), 0),
(self.config.broadcast_ip, 9),
)
.await
.map_err(|err| {
error!(
id = Device::get_id(self),
"Failed to activate computer: {err}"
);
google_home::errors::DeviceError::TransientError.into()
})
.map(|_| debug!(id = Device::get_id(self), "Success!"))
}
}
}

View File

@@ -0,0 +1,141 @@
use std::sync::Arc;
use async_trait::async_trait;
use automation_lib::config::MqttDeviceConfig;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{self, Event, EventChannel, OnMqtt};
use automation_lib::messages::PowerMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_lib::ntfy::{Notification, Priority};
use automation_macro::LuaDeviceConfig;
use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, error, trace, warn};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
pub identifier: String,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
// Power in Watt
pub threshold: f32,
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
#[derive(Debug)]
pub struct State {
running: isize,
}
// TODO: Add google home integration
#[derive(Debug, Clone)]
pub struct Washer {
config: Config,
state: Arc<RwLock<State>>,
}
impl Washer {
async fn state(&self) -> RwLockReadGuard<State> {
self.state.read().await
}
async fn state_mut(&self) -> RwLockWriteGuard<State> {
self.state.write().await
}
}
#[async_trait]
impl LuaDeviceCreate for Washer {
type Config = Config;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
trace!(id = config.identifier, "Setting up Washer");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
let state = State { running: 0 };
let state = Arc::new(RwLock::new(state));
Ok(Self { config, state })
}
}
impl Device for Washer {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
// The washer needs to have a power draw above the threshold multiple times before the washer is
// actually marked as running
// This helps prevent false positives
const HYSTERESIS: isize = 10;
#[async_trait]
impl OnMqtt for Washer {
async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
return;
}
let power = match PowerMessage::try_from(message) {
Ok(state) => state.power(),
Err(err) => {
error!(
id = self.config.identifier,
"Failed to parse message: {err}"
);
return;
}
};
// debug!(id = self.identifier, power, "Washer state update");
if power < self.config.threshold && self.state().await.running >= HYSTERESIS {
// The washer is done running
debug!(
id = self.config.identifier,
power,
threshold = self.config.threshold,
"Washer is done"
);
self.state_mut().await.running = 0;
let notification = Notification::new()
.set_title("Laundy is done")
.set_message("Don't forget to hang it!")
.add_tag("womans_clothes")
.set_priority(Priority::High);
if self
.config
.tx
.send(Event::Ntfy(notification))
.await
.is_err()
{
warn!("There are no receivers on the event channel");
}
} else if power < self.config.threshold {
// Prevent false positives
self.state_mut().await.running = 0;
} else if power >= self.config.threshold && self.state().await.running < HYSTERESIS {
// Washer could be starting
debug!(
id = self.config.identifier,
power,
threshold = self.config.threshold,
"Washer is starting"
);
self.state_mut().await.running += 1;
}
}
}