make a lot more readable
This commit is contained in:
parent
7d820826a3
commit
e62d2596cd
262
src/main.rs
262
src/main.rs
@ -2,7 +2,7 @@ use std::time::Duration;
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use rumqttc::{Client, Event, MqttOptions, Outgoing, Packet, QoS};
|
use rumqttc::{Client, Connection, Event, MqttOptions, Outgoing, Packet, QoS};
|
||||||
use crossbeam::channel::{unbounded, Sender};
|
use crossbeam::channel::{unbounded, Sender};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
@ -11,8 +11,30 @@ struct MqttMessage {
|
|||||||
payload: String
|
payload: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mod json_parser {
|
||||||
|
pub enum Error {
|
||||||
|
Null,
|
||||||
|
InvalidType,
|
||||||
|
ConvertionFaild,
|
||||||
|
JsonParseError(String)
|
||||||
|
}
|
||||||
|
impl Error {
|
||||||
|
pub fn to_string(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Error::Null => String::from("path not found"),
|
||||||
|
Error::InvalidType => String::from("invalid type"),
|
||||||
|
Error::ConvertionFaild => String::from("type convertion faild"),
|
||||||
|
Error::JsonParseError(s) => s.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn json_get_value(value: json::JsonValue, mut path: Vec<String>) -> json::JsonValue {
|
pub enum Json {
|
||||||
|
Value(json::JsonValue),
|
||||||
|
Text(String)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_value(value: json::JsonValue, mut path: Vec<String>) -> json::JsonValue {
|
||||||
if path.len() == 0 {
|
if path.len() == 0 {
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
@ -20,14 +42,14 @@ fn json_get_value(value: json::JsonValue, mut path: Vec<String>) -> json::JsonVa
|
|||||||
json::JsonValue::Object(obj) => {
|
json::JsonValue::Object(obj) => {
|
||||||
let key = path[0].clone();
|
let key = path[0].clone();
|
||||||
path.remove(0);
|
path.remove(0);
|
||||||
json_get_value(obj[key].clone(), path)
|
get_value(obj[key].clone(), path)
|
||||||
},
|
},
|
||||||
json::JsonValue::Array(a) => {
|
json::JsonValue::Array(a) => {
|
||||||
let key = path[0].clone();
|
let key = path[0].clone();
|
||||||
match key.parse::<usize>() {
|
match key.parse::<usize>() {
|
||||||
Ok(i) => {
|
Ok(i) => {
|
||||||
if i < a.len() {
|
if i < a.len() {
|
||||||
json_get_value(a[i].clone(), path)
|
get_value(a[i].clone(), path)
|
||||||
} else {
|
} else {
|
||||||
json::JsonValue::Null
|
json::JsonValue::Null
|
||||||
}
|
}
|
||||||
@ -41,83 +63,96 @@ fn json_get_value(value: json::JsonValue, mut path: Vec<String>) -> json::JsonVa
|
|||||||
json::JsonValue::Boolean(_) => json::JsonValue::Null,
|
json::JsonValue::Boolean(_) => json::JsonValue::Null,
|
||||||
json::JsonValue::Null => json::JsonValue::Null,
|
json::JsonValue::Null => json::JsonValue::Null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
pub fn get_u32(data: Json, path: Vec<String>) -> Result<u32,Error> {
|
||||||
enum JsonGetError {
|
match data {
|
||||||
Null,
|
Json::Value(value) => match get_value(value, path) {
|
||||||
InvalidType,
|
json::JsonValue::Object(_) => Err(Error::InvalidType),
|
||||||
ConvertionFaild
|
json::JsonValue::Array(_) => Err(Error::InvalidType),
|
||||||
}
|
json::JsonValue::String(_) => Err(Error::InvalidType),
|
||||||
|
json::JsonValue::Short(_) => Err(Error::InvalidType),
|
||||||
fn json_get_u32(value: json::JsonValue, path: Vec<String>) -> Result<u32,JsonGetError> {
|
|
||||||
match json_get_value(value, path) {
|
|
||||||
json::JsonValue::Object(_) => Err(JsonGetError::InvalidType),
|
|
||||||
json::JsonValue::Array(_) => Err(JsonGetError::InvalidType),
|
|
||||||
json::JsonValue::String(_) => Err(JsonGetError::InvalidType),
|
|
||||||
json::JsonValue::Short(_) => Err(JsonGetError::InvalidType),
|
|
||||||
json::JsonValue::Number(num) => {
|
json::JsonValue::Number(num) => {
|
||||||
match u32::try_from(num) {
|
match u32::try_from(num) {
|
||||||
Err(_) => Err(JsonGetError::ConvertionFaild),
|
Err(_) => Err(Error::ConvertionFaild),
|
||||||
Ok(n) => Ok(n)
|
Ok(n) => Ok(n)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
json::JsonValue::Boolean(_) => Err(JsonGetError::InvalidType),
|
json::JsonValue::Boolean(_) => Err(Error::InvalidType),
|
||||||
json::JsonValue::Null => Err(JsonGetError::Null),
|
json::JsonValue::Null => Err(Error::Null),
|
||||||
|
}
|
||||||
|
Json::Text(data) => match json::parse(&data) {
|
||||||
|
Err(e) => {
|
||||||
|
Err(Error::JsonParseError(e.to_string()))
|
||||||
|
},
|
||||||
|
Ok(value) => get_u32(Json::Value(value), path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_publish(publish: &Sender<MqttMessage>, message: MqttMessage) {
|
struct Automation {
|
||||||
match publish.send(message) {
|
publish: Sender<MqttMessage>,
|
||||||
|
clock_dow: u8
|
||||||
|
}
|
||||||
|
impl Automation {
|
||||||
|
fn new(publish: Sender<MqttMessage>) -> Automation {
|
||||||
|
Automation {
|
||||||
|
publish,
|
||||||
|
clock_dow: u8::MAX
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(self) fn tx(&self, message: MqttMessage) {
|
||||||
|
match self.publish.send(message) {
|
||||||
Err(n) => println!("ERROR: faild to send publish ({:?})", n),
|
Err(n) => println!("ERROR: faild to send publish ({:?})", n),
|
||||||
Ok(_n) => {}
|
Ok(_n) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lamp01_set(publish: &Sender<MqttMessage>, state: bool) {
|
pub(self) fn lamp01_set(&self, state: bool) {
|
||||||
let payload: String;
|
let payload: String;
|
||||||
if state {
|
if state {
|
||||||
payload = String::from("ON");
|
payload = String::from("ON");
|
||||||
} else {
|
} else {
|
||||||
payload = String::from("OFF");
|
payload = String::from("OFF");
|
||||||
}
|
}
|
||||||
send_publish(publish, { MqttMessage {
|
self.tx({ MqttMessage {
|
||||||
topic: String::from("/cool/devices/lamp-01/set"),
|
topic: String::from("/cool/devices/lamp-01/set"),
|
||||||
payload: payload
|
payload: payload
|
||||||
}});
|
}});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mqtt_automation(publish: &Sender<MqttMessage>, message: MqttMessage) {
|
fn rx(&mut self, message: MqttMessage) {
|
||||||
println!("DEBUG: mqtt_automation: {}: {}", message.topic, message.payload);
|
println!("INFO : mqtt_automation: {}: {}", message.topic, message.payload);
|
||||||
if message.topic.eq("clock/hour") && message.payload.eq("7") {
|
if message.topic.eq("clock/hour") {
|
||||||
|
|
||||||
lamp01_set(publish, true);
|
if message.payload.eq("7") && (self.clock_dow >= 1 && self.clock_dow <= 7) {
|
||||||
|
self.lamp01_set(true);
|
||||||
|
}
|
||||||
|
|
||||||
} else if message.topic.eq("/cool/devices/KNMITemp/values") {
|
} else if message.topic.eq("/cool/devices/KNMITemp/values") {
|
||||||
|
|
||||||
match json::parse(&message.payload) {
|
match json_parser::get_u32(json_parser::Json::Text(message.payload), Vec::from([String::from("gr")])) {
|
||||||
// Err(e) => println!("ERROR: mqtt_automation: KNMITemp: invalid json ({})", e),
|
|
||||||
Err(e) => println!("ERROR: mqtt_automation: KNMITemp faild to parse json ({})", e),
|
|
||||||
Ok(payload) => {
|
|
||||||
match json_get_u32(payload, Vec::from([String::from("gr")])) {
|
|
||||||
Ok(gr) => {
|
Ok(gr) => {
|
||||||
println!("DEBUG: mqtt_automation: KNMITemp: gr = {}", gr);
|
|
||||||
if gr > 30 {
|
if gr > 30 {
|
||||||
lamp01_set(publish, false);
|
self.lamp01_set(false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Err(e) => print!("ERROR: mqtt_automation: KNMITemp: {:?}", e)
|
Err(e) => print!("ERROR: mqtt_automation: KNMITemp: {}", e.to_string())
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
// else if message.topic.eq("clock/dow") {
|
else if message.topic.eq("clock/dow") {
|
||||||
// match u8::try_from(message.payload) {
|
|
||||||
// Err(e) => println!("ERROR: mqtt_automation: clock/dow has invalid payload ({:?})", e),
|
match message.payload.parse::<u8>() {
|
||||||
// Ok(n) => automation_dow = n
|
Err(e) => println!("ERROR: mqtt_automation: clock/dow has invalid payload ({:?})", e),
|
||||||
// }
|
Ok(n) => self.clock_dow = n
|
||||||
// }
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -172,63 +207,8 @@ fn read_config() -> Result<Settings,SettingsError> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn mqtt_hadeler(mut connection: Connection, mqtt_publish: Sender<MqttMessage>) {
|
||||||
let (mqtt_publish, mqtt_publish_rx) = unbounded::<MqttMessage>();
|
let mut automation: Automation = Automation::new(mqtt_publish);
|
||||||
|
|
||||||
// get setting
|
|
||||||
let conf_ok: bool;
|
|
||||||
let conf: Settings;
|
|
||||||
match read_config() {
|
|
||||||
Ok(n) => {
|
|
||||||
conf = n;
|
|
||||||
conf_ok = true;
|
|
||||||
},
|
|
||||||
Err(_) => {
|
|
||||||
conf = Settings {
|
|
||||||
mqtt: SettingsMQTT {host:String::new(),port:0,client:String::new(),user:String::new(),pass:String::new()}
|
|
||||||
};
|
|
||||||
conf_ok = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if conf_ok {
|
|
||||||
let mut mqttoptions = MqttOptions::new(conf.mqtt.client, conf.mqtt.host, conf.mqtt.port);
|
|
||||||
mqttoptions.set_keep_alive(Duration::from_secs(5));
|
|
||||||
mqttoptions.set_credentials(conf.mqtt.user, conf.mqtt.pass);
|
|
||||||
let (client, mut connection) = Client::new(mqttoptions, 10);
|
|
||||||
|
|
||||||
match client.subscribe("clock/hour", QoS::AtMostOnce) {
|
|
||||||
Err(e) => println!("ERROR: main: faild to subscribe to clock/hour ({})", e),
|
|
||||||
Ok(_) => {}
|
|
||||||
}
|
|
||||||
match client.subscribe("/cool/devices/KNMITemp/values", QoS::AtMostOnce) {
|
|
||||||
Err(e) => println!("ERROR: main: faild to subscribe to .../KNMITemp/values ({})", e),
|
|
||||||
Ok(_) => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// thread publisher
|
|
||||||
let publisher = thread::Builder::new()
|
|
||||||
.name("publisher".to_string())
|
|
||||||
.spawn(move || {
|
|
||||||
loop {
|
|
||||||
let message = mqtt_publish_rx.recv();
|
|
||||||
match message {
|
|
||||||
Err(e) => println!("ERROR: publisher: faild to receve an message ({})", e),
|
|
||||||
Ok(msg) => {
|
|
||||||
println!("DEBUG: publisher: topic={}; payload={}", msg.topic, msg.payload);
|
|
||||||
match client.publish(msg.topic, QoS::AtMostOnce, false, msg.payload) {
|
|
||||||
Err(_n) => println!("ERROR: publisher: faild to publish"),
|
|
||||||
Ok(_n) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
match publisher {
|
|
||||||
Err(_n) => println!("ERROR: main: fait to create publisher thread"),
|
|
||||||
Ok(_n) => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (_i, notification) in connection.iter().enumerate() {
|
for (_i, notification) in connection.iter().enumerate() {
|
||||||
let mut delay: bool = false;
|
let mut delay: bool = false;
|
||||||
match notification {
|
match notification {
|
||||||
@ -290,7 +270,7 @@ fn main() {
|
|||||||
payload: payload
|
payload: payload
|
||||||
}};
|
}};
|
||||||
|
|
||||||
mqtt_automation(&mqtt_publish, message);
|
automation.rx(message);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Packet::PubAck(_) => {}, //println!("INFO : mqtt_recive: in PubAck"),
|
Packet::PubAck(_) => {}, //println!("INFO : mqtt_recive: in PubAck"),
|
||||||
@ -312,6 +292,78 @@ fn main() {
|
|||||||
thread::sleep(Duration::from_millis(500));
|
thread::sleep(Duration::from_millis(500));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let (mqtt_publish, mqtt_publish_rx) = unbounded::<MqttMessage>();
|
||||||
|
|
||||||
|
// get setting
|
||||||
|
let conf_ok: bool;
|
||||||
|
let conf: Settings;
|
||||||
|
match read_config() {
|
||||||
|
Ok(n) => {
|
||||||
|
conf = n;
|
||||||
|
conf_ok = true;
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
conf = Settings {
|
||||||
|
mqtt: SettingsMQTT {host:String::new(),port:0,client:String::new(),user:String::new(),pass:String::new()}
|
||||||
|
};
|
||||||
|
conf_ok = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if conf_ok {
|
||||||
|
let mut mqttoptions = MqttOptions::new(conf.mqtt.client, conf.mqtt.host, conf.mqtt.port);
|
||||||
|
mqttoptions.set_keep_alive(Duration::from_secs(5));
|
||||||
|
mqttoptions.set_credentials(conf.mqtt.user, conf.mqtt.pass);
|
||||||
|
let (client, connection) = Client::new(mqttoptions, 10);
|
||||||
|
|
||||||
|
match client.subscribe("clock/hour", QoS::AtMostOnce) {
|
||||||
|
Err(e) => println!("ERROR: main: faild to subscribe to clock/hour ({})", e),
|
||||||
|
Ok(_) => {}
|
||||||
|
}
|
||||||
|
match client.subscribe("/cool/devices/KNMITemp/values", QoS::AtMostOnce) {
|
||||||
|
Err(e) => println!("ERROR: main: faild to subscribe to .../KNMITemp/values ({})", e),
|
||||||
|
Ok(_) => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// thread publisher
|
||||||
|
let publisher = thread::Builder::new()
|
||||||
|
.name("publisher".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
loop {
|
||||||
|
let message = mqtt_publish_rx.recv();
|
||||||
|
match message {
|
||||||
|
Err(e) => println!("ERROR: publisher: faild to receve an message ({})", e),
|
||||||
|
Ok(msg) => {
|
||||||
|
println!("INFO : publisher: topic={}; payload={}", msg.topic, msg.payload);
|
||||||
|
match client.publish(msg.topic, QoS::AtMostOnce, false, msg.payload) {
|
||||||
|
Err(_n) => println!("ERROR: publisher: faild to publish"),
|
||||||
|
Ok(_n) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
match publisher {
|
||||||
|
Err(_n) => println!("ERROR: main: fait to create publisher thread"),
|
||||||
|
Ok(_n) => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// thread mqtt
|
||||||
|
let mqtt = thread::Builder::new()
|
||||||
|
.name("mqtt".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
mqtt_hadeler(connection, mqtt_publish);
|
||||||
|
});
|
||||||
|
match mqtt {
|
||||||
|
Err(_n) => println!("ERROR: main: fait to create mqtt thread"),
|
||||||
|
Ok(join) => match join.join() {
|
||||||
|
Err(_) => println!("ERROR: main: failt to join mqtt thread"),
|
||||||
|
Ok(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
println!("INFO : main: exit");
|
println!("INFO : main: exit");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user