view rust/src/config.rs @ 639:89818a14648b rust tip

- switch to using anyhow for errors, surf for http runs but surf has problems
author Matt Johnston <matt@ucc.asn.au>
date Thu, 28 Nov 2019 23:57:00 +0800
parents 43eb3cfdf769
children
line wrap: on
line source

use serde::{Serialize,Deserialize};
use anyhow::{Context, anyhow, Result, Error};

#[derive(Deserialize,Serialize,Debug,Clone)]
pub struct Config {
    pub sensor_sleep: u64,
    pub upload_sleep: u64,

    pub fridge_delay: u64,
    pub fridge_wort_invalid_time: u64,

    pub max_readings: u32,

    pub params_file: String,

    pub sensor_base_dir: String,
    pub fridge_gpio_pin: u32,

    pub ambient_name: String,
    pub fridge_name: String,
    pub wort_name: String,
    pub internal_temperature: String,

    pub hmac_key: String,
    pub server_url: String,
    pub update_url: String, 
    pub settings_url: String,
}

impl Config {
    pub fn default_toml() -> &'static str {
        include_str!("defconfig.toml")
    }

    pub fn load(conf_file: &str) -> Result<Self> {
        let mut c = config::Config::default();
        c.merge(config::File::from_str(Self::default_toml(), config::FileFormat::Toml)).expect("Bad default config");
        c.merge(config::File::with_name(conf_file)).or_else(|e| {
            Err(match e {
                config::ConfigError::NotFound(_) => anyhow!("Missing config {}", conf_file),
                // XXX this is ugly, why won't e.with_context() work?
                _ => Error::new(e).context(format!("Problem parsing {}", conf_file)),
            })
        })?;
        c.merge(config::Environment::with_prefix("TEMPLOG"))
            .context("Failed loading from TEMPLOG_ environment variables")?;
        Ok(c.try_into().with_context(|| format!("Problem loading config {}", conf_file))?)
    }
}