diff options
author | Tomasz Kramkowski <tomasz@kramkow.ski> | 2025-06-27 00:46:44 +0100 |
---|---|---|
committer | Tomasz Kramkowski <tomasz@kramkow.ski> | 2025-06-27 00:48:01 +0100 |
commit | 14519559686525121352de3e3c9b9cacc4242038 (patch) | |
tree | 0bb2fb296cd752ddab1f4a81c75bb65d78297182 /src/config.rs | |
download | mqttr-14519559686525121352de3e3c9b9cacc4242038.tar.gz mqttr-14519559686525121352de3e3c9b9cacc4242038.tar.xz mqttr-14519559686525121352de3e3c9b9cacc4242038.zip |
Initial commit
Diffstat (limited to 'src/config.rs')
-rw-r--r-- | src/config.rs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..1190b9a --- /dev/null +++ b/src/config.rs @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2025 Tomasz Kramkowski <tomasz@kramkow.ski> +// SPDX-License-Identifier: GPL-3.0-or-later + +use std::{collections::HashMap, fs, path::Path, process, time::Duration}; + +use rumqttc::{Client, Connection, MqttOptions}; +use serde::Deserialize; + +use crate::PROGRAM; + +#[derive(Deserialize, Debug)] +pub struct Credentials { + pub username: String, + pub password: String, +} + +fn default_host() -> String { + "localhost".to_string() +} + +fn default_port() -> u16 { + 1883 +} + +fn default_id() -> String { + PROGRAM.to_string() +} + +#[derive(Deserialize, Debug)] +pub struct Config { + #[serde(default = "default_host")] + pub host: String, + #[serde(default = "default_port")] + pub port: u16, + pub credentials: Option<Credentials>, + #[serde(default = "default_id")] + pub id: String, + // TODO: Figure out a way to allow arbitrary unix paths (arbitrary + // non-unicode) without base64 + pub routes: HashMap<String, Vec<Vec<String>>>, +} + +impl Config { + pub fn mqtt_client(&self) -> (Client, Connection) { + let client_id = format!("{}_{}", self.id, process::id()); + let mut options = MqttOptions::new(client_id, &self.host, self.port); + if let Some(credentials) = &self.credentials { + options.set_credentials(&credentials.username, &credentials.password); + } + options.set_keep_alive(Duration::from_secs(5)); + options.set_max_packet_size(10 * 1024 * 1024, 10 * 1024 * 1024); + Client::new(options, 10) + } +} + +pub fn load<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> { + let config = fs::read_to_string(&path)?; + Ok(toml::from_str(&config)?) +} |