From 4a4584762dcb6e8552ab306015ab2ceb3056ed4e Mon Sep 17 00:00:00 2001 From: Dennis Luxen Date: Wed, 6 Dec 2023 13:11:48 +0100 Subject: [PATCH] Override TOML config from environment variables --- hms2mqtt/src/mqtt_config.rs | 44 ++++++++++++++++++++++++++++++++++++- src/main.rs | 28 +++++++++++------------ 2 files changed, 56 insertions(+), 16 deletions(-) diff --git a/hms2mqtt/src/mqtt_config.rs b/hms2mqtt/src/mqtt_config.rs index 47f61ee6..edce5de9 100644 --- a/hms2mqtt/src/mqtt_config.rs +++ b/hms2mqtt/src/mqtt_config.rs @@ -1,9 +1,51 @@ use serde_derive::Deserialize; -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Default, Deserialize)] pub struct MqttConfig { pub host: String, pub port: Option, pub username: Option, pub password: Option, } + +impl MqttConfig { + pub fn is_valid(&self) -> bool { + !self.host.is_empty() + } +} + +mod tests { + #[test] + fn valid_config() { + use super::MqttConfig; + + let mqtt_config = MqttConfig { + host: "lala".into(), + port: None, + username: None, + password: None, + }; + assert!(mqtt_config.is_valid()); + } + + #[test] + fn invalid_config() { + use super::MqttConfig; + + let mqtt_config = MqttConfig { + host: "".into(), + port: None, + username: None, + password: None, + }; + assert!(!mqtt_config.is_valid()); + } + + #[test] + fn default_invalid_config() { + use super::MqttConfig; + + let mqtt_config = MqttConfig::default(); + assert!(!mqtt_config.is_valid()); + } +} diff --git a/src/main.rs b/src/main.rs index 156e39df..b923efdc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,29 +1,23 @@ // TODO: support CA33 command to take over metrics consumption // TODO: support publishing to S-Miles cloud, too +mod config; mod logging; mod rumqttc_wrapper; use hms2mqtt::home_assistant::HomeAssistant; use hms2mqtt::inverter::Inverter; use hms2mqtt::metric_collector::MetricCollector; -use hms2mqtt::mqtt_config; use hms2mqtt::simple_mqtt::SimpleMqtt; -use mqtt_config::MqttConfig; +use log::{error, info}; use rumqttc_wrapper::RumqttcWrapper; -use serde_derive::Deserialize; -use std::fs; + +use std::env; + use std::thread; use std::time::Duration; -use log::{error, info}; - -#[derive(Debug, Deserialize)] -struct Config { - inverter_host: String, - home_assistant: Option, - simple_mqtt: Option, -} +use crate::config::Config; static REQUEST_DELAY: u64 = 30_500; @@ -34,9 +28,13 @@ fn main() { error!("Arguments passed. Tool is configured by config.toml in its path"); } - let filename = "config.toml"; - let contents = fs::read_to_string(filename).expect("Could not read config.toml"); - let config: Config = toml::from_str(&contents).expect("toml config unparsable"); + let config = Config::load(); + if !config.is_valid() { + error!("configuration is invalid: {config:?}"); + return; + } + + println!("{config:#?}"); info!("inverter host: {}", config.inverter_host);