53 lines
1.6 KiB
Rust
53 lines
1.6 KiB
Rust
use std::path::Path;
|
|
use std::fs::File;
|
|
use std::io::{ErrorKind, Read};
|
|
|
|
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"),
|
|
}
|
|
}
|
|
} |