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
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
use crate::bits::{MAX_3BIT, MAX_7BIT};
use crate::result::{diagnostic::Location, CompilerResult};
use crate::test_binary::DeviceAddress;
use serde::Deserialize;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::Hash;
use std::iter::FromIterator;
use std::path::PathBuf;
use std::u16;

/// Represents a configuration TOML file.
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Maximum micro seconds to process a relay statement
    pub relay_micros: u32,

    /// Maximum micro seconds to process a sensor statement
    pub sensor_micros: u32,

    /// Maximum micro seconds to process an entire segment
    pub max_segment_length_micros: u32,

    /// A vector of relay names for firmware to set in the safe state
    pub safe_state: Vec<String>,

    /// Path to drivers.toml
    pub drivers_path: Option<PathBuf>,

    /// The mapping from relay name to relay device address
    pub relays: HashMap<String, RelayRecord>,

    /// The mapping from sensor name to sensor metadata
    pub sensors: HashMap<String, SensorRecord>,

    /// Mapping to virtual sensors and relays
    #[serde(rename = "virtual")]
    pub virtuals: Virtual,

    /// The mapping from sensor name to a global bound
    pub global_bounds: Option<HashMap<String, ConfigSensorBound>>,
}

/// Represents the configuration for a sensor.
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SensorRecord {
    /// The device address for the sensor.
    pub device_address: ConfigDeviceAddress,
    /// Polling interval for this sensor
    // TODO currently units are ignored in config_binary
    // so only ms are supported
    pub polling_interval_ms: u16,
    /// The path to the calibration file that this sensor goes with.
    pub calibration: PathBuf,
}

/// Represents the configuration for a relay.
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RelayRecord {
    /// The device address for the relay.
    pub device_address: ConfigDeviceAddress,
}
/// Represents the metadata for a virtual sensor.
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Virtual {
    /// Mapping from virtual sensor name to metadata
    pub sensors: HashMap<String, VirtualSensorRecord>,

    /// Mapping from virtual relay name to metadata
    pub relays: HashMap<String, VirtualRelayRecord>,
}

/// Represents the metadata for a virtual sensor.
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VirtualSensorRecord {
    /// The device address for the sensor.
    pub device_address: ConfigDeviceAddress,
    /// Driver
    pub driver: String,
    /// Additional driver arguments
    pub args: Option<BTreeMap<String, u16>>,
    /// Polling interval for the virtual sensor
    pub polling_interval_ms: u16,
    /// The optional path to the calibration file that this sensor goes with.
    pub calibration: Option<PathBuf>,
}

/// Represents the metadata for a virtual relay.
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VirtualRelayRecord {
    /// The device address for the relay.
    pub device_address: ConfigDeviceAddress,
    /// Driver
    pub driver: String,
    /// Additional driver arguments
    pub args: Option<BTreeMap<String, u16>>,
}

#[derive(Debug, PartialEq, Deserialize, Clone, Copy)]
#[serde(deny_unknown_fields)]
pub struct ConfigDeviceAddress {
    // 7 bit board address
    pub board_address: u8,
    // 3 bit channel
    pub channel: u8,
}

#[derive(Debug, PartialEq, Deserialize, Clone, Copy)]
#[serde(deny_unknown_fields)]
pub struct ConfigSensorBound {
    pub left: f64,
    pub right: f64,
}

impl Config {
    /// Convert sensor id used in TDF file to virtual address
    pub fn get_sensor_device_address(&self, sensor_id: &str) -> CompilerResult<DeviceAddress> {
        let mut res = CompilerResult::new("Get virtual address for a sensor_id");
        if let Some(record) = self.sensors.get(sensor_id) {
            return res.with_value(DeviceAddress {
                value: u16::from(record.device_address),
                virtuality: 0,
            });
        }
        //Either virtual sensor or invalid function call
        if let Some(record) = self.virtuals.sensors.get(sensor_id) {
            return res.with_value(DeviceAddress {
                value: u16::from(record.device_address),
                virtuality: 1,
            });
        }
        res.error(format!(
            "No sensor or virtual sensor with sensor_id: {} found in environment",
            sensor_id
        ));
        res
    }

    /// Convert relay id used in TDF file to virtual address
    pub fn get_relay_device_address(&self, relay_id: &str) -> CompilerResult<DeviceAddress> {
        let mut res = CompilerResult::new("Get device address for a relay_id");
        if let Some(record) = self.relays.get(relay_id) {
            res.with_value(DeviceAddress {
                value: u16::from(record.device_address),
                virtuality: 0,
            })
        } else {
            //Either virtual relay or invalid function call
            if let Some(record) = self.virtuals.relays.get(relay_id) {
                return res.with_value(DeviceAddress {
                    value: u16::from(record.device_address),
                    virtuality: 1,
                });
            }
            res.error(format!(
                "No relay or virtual relay with relay_id: {} found in environment",
                relay_id
            ));
            res
        }
    }

    /// Function to get a vector containing every physical relay record for relays in the safe state
    pub fn get_safe_state_relay_records(&self) -> Vec<&RelayRecord> {
        let mut records: Vec<&RelayRecord> = Vec::new();
        for relay_name in &self.safe_state {
            match self.relays.get(relay_name) {
                Some(record) => records.push(record),
                // This relay name must be a virtual
                None => (),
            }
        }

        records
    }

    /// Function to get a vector containing every virtual relay record for relays in the safe state
    pub fn get_safe_state_v_relay_records(&self) -> Vec<&VirtualRelayRecord> {
        let mut records: Vec<&VirtualRelayRecord> = Vec::new();
        for relay_name in &self.safe_state {
            match self.virtuals.relays.get(relay_name) {
                Some(record) => records.push(record),
                // This relay name must be a physical
                None => (),
            }
        }

        records
    }

    /// Function to get a vector of every relay record in the config.toml.
    /// The vector is output in sorted order by device address values
    pub fn get_relay_records(&self) -> Vec<&RelayRecord> {
        let mut records: Vec<&RelayRecord> = self.relays.values().collect();
        records.sort_by_key(|record| u16::from(record.device_address));
        records
    }

    /// Function to get a vector of every sensor record in the config.toml.
    /// The vector is output in sorted order by device address values
    pub fn get_sensor_records(&self) -> Vec<&SensorRecord> {
        let mut records: Vec<&SensorRecord> = self.sensors.values().collect();
        records.sort_by_key(|record| u16::from(record.device_address));
        records
    }

    /// Function to get a vector of every virtual relay record in the config.toml.
    /// The vector is output in sorted order by device address values
    pub fn get_v_relay_records(&self) -> Vec<&VirtualRelayRecord> {
        let mut records: Vec<&VirtualRelayRecord> = self.virtuals.relays.values().collect();
        records.sort_by_key(|record| u16::from(record.device_address));
        records
    }

    /// Function to get a vector of every virtual sensor record in the config.toml.
    /// The vector is output in sorted order by device address values
    pub fn get_v_sensor_records(&self) -> Vec<&VirtualSensorRecord> {
        let mut records: Vec<&VirtualSensorRecord> = self.virtuals.sensors.values().collect();
        records.sort_by_key(|record| u16::from(record.device_address));
        records
    }

    /// Function to validate that no physical relay or sensor shares the
    /// same device address value.
    pub fn validate_device_addresses(&self, file_name: &String) -> CompilerResult<()> {
        let mut res =
            CompilerResult::status_only("Validating physical device address values in config.toml");

        // Check every channel value
        let sensor_device_addresses: Vec<ConfigDeviceAddress> = self
            .get_sensor_records()
            .iter()
            .map(|record| record.device_address)
            .collect();
        let relay_device_addresses: Vec<ConfigDeviceAddress> = self
            .get_relay_records()
            .iter()
            .map(|record| record.device_address)
            .collect();

        res.require(Config::validate_device_address_values(
            sensor_device_addresses,
            file_name,
        ));
        res.require(Config::validate_device_address_values(
            relay_device_addresses,
            file_name,
        ));

        // Look for duplicated device addresses
        let relay_device_addresses: Vec<u16> = self
            .get_relay_records()
            .iter()
            .map(|record| u16::from(record.device_address))
            .collect();
        let sensor_device_addresses: Vec<u16> = self
            .get_sensor_records()
            .iter()
            .map(|record| u16::from(record.device_address))
            .collect();
        // Get every duplicated device address
        let duplicate_device_addresses = Config::find_duplicate_device_address_values(
            sensor_device_addresses,
            relay_device_addresses,
        );
        // Comparing both vectors
        for device_address in duplicate_device_addresses {
            res.error(format!(
                "Duplicated device address: {}.\n\t{:?}",
                device_address, file_name
            ));
        }
        res
    }

    /// Function to validate that device addresses are valid and no virtual relay or sensor shares the
    /// same device address value.
    pub fn validate_v_device_addresses(&self, file_name: &String) -> CompilerResult<()> {
        let mut res =
            CompilerResult::status_only("Validating virtual device address values in config.toml");

        // Check every device address value
        let v_sensor_device_addresses: Vec<ConfigDeviceAddress> = self
            .get_v_sensor_records()
            .iter()
            .map(|record| record.device_address)
            .collect();
        let v_relay_device_addresses: Vec<ConfigDeviceAddress> = self
            .get_v_relay_records()
            .iter()
            .map(|record| record.device_address)
            .collect();

        res.require(Config::validate_device_address_values(
            v_sensor_device_addresses,
            file_name,
        ));
        res.require(Config::validate_device_address_values(
            v_relay_device_addresses,
            file_name,
        ));

        // Look for duplicated device addresses
        let v_sensor_device_addresses: Vec<u16> = self
            .get_v_sensor_records()
            .iter()
            .map(|record| u16::from(record.device_address))
            .collect();
        let v_relay_device_addresses: Vec<u16> = self
            .get_v_relay_records()
            .iter()
            .map(|record| u16::from(record.device_address))
            .collect();
        // Get every duplicated device address
        let duplicate_device_addresses = Config::find_duplicate_device_address_values(
            v_sensor_device_addresses,
            v_relay_device_addresses,
        );
        // Comparing both vectors
        for device_address in duplicate_device_addresses {
            res.error(format!(
                "Duplicated virtual device address: {:?}.\n\t{:?}",
                ConfigDeviceAddress::from(device_address),
                file_name
            ));
        }
        res
    }

    /// Validate that every channel value in the config is no more than 3 bits large
    fn validate_device_address_values(
        device_addresses: Vec<ConfigDeviceAddress>,
        file_name: &String,
    ) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Validate channel values");
        for addr in device_addresses {
            if addr.channel > MAX_3BIT {
                res.error(format!("Invalid channel: {:?}\n\t{:?}", addr, file_name));
            }
            if addr.board_address > MAX_7BIT {
                res.error(format!(
                    "Invalid board address: {:?}\n\t{:?}",
                    addr, file_name
                ));
            }
        }

        res
    }

    /// Return the duplicated device addresses provided across both vectors
    fn find_duplicate_device_address_values(
        mut device_addresses1: Vec<u16>,
        mut device_addresses2: Vec<u16>,
    ) -> HashSet<u16> {
        let mut duplicate_device_addresses: HashSet<u16> = HashSet::new();

        // Sort vectors to make duplicate checking simpler
        device_addresses1.sort();
        device_addresses2.sort();
        for i in 1..device_addresses1.len() {
            if device_addresses1[i] == device_addresses1[i - 1]
                && !(duplicate_device_addresses.contains(&device_addresses1[i]))
            {
                duplicate_device_addresses.insert(device_addresses1[i]);
            }
        }

        for i in 1..device_addresses2.len() {
            if device_addresses2[i] == device_addresses2[i - 1]
                && !(duplicate_device_addresses.contains(&device_addresses2[i]))
            {
                duplicate_device_addresses.insert(device_addresses2[i]);
            }
        }

        device_addresses1.dedup();
        for device_address in device_addresses1 {
            if device_addresses2.contains(&device_address) {
                duplicate_device_addresses.insert(device_address);
            }
        }
        duplicate_device_addresses
    }

    /// Function to ensure all device ids in the config.toml do not violate any naming constraints
    /// such as an identical relay or sensor name
    pub fn validate_device_ids(&self, file_name: &String) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Validate device IDs");
        let mut device_ids: HashSet<String> = HashSet::new();
        let mut duplicate_ids: HashSet<String> = HashSet::new();

        let mut all_device_ids = Vec::new();
        all_device_ids.extend(self.relays.keys());
        all_device_ids.extend(self.sensors.keys());
        all_device_ids.extend(self.virtuals.relays.keys());
        all_device_ids.extend(self.virtuals.sensors.keys());
        // Add relays to device_ids
        for id in all_device_ids {
            // If we are already reporting this duplicate ID skip it
            if duplicate_ids.contains(id) {
                continue;
            }
            // Check if this ID is a duplicate against the hashset
            else if device_ids.contains(id) {
                duplicate_ids.insert(id.clone());
            }
            // If it's not a duplicate insert into hashset
            else {
                device_ids.insert(id.clone());
            }
        }

        if !duplicate_ids.is_empty() {
            res.error(format!(
                "The following device IDs are duplicated: {:?}.\n\t{}",
                duplicate_ids.into_iter().collect::<Vec<String>>(),
                file_name
            ));
        }
        res
    }

    /// Function to ensure every relay in the safe state actually exists
    pub fn validate_safe_state(&mut self, file_name: &String) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Validating safe state relay IDs");

        // Construct vector with all relay IDs
        let mut relay_ids: Vec<&String> = Vec::new();
        relay_ids.extend(self.relays.keys());
        relay_ids.extend(self.virtuals.relays.keys());

        let missing = Self::find_missing(self.safe_state.iter().map(|x| x).collect(), relay_ids);

        // Create an error message if any relay was not found
        if !missing.is_empty() {
            res.error(format!(
                "The following relay names used in the safe state are not defined: {:?}.\n\t{}",
                missing.into_iter().collect::<Vec<&String>>(),
                file_name
            ))
        }

        res
    }

    /// Function to ensure every sensor in the global bounds actually exists
    pub fn validate_global_bounds(&mut self, file_name: &String) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Validating global bounds sensor IDs");

        if let Some(global_bounds) = &self.global_bounds {
            // Construct vector with all sensor IDs
            let mut sensor_ids: Vec<&String> = Vec::new();
            sensor_ids.extend(self.sensors.keys());
            sensor_ids.extend(self.virtuals.sensors.keys());

            // Vector with all sensor IDs in global bounds
            let global_bound_ids: Vec<&String> = global_bounds.keys().collect();

            // Hashset containing the name of every safe state relay that is not defined in the config.toml
            let missing = Self::find_missing(global_bound_ids, sensor_ids);

            // Create an error message if any relay was not found
            if !missing.is_empty() {
                res.error(format!(
                    "The following sensor IDs used in the global bounds are not defined: {:?}.\n\t{}",
                    missing.into_iter().collect::<Vec<&String>>(), file_name
                ))
            }
        }

        res
    }

    /// Given a vector of given values and a second vector, returns all values in the to_check vector
    /// that do not exist in the given_values vector.
    fn find_missing<T: Clone + Hash + Eq>(to_check: Vec<T>, given_values: Vec<T>) -> HashSet<T> {
        let mut missing: HashSet<T> = HashSet::new();

        // Compute hashset with given vector of values
        let given: HashSet<T> = HashSet::from_iter(given_values.iter().cloned());

        for val in to_check {
            if !given.contains(&val) {
                missing.insert(val.clone());
            }
        }
        missing
    }
}

/// Parse a Config value from toml.
pub fn parse(file_id: usize, file_name: String, contents: &str) -> CompilerResult<Config> {
    let mut res = CompilerResult::new("Parsing a Config file");

    let taplo_parse = taplo::parser::parse(contents);

    let taplo_dom = taplo_parse.clone().into_dom();

    //Check for TOML syntax errors
    if !taplo_parse.errors.is_empty() {
        for error in taplo_parse.errors {
            let location = Location::from_raw(
                file_id,
                error.range.start().into(),
                error.range.end().into(),
            );
            res.error((location, error.to_string()));
        }
    }

    //Check for TOML semantic errors
    if !taplo_dom.errors().is_empty() {
        for error in taplo_dom.errors() {
            res.error(format!("{}\n\t{}", error.to_string(), file_name));
        }
    }

    let mut config: Config = check!(res, toml::from_str(contents));

    // Config validation functions
    res.require(config.validate_device_ids(&file_name));
    res.require(config.validate_device_addresses(&file_name));
    res.require(config.validate_v_device_addresses(&file_name));
    res.require(config.validate_safe_state(&file_name));
    res.require(config.validate_global_bounds(&file_name));
    res.with_value(config)
}

impl From<u16> for ConfigDeviceAddress {
    /// Create a device address board and channel from a single u16
    fn from(device_address: u16) -> Self {
        // The first 7 bits are the board address with 3 channel bits
        ConfigDeviceAddress {
            board_address: (device_address / 8) as u8,
            channel: (device_address % 8) as u8,
        }
    }
}

impl From<ConfigDeviceAddress> for u16 {
    /// Convert a device address board and channel into a single u16
    fn from(device_address: ConfigDeviceAddress) -> Self {
        // The first 7 bits are the board address with 3 channel bits
        // so shift board address left three times
        return (device_address.board_address as u16) * 8 + device_address.channel as u16;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::result::Status;

    static INPUT: &str = r#"
        relay_micros = 100
        sensor_micros = 100
        max_segment_length_micros = 1000
        safe_state = []

        drivers_path = "./empty_drivers.toml"

        [relays]
        a = { device_address = {board_address = 0, channel = 1} }
        b = { device_address = {board_address = 0, channel = 2} }

        [sensors]
        d = { device_address = {board_address = 0, channel = 3}, polling_interval_ms = 5, calibration = "./d.ncf" }
        e = { device_address = {board_address = 0, channel = 4}, polling_interval_ms = 5, calibration = "./e.ncf" }
        f = { device_address = {board_address = 0, channel = 5}, polling_interval_ms = 5, calibration = "./f.ncf" }
        g = { device_address = {board_address = 0, channel = 6}, polling_interval_ms = 5, calibration = "./g.ncf" }
        h = { device_address = {board_address = 0, channel = 7}, polling_interval_ms = 5, calibration = "./h.ncf" }
        i = { device_address = {board_address = 1, channel = 0}, polling_interval_ms = 5, calibration = "./i.ncf" }
        j = { device_address = {board_address = 1, channel = 1}, polling_interval_ms = 5, calibration = "./j.ncf" }

        [virtual.relays]
        prepare_confirm_button = { device_address = {board_address = 0, channel = 0}, driver = "MissionControl/UDP_Command", args = { id = 14 } }


        [virtual.sensors]
        confirm_button = { device_address = {board_address = 0, channel = 1}, driver = "MissionControl/UDP_Request", polling_interval_ms = 5, args = { stand_id = 23 } }
        
        [global_bounds]
        d = {left=1.0, right=2.0}
        
        "#;

    #[test]
    fn toml_test() {
        let relays: Vec<(String, RelayRecord)> = vec![
            (
                "a".into(),
                RelayRecord {
                    device_address: 1.into(),
                },
            ),
            (
                "b".into(),
                RelayRecord {
                    device_address: 2.into(),
                },
            ),
        ];

        let sensors: Vec<(String, SensorRecord)> = vec![
            (
                "d".into(),
                SensorRecord {
                    device_address: 3.into(),
                    polling_interval_ms: 5,
                    calibration: "./d.ncf".into(),
                },
            ),
            (
                "e".into(),
                SensorRecord {
                    device_address: 4.into(),
                    polling_interval_ms: 5,
                    calibration: "./e.ncf".into(),
                },
            ),
            (
                "f".into(),
                SensorRecord {
                    device_address: 5.into(),
                    polling_interval_ms: 5,
                    calibration: "./f.ncf".into(),
                },
            ),
            (
                "g".into(),
                SensorRecord {
                    device_address: 6.into(),
                    polling_interval_ms: 5,
                    calibration: "./g.ncf".into(),
                },
            ),
            (
                "h".into(),
                SensorRecord {
                    device_address: 7.into(),
                    polling_interval_ms: 5,
                    calibration: "./h.ncf".into(),
                },
            ),
            (
                "i".into(),
                SensorRecord {
                    device_address: 8.into(),
                    polling_interval_ms: 5,
                    calibration: "./i.ncf".into(),
                },
            ),
            (
                "j".into(),
                SensorRecord {
                    device_address: 9.into(),
                    polling_interval_ms: 5,
                    calibration: "./j.ncf".into(),
                },
            ),
        ];

        let mut virtual_relay_args1 = BTreeMap::new();
        virtual_relay_args1.insert("id".into(), 14);
        let virtual_relays: Vec<(String, VirtualRelayRecord)> = vec![(
            "prepare_confirm_button".into(),
            VirtualRelayRecord {
                device_address: 0.into(),
                driver: "MissionControl/UDP_Command".into(),
                args: Some(virtual_relay_args1),
            },
        )];

        let mut virtual_sensor_args1 = BTreeMap::new();
        virtual_sensor_args1.insert("stand_id".into(), 23);
        let virtual_sensors: Vec<(String, VirtualSensorRecord)> = vec![(
            "confirm_button".into(),
            VirtualSensorRecord {
                device_address: 1.into(),
                driver: "MissionControl/UDP_Request".into(),
                args: Some(virtual_sensor_args1),
                polling_interval_ms: 5,
                calibration: None,
            },
        )];

        let virtuals = Virtual {
            sensors: virtual_sensors.into_iter().collect(),
            relays: virtual_relays.into_iter().collect(),
        };

        let mut global_bounds: HashMap<String, ConfigSensorBound> = HashMap::new();
        global_bounds.insert(
            "d".into(),
            ConfigSensorBound {
                left: 1.0,
                right: 2.0,
            },
        );

        let expected = Config {
            relay_micros: 100,
            sensor_micros: 100,
            max_segment_length_micros: 1000,
            safe_state: vec![],
            drivers_path: Some(PathBuf::from("./empty_drivers.toml")),
            relays: relays.into_iter().collect(),
            sensors: sensors.into_iter().collect(),
            virtuals: virtuals,
            global_bounds: Some(global_bounds),
        };
        let actual: Config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        assert_eq!(expected.relays, actual.relays);
        assert_eq!(expected.sensors, actual.sensors);
        assert_eq!(
            actual
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );
        assert_eq!(
            actual
                .validate_v_device_addresses(&String::from(&"notafile".to_string()))
                .get_status(),
            Status::Unresolved,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn find_duplicate_device_address_values() {
        // No shared values
        let device_addresses1 = vec![0, 1, 2, 3];
        let device_addresses2 = vec![10, 11, 12, 14, 15, 16, 17];

        assert_eq!(
            Config::find_duplicate_device_address_values(
                device_addresses1.clone(),
                device_addresses2.clone()
            ),
            HashSet::new(),
        );

        // Duplicates between vectors
        let device_addresses1 = vec![0, 1, 2, 3];
        let device_addresses3 = vec![1, 2, 3, 4, 5, 6, 7];
        let three_dupes: HashSet<u16> = [1, 2, 3].iter().cloned().collect();
        assert_eq!(
            Config::find_duplicate_device_address_values(
                device_addresses1.clone(),
                device_addresses3.clone()
            ),
            three_dupes,
        );

        // Non-empty & empty device_addresse vector
        let device_addresses3 = vec![1, 2, 3, 4, 5, 6, 7];
        let device_addresses4 = Vec::new();
        assert_eq!(
            Config::find_duplicate_device_address_values(
                device_addresses3.clone(),
                device_addresses4.clone()
            ),
            HashSet::new(),
        );

        // Dupes within vector
        // The 2 vectors don't share any values, but device_addresses5 has duplicates in it
        let mut device_addresses2 = vec![10, 11, 12, 14, 15, 16, 17];
        let device_addresses5 = vec![0, 1, 1, 3, 3, 3, 2];
        let dupes_within: HashSet<u16> = [1, 3].iter().cloned().collect();
        assert_eq!(
            Config::find_duplicate_device_address_values(
                device_addresses2.clone(),
                device_addresses5.clone()
            ),
            dupes_within,
        );

        // Appending device_addresse1 to device_addresse2
        // Duplicates should be all of device_addresse1
        let mut device_addresses1 = vec![0, 1, 2, 3];
        device_addresses2.append(&mut device_addresses1);
        let dupes_append: HashSet<u16> = device_addresses1.iter().cloned().collect();
        assert_eq!(
            Config::find_duplicate_device_address_values(
                device_addresses1.clone(),
                device_addresses2.clone()
            ),
            dupes_append,
        );
    }

    #[test]
    fn parsed_toml_invalid_board_address_values() {
        // There are no invalid channels yet, so we should get a valid Config
        let mut config: Config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        // Ensure it hasn't failed yet
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );

        // Modify a single physical channel
        config.relays.get_mut("a").unwrap().device_address = ConfigDeviceAddress {
            // Should be MAX_7BIT + 1
            board_address: 0b10000001,
            channel: 2,
        };

        // It should now be failing
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
        // virtuals should be fine
        assert_eq!(
            config
                .validate_v_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );

        // Reset the config
        config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        // Modify a virtual device address channel
        config
            .virtuals
            .relays
            .get_mut("prepare_confirm_button")
            .unwrap()
            .device_address = ConfigDeviceAddress {
            board_address: 1 << 7,
            channel: 5,
        };

        // It should now be failing for virtuals
        assert_eq!(
            config
                .validate_v_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
        // physical channels should be fine
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );

        // Modify a single physical channel in addition
        config.relays.get_mut("a").unwrap().device_address = ConfigDeviceAddress {
            board_address: 1 << 7,
            channel: 3,
        };

        // Both should be failing
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
        assert_eq!(
            config
                .validate_v_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
    }

    #[test]
    fn parsed_toml_invalid_channel_values() {
        // There are no invalid channels yet, so we should get a valid Config
        let mut config: Config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        // Ensure it hasn't failed yet
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );

        // Modify a single physical channel
        config.relays.get_mut("a").unwrap().device_address = ConfigDeviceAddress {
            board_address: 0,
            channel: 8,
        };

        // It should now be failing
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
        // virtuals should be fine
        assert_eq!(
            config
                .validate_v_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );

        // Reset the config
        config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        // Modify a virtual device address channel
        config
            .virtuals
            .relays
            .get_mut("prepare_confirm_button")
            .unwrap()
            .device_address = ConfigDeviceAddress {
            board_address: 5,
            channel: 9,
        };

        // It should now be failing for virtuals
        assert_eq!(
            config
                .validate_v_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
        // physical channels should be fine
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );

        // Modify a single physical channel in addition
        config.relays.get_mut("a").unwrap().device_address = ConfigDeviceAddress {
            board_address: 0,
            channel: 8,
        };

        // Both should be failing
        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
        assert_eq!(
            config
                .validate_v_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
    }

    #[test]
    fn parsed_toml_duplicate_device_addresses() {
        // There are no address conflicts yet, so this we should get a valid Config
        let mut config: Config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        // Modify 2 device addresses to create a physical address conflict and a virtual conflict
        config.relays.get_mut("a").unwrap().device_address = 3.into();
        config
            .virtuals
            .relays
            .get_mut("prepare_confirm_button")
            .unwrap()
            .device_address = 1.into();

        assert_eq!(
            config
                .validate_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );

        assert_eq!(
            config
                .validate_v_device_addresses(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
    }

    #[test]
    fn test_get_safe_state_relay_records() {
        let mut config: Config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        // no physical relays
        assert_eq!(
            config
                .get_safe_state_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            Vec::<u16>::new()
        );
        // no virtual relays
        assert_eq!(
            config
                .get_safe_state_v_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            Vec::<u16>::new()
        );

        config.safe_state = vec!["a".into()];
        assert_eq!(
            config
                .get_safe_state_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            vec![1]
        );
        // no virtual relays
        assert_eq!(
            config
                .get_safe_state_v_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            Vec::<u16>::new()
        );

        config.safe_state = vec!["a".into(), "b".into()];
        assert_eq!(
            config
                .get_safe_state_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            vec![1, 2]
        );
        // no virtual relays
        assert_eq!(
            config
                .get_safe_state_v_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            Vec::<u16>::new()
        );

        config.safe_state = vec!["prepare_confirm_button".into(), "b".into()];
        assert_eq!(
            config
                .get_safe_state_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            vec![2]
        );
        // one virtual relay
        assert_eq!(
            config
                .get_safe_state_v_relay_records()
                .into_iter()
                .map(|r| u16::from(r.device_address))
                .collect::<Vec<u16>>(),
            vec![0]
        );
    }

    #[test]
    fn safe_state_undefined_relay_name() {
        // There are no undefined safe state relays yet, so this we should get a valid Config
        let mut config: Config = parse(0, "empty".to_string(), INPUT).to_option().unwrap();

        // Make sure the safe state is valid after adding a defined physical and virtual relay
        config.safe_state = vec!["a".into(), "prepare_confirm_button".into()];
        assert_eq!(
            config
                .validate_safe_state(&"notafile".to_string())
                .get_status(),
            Status::Unresolved,
        );

        // Add an undefined relay name to the safe state
        config.safe_state.push("imnotarelay".into());

        assert_eq!(
            config
                .validate_safe_state(&"notafile".to_string())
                .get_status(),
            Status::Failed,
        );
    }
}