Ingen beskrivning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.rs 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. use std::fs;
  2. use std::path::Path;
  3. use serde::Deserialize;
  4. #[derive(Deserialize)]
  5. pub struct Config {
  6. pub influxdb: InfluxDbConfig,
  7. pub mqtt: MQTTConfig,
  8. }
  9. impl Config {
  10. pub fn load<P: AsRef<Path>>(path: P) -> Result<Config, ConfigError> {
  11. let file = fs::read(path)?;
  12. let config = toml::from_slice::<Config>(&file)?;
  13. config.validate()?;
  14. Ok(config)
  15. }
  16. fn validate(&self) -> Result<(), ConfigError> {
  17. self.influxdb.validate()?;
  18. self.mqtt.validate()?;
  19. Ok(())
  20. }
  21. }
  22. #[derive(Deserialize)]
  23. pub struct InfluxDbConfig {
  24. #[serde(default)]
  25. pub enabled: bool,
  26. #[serde(default)]
  27. pub address: String,
  28. #[serde(default)]
  29. pub user: String,
  30. #[serde(default)]
  31. pub password: String,
  32. }
  33. impl InfluxDbConfig {
  34. fn validate(&self) -> Result<(), ConfigError> {
  35. if (self.user != "") != (self.password != "") {
  36. return Err(ConfigError::Settings(
  37. "need to specify both InfluxDB user and password".to_owned(),
  38. ));
  39. }
  40. Ok(())
  41. }
  42. }
  43. impl Default for InfluxDbConfig {
  44. fn default() -> InfluxDbConfig {
  45. InfluxDbConfig {
  46. enabled: false,
  47. address: "http://localhost:8086".to_owned(),
  48. user: "".to_owned(),
  49. password: "".to_owned(),
  50. }
  51. }
  52. }
  53. #[derive(Clone, Deserialize)]
  54. pub struct MQTTConfig {
  55. #[serde(default)]
  56. pub enabled: bool,
  57. #[serde(default)]
  58. pub address: String,
  59. }
  60. impl MQTTConfig {
  61. fn validate(&self) -> Result<(), ConfigError> {
  62. Ok(())
  63. }
  64. }
  65. impl Default for MQTTConfig {
  66. fn default() -> MQTTConfig {
  67. MQTTConfig {
  68. enabled: false,
  69. address: "http://localhost:1883".to_owned(),
  70. }
  71. }
  72. }
  73. #[derive(thiserror::Error, Debug)]
  74. pub enum ConfigError {
  75. #[error("I/O error")]
  76. Io(#[from] std::io::Error),
  77. #[error("Parser error")]
  78. Parser(#[from] toml::de::Error),
  79. #[error("Invalid settings")]
  80. Settings(String),
  81. }