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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
use std::fmt;

use crate::bits::{BitWriter, MAX_10BIT, MAX_12BIT, MAX_20BIT};
use crate::environment::config::Config;
use crate::result::CompilerResult;

/// An Instruction Segment is a conceptual unit that contains all of
/// the actions that take place at a specific moment in time
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
    /// The relative
    relative_time: u32,
    /// The relay instructions in this segment
    pub relay_instructions: Vec<RelayInstr>,
    /// The sensor instructions in this segment
    pub sensor_instructions: Vec<SensorInstr>,
}

impl Segment {
    const HEADER_LEN: u32 = 7;

    /// Creates a new Instruction Segment
    pub fn try_new(relative_time: u32) -> CompilerResult<Self> {
        let mut res = CompilerResult::new("Creating an Instruction Segment");
        res.assert(
            relative_time <= MAX_20BIT,
            format!("relative_time {} does not fit in 20 bits", relative_time),
        );

        res.with_value(Segment {
            relative_time,
            relay_instructions: Vec::new(),
            sensor_instructions: Vec::new(),
        })
    }

    fn append_header_to_buffer(&self, buffer: &mut BitWriter) {
        // Prefix
        buffer.append_tail(0u8, 3);
        // z
        buffer.append_tail(0u8, 1);
        // amount
        buffer.append_tail(self.relative_time, 20);
        // num_sensors
        buffer.append(self.sensor_instructions.len() as u16);
        // num_relays
        buffer.append(self.relay_instructions.len() as u16);
    }

    /// Append the Instruction Segment to the provided buffer
    pub fn append_to_buffer(&self, buffer: &mut BitWriter) {
        self.append_header_to_buffer(buffer);

        for sensor_inst in self.sensor_instructions.iter() {
            sensor_inst.append_to_buffer(buffer);
        }
        for relay_inst in self.relay_instructions.iter() {
            relay_inst.append_to_buffer(buffer);
        }
    }

    /// Format segment struct elements for TAF output
    pub fn append_assembly_to_string(&self, lines: &mut String) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Segment disassembly");
        lines.push_str(format!("segment +{}ms\n", self.relative_time).as_str());

        for s_instruction in &self.sensor_instructions {
            check!(res, s_instruction.append_assembly_to_string(lines));
        }

        for r_instruction in &self.relay_instructions {
            check!(res, r_instruction.append_assembly_to_string(lines));
        }
        lines.push_str("\n");
        res
    }

    /// Compute the length of this segment
    pub fn len(&self) -> u32 {
        let sensors_len = self.sensor_instructions.len() as u32 * SensorInstr::len();
        let relay_len = self.relay_instructions.len() as u32 * RelayInstr::len();

        Segment::HEADER_LEN + sensors_len + relay_len
    }

    /// Based on the firmware timing guarantees for sensor and relay
    /// instructions, ensure that the total time to complete the segment
    /// instructions is below the max_segment_length_micros
    pub fn check_segment_length(&self, config: &Config) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Check time length of segment instructions.");

        let total_length = config.sensor_micros * self.sensor_instructions.len() as u32
            + config.relay_micros * self.relay_instructions.len() as u32;
        if total_length > config.max_segment_length_micros {
            res.error("This segment has too many sensor and relay instructions");
        }
        res
    }
}

/// A Device Address for a relay or sensor
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceAddress {
    /// The Device Address value
    pub value: u16,
    /// Whether or not this is a virtual device address
    pub virtuality: u16,
}

impl fmt::Display for DeviceAddress {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.virtuality {
            0 => write!(f, "P{}", self.value),
            1 => write!(f, "V{}", self.value),
            _ => Err(std::fmt::Error),
        }
    }
}

/// A RelayInstr Instruction either sets or unsets a specified relay
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelayInstr {
    /// Whether the relay will be set or unset by this instruction
    action: RelayAction,
    /// The device address of the relay
    device_address: DeviceAddress,
}

/// The two different actions that can be performed on a relay
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelayAction {
    Set,
    Unset,
}

impl RelayInstr {
    /// Attempts to create a new Relay Instruction.
    /// Fails if the device address cannot fit in 10 bits.
    pub fn try_new(action: RelayAction, device_address: DeviceAddress) -> CompilerResult<Self> {
        let mut res = CompilerResult::new("Creating a Relay Instruction");
        res.assert(
            device_address.value <= MAX_10BIT,
            format!(
                "device address {} does not fit in 10 bits",
                device_address.value
            ),
        );

        res.with_value(RelayInstr {
            action,
            device_address,
        })
    }

    /// Append the RelayInstr Instruction to the provided buffer.
    pub fn append_to_buffer(&self, buffer: &mut BitWriter) {
        let opcode = self.action.get_opcode();

        buffer.append_tail(0b001u8, 3);
        buffer.append_tail(opcode, 2);
        buffer.append_tail(self.device_address.virtuality, 1);
        buffer.append_tail(self.device_address.value, 10);
    }

    /// Format RelayInstr Insruction for TAF output
    pub fn append_assembly_to_string(&self, lines: &mut String) -> CompilerResult<()> {
        let res = CompilerResult::status_only("Relay Instruction disassembly");
        lines.push_str(format!("{} {}\n", self.action, self.device_address).as_str());

        res
    }

    /// The length of a relay instruction in bytes
    pub fn len() -> u32 {
        2
    }
}

impl RelayAction {
    /// Computes the 2 bit numeric opcode for a specific relay action
    pub fn get_opcode(&self) -> u8 {
        match self {
            RelayAction::Set => 0b00,
            RelayAction::Unset => 0b01,
        }
    }

    /// Attempts to read in a relay action from a string representation.
    /// Note: this is really assembler functionality and could/should be relocated.
    pub fn parse(text: &str) -> CompilerResult<Self> {
        let mut res = CompilerResult::new("Parsing Relay Opcode");
        match text {
            "set" => res.with_value(RelayAction::Set),
            "unset" => res.with_value(RelayAction::Unset),
            _ => {
                res.error(format!("Could not parse {} as \"set\" or \"unset\"", text));
                res
            }
        }
    }
}

impl fmt::Display for RelayAction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            RelayAction::Set => write!(f, "set"),
            RelayAction::Unset => write!(f, "unset"),
        }
    }
}

/// A representation of all the fields of a sensor instruction.
/// This canonically represents an exact binary representation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SensorInstr {
    /// The Opcode of the Sensor Instruction
    action: SensorAction,
    /// The index of the abort
    abort_idx: u8,
    /// The Virtual Address of the Relay
    device_address: DeviceAddress,
    /// The left bound for comparison
    left_bound: u16,
    /// The right bound for comparison
    right_bound: u16,
}

/// Represents the opcodes for a Sensor instruction.
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SensorAction {
    is_now_in,
    start_check_in,
    stop_check,
}

impl fmt::Display for SensorAction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            SensorAction::is_now_in => write!(f, "is_now_in"),
            SensorAction::start_check_in => write!(f, "start_check_in"),
            SensorAction::stop_check => write!(f, "stop_check"),
        }
    }
}

impl SensorInstr {
    /// Tries to create a new sensor stop instruction.
    pub fn try_new_stop(device_address: DeviceAddress) -> CompilerResult<Self> {
        let mut res = CompilerResult::new("Validating a Sensor Instruction");

        res.assert(
            device_address.value <= MAX_10BIT,
            format!(
                "device address {} does not fit in 10 bits",
                device_address.value
            ),
        );

        res.with_value(SensorInstr {
            action: SensorAction::stop_check,
            abort_idx: 0,
            device_address,
            left_bound: 0,
            right_bound: 0,
        })
    }

    /// Tries to create a new standard sensor instruction with abort index.
    pub fn try_new(
        action: SensorAction,
        abort_idx: u8,
        device_address: DeviceAddress,
        left_bound: u16,
        right_bound: u16,
    ) -> CompilerResult<Self> {
        let mut res = CompilerResult::new("Validating a Sensor Instruction");

        res.assert(
            abort_idx <= 15,
            format!("abort_idx {} is greater than the maximum (15)", abort_idx),
        );
        res.assert(
            device_address.value <= MAX_10BIT,
            format!(
                "Device Address {} does not fit in 10 bits",
                device_address.value
            ),
        );
        res.assert(
            left_bound <= MAX_12BIT,
            format!(
                "left_bound {} is greater than {} and does not fit in 12 bits",
                left_bound, MAX_12BIT
            ),
        );
        res.assert(
            right_bound <= MAX_12BIT,
            format!(
                "right_bound {} is greater than {} and does not fit in 12 bits",
                left_bound, MAX_12BIT
            ),
        );

        res.with_value(SensorInstr {
            action,
            abort_idx,
            device_address,
            left_bound,
            right_bound,
        })
    }

    /// Append the SensorInstr Instruction to the provided bit buffer
    pub fn append_to_buffer(&self, buffer: &mut BitWriter) {
        let opcode = self.action.get_opcode();

        buffer.append_tail(0b010u8, 3); //prefix
        buffer.append_tail(opcode, 6);
        buffer.append_tail(self.abort_idx, 4);
        buffer.append_tail(self.device_address.virtuality, 1);
        buffer.append_tail(self.device_address.value, 10);
        buffer.append_tail(self.left_bound, 12);
        buffer.append_tail(self.right_bound, 12);
    }

    /// Format SensorInstr Insruction for TAF output
    pub fn append_assembly_to_string(&self, lines: &mut String) -> CompilerResult<()> {
        let res = CompilerResult::status_only("Sensor Instruction disassembly");
        // stop_check's opcode is 0, and has a different format
        if self.action.get_opcode() != 0 {
            lines.push_str(
                format!(
                    "{action} {device_address}, {left:#X}, {right:#X}, #{abort}\n",
                    action = self.action,
                    device_address = self.device_address,
                    left = self.left_bound,
                    right = self.right_bound,
                    abort = self.abort_idx
                )
                .as_str(),
            );
        } else {
            lines.push_str(
                format!(
                    "{action} {device_address}\n",
                    action = self.action,
                    device_address = self.device_address,
                )
                .as_str(),
            );
        }

        res
    }

    /// Length of a sensor instruction in bytes
    pub fn len() -> u32 {
        6
    }

    /// Get the sensor action for this instruction
    pub fn get_action(&self) -> SensorAction {
        self.action
    }
}

impl SensorAction {
    /// Computes the 6 bit numeric opcode for a specific sensor action
    fn get_opcode(&self) -> u8 {
        match self {
            SensorAction::stop_check => 0,
            SensorAction::start_check_in => 1,
            SensorAction::is_now_in => 0xFF,
        }
    }

    /// Attempts to read in a sensor action from a string representation.
    /// TODO: this is really assembler functionality and could/should be relocated.
    pub fn parse(text: &str) -> CompilerResult<Self> {
        let mut res = CompilerResult::new("Parse Sensor Opcode");
        match text {
            "is_now_in" => res.with_value(SensorAction::is_now_in),
            "start_check_in" => res.with_value(SensorAction::start_check_in),
            "stop_check" => res.with_value(SensorAction::stop_check),
            _ => {
                res.error(format!("Could not parse {} as a Sensor Action", text));
                res
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::result::Status;
    use crate::{bits::BitReader, bits::BitWriter};
    use test_case::test_case;

    #[test_case(RelayAction::Set, 0)]
    #[test_case(RelayAction::Unset, 1)]
    #[test_case(RelayAction::Unset, 143)]
    fn virtuality_relay_test(relay_action: RelayAction, device_address_num: u16) {
        // Check that a physical version of this relay instruction is encoded with a 0
        let physical_relay = RelayInstr::try_new(
            relay_action,
            DeviceAddress {
                value: device_address_num,
                virtuality: 0,
            },
        )
        .to_option()
        .unwrap();

        let mut physical_writer = BitWriter::new();
        physical_relay.append_to_buffer(&mut physical_writer);
        let mut physical_reader: BitReader = physical_writer.into();

        physical_reader.read_u8(5);
        assert_eq!(Some(0), physical_reader.read_u8(1));

        // Check that a virtual version of this relay instruction is encoded with a 1
        let virtual_relay = RelayInstr::try_new(
            relay_action,
            DeviceAddress {
                value: device_address_num,
                virtuality: 1,
            },
        )
        .to_option()
        .unwrap();

        let mut virtual_writer = BitWriter::new();
        virtual_relay.append_to_buffer(&mut virtual_writer);
        let mut virtual_reader: BitReader = virtual_writer.into();

        virtual_reader.read_u8(5);
        assert_eq!(Some(1), virtual_reader.read_u8(1));
    }

    #[test]
    fn segment_relative_time_within_limits() {
        assert_eq!(Segment::try_new(0).get_status(), Status::Passed);
        assert_eq!(
            Segment::try_new(u32::pow(2, 20) - 1).get_status(),
            Status::Passed
        );
        assert_eq!(
            Segment::try_new(u32::pow(2, 20)).get_status(),
            Status::Failed
        );
        assert_eq!(Segment::try_new(u32::MAX).get_status(), Status::Failed);
    }

    #[test_case(RelayAction::Set, 0, 0)]
    #[test_case(RelayAction::Unset, 1, 1)]
    #[test_case(RelayAction::Set, 0, 2)]
    #[test_case(RelayAction::Unset, 1, 3)]
    fn relay_append_to_buffer(relay_action: RelayAction, opcode: u8, device_address: u16) {
        let relay = RelayInstr::try_new(
            relay_action,
            DeviceAddress {
                value: device_address,
                virtuality: 0,
            },
        )
        .to_option()
        .unwrap();

        let mut writer = BitWriter::new();
        relay.append_to_buffer(&mut writer);
        assert_eq!(writer.len() as u32, RelayInstr::len() * 8);

        let mut reader: BitReader = writer.into();
        assert_eq!(Some(0b001u8), reader.read_u8(3));
        assert_eq!(Some(opcode), reader.read_u8(2));
        assert_eq!(Some(0), reader.read_u16(1));
        assert_eq!(Some(device_address), reader.read_u16(10));
    }

    #[test_case(660)]
    #[test_case(483)]
    #[test_case(1023)]
    fn sensor_stop_append_to_buffer(device_address: u16) {
        let sensor = SensorInstr::try_new_stop(DeviceAddress {
            value: device_address,
            virtuality: 0,
        })
        .to_option()
        .unwrap();

        let mut writer = BitWriter::new();
        sensor.append_to_buffer(&mut writer);
        assert_eq!(writer.len() as u32, SensorInstr::len() * 8);

        let mut reader: BitReader = writer.into();
        assert_eq!(Some(0b010u8), reader.read_u8(3));
        assert_eq!(Some(0), reader.read_u8(6));
        assert_eq!(Some(0), reader.read_u8(4));
        assert_eq!(Some(0), reader.read_u16(1));
        assert_eq!(Some(device_address), reader.read_u16(10));
        assert_eq!(Some(0), reader.read_u16(12));
        assert_eq!(Some(0), reader.read_u16(12));
    }

    #[test_case(SensorAction::is_now_in, 63, 5, 2, 0, 3000)]
    #[test_case(SensorAction::start_check_in, 1, 10, 424, 200, 3210)]
    fn sensor_check_append_to_buffer(
        action: SensorAction,
        opcode: u8,
        abort_idx: u8,
        device_address: u16,
        left_bound: u16,
        right_bound: u16,
    ) {
        let sensor = SensorInstr::try_new(
            action,
            abort_idx,
            DeviceAddress {
                value: device_address,
                virtuality: 0,
            },
            left_bound,
            right_bound,
        )
        .to_option()
        .unwrap();

        let mut writer = BitWriter::new();
        sensor.append_to_buffer(&mut writer);
        assert_eq!(writer.len() as u32, SensorInstr::len() * 8);

        let mut reader: BitReader = writer.into();
        assert_eq!(Some(0b010u8), reader.read_u8(3));
        assert_eq!(Some(opcode), reader.read_u8(6));
        assert_eq!(Some(abort_idx), reader.read_u8(4));
        assert_eq!(Some(0), reader.read_u16(1));
        assert_eq!(Some(device_address), reader.read_u16(10));
        assert_eq!(Some(left_bound), reader.read_u16(12));
        assert_eq!(Some(right_bound), reader.read_u16(12));
    }

    #[test_case(RelayAction::Set, u16::pow(2, 10))]
    #[test_case(RelayAction::Set, u16::pow(2, 12))]
    fn test_invalid_device_address_values(relay_action: RelayAction, device_address: u16) {
        let relay = RelayInstr::try_new(
            relay_action,
            DeviceAddress {
                value: device_address,
                virtuality: 0,
            },
        );
        assert_eq!(relay.get_status(), Status::Failed);
    }

    #[test]
    fn test_parse_valid_relay_set() {
        let relay_value = RelayAction::parse("set");
        let relay_opcode = RelayAction::Set.get_opcode();

        assert_ne!(relay_value.get_status(), Status::Failed);
        assert_eq!(relay_opcode, 0b00);
    }

    #[test]
    fn test_parse_valid_relay_unset() {
        let relay_value = RelayAction::parse("unset");
        let relay_opcode = RelayAction::Unset.get_opcode();

        assert_ne!(relay_value.get_status(), Status::Failed);
        assert_eq!(relay_opcode, 0b01);
    }
}