65 lines
1.9 KiB
Rust

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,
pub access_token: String,
pub light_entity_id: String,
}
impl JsonStruct {
fn validate_content(&self) -> bool {
!self.ha_url.is_empty() && !self.access_token.is_empty() && !self.light_entity_id.is_empty()
}
}
pub fn get_json(path: &Path) -> JsonStruct {
let json_data = read_file(path);
let parsed_data = json::parse(json_data.as_str()).expect("[ERROR] Invalid JSON");
let data = JsonStruct {
ha_url: json::stringify(parsed_data["ha_url"].clone()),
access_token: json::stringify(parsed_data["access_token"].clone()),
light_entity_id: json::stringify(parsed_data["light_entity_id"].clone()),
};
if !data.validate_content() {
panic!("[ERROR] JSON data is NULL");
}
data
}
fn read_file(path: &Path) -> String {
let read_result = File::open(path);
let mut result = String::new();
match read_result {
Ok(mut t) => {
// file exists
println!("[INFO] JSON file located, reading ...");
match t.read_to_string(&mut result) {
// handling the reading
Ok(_r) => result,
Err(e) => panic!("[ERROR] While reading the file: {e}"),
}
},
Err(err) => match err.kind() {
ErrorKind::NotFound => panic!("[ERROR] The file '{}' does not exist", path.display()),
_ => panic!("[ERROR] Unexpected error reading the JSON"),
}
}
}
pub fn get_state(response: String) -> Result<Option<bool>, 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),
}
}