1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/// The calibration of sensor values.
pub mod calibration;
/// The configuration files.
pub mod config;
pub mod drivers;

use crate::result::CompilerResult;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::{ffi::OsStr, fs::read_to_string};

use std::collections::{BTreeMap, HashMap, HashSet};

use calibration::{BooleanCalibration, Calibration, NumericCalibration};
use codespan_reporting::files::SimpleFiles;
use config::{Config, Virtual};
use drivers::{Drivers, DriversFile};

use self::drivers::{VirtualRelayDriver, VirtualSensorDriver};

use fixed::traits::ToFixed;
/// Represents the contextual information for interpretting a test descriptor file.
/// This is really just a wrapper around Config with an in memory cache of all the calibration tables needed.
#[derive(Debug, PartialEq)]
pub struct Environment {
    pub config: Config,
    pub drivers_file: Option<DriversFile>,
    pub table_cache: HashMap<PathBuf, Calibration>,
}

impl Environment {
    /// Get calibration for provided sensor id
    pub fn get_calibration(&self, sensor_id: &str) -> CompilerResult<Option<&Calibration>> {
        let mut res = CompilerResult::new("Retrieve calibration for a sensor");
        let sensors = &self.config.sensors;
        let virtual_sensors = &self.config.virtuals.sensors;
        if let Some(record) = sensors.get(sensor_id) {
            let table_path = &record.calibration;
            if let Some(calibration) = self.table_cache.get(table_path) {
                return res.with_value(Some(calibration));
            }
            res.error(format!(
                "Failed to find calibration for the sensor {}",
                sensor_id
            ));
            return res;
        } else if let Some(record) = virtual_sensors.get(sensor_id) {
            let table_path = &record.calibration;
            match table_path {
                Some(path) => {
                    if let Some(calibration) = self.table_cache.get(path) {
                        return res.with_value(Some(calibration));
                    }
                }
                None => {
                    return res.with_value(None);
                }
            }
        }
        res.error(format!(
            "No sensor or virtual sensor found with name: {}",
            sensor_id
        ));
        res
    }
    /// Attempt to perform a calibration lookup on the boolean input value using the
    /// provided boolean calibration table.
    pub fn boolean_calibration_lookup(
        calibration: &BooleanCalibration,
        bool_value: bool,
    ) -> CompilerResult<(u16, u16)> {
        let mut res = CompilerResult::new("Perform calibration lookup for a boolean sensor.");
        let left_bound: u16 = calibration.lower_bound(bool_value);
        let right_bound: u16 = calibration.upper_bound(bool_value);
        res.with_value((left_bound, right_bound))
    }

    /// Attempt to perform a calibration lookup on the sensor constraint using the
    /// input numeric calibration.
    pub fn numeric_calibration_lookup(
        calibration: &NumericCalibration,
        constraint: (f64, f64),
    ) -> CompilerResult<(u16, u16)> {
        let mut res = CompilerResult::new("Perform calibration lookup for a numeric sensor.");
        let left_bound_opt = calibration.inverse_lookup(constraint.0.to_fixed());
        let right_bound_opt = calibration.inverse_lookup(constraint.1.to_fixed());
        //TODO better reportable message
        let left_bound: u16 = check!(
            res,
            Reportable::from((
                left_bound_opt,
                format!(
                    "Inverse lookup for sensor constraint left bound: {}",
                    constraint.0
                )
            ))
        );
        let right_bound: u16 = check!(
            res,
            Reportable::from((
                right_bound_opt,
                format!(
                    "Inverse lookup for sensor constraint right bound: {}",
                    constraint.1
                )
            ))
        );
        res.with_value((left_bound, right_bound))
    }

    pub fn raw_calibration_lookup(constraint: (f64, f64)) -> CompilerResult<(u16, u16)> {
        let mut res = CompilerResult::new(
            "Perform raw calibration lookup for a numeric sensor with no calibration file.",
        );
        if constraint.0.fract() != 0.0 || constraint.1.fract() != 0.0 {
            res.error(
                "Cannot encode fractional sensor bounds for virtual sensor without a calibration",
            );
            return res;
        }
        let left_bound: u16 = constraint.0 as u16;
        let right_bound: u16 = constraint.1 as u16;
        return res.with_value((left_bound, right_bound));
    }
}

/// Reads in an entire environment from the file system using the path to a config file.
/// All calibration tables are referenced using relative paths from the config files location,
/// so we are able to fetch all of this at once.
pub fn read_environment(
    config_path_relative: &Path,
    codespan_files: &mut SimpleFiles<String, String>,
) -> CompilerResult<Environment> {
    let mut res = CompilerResult::new("Reading in Environment");

    let config_path: PathBuf = check!(res, config_path_relative.canonicalize());
    let base_path = check!(
        res,
        config_path.parent(),
        "Could not find base path for config file"
    );

    let config_contents = check!(res, read_to_string(config_path.clone()));

    // Add config.toml contents to codespan SimpleFiles
    let file_name: String = config_path.to_str().unwrap().into();
    let file_id = codespan_files.add(file_name.clone(), config_contents.clone());

    let config: Config = check!(
        res,
        config::parse(file_id, file_name.clone(), &config_contents)
    );

    let mut drivers_file = None;

    if let Some(drivers_path) = config.drivers_path.clone() {
        // Assume drivers_path has same base as config_path
        let mut drivers_path = base_path.join(drivers_path.clone());
        drivers_path = check!(res, drivers_path.canonicalize());
        let drivers_contents = check!(res, read_to_string(drivers_path.clone()));
        // Add drivers.toml contents to codespan SimpleFiles
        let drivers_name: String = drivers_path.to_str().unwrap().into();
        let drivers_id = codespan_files.add(drivers_name.clone(), drivers_contents.clone());
        drivers_file = Some(check!(
            res,
            Drivers::parse(drivers_id, drivers_name, &drivers_contents)
        ));
    }

    // Load calibration files
    let paths = collect_paths(&config);
    let cache = check!(res, collect_calibration_tables(base_path, &paths));

    let environment = Environment {
        config,
        drivers_file,
        table_cache: cache,
    };
    res.require(validate_drivers(&environment, &file_name));
    res.with_value(environment)
}

/// Iterate through a config and collect all of the PathBufs it includes
/// to reference calibration tables.
pub fn collect_paths(config: &Config) -> HashSet<PathBuf> {
    let mut paths = HashSet::new();

    for (_name, record) in config.sensors.iter() {
        let path: PathBuf = record.calibration.clone();
        paths.insert(path);
    }
    for (_name, record) in config.virtuals.sensors.iter() {
        if let Some(path) = &record.calibration {
            paths.insert(path.clone());
        }
    }

    paths
}

/// Combine the config file base path with the realtive paths of the calibration tables it references
/// and then read in all of the calibration tables into a relative-path keyed cache.
pub fn collect_calibration_tables(
    base_path: &Path,
    paths: &HashSet<PathBuf>,
) -> CompilerResult<HashMap<PathBuf, Calibration>> {
    let mut res = CompilerResult::new("Read calibration tables from the file system");
    let mut cache = HashMap::new();

    for path in paths.iter() {
        let resolved_path = base_path.join(path);
        let mut file = check!(res, File::open(resolved_path.clone()));
        match resolved_path.extension().and_then(OsStr::to_str) {
            Some("bcf") => {
                let table = Calibration::Boolean(check!(
                    res,
                    BooleanCalibration::read_from_file(&mut file)
                ));
                cache.insert(path.clone(), table);
            }
            Some("ncf") => {
                let table = Calibration::Numeric(check!(
                    res,
                    NumericCalibration::read_from_file(&mut file)
                ));
                cache.insert(path.clone(), table);
            }
            _ => res.error(format!(
                "Path {:?} does not have a valid extension",
                resolved_path
            )),
        }
    }
    res.with_value(cache)
}

/// Iterate through the environment and ensure all virtual relay or sensor
/// drivers are used correctly in config.toml
pub fn validate_drivers(environment: &Environment, file_name: &String) -> CompilerResult<()> {
    let mut res = CompilerResult::status_only("Check all drivers used in config.toml are valid");
    let virtuals: &Virtual = &environment.config.virtuals;

    let sensors = &virtuals.sensors;
    let relays = &virtuals.relays;
    // Construct hashsets containing all drivers and verify there are no duplicates
    let mut sensor_drivers: HashMap<String, &VirtualSensorDriver> = HashMap::new();
    let mut relay_drivers: HashMap<String, &VirtualRelayDriver> = HashMap::new();
    if let Some(drivers_file) = &environment.drivers_file {
        let drivers = &drivers_file.drivers;
        for sensor_driver in &drivers.sensor {
            let name = format!("{}/{}", sensor_driver.namespace, sensor_driver.function);
            if sensor_drivers.contains_key(&name) {
                res.error(format!("Duplicate sensor driver {} in drivers file.", name));
            } else {
                sensor_drivers.insert(name, sensor_driver);
            }
        }
        for relay_driver in &drivers.relay {
            let name = format!("{}/{}", relay_driver.namespace, relay_driver.function);
            if relay_drivers.contains_key(&name) {
                res.error(format!("Duplicate relay driver {} in drivers file.", name));
            } else {
                relay_drivers.insert(name, relay_driver);
            }
        }
    } else if sensors.len() > 0 || relays.len() > 0 {
        res.error(format!(
            "No drivers.toml provided, but config.toml contains virtuals.\n\t{:?}",
            file_name
        ));
        return res;
    }

    // For every virtual sensor and relay specified in the config.toml file, check that the
    // driver it specifies exists, all arguments required by the driver are specified in
    // the config, and that no unspecified arguments are provided in the config
    for (name, sensor) in sensors.iter() {
        // Check the driver exists
        let driver = check!(
            res,
            sensor_drivers.get(&sensor.driver),
            format!(
                "No virtual sensor driver with name: \"{}\"\n\t{:?}",
                sensor.driver, file_name
            )
        );
        // Validate the provided arguments
        let res_args =
            CompilerResult::status_only(format!("Validate arguments for sensor: {}", name));
        res.require(validate_driver_args(res_args, &sensor.args, &driver.fields));
    }
    for (name, relay) in relays.iter() {
        // Check the driver exists
        let driver = check!(
            res,
            relay_drivers.get(&relay.driver),
            format!(
                "No virtual relay driver with name: \"{}\"\n\t{:?}",
                relay.driver, file_name
            )
        );
        // Validate the provided arguments
        let res_args =
            CompilerResult::status_only(format!("Validate arguments for relay: {}", name));
        res.require(validate_driver_args(res_args, &relay.args, &driver.fields));
    }

    res
}

/// Compare the given arguments with the required driver fields. If any arguments are
/// not provided or any undefined arguments are provided, return a failed CompilerResult.
fn validate_driver_args(
    mut res: CompilerResult<()>,
    given_args: &Option<BTreeMap<String, u16>>,
    driver_fields: &Option<Vec<BTreeMap<String, String>>>,
) -> CompilerResult<()> {
    let mut args: HashSet<&str> = HashSet::new();
    if let Some(given_args) = given_args {
        for arg in given_args.keys() {
            args.insert(arg);
        }
    }
    // Attempt to remove every driver argument from the set of given args.
    // If we can't remove an arg, the config failed to specify it
    if let Some(driver_fields) = driver_fields {
        for arg in driver_fields {
            if !args.remove(arg.get("name").unwrap().as_str()) {
                res.error(format!(
                    "Required argument: \"{}\" wasn't provided!",
                    arg.get("name").unwrap()
                ));
            }
        }
    }
    // Any leftover args are unknown args provided in the config
    for arg in args {
        res.error(format!(
            "Argument: \"{}\" was given when its driver doesn't define it!",
            arg
        ));
    }
    res
}