Skip to content

Commit

Permalink
Override TOML config from environment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
DennisOSRM committed Dec 6, 2023
1 parent af386d0 commit 4a45847
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 16 deletions.
44 changes: 43 additions & 1 deletion hms2mqtt/src/mqtt_config.rs
Original file line number Diff line number Diff line change
@@ -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<u16>,
pub username: Option<String>,
pub password: Option<String>,
}

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());
}
}
28 changes: 13 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -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<MqttConfig>,
simple_mqtt: Option<MqttConfig>,
}
use crate::config::Config;

static REQUEST_DELAY: u64 = 30_500;

Expand All @@ -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);

Expand Down

0 comments on commit 4a45847

Please sign in to comment.