mod json; //AUTO mod auto; use std::{thread, time::Duration}; use serde::Deserialize; use mqtt_client::{MqttMessage, MqttEvent, Sender, Receiver, QoS}; use mqtt_client::mqtt_client; use crate::automation::json::json_parser; //AUTO use crate::automation::auto::automation::{Automation as AutoConfig, Generator}; #[derive(Deserialize)] pub struct SettingsConf { base_topic: String, alarm_hour: u8, alarm_minute: u8, //AUTO auto: Vec } struct PingStats { total: u16, fails: u16, avg: f32 } fn ping_stat_update(stats: &mut PingStats, payload: String) -> Option { let mut new_value: Option = None; if !payload.eq("false") { match payload.parse::() { Ok(value) => new_value = Some(value), Err(_) => {} } } stats.total += 1; match new_value { Some(value) => stats.avg += (value - stats.avg) / f32::from(stats.total - stats.fails), None => stats.fails += 1 } new_value } pub struct Automation { tx: Sender, client: mqtt_client::Client, clock_dow: u8, clock_hour: u8, clock_min: u8, clock_sec: u8, elfdesktop_last_on: u32, elfdesktop_state: bool, ping_elfdesktop: PingStats, config: SettingsConf, //AUTO generator: Generator } impl Automation { fn tx(&self, message: MqttMessage) { match self.tx.send(message) { Err(n) => println!("ERROR: faild to send publish ({:?})", n), Ok(_n) => {} } } fn tx_set(&self, topic: String, state: bool) { let payload: String; if state { payload = String::from("ON"); } else { payload = String::from("OFF"); } self.tx({ MqttMessage { topic: topic, payload: payload, retain: false, qos: mqtt_client::QoS::AtMostOnce, }}); } fn lamp01_set(&self, state: bool) { self.tx_set(String::from("/cool/devices/lamp-01/set"), state); } fn pc_sw_set(&self, state: bool) { self.tx_set(String::from("/cool/devices/sw-01/set"), state); } fn get_current_time(&self) -> u32 { self.get_time(None, None, None, None) } fn get_time(&self, dow: Option, hour: Option, min: Option, sec: Option) -> u32 { let d = match dow { Some(n) => n, None => self.clock_dow }; let h = match hour { Some(n) => n, None => self.clock_hour }; let m = match min { Some(n) => n, None => self.clock_min }; let s = match sec { Some(n) => n, None => self.clock_sec }; ((u32::from(d) * 24 + u32::from(h)) * 60 + u32::from(m)) * 60 + u32::from(s) } fn alarm_trigger(&self) { self.lamp01_set(true); } fn alarm_send_config(&self) { self.tx({ MqttMessage { topic: format!("{}alarm", self.config.base_topic), payload: format!("{}:{}", self.config.alarm_hour, self.config.alarm_minute), retain: true, qos: mqtt_client::QoS::AtMostOnce, }}); } fn config_message_in(&mut self, message: MqttMessage, topic: String) { if topic.starts_with("alarm/set") { let mut time = message.payload.split(':'); if time.clone().count() != 2 && time.clone().count() != 3 { println!("ERROR: config_message_in: alarm/set has invalid payload. incorect number of slices ({})", message.payload) } else { let hour_str = time.next().unwrap(); let min_str = time.next().unwrap(); let mut hour: Option = None; let mut min: Option = None; match hour_str.parse::() { Err(_) => println!("ERROR: config_message_in: alarm/set has invalid payload. hour is NaN ({})", message.payload), Ok(n) => hour = Some(n) } match min_str.parse::() { Err(_) => println!("ERROR: config_message_in: alarm/set has invalid payload. min is NaN ({})", message.payload), Ok(n) => min = Some(n) } if hour != None && min != None { self.config.alarm_hour = hour.unwrap(); self.config.alarm_minute = min.unwrap(); } } self.alarm_send_config(); } } fn clock_message_in(&mut self, message: MqttMessage) { if message.topic.eq("clock/time/second") { match message.payload.parse::() { Err(e) => println!("ERROR: clock_message_in: clock/time/second has invalid payload ({:?})", e), Ok(n) => { self.clock_sec = n; if n % 20 == 0 { let json = format!( "{{ \"deviceID\": 0, \"ping\": {}, \"pong\": {} }}", self.ping_elfdesktop.avg, 1.0 - (f32::from(self.ping_elfdesktop.fails) / f32::from(self.ping_elfdesktop.total)) ); self.tx({ MqttMessage { topic: String::from("/kees/db/insert/ping"), payload: json, retain: false, qos: mqtt_client::QoS::AtMostOnce, }}); self.ping_elfdesktop.total = 0; self.ping_elfdesktop.fails = 0; self.ping_elfdesktop.avg = 0.0; } } } } else if message.topic.eq("clock/time/minute") { match message.payload.parse::() { Err(e) => println!("ERROR: clock_message_in: clock/time/minute has invalid payload ({:?})", e), Ok(n) => { self.clock_min = n; if n == self.config.alarm_minute && n != 0 && self.clock_hour == self.config.alarm_hour && self.clock_dow < 5 { self.alarm_trigger(); } } } } else if message.topic.eq("clock/time/hour") { match message.payload.parse::() { Err(e) => println!("ERROR: clock_message_in: clock/time/hour has invalid payload ({:?})", e), Ok(n) => { self.clock_hour = n; self.alarm_send_config(); if self.config.alarm_minute == 0 && n == self.config.alarm_hour && self.clock_dow < 5 { self.alarm_trigger(); } } } } else if message.topic.eq("clock/date/dow") { match message.payload.parse::() { Err(e) => println!("ERROR: clock_message_in: clock/date/dow has invalid payload ({:?})", e), Ok(n) => self.clock_dow = n } } // println!("DEBUG: clock_message_in: current time: {}:{}:{}", self.clock_hour, self.clock_min, self.clock_sec); } fn message_in(&mut self, message: MqttMessage) { // println!("DEBUG : mqtt_automation: {}: {}", message.topic, message.payload); if message.topic.starts_with(&self.config.base_topic) { let topic = message.topic[self.config.base_topic.len()..].to_string(); self.config_message_in(message, topic); } else if message.topic.starts_with("clock/") { self.clock_message_in(message); } else if message.topic.eq("/cool/devices/KNMITemp/values") { let payload_json = json_parser::Json::Text(message.payload); let path = Vec::from([String::from("gr")]); match json_parser::get_u32(payload_json, path) { Ok(gr) => { if gr > 30 { let alarm_time = self.get_time(None, Some(self.config.alarm_hour), Some(self.config.alarm_minute), Some(0)); let time_30min = self.get_time(Some(0), Some(0), Some(29), Some(0)); let time_diff: i64 = i64::from(self.get_current_time()) - i64::from(alarm_time); if self.clock_dow >= 5 || time_diff < 0 || time_diff > i64::from(time_30min) { self.lamp01_set(false); } } }, Err(e) => print!("ERROR: mqtt_automation: KNMITemp: {}", e.to_string()) } } else if message.topic.eq("/kees/ping/elfdesktop") { let now: u32 = self.get_current_time(); let ping = ping_stat_update(&mut self.ping_elfdesktop, message.payload); match ping { None => { if self.elfdesktop_last_on < now - 3 { if self.elfdesktop_state { self.pc_sw_set(false); self.elfdesktop_state = false; } } }, Some(_) => { self.elfdesktop_last_on = now; if !self.elfdesktop_state { self.pc_sw_set(true); self.elfdesktop_state = true; } } } } } fn init(&self) { println!("DEBUG: init"); match self.client.subscribe("clock/time/#", QoS::AtMostOnce) { Err(e) => println!("ERROR: main: faild to subscribe to clock/time/hour ({})", e), Ok(_) => {} } match self.client.subscribe("clock/date/dow", QoS::AtMostOnce) { Err(e) => println!("ERROR: main: faild to subscribe to clock/date/dow ({})", e), Ok(_) => {} } match self.client.subscribe("/kees/automation/#", QoS::AtMostOnce) { Err(e) => println!("ERROR: main: faild to subscribe to automation/alarm/# ({})", e), Ok(_) => {} } match self.client.subscribe("/cool/devices/KNMITemp/values", QoS::AtMostOnce) { Err(e) => println!("ERROR: main: faild to subscribe to KNMITemp/values ({})", e), Ok(_) => {} } match self.client.subscribe("/kees/ping/#", QoS::AtMostOnce) { Err(e) => println!("ERROR: main: faild to subscribe to KNMITemp/values ({})", e), Ok(_) => {} } self.alarm_send_config(); } } impl mqtt_client::MqttTool for Automation { fn new(tx: Sender, config: SettingsConf, client: mqtt_client::Client) -> Automation { Automation { tx, client, clock_dow: u8::MAX, clock_hour: u8::MAX, clock_min: u8::MAX, clock_sec: u8::MAX, elfdesktop_last_on: u32::MAX, elfdesktop_state: false, ping_elfdesktop: { PingStats { total: 0, fails: 0, avg: 0.0 } }, config: config, //AUTO generator: Generator::new() } } fn run(&mut self, rx: Receiver) { loop { let message = rx.recv(); match message { Err(e) => { println!("ERROR: mqttAutomation: failed to receve an message ({})", e); thread::sleep(Duration::from_millis(500)); }, Ok(event) => { match event { MqttEvent::Connected => { self.init(); }, MqttEvent::Disconnected => {}, MqttEvent::Message(message) => { self.message_in(message); }, } } } } } }