From 24f8a351622457967d4d574a669c35665602122d Mon Sep 17 00:00:00 2001 From: Marto Date: Sun, 19 Jan 2025 15:57:19 +0100 Subject: [PATCH] improvements to netcode and new functionality --- src/curl.rs | 40 +++++++++++++++++--------------------- src/json.rs | 12 ++++++++++++ src/main.rs | 6 ++---- src/serial.rs | 53 ++++++++++++++++++++++++++++++++------------------- 4 files changed, 65 insertions(+), 46 deletions(-) diff --git a/src/curl.rs b/src/curl.rs index c082ab4..bae2a1c 100644 --- a/src/curl.rs +++ b/src/curl.rs @@ -1,4 +1,3 @@ - use std::io::Read; pub fn startup(json: &crate::json::JsonStruct) -> (curl::easy::Easy, String) { @@ -19,29 +18,26 @@ pub fn startup(json: &crate::json::JsonStruct) -> (curl::easy::Easy, String) { (request, data) } -pub fn request(request: &mut curl::easy::Easy, data: &str) -> Result { - let mut transfer = request.transfer(); +pub fn request(request: &mut curl::easy::Easy, data: &str) -> Result<(u32, String), curl::Error> { - if let Err(e) = transfer.read_function(|buf| { - Ok(data.as_bytes().read(buf).unwrap_or(0)) - }) { - eprintln!("[ERROR] Failed to read the data:\n{e}"); - return Err(e); - } + let mut buf = String::new(); - if let Err(e) = transfer.perform() { - eprintln!("[ERROR] Failed to perform the CURL request:\n{e}"); - return Err(e); - } + let mut transfer = request.transfer(); + transfer.read_function(|buf| { + Ok(data.as_bytes().read(buf).unwrap_or(0)) + })?; + + transfer.write_function(|rdata| { + buf.push_str(&String::from_utf8_lossy(rdata)); + Ok(rdata.len()) + })?; + + // returns errors if it fails, contuinues normally if not + transfer.perform()?; - // drop transfer so we can access request.response_code below drop(transfer); - - match request.response_code() { - Ok(t) => Ok(t), - Err(e) => { - eprintln!("[ERROR] Failed to retrieve the response code:\n{e}"); - Err(e) - }, - } + // return error if this fails + let result = request.response_code()?; + // return result + Ok((result, buf)) } \ No newline at end of file diff --git a/src/json.rs b/src/json.rs index 481b340..49d3870 100644 --- a/src/json.rs +++ b/src/json.rs @@ -1,6 +1,7 @@ use std::path::Path; use std::fs::File; use std::io::{ErrorKind, Read}; +use json::Error as JsonError; pub struct JsonStruct { pub ha_url: String, @@ -50,4 +51,15 @@ fn read_file(path: &Path) -> String { _ => panic!("[ERROR] Unexpected error reading the JSON"), } } +} + +pub fn get_state(response: String) -> Result, JsonError> { + let json = json::parse(response.as_str())?; + let state = json::stringify(json[0]["state"].as_str()); + + match &state[1..&state.len()-1] { + "on" => Ok(Some(true)), + "off" => Ok(Some(false)), + _ => Ok(None), + } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index ee52702..9006169 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,9 +6,7 @@ mod serial; fn main() { let data_file = std::path::Path::new("data.json"); let data = json::get_json(data_file); - let req; - let dt; - (req, dt) = curl::startup(&data); - serial::read_messages(req, &dt); + let (req, dt) = curl::startup(&data); + serial::read_messages(req, dt); } diff --git a/src/serial.rs b/src/serial.rs index 6800a3c..9d6eb55 100644 --- a/src/serial.rs +++ b/src/serial.rs @@ -1,5 +1,8 @@ -use std::time::Duration; use serialport::SerialPortInfo; +use std::time::Duration; + +const BAUD: u32 = 9600; +const TIMEOUT: u64 = 1000; fn get_port(ports: Vec) -> Option { for p in ports { @@ -7,34 +10,44 @@ fn get_port(ports: Vec) -> Option { return Some(p); } } - + None } -pub fn read_messages(mut request: curl::easy::Easy, data: &str) { +pub fn read_messages(mut request: curl::easy::Easy, data: String) { let ports = serialport::available_ports().expect("No ports found!"); - let r = get_port(ports).unwrap().port_name; - let mut connection = serialport::new(r, 9600) - .timeout(Duration::from_millis(1000)) - .open().expect("Failed to open the port"); + let r = get_port(ports) + .expect("[ERROR] Failed to get the port") + .port_name; + let mut connection = serialport::new(r, BAUD) + .timeout(Duration::from_millis(TIMEOUT)) + .open() + .expect("Failed to open the port"); let mut serial_buf: Vec = vec![0; 1024]; - + loop { - match connection.read(serial_buf.as_mut_slice()) { - Ok(t) => { - if t < 1 { continue; } - let output = String::from_utf8_lossy(&serial_buf[..t]); - if output.contains("1") { - // send curl request - let res = crate::curl::request(&mut request, &data); - match res { - Ok(t) => println!("Response code: {t}"), - Err(e) => eprintln!("[ERROR] Something went wrong with the CURL request:\n{e}"), + if let Ok(bytes) = connection.read(serial_buf.as_mut_slice()) { + if bytes < 1 { continue; } + let output = String::from_utf8_lossy(&serial_buf[..bytes]); + if output.contains("1") { + // send curl request + let res = crate::curl::request(&mut request, &data); + match res { + Ok((code, response)) => { + println!("Response code: {code}"); + match crate::json::get_state(response) { + Ok(state) => { + if let Some(valid_state) = state { + println!("State: {}", valid_state); + } + } + Err(e) => eprintln!("[ERROR] Failed to acquire entity state:\n{e}"), + } } + Err(e) => eprintln!("[ERROR] Something went wrong with the CURL request:\n{e}"), } - }, - Err(_) => {} + } } } } \ No newline at end of file