Move ntfy and presence to automation_devices
This commit is contained in:
@@ -9,7 +9,6 @@ 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::{LuaDevice, LuaDeviceConfig};
|
||||
use google_home::device;
|
||||
use google_home::errors::{DeviceError, ErrorCode};
|
||||
@@ -20,6 +19,8 @@ use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::{debug, error, trace, warn};
|
||||
|
||||
use crate::presence::DEFAULT_PRESENCE;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Copy)]
|
||||
pub enum SensorType {
|
||||
Door,
|
||||
|
||||
@@ -7,6 +7,8 @@ mod hue_switch;
|
||||
mod ikea_remote;
|
||||
mod kasa_outlet;
|
||||
mod light_sensor;
|
||||
mod ntfy;
|
||||
mod presence;
|
||||
mod wake_on_lan;
|
||||
mod washer;
|
||||
mod zigbee;
|
||||
@@ -24,6 +26,8 @@ pub use self::hue_switch::HueSwitch;
|
||||
pub use self::ikea_remote::IkeaRemote;
|
||||
pub use self::kasa_outlet::KasaOutlet;
|
||||
pub use self::light_sensor::LightSensor;
|
||||
pub use self::ntfy::*;
|
||||
pub use self::presence::Presence;
|
||||
pub use self::wake_on_lan::WakeOnLAN;
|
||||
pub use self::washer::Washer;
|
||||
|
||||
@@ -35,11 +39,6 @@ macro_rules! register_device {
|
||||
}
|
||||
|
||||
pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
|
||||
register_device!(lua, LightOnOff);
|
||||
register_device!(lua, LightBrightness);
|
||||
register_device!(lua, LightColorTemperature);
|
||||
register_device!(lua, OutletOnOff);
|
||||
register_device!(lua, OutletPower);
|
||||
register_device!(lua, AirFilter);
|
||||
register_device!(lua, ContactSensor);
|
||||
register_device!(lua, DebugBridge);
|
||||
@@ -48,7 +47,14 @@ pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
|
||||
register_device!(lua, HueSwitch);
|
||||
register_device!(lua, IkeaRemote);
|
||||
register_device!(lua, KasaOutlet);
|
||||
register_device!(lua, LightBrightness);
|
||||
register_device!(lua, LightColorTemperature);
|
||||
register_device!(lua, LightOnOff);
|
||||
register_device!(lua, LightSensor);
|
||||
register_device!(lua, Ntfy);
|
||||
register_device!(lua, OutletOnOff);
|
||||
register_device!(lua, OutletPower);
|
||||
register_device!(lua, Presence);
|
||||
register_device!(lua, WakeOnLAN);
|
||||
register_device!(lua, Washer);
|
||||
|
||||
|
||||
185
automation_devices/src/ntfy.rs
Normal file
185
automation_devices/src/ntfy.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
use std::collections::HashMap;
|
||||
use std::convert::Infallible;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||
use automation_lib::event::{self, EventChannel};
|
||||
use automation_lib::lua::traits::AddAdditionalMethods;
|
||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
||||
use mlua::LuaSerdeExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_repr::*;
|
||||
use tracing::{error, trace, warn};
|
||||
|
||||
#[derive(Debug, Serialize_repr, Deserialize, Clone, Copy)]
|
||||
#[repr(u8)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Priority {
|
||||
Min = 1,
|
||||
Low,
|
||||
Default,
|
||||
High,
|
||||
Max,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "snake_case", tag = "action")]
|
||||
pub enum ActionType {
|
||||
Broadcast {
|
||||
#[serde(skip_serializing_if = "HashMap::is_empty")]
|
||||
extras: HashMap<String, String>,
|
||||
},
|
||||
// View,
|
||||
// Http
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Action {
|
||||
#[serde(flatten)]
|
||||
pub action: ActionType,
|
||||
pub label: String,
|
||||
pub clear: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct NotificationFinal {
|
||||
topic: String,
|
||||
#[serde(flatten)]
|
||||
inner: Notification,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Clone, Deserialize)]
|
||||
pub struct Notification {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
title: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
message: Option<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
|
||||
tags: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
priority: Option<Priority>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
|
||||
actions: Vec<Action>,
|
||||
}
|
||||
|
||||
impl Notification {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
title: None,
|
||||
message: None,
|
||||
tags: Vec::new(),
|
||||
priority: None,
|
||||
actions: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_title(mut self, title: &str) -> Self {
|
||||
self.title = Some(title.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_message(mut self, message: &str) -> Self {
|
||||
self.message = Some(message.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_tag(mut self, tag: &str) -> Self {
|
||||
self.tags.push(tag.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_priority(mut self, priority: Priority) -> Self {
|
||||
self.priority = Some(priority);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_action(mut self, action: Action) -> Self {
|
||||
self.actions.push(action);
|
||||
self
|
||||
}
|
||||
|
||||
fn finalize(self, topic: &str) -> NotificationFinal {
|
||||
NotificationFinal {
|
||||
topic: topic.into(),
|
||||
inner: self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Notification {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
||||
pub struct Config {
|
||||
#[device_config(default("https://ntfy.sh".into()))]
|
||||
pub url: String,
|
||||
pub topic: String,
|
||||
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
|
||||
pub tx: event::Sender,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, LuaDevice)]
|
||||
#[traits(AddAdditionalMethods)]
|
||||
pub struct Ntfy {
|
||||
config: Config,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl LuaDeviceCreate for Ntfy {
|
||||
type Config = Config;
|
||||
type Error = Infallible;
|
||||
|
||||
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
|
||||
trace!(id = "ntfy", "Setting up Ntfy");
|
||||
Ok(Self { config })
|
||||
}
|
||||
}
|
||||
|
||||
impl Device for Ntfy {
|
||||
fn get_id(&self) -> String {
|
||||
"ntfy".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Ntfy {
|
||||
async fn send(&self, notification: Notification) {
|
||||
let notification = notification.finalize(&self.config.topic);
|
||||
|
||||
// Create the request
|
||||
let res = reqwest::Client::new()
|
||||
.post(self.config.url.clone())
|
||||
.json(¬ification)
|
||||
.send()
|
||||
.await;
|
||||
|
||||
if let Err(err) = res {
|
||||
error!("Something went wrong while sending the notification: {err}");
|
||||
} else if let Ok(res) = res {
|
||||
let status = res.status();
|
||||
if !status.is_success() {
|
||||
warn!("Received status {status} when sending notification");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AddAdditionalMethods for Ntfy {
|
||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
||||
where
|
||||
Self: Sized + 'static,
|
||||
{
|
||||
methods.add_async_method(
|
||||
"send_notification",
|
||||
|lua, this, notification: mlua::Value| async move {
|
||||
let notification: Notification = lua.from_value(notification)?;
|
||||
|
||||
this.send(notification).await;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
134
automation_devices/src/presence.rs
Normal file
134
automation_devices/src/presence.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
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::event::{self, Event, EventChannel, OnMqtt};
|
||||
use automation_lib::messages::PresenceMessage;
|
||||
use automation_lib::mqtt::WrappedAsyncClient;
|
||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
||||
use rumqttc::Publish;
|
||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
use tracing::{debug, trace, warn};
|
||||
|
||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
||||
pub struct Config {
|
||||
#[device_config(flatten)]
|
||||
pub mqtt: MqttDeviceConfig,
|
||||
#[device_config(from_lua, rename("event_channel"), with(|ec: EventChannel| ec.get_tx()))]
|
||||
pub tx: event::Sender,
|
||||
|
||||
#[device_config(from_lua, default)]
|
||||
pub callback: ActionCallback<Presence, bool>,
|
||||
|
||||
#[device_config(from_lua)]
|
||||
pub client: WrappedAsyncClient,
|
||||
}
|
||||
|
||||
pub const DEFAULT_PRESENCE: bool = false;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct State {
|
||||
devices: HashMap<String, bool>,
|
||||
current_overall_presence: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, LuaDevice)]
|
||||
pub struct Presence {
|
||||
config: Config,
|
||||
state: Arc<RwLock<State>>,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
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 Presence {
|
||||
type Config = Config;
|
||||
type Error = rumqttc::ClientError;
|
||||
|
||||
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
|
||||
trace!(id = "presence", "Setting up Presence");
|
||||
|
||||
config
|
||||
.client
|
||||
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
|
||||
.await?;
|
||||
|
||||
let state = State {
|
||||
devices: HashMap::new(),
|
||||
current_overall_presence: DEFAULT_PRESENCE,
|
||||
};
|
||||
let state = Arc::new(RwLock::new(state));
|
||||
|
||||
Ok(Self { config, state })
|
||||
}
|
||||
}
|
||||
|
||||
impl Device for Presence {
|
||||
fn get_id(&self) -> String {
|
||||
"presence".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl OnMqtt for Presence {
|
||||
async fn on_mqtt(&self, message: Publish) {
|
||||
if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
|
||||
return;
|
||||
}
|
||||
|
||||
let offset = self
|
||||
.config
|
||||
.mqtt
|
||||
.topic
|
||||
.find('+')
|
||||
.or(self.config.mqtt.topic.find('#'))
|
||||
.expect("Presence::create fails if it does not contain wildcards");
|
||||
let device_name = message.topic[offset..].into();
|
||||
|
||||
if message.payload.is_empty() {
|
||||
// Remove the device from the map
|
||||
debug!("State of device [{device_name}] has been removed");
|
||||
self.state_mut().await.devices.remove(&device_name);
|
||||
} else {
|
||||
let present = match PresenceMessage::try_from(message) {
|
||||
Ok(state) => state.presence(),
|
||||
Err(err) => {
|
||||
warn!("Failed to parse message: {err}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("State of device [{device_name}] has changed: {}", present);
|
||||
self.state_mut().await.devices.insert(device_name, present);
|
||||
}
|
||||
|
||||
let overall_presence = self.state().await.devices.iter().any(|(_, v)| *v);
|
||||
if overall_presence != self.state().await.current_overall_presence {
|
||||
debug!("Overall presence updated: {overall_presence}");
|
||||
self.state_mut().await.current_overall_presence = overall_presence;
|
||||
|
||||
if self
|
||||
.config
|
||||
.tx
|
||||
.send(Event::Presence(overall_presence))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
warn!("There are no receivers on the event channel");
|
||||
}
|
||||
|
||||
self.config.callback.call(self, &overall_presence).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user