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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use crc_any::CRCu32;

use crate::environment::calibration::Calibration;
use crate::environment::config;
use crate::result::CompilerResult;
use crate::version;
use crate::{bits::BitWriter, environment::Environment};
use config::VirtualRelayRecord;
use config::VirtualSensorRecord;

impl Environment {
    /// Length of the binary config header in bytes
    const HEADER_LEN: u32 = 76;
    /// Length of the binary config section headers in bytes
    const SECTION_HEADER: u32 = 4;
    /// Length of a single relay in bytes
    const RELAY_LEN: u32 = 2;
    /// Length of a single sensor in bytes
    const SENSOR_LEN: u32 = 3;
    /// Length of a single global bounds entry in bytes
    const GLOBAL_BOUNDS_LEN: u32 = 4;

    /// Appends the binary config header to a buffer
    fn append_header_to_buffer(&self, buffer: &mut BitWriter) {
        // compute offsets for all sections
        let mut offset = Environment::HEADER_LEN;
        let relay_offset = offset;

        offset +=
            Environment::SECTION_HEADER + self.config.relays.len() as u32 * Environment::RELAY_LEN;
        let sensors_offset = offset;

        offset += Environment::SECTION_HEADER
            + self.config.sensors.len() as u32 * Environment::SENSOR_LEN;
        let virtual_relays_offset = offset;

        offset += Environment::SECTION_HEADER;
        for v_relay in self.config.virtuals.relays.values() {
            offset += v_relay.len()
        }
        let virtual_sensors_offset = offset;

        offset += Environment::SECTION_HEADER;
        for v_sensor in self.config.virtuals.sensors.values() {
            offset += v_sensor.len()
        }
        let safe_state_offset = offset;

        offset += Environment::SECTION_HEADER
            + Environment::RELAY_LEN * self.config.safe_state.len() as u32;

        let global_bounds_offset = offset;

        let mut num_global_bounds = 0;
        if let Some(global_bounds_ref) = self.config.global_bounds.as_ref() {
            num_global_bounds = global_bounds_ref.len();
        }
        offset +=
            Environment::SECTION_HEADER + Environment::GLOBAL_BOUNDS_LEN * num_global_bounds as u32;
        let footer_offset = offset;

        // Create the Header>

        // Prefix (0:3)
        buffer.append(b'.');
        buffer.append(b'C');
        buffer.append(b'B');
        buffer.append(b'F');

        // Timestamp (4:11)
        buffer.append(now());

        // Versioning (major, minor, patch) (12:15)
        buffer.append(version::MAJOR);
        buffer.append(version::MINOR);
        buffer.append(version::PATCH);
        buffer.append(0u8); //padding

        // Drivers hash
        // If drivers exist append hash to buffer
        if let Some(drivers_file) = &self.drivers_file {
            for byte in &drivers_file.hash {
                buffer.append(*byte);
            }
        }
        // Else append 32 bytes of zero
        else {
            buffer.append(0u128);
            buffer.append(0u128);
        }

        // Relays offset (20:23)
        buffer.append(relay_offset);

        // Sensors offset (24:27)
        buffer.append(sensors_offset);

        // Virtual relays offset (28:31)
        buffer.append(virtual_relays_offset);

        // Virtual sensors offset (32:35)
        buffer.append(virtual_sensors_offset);

        // Safe state offset (36:39)
        buffer.append(safe_state_offset);

        // Global bounds offset (40:43)
        buffer.append(global_bounds_offset);

        // Footer offset (44:47)
        buffer.append(footer_offset);
    }

    /// Appends the relays to a buffer
    fn append_relays_to_buffer(&self, buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF0u8);
        // Section Length
        buffer.append_tail(
            Environment::SECTION_HEADER + self.config.relays.len() as u32 * Environment::RELAY_LEN,
            24,
        );
        // Relays
        for relay_record in self.config.get_relay_records() {
            // Append '001000'b
            buffer.append_tail(0b001000 as u16, 6);
            // Append 10-bit virtual address
            buffer.append_tail(u16::from(relay_record.device_address), 10)
        }
    }

    /// Appends the sensors to a buffer
    fn append_sensors_to_buffer(&self, buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF1u8);
        // Section Length
        buffer.append_tail(
            Environment::SECTION_HEADER
                + self.config.sensors.len() as u32 * Environment::SENSOR_LEN,
            24,
        );
        // Sensors
        for sensor_record in self.config.get_sensor_records() {
            // Append '010000'b
            buffer.append_tail(0b010000 as u16, 6);
            // Append 10-bit virtual device_address
            buffer.append_tail(u16::from(sensor_record.device_address), 10);
            buffer.append_tail(sensor_record.polling_interval_ms, 8);
        }
    }

    /// Appends the virtual relays to a buffer
    fn append_v_relays_to_buffer(&self, buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF2u8);
        // Section Length
        let mut length = Environment::SECTION_HEADER;
        for v_relay in self.config.virtuals.relays.values() {
            length += v_relay.len();
        }
        buffer.append_tail(length, 24);

        // Virtual Relays
        for v_relay in &self.config.get_v_relay_records() {
            let v_relay_record = v_relay;
            // This unwrap shouldn't ever fail
            let drivers = &self.drivers_file.as_ref().unwrap().drivers;
            // Add drivers table index
            let driver_index = drivers.get_relay_driver_index(v_relay_record.driver.as_str());
            buffer.append_tail(driver_index.unwrap(), 6);
            // Add device_address
            buffer.append_tail(u16::from(v_relay_record.device_address), 10);
            // Add args
            if let Some(args) = v_relay_record.args.as_ref() {
                // get the specific driver struct from the name of the driver
                let driver_opt = drivers.get_relay_driver(v_relay_record.driver.as_str());
                // This unwrap should never fail due to earlier error checking
                let driver = driver_opt.unwrap();

                let mut args_vec: Vec<(&String, &u16)> = args.into_iter().collect();
                let num_args = args_vec.len() as u16;
                // Sort the arguments provided in the config.toml by their indices
                // in the arguments vector for this driver.
                args_vec.sort_by(|a, b| driver.get_arg_index(a.0).cmp(&driver.get_arg_index(b.0)));

                // Append the number of arguments to the buffer
                buffer.append_tail(num_args, 8);

                // Append every argument to the buffer
                for arg in args_vec {
                    buffer.append_tail(*arg.1, 16);
                }
            }
        }
    }

    /// Appends the virtual sensors to a buffer
    fn append_v_sensors_to_buffer(&self, buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF3u8);
        // Section Length
        let mut length = Environment::SECTION_HEADER;
        for v_sensor in self.config.virtuals.sensors.values() {
            length += v_sensor.len();
        }
        buffer.append_tail(length, 24);
        // Virtual Sensors
        for v_sensor_record in &self.config.get_v_sensor_records() {
            // This unwrap shouldn't ever fail
            let drivers = &self.drivers_file.as_ref().unwrap().drivers;
            // Add drivers table index
            let driver_index = drivers.get_sensor_driver_index(v_sensor_record.driver.as_str());
            buffer.append_tail(driver_index.unwrap(), 6);
            // Add device_address
            buffer.append_tail(u16::from(v_sensor_record.device_address), 10);
            buffer.append_tail(v_sensor_record.polling_interval_ms, 8);
            // Add args
            if let Some(args) = v_sensor_record.args.as_ref() {
                // get the specific driver struct from the name of the driver
                let driver_opt = drivers.get_sensor_driver(&v_sensor_record.driver);
                // This unwrap should never fail due to earlier error checking
                let driver = driver_opt.unwrap();

                let mut args_vec: Vec<(&String, &u16)> = args.into_iter().collect();
                let num_args = args_vec.len() as u16;

                // Sort the arguments provided in the config.toml by their indices
                // in the arguments vector for this driver.
                args_vec.sort_by(|a, b| driver.get_arg_index(a.0).cmp(&driver.get_arg_index(b.0)));

                // Append the number of arguments to the buffer
                buffer.append_tail(num_args, 8);

                // Append every argument to the buffer
                for arg in args_vec {
                    buffer.append_tail(*arg.1, 16);
                }
            }
        }
    }

    /// Appends the safe state to a buffer
    fn append_safe_state_to_buffer(&self, buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF4u8);
        // Section Length
        buffer.append_tail(
            Environment::SECTION_HEADER
                + self.config.safe_state.len() as u32 * Environment::RELAY_LEN,
            24,
        );
        // Physical Relays
        for relay_record in self.config.get_safe_state_relay_records() {
            // Append 1-bit '0'b physical address flag
            buffer.append_tail(0b0 as u16, 1);
            // Append 10-bit device address
            buffer.append_tail(u16::from(relay_record.device_address), 10);
            // Append '00000'b padding
            buffer.append_tail(0b00000 as u16, 5);
        }
        // Virtual Relays
        for relay_record in self.config.get_safe_state_v_relay_records() {
            // Append 1-bit '1'b physical address flag
            buffer.append_tail(0b1 as u16, 1);
            // Append 10-bit device address
            buffer.append_tail(u16::from(relay_record.device_address), 10);
            // Append '00000'b padding
            buffer.append_tail(0b00000 as u16, 5);
        }
    }

    /// Appends the global bounds to a buffer
    fn append_global_bounds_to_buffer(&self, buffer: &mut BitWriter) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Append global bounds to CBF buffer");
        // Header Prefix
        buffer.append(0xF6u8);
        if let Some(global_bounds) = self.config.global_bounds.clone() {
            let num_bounds = global_bounds.keys().len() as u32;
            // append header length
            buffer.append_tail(Environment::SECTION_HEADER + num_bounds * 4, 24);

            for (sensor_id, bound) in global_bounds.into_iter() {
                let device_addr = self
                    .config
                    .get_sensor_device_address(&sensor_id)
                    .to_option();

                // Get the calibration file for this sensor if it exists
                let calibration_opt = check!(res, self.get_calibration(&sensor_id));

                // Convert the floating point bounds using a calibration lookup
                let bounds_res = match calibration_opt {
                    Some(calibration) => match calibration {
                        Calibration::Numeric(numeric_calibration) => {
                            Environment::numeric_calibration_lookup(
                                numeric_calibration,
                                (bound.left, bound.right),
                            )
                        }
                        Calibration::Boolean(_) => unimplemented!(
                            "Global bounds for a boolean sensore are not implemented!"
                        ),
                    },
                    None => Environment::raw_calibration_lookup((bound.left, bound.right)),
                };
                let bounds = check!(res, bounds_res);

                match device_addr {
                    Some(addr) => {
                        buffer.append_tail(addr.virtuality, 1);
                        buffer.append_tail(addr.value, 10);
                        buffer.append_tail(bounds.0,12);
                        buffer.append_tail(bounds.1,12);
                        // append padding
                        buffer.append_tail(0u16, 5);
                    },
                    None => res.error("Sensor ID not found in config. validate_safe_state function must have failed"),
                }
            }
        // We don't have any entries so just append base section length
        } else {
            buffer.append_tail(Environment::SECTION_HEADER, 24)
        }

        res
    }

    /// Appends the binary config footer to the buffer
    fn append_footer_to_buffer(&self, buffer: &mut BitWriter) -> u32 {
        let buffer_clone = buffer.clone();
        let config_bytes = buffer_clone.as_bytes();

        // Section Prefix
        buffer.append(0xF5u8);

        // Hash
        let mut crc32 = CRCu32::crc32q();
        crc32.digest(config_bytes);
        buffer.append(crc32.get_crc());
        // NL - Newline to assist editors
        buffer.append(b'\n');

        // Return the crc hash
        crc32.get_crc()
    }

    /// Appends the body of the config to a buffer
    pub fn append_to_buffer(&self, buffer: &mut BitWriter) -> u32 {
        // Append header
        self.append_header_to_buffer(buffer);

        // Append relays
        self.append_relays_to_buffer(buffer);

        // Append sensors
        self.append_sensors_to_buffer(buffer);

        // Append virtual relays
        self.append_v_relays_to_buffer(buffer);

        // Append virtual sensors
        self.append_v_sensors_to_buffer(buffer);

        // Append safe state
        self.append_safe_state_to_buffer(buffer);

        // Append global bounds
        self.append_global_bounds_to_buffer(buffer);

        // Append footer
        let crc_hash = self.append_footer_to_buffer(buffer);

        // return the crc hash
        crc_hash
    }
}

impl VirtualRelayRecord {
    /// Computes the number of bytes this virtual
    /// relay will use after serialization
    pub fn len(&self) -> u32 {
        // Driver index, device_address, and num_args take up 3 bytes
        let mut len: u32 = 3;
        // Add two bytes for every argument to the virtual relay driver
        if let Some(args) = self.args.as_ref() {
            len += args.len() as u32 * 2;
        }
        len
    }
}

impl VirtualSensorRecord {
    /// Computes the number of bytes this virtual
    /// relay will use after serialization
    pub fn len(&self) -> u32 {
        // Driver index, device_address, polling_interval, and num_args take up 4 bytes
        let mut len: u32 = 4;
        // Add two bytes for every argument to the virtual sensor driver
        if let Some(args) = self.args.as_ref() {
            len += args.len() as u32 * 2;
        }
        len
    }
}

fn now() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};

    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");

    since_the_epoch.as_millis() as u64
}