zencan-common 0.0.4

Shared code for zencan-node and zencan-client
Documentation
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
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! Device config file
//!
//! A DeviceConfig is created from a TOML file, and provides build-time configuration for a zencan
//! node. The device config specifies all of the objects in the object dictionary of the node,
//! including custom ones defined for the specific application.
//!
//! # An example TOML file
//!
//! ```toml
//! device_name = "can-io"
//! software_version = "v0.0.1"
//! hardware_version = "rev1"
//!
//! # How frequently to send heartbeat messages (ms)
//! heartbeat_period = 1000
//!
//! # Sets the default value of the Auto-start object
//! autostart = "enabled"
//!
//! # Define 3 out of 4 device unique identifiers. These define the application/device, the fourth is
//! # the serial number, which must be provided at run-time by the application.
//! [identity]
//! vendor_id = 0xCAFE
//! product_code = 1032
//! revision_number = 1
//!
//! # Defines the number of PDOs the device will support, and their default configurations
//! [pdos]
//! num_rpdo = 4
//! num_tpdo = 4
//!
//! # Configure the first TPDO to transmit object 0x2000sub1 on COB ID (0x200 + NODE_ID)
//! [pdos.tpdo.0]
//! enabled = true # Enabled by default
//! cob_id = 0x200 # The base COB ID
//! add_node_id = true # Add NODE ID to the base COB ID above
//! transmission_type = 254 # Send asynchronously whenever the object is written to
//! mappings = [
//!     { index=0x2000, sub=1, size=32 },
//! ]
//!
//! # User's can create custom objects to hold application specific data
//! [[objects]]
//! index = 0x2000
//! parameter_name = "Raw Analog Input"
//! object_type = "array"
//! data_type = "uint16"
//! access_type = "ro"
//! array_size = 4
//! default_value = [0, 0, 0, 0]
//! pdo_mapping = "tpdo"
//! ```
//!
//! # Object Namespaces
//!
//! Application specific objects should be defined in the range 0x2000-0x4fff. Many objects will be
//! created by default in addition to the ones defined by the user.
//!
//! # Standard Objects
//!
//! ## 0x1008 - Device Name
//!
//! A VAR object containing a string with a human readable device name. This value is set by
//! [DeviceConfig::device_name].
//!
//! ## 0x1009 - Hardware Version
//!
//! A VAR object containing a string with a human readable hardware version. This value is set by
//! [DeviceConfig::hardware_version].
//!
//! ## 0x100A - Software Version
//!
//! A VAR object containing a string with a human readable software version. This value is set by
//! [DeviceConfig::software_version]
//!
//! ## 0x1010 - Object Save Command
//!
//! An array object used to command the node to store its current object values.
//!
//! Array size: 1 Data type: u32
//!
//! When read, sub-object 1 will return a 1 if a storage callback has been provided by the
//! application, indicating that saving is supported.
//!
//! To trigger a save, write a u32 with the [magic value](crate::constants::values::SAVE_CMD).
//!
//! ## 0x1017 - Heartbeat Producer Time
//!
//! A VAR object of type U16.
//!
//! This object stores the period at which the heartbeat is sent by the device, in milliseconds. It
//! is set by [DeviceConfig::heartbeat_period].
//!
//! ## 0x1018 - Identity
//!
//! A record object which stores the 128-bit unique identifier for the node.
//!
//! | Sub Object | Type | Description |
//! | ---------- | ---- | ----------- |
//! | 0          | u8   | Max sub index - always 4 |
//! | 1          | u32  | Vendor ID    |
//! | 2          | u32  | Product Code |
//! | 3          | u32  | Revision |
//! | 4          | u32  | Serial |
//!
//! ## 0x1400 to 0x1400 + N - RPDO Communications Parameter
//!
//! One object for each RPDO supported by the node. This configures how the PDO is received.
//!
//! ## 0x1600 to 0x1600 + N - RPDO Mapping Parameters
//!
//! One object for each RPDO supported by the node. This configures which sub objects the data in
//! the PDO message maps to.
//!
//! Sub Object 0 contains the number of valid mappings. Sub objects 1 through 9 specify a list of
//! sub objects to map to.
//!
//! ## 0x1800 to 0x1800 + N - TPDO Communications Parameter
//!
//! One object for each TPDO supported by the node. This configures how the PDO is transmitted.
//!
//! ## 0x1A00 to 0x1A00 + N - TPDO Mapping Parameters
//!
//! One object for each TPDO supported by the node. This configures which sub objects the data in
//! the PDO message maps to.
//!
//! Sub Object 0 contains the number of valid mappings. Sub objects 1 through 9 specify a list of
//! sub objects to map to.
//!
//! # Zencan Extensions
//!
//! ## 0x5000 - Auto Start
//!
//! Setting this to a non-zero value causes the node to immediately move into the Operational state
//! after power-on, without receiving an NMT command to do so. Note that, if the device is later put
//! into PreOperational via an NMT command, it will not auto-transition to Operational.
//!
use std::collections::HashMap;

use crate::node_configuration::deserialize_pdo_map;
use crate::objects::{AccessType, ObjectCode, PdoMappable};
use crate::pdo::PdoMapping;
use serde::{de::Error, Deserialize};

use snafu::ResultExt as _;
use snafu::Snafu;

/// Error returned when loading a device config fails
#[derive(Debug, Snafu)]
pub enum LoadError {
    /// An IO error occured while reading the file
    #[snafu(display("IO error: {source}"))]
    Io {
        /// The underlying IO error
        source: std::io::Error,
    },
    /// An error occured in the TOML parser
    #[snafu(display("Toml parse error: {source}"))]
    TomlParsing {
        /// The toml error which led to this error
        source: toml::de::Error,
    },
    /// Multiple objects defined with same index
    #[snafu(display("Multiple definitions for object with index 0x{id:x}"))]
    DuplicateObjectIds {
        /// index which was defined multiple times
        id: u16,
    },
    /// Duplicate sub objects defined on a record
    #[snafu(display("Multiple definitions of sub index {sub} on object 0x{index:x}"))]
    DuplicateSubObjects {
        /// Index of the record object containing duplicate subs
        index: u16,
        /// Duplicated sub index
        sub: u8,
    },
}

fn mandatory_objects(config: &DeviceConfig) -> Vec<ObjectDefinition> {
    let mut objects = vec![
        ObjectDefinition {
            index: 0x1000,
            parameter_name: "Device Type".to_string(),
            application_callback: false,
            object: Object::Var(VarDefinition {
                data_type: DataType::UInt32,
                access_type: AccessType::Const.into(),
                default_value: Some(DefaultValue::Integer(0x00000000)),
                pdo_mapping: PdoMappable::None,
                ..Default::default()
            }),
        },
        ObjectDefinition {
            index: 0x1001,
            parameter_name: "Error Register".to_string(),
            application_callback: false,
            object: Object::Var(VarDefinition {
                data_type: DataType::UInt8,
                access_type: AccessType::Ro.into(),
                default_value: Some(DefaultValue::Integer(0x00000000)),
                pdo_mapping: PdoMappable::None,
                ..Default::default()
            }),
        },
        ObjectDefinition {
            index: 0x1008,
            parameter_name: "Manufacturer Device Name".to_string(),
            application_callback: false,
            object: Object::Var(VarDefinition {
                data_type: DataType::VisibleString(config.device_name.len()),
                access_type: AccessType::Const.into(),
                default_value: Some(DefaultValue::String(config.device_name.clone())),
                pdo_mapping: PdoMappable::None,
                ..Default::default()
            }),
        },
        ObjectDefinition {
            index: 0x1009,
            parameter_name: "Manufacturer Hardware Version".to_string(),
            application_callback: false,
            object: Object::Var(VarDefinition {
                data_type: DataType::VisibleString(config.hardware_version.len()),
                access_type: AccessType::Const.into(),
                default_value: Some(DefaultValue::String(config.hardware_version.clone())),
                pdo_mapping: PdoMappable::None,
                ..Default::default()
            }),
        },
        ObjectDefinition {
            index: 0x100A,
            parameter_name: "Manufacturer Software Version".to_string(),
            application_callback: false,
            object: Object::Var(VarDefinition {
                data_type: DataType::VisibleString(config.software_version.len()),
                access_type: AccessType::Const.into(),
                default_value: Some(DefaultValue::String(config.software_version.clone())),
                pdo_mapping: PdoMappable::None,
                ..Default::default()
            }),
        },
        ObjectDefinition {
            index: 0x1017,
            parameter_name: "Heartbeat Producer Time (ms)".to_string(),
            application_callback: false,
            object: Object::Var(VarDefinition {
                data_type: DataType::UInt16,
                access_type: AccessType::Const.into(),
                default_value: Some(DefaultValue::Integer(config.heartbeat_period as i64)),
                pdo_mapping: PdoMappable::None,
                persist: false,
            }),
        },
        ObjectDefinition {
            index: 0x1018,
            parameter_name: "Identity".to_string(),
            application_callback: false,
            object: Object::Record(RecordDefinition {
                subs: vec![
                    SubDefinition {
                        sub_index: 1,
                        parameter_name: "Vendor ID".to_string(),
                        field_name: Some("vendor_id".into()),
                        data_type: DataType::UInt32,
                        access_type: AccessType::Const.into(),
                        default_value: Some(DefaultValue::Integer(
                            config.identity.vendor_id as i64,
                        )),
                        pdo_mapping: PdoMappable::None,
                        ..Default::default()
                    },
                    SubDefinition {
                        sub_index: 2,
                        parameter_name: "Product Code".to_string(),
                        field_name: Some("product_code".into()),
                        data_type: DataType::UInt32,
                        access_type: AccessType::Const.into(),
                        default_value: Some(DefaultValue::Integer(
                            config.identity.product_code as i64,
                        )),
                        pdo_mapping: PdoMappable::None,
                        ..Default::default()
                    },
                    SubDefinition {
                        sub_index: 3,
                        parameter_name: "Revision Number".to_string(),
                        field_name: Some("revision".into()),
                        data_type: DataType::UInt32,
                        access_type: AccessType::Const.into(),
                        default_value: Some(DefaultValue::Integer(
                            config.identity.revision_number as i64,
                        )),
                        pdo_mapping: PdoMappable::None,
                        ..Default::default()
                    },
                    SubDefinition {
                        sub_index: 4,
                        parameter_name: "Serial Number".to_string(),
                        field_name: Some("serial".into()),
                        data_type: DataType::UInt32,
                        access_type: AccessType::Const.into(),
                        default_value: Some(DefaultValue::Integer(0)),
                        pdo_mapping: PdoMappable::None,
                        ..Default::default()
                    },
                ],
            }),
        },
    ];

    let (create_autostart, default) = match config.autostart {
        AutoStartConfig::Disabled => (true, 0),
        AutoStartConfig::Enabled => (true, 1),
        AutoStartConfig::Unsupported => (false, 0),
    };
    if create_autostart {
        objects.push(ObjectDefinition {
            index: 0x5000,
            parameter_name: "Auto Start".to_string(),
            application_callback: false,
            object: Object::Var(VarDefinition {
                data_type: DataType::UInt8,
                access_type: AccessType::Rw.into(),
                default_value: Some(DefaultValue::Integer(default)),
                pdo_mapping: PdoMappable::None,
                persist: true,
            }),
        });
    }

    objects
}

fn pdo_objects(num_rpdo: usize, num_tpdo: usize) -> Vec<ObjectDefinition> {
    let mut objects = Vec::new();

    fn add_objects(objects: &mut Vec<ObjectDefinition>, i: usize, tx: bool) {
        let pdo_type = if tx { "TPDO" } else { "RPDO" };
        let comm_index = if tx { 0x1800 } else { 0x1400 };
        let mapping_index = if tx { 0x1A00 } else { 0x1600 };

        objects.push(ObjectDefinition {
            index: comm_index + i as u16,
            parameter_name: format!("{}{} Communication Parameter", pdo_type, i),
            application_callback: true,
            object: Object::Record(RecordDefinition {
                subs: vec![
                    SubDefinition {
                        sub_index: 1,
                        parameter_name: format!("COB-ID for {}{}", pdo_type, i),
                        field_name: None,
                        data_type: DataType::UInt32,
                        access_type: AccessType::Rw.into(),
                        default_value: None,
                        pdo_mapping: PdoMappable::None,
                        persist: true,
                    },
                    SubDefinition {
                        sub_index: 2,
                        parameter_name: format!("Transmission type for {}{}", pdo_type, i),
                        field_name: None,
                        data_type: DataType::UInt8,
                        access_type: AccessType::Rw.into(),
                        default_value: None,
                        pdo_mapping: PdoMappable::None,
                        persist: true,
                    },
                ],
            }),
        });

        let mut mapping_subs = vec![SubDefinition {
            sub_index: 0,
            parameter_name: "Valid Mappings".to_string(),
            field_name: None,
            data_type: DataType::UInt8,
            access_type: AccessType::Rw.into(),
            default_value: Some(DefaultValue::Integer(0)),
            pdo_mapping: PdoMappable::None,
            persist: true,
        }];
        for sub in 1..65 {
            mapping_subs.push(SubDefinition {
                sub_index: sub,
                parameter_name: format!("{}{} Mapping App Object {}", pdo_type, i, sub),
                field_name: None,
                data_type: DataType::UInt32,
                access_type: AccessType::Rw.into(),
                default_value: None,
                pdo_mapping: PdoMappable::None,
                persist: true,
            });
        }

        objects.push(ObjectDefinition {
            index: mapping_index + i as u16,
            parameter_name: format!("{}{} Mapping Parameters", pdo_type, i),
            application_callback: true,
            object: Object::Record(RecordDefinition { subs: mapping_subs }),
        });
    }
    for i in 0..num_rpdo {
        add_objects(&mut objects, i, false);
    }
    for i in 0..num_tpdo {
        add_objects(&mut objects, i, true);
    }
    objects
}

fn bootloader_objects(cfg: &BootloaderConfig) -> Vec<ObjectDefinition> {
    let mut objects = Vec::new();

    if cfg.sections.is_empty() {
        return objects;
    }
    objects.push(ObjectDefinition {
        index: 0x5500,
        parameter_name: "Bootloader Info".into(),
        application_callback: false,
        object: Object::Record(RecordDefinition {
            subs: vec![
                SubDefinition {
                    sub_index: 1,
                    parameter_name: "Bootloader Config".into(),
                    field_name: Some("config".into()),
                    data_type: DataType::UInt32,
                    access_type: AccessType::Ro.into(),
                    default_value: Some(0.into()),
                    pdo_mapping: PdoMappable::None,
                    persist: false,
                },
                SubDefinition {
                    sub_index: 2,
                    parameter_name: "Number of Section".into(),
                    field_name: Some("num_sections".into()),
                    data_type: DataType::UInt8,
                    access_type: AccessType::Ro.into(),
                    default_value: Some(cfg.sections.len().into()),
                    pdo_mapping: PdoMappable::None,
                    persist: false,
                },
                SubDefinition {
                    sub_index: 3,
                    parameter_name: "Reset to Bootloader Command".into(),
                    field_name: None,
                    data_type: DataType::UInt32,
                    access_type: AccessType::Wo.into(),
                    default_value: None,
                    pdo_mapping: PdoMappable::None,
                    persist: false,
                },
            ],
        }),
    });

    for (i, section) in cfg.sections.iter().enumerate() {
        objects.push(ObjectDefinition {
            index: 0x5510 + i as u16,
            parameter_name: format!("Bootloader Section {i}"),
            application_callback: true,
            object: Object::Record(RecordDefinition {
                subs: vec![
                    SubDefinition {
                        sub_index: 1,
                        parameter_name: "Mode bits".into(),
                        data_type: DataType::UInt8,
                        access_type: AccessType::Const.into(),
                        ..Default::default()
                    },
                    SubDefinition {
                        sub_index: 2,
                        parameter_name: "Section Name".into(),
                        data_type: DataType::VisibleString(0),
                        access_type: AccessType::Const.into(),
                        default_value: Some(section.name.as_str().into()),
                        ..Default::default()
                    },
                    SubDefinition {
                        sub_index: 3,
                        parameter_name: "Section Size".into(),
                        data_type: DataType::UInt32,
                        access_type: AccessType::Const.into(),
                        default_value: Some((section.size as i64).into()),
                        ..Default::default()
                    },
                    SubDefinition {
                        sub_index: 4,
                        parameter_name: "Erase Command".into(),
                        data_type: DataType::UInt8,
                        access_type: AccessType::Wo.into(),
                        ..Default::default()
                    },
                    SubDefinition {
                        sub_index: 5,
                        parameter_name: "Data".into(),
                        data_type: DataType::Domain,
                        access_type: AccessType::Rw.into(),
                        ..Default::default()
                    },
                ],
            }),
        });
    }

    objects
}

fn object_storage_objects(dev: &DeviceConfig) -> Vec<ObjectDefinition> {
    if dev.support_storage {
        vec![ObjectDefinition {
            index: 0x1010,
            parameter_name: "Object Save Command".to_string(),
            application_callback: false,
            object: Object::Array(ArrayDefinition {
                data_type: DataType::UInt32,
                access_type: AccessType::Rw.into(),
                array_size: 1,
                persist: false,
                ..Default::default()
            }),
        }]
    } else {
        vec![]
    }
}

fn default_num_rpdo() -> u8 {
    4
}
fn default_num_tpdo() -> u8 {
    4
}
fn default_true() -> bool {
    true
}

/// Options for Autostart config
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AutoStartConfig {
    /// Autostart is supported, but defaults to off
    #[default]
    Disabled,
    /// Autostart defaults to enabled
    Enabled,
    /// Autostart is not supported -- no 0x5000 object will be created
    Unsupported,
}

/// Represents the configuration parameters for a single PDO
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct PdoDefaultConfig {
    /// The COB ID this PDO will use to send/receive
    pub cob_id: u32,
    /// The COB ID is an extended 29-bit ID
    #[serde(default)]
    pub extended: bool,
    /// The node ID should be added to `cob_id`` at runtime
    pub add_node_id: bool,
    /// Indicates if this PDO is enabled
    pub enabled: bool,
    /// If set, this PDO will not respond to requests
    #[serde(default)]
    pub rtr_disabled: bool,
    /// List of mapping specifying what sub objects are mapped to this PDO
    pub mappings: Vec<PdoMapping>,
    /// Specifies when a PDO is sent or latched
    ///
    /// - 0: Sent in response to sync, but only after an application specific event (e.g. it may be
    ///   sent when the value changes, but not when it has not)
    /// - 1 - 240: Sent in response to every Nth sync
    /// - 254: Event driven (application to send it whenever it wants)
    pub transmission_type: u8,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub(crate) struct PdoDefaultConfigMapSerializer(
    #[serde(deserialize_with = "deserialize_pdo_map", default)] pub HashMap<usize, PdoDefaultConfig>,
);

impl From<PdoDefaultConfigMapSerializer> for HashMap<usize, PdoDefaultConfig> {
    fn from(value: PdoDefaultConfigMapSerializer) -> Self {
        value.0
    }
}

/// Private struct for deserializing [pdos] section of device config TOML
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct DevicePdoConfigSerializer {
    #[serde(default = "default_num_rpdo")]
    /// The number of TX PDO slots available in the device. Defaults to 4.
    pub num_tpdo: u8,
    #[serde(default = "default_num_tpdo")]
    /// The number of RX PDO slots available in the device. Defaults to 4.
    pub num_rpdo: u8,

    /// Map of default configurations for individual TPDOs
    #[serde(default)]
    pub tpdo: PdoDefaultConfigMapSerializer,
    #[serde(default)]
    pub rpdo: PdoDefaultConfigMapSerializer,
}

impl From<DevicePdoConfigSerializer> for DevicePdoConfig {
    fn from(value: DevicePdoConfigSerializer) -> Self {
        Self {
            num_tpdo: value.num_tpdo,
            num_rpdo: value.num_rpdo,
            tpdo_defaults: value.tpdo.0,
            rpdo_defaults: value.rpdo.0,
        }
    }
}

/// Device PDO configuration options
///
/// This controls how many TPDO/RPDO slots are created, and how they are configured by default
#[derive(Clone, Debug, Deserialize)]
#[serde(try_from = "DevicePdoConfigSerializer")]
pub struct DevicePdoConfig {
    /// The number of TX PDO slots available in the device. Defaults to 4.
    pub num_tpdo: u8,
    /// The number of RX PDO slots available in the device. Defaults to 4.
    pub num_rpdo: u8,

    /// Map of default configurations for individual TPDOs
    pub tpdo_defaults: HashMap<usize, PdoDefaultConfig>,
    /// Map of default configurations for individual RPDOs
    pub rpdo_defaults: HashMap<usize, PdoDefaultConfig>,
}

impl Default for DevicePdoConfig {
    fn default() -> Self {
        Self {
            num_tpdo: default_num_tpdo(),
            num_rpdo: default_num_rpdo(),
            tpdo_defaults: HashMap::new(),
            rpdo_defaults: HashMap::new(),
        }
    }
}

/// The device identity is a unique 128-bit number used for addressing the device on the bus
///
/// The configures the three hardcoded components of the identity. The serial number component of
/// the identity must be set by the application to be unique, e.g. based on a value programmed into
/// non-volatile memory or from a UID register on the MCU.
#[derive(Deserialize, Debug, Default, Clone, Copy)]
#[serde(deny_unknown_fields)]
pub struct IdentityConfig {
    /// The 32-bit vendor ID for this device
    pub vendor_id: u32,
    /// The 32-bit product code for this device
    pub product_code: u32,
    /// The 32-bit revision number for this device
    pub revision_number: u32,
}

/// Configuration object to define a programmable bootloader section
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BootloaderSection {
    /// Name of the section
    pub name: String,
    /// Size of the section
    pub size: u32,
}

/// Configuration of bootloader parameters
#[derive(Clone, Deserialize, Debug, Default)]
#[serde(deny_unknown_fields)]
pub struct BootloaderConfig {
    /// If true, this node is an application which supports resetting to a bootloader, rather than a
    /// bootloader implementation
    #[serde(default)]
    pub application: bool,
    /// List of programmable sections
    #[serde(default)]
    pub sections: Vec<BootloaderSection>,
}

#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
/// Private struct for seserializing device config files
pub struct DeviceConfig {
    /// The name describing the type of device (e.g. a model)
    pub device_name: String,

    /// Configures support for the AutoStart (0x5000) object and its default value
    ///
    /// Allowed values:
    /// - 'unsupported': No autostart object is created
    /// - 'disabled': An autostart object is created, and it defaults to disabled
    /// - 'enabled': An autostart object is created, and it defaults to enabled
    #[serde(default)]
    pub autostart: AutoStartConfig,

    /// Enables object storage commands (object 0x1010)
    ///
    /// Default: true
    #[serde(default = "default_true")]
    pub support_storage: bool,

    /// A version describing the hardware
    #[serde(default)]
    pub hardware_version: String,
    /// A version describing the software
    #[serde(default)]
    pub software_version: String,

    /// The period at which to transmit heartbeat messages in milliseconds
    #[serde(default)]
    pub heartbeat_period: u16,

    /// Configures the identity object on the device
    pub identity: IdentityConfig,

    /// Configure PDO settings
    #[serde(default)]
    pub pdos: DevicePdoConfig,

    /// Configure bootloader options
    #[serde(default)]
    pub bootloader: BootloaderConfig,

    /// A list of application specific objects to define on the device
    #[serde(default)]
    pub objects: Vec<ObjectDefinition>,
}

/// Defines a sub-object in a record
#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct SubDefinition {
    /// Sub index for the sub-object being defined
    pub sub_index: u8,
    /// A human readable name for the value stored in this sub-object
    #[serde(default)]
    pub parameter_name: String,
    /// Used to name the struct field associated with this sub object
    ///
    /// This is only applicable to record objects. If no name is provided, the default field name
    /// will be `sub[index]`, where index is the uppercase hex representation of the sub index
    #[serde(default)]
    pub field_name: Option<String>,
    /// The data type of the sub object
    pub data_type: DataType,
    /// Access permissions for the sub object
    #[serde(default)]
    pub access_type: AccessTypeDeser,
    /// The default value for the sub object
    #[serde(default)]
    pub default_value: Option<DefaultValue>,
    /// Indicates whether this sub object can be mapped to PDOs
    #[serde(default)]
    pub pdo_mapping: PdoMappable,
    /// Indicates if this sub object should be saved when the save command is sent
    #[serde(default)]
    pub persist: bool,
}

/// An enum to represent object default values
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum DefaultValue {
    /// A default value for integer fields
    Integer(i64),
    /// A default value for float fields
    Float(f64),
    /// A default value for string fields
    String(String),
}

impl From<i64> for DefaultValue {
    fn from(value: i64) -> Self {
        Self::Integer(value)
    }
}

impl From<i32> for DefaultValue {
    fn from(value: i32) -> Self {
        Self::Integer(value as i64)
    }
}

impl From<usize> for DefaultValue {
    fn from(value: usize) -> Self {
        Self::Integer(value as i64)
    }
}

impl From<f64> for DefaultValue {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

impl From<&str> for DefaultValue {
    fn from(value: &str) -> Self {
        Self::String(value.to_string())
    }
}

/// An enum representing the different types of objects which can be defined in a device config
#[derive(Deserialize, Debug, Clone)]
#[serde(tag = "object_type", rename_all = "lowercase")]
pub enum Object {
    /// A var object is just a single value
    Var(VarDefinition),
    /// An array object is an array of values, all with the same type
    Array(ArrayDefinition),
    /// A record is a collection of sub objects all with different types
    Record(RecordDefinition),
}

/// Descriptor for a var object
#[derive(Default, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct VarDefinition {
    /// Indicates the type of data stored in the object
    pub data_type: DataType,
    /// Indicates how this object can be accessed
    pub access_type: AccessTypeDeser,
    /// The default value for this object
    pub default_value: Option<DefaultValue>,
    /// Determines which if type of PDO this object can me mapped to
    #[serde(default)]
    pub pdo_mapping: PdoMappable,
    /// Indicates that this object should be saved
    #[serde(default)]
    pub persist: bool,
}

/// Descriptor for an array object
#[derive(Default, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct ArrayDefinition {
    /// The datatype of array fields
    pub data_type: DataType,
    /// Access type for all array fields
    pub access_type: AccessTypeDeser,
    /// The number of elements in the array
    pub array_size: usize,
    /// Default values for all array fields
    pub default_value: Option<Vec<DefaultValue>>,
    #[serde(default)]
    /// Whether fields in this array can be mapped to PDOs
    pub pdo_mapping: PdoMappable,
    #[serde(default)]
    /// Whether this array should be saved to flash on command
    pub persist: bool,
}

/// Descriptor for a record object
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct RecordDefinition {
    /// The sub object definitions for this record object
    #[serde(default)]
    pub subs: Vec<SubDefinition>,
}

/// Descriptor for a domain object
///
/// Not yet implemented
#[derive(Clone, Copy, Deserialize, Debug)]
pub struct DomainDefinition {}

/// Descriptor for an object in the object dictionary
#[derive(Deserialize, Debug, Clone)]
pub struct ObjectDefinition {
    /// The index of the object
    pub index: u16,
    /// A human readable name to describe the contents of the object
    #[serde(default)]
    pub parameter_name: String,
    #[serde(default)]
    /// If true, this object is implemented by an application callback, and no storage will be
    /// allocated for it in the object dictionary.
    pub application_callback: bool,
    /// The descriptor for the object
    #[serde(flatten)]
    pub object: Object,
}

impl ObjectDefinition {
    /// Get the object code specifying the type of this object
    pub fn object_code(&self) -> ObjectCode {
        match self.object {
            Object::Var(_) => ObjectCode::Var,
            Object::Array(_) => ObjectCode::Array,
            Object::Record(_) => ObjectCode::Record,
        }
    }
}

impl DeviceConfig {
    /// Try to read a device config from a file
    pub fn load(config_path: impl AsRef<std::path::Path>) -> Result<Self, LoadError> {
        let config_str = std::fs::read_to_string(&config_path).context(IoSnafu)?;
        Self::load_from_str(&config_str)
    }

    /// Try to read a config from a &str
    pub fn load_from_str(config_str: &str) -> Result<Self, LoadError> {
        let mut config: DeviceConfig = toml::from_str(config_str).context(TomlParsingSnafu)?;

        // Add mandatory objects to the config
        config.objects.extend(mandatory_objects(&config));
        config
            .objects
            .extend(bootloader_objects(&config.bootloader));
        config.objects.extend(pdo_objects(
            config.pdos.num_rpdo as usize,
            config.pdos.num_tpdo as usize,
        ));
        config.objects.extend(object_storage_objects(&config));

        Self::validate_unique_indices(&config.objects)?;

        Ok(config)
    }

    fn validate_unique_indices(objects: &[ObjectDefinition]) -> Result<(), LoadError> {
        let mut found_indices = HashMap::new();
        for obj in objects {
            if found_indices.contains_key(&obj.index) {
                return DuplicateObjectIdsSnafu { id: obj.index }.fail();
            }
            found_indices.insert(&obj.index, ());

            if let Object::Record(record) = &obj.object {
                let mut found_subs = HashMap::new();
                for sub in &record.subs {
                    if found_subs.contains_key(&sub.sub_index) {
                        return DuplicateSubObjectsSnafu {
                            index: obj.index,
                            sub: sub.sub_index,
                        }
                        .fail();
                    }
                    found_subs.insert(&sub.sub_index, ());
                }
            }
        }

        Ok(())
    }
}

/// A newtype on AccessType to implement serialization
#[derive(Clone, Copy, Debug, Default)]
pub struct AccessTypeDeser(pub AccessType);
impl<'de> serde::Deserialize<'de> for AccessTypeDeser {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.to_lowercase().as_str() {
            "ro" => Ok(AccessTypeDeser(AccessType::Ro)),
            "rw" => Ok(AccessTypeDeser(AccessType::Rw)),
            "wo" => Ok(AccessTypeDeser(AccessType::Wo)),
            "const" => Ok(AccessTypeDeser(AccessType::Const)),
            _ => Err(D::Error::custom(format!(
                "Invalid access type: {} (allowed: 'ro', 'rw', 'wo', or 'const')",
                s
            ))),
        }
    }
}
impl From<AccessType> for AccessTypeDeser {
    fn from(access_type: AccessType) -> Self {
        AccessTypeDeser(access_type)
    }
}

/// A type to represent data_type fields in a device config
///
/// This is similar, but slightly different from the DataType defined in `zencan_common`
#[derive(Clone, Copy, Debug, Default)]
#[allow(missing_docs)]
pub enum DataType {
    Boolean,
    Int8,
    Int16,
    Int24,
    Int32,
    Int64,
    #[default]
    UInt8,
    UInt16,
    UInt24,
    UInt32,
    UInt64,
    Real32,
    Real64,
    VisibleString(usize),
    OctetString(usize),
    UnicodeString(usize),
    TimeOfDay,
    TimeDifference,
    Domain,
}

impl DataType {
    /// Returns true if the type is one of the stringy types
    pub fn is_str(&self) -> bool {
        matches!(
            self,
            DataType::VisibleString(_) | DataType::OctetString(_) | DataType::UnicodeString(_)
        )
    }

    /// Get the storage size of the data type
    pub fn size(&self) -> usize {
        match self {
            DataType::Boolean => 1,
            DataType::Int8 => 1,
            DataType::Int16 => 2,
            DataType::Int24 => 3,
            DataType::Int32 => 4,
            DataType::Int64 => 8,
            DataType::UInt8 => 1,
            DataType::UInt16 => 2,
            DataType::UInt24 => 3,
            DataType::UInt32 => 4,
            DataType::UInt64 => 8,
            DataType::Real32 => 4,
            DataType::Real64 => 8,
            DataType::VisibleString(size) => *size,
            DataType::OctetString(size) => *size,
            DataType::UnicodeString(size) => *size,
            DataType::TimeOfDay => 4,
            DataType::TimeDifference => 4,
            DataType::Domain => 0, // Domain size is variable
        }
    }
}

impl<'de> serde::Deserialize<'de> for DataType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let re_visiblestring = regex::Regex::new(r"^visiblestring\((\d+)\)$").unwrap();
        let re_octetstring = regex::Regex::new(r"^octetstring\((\d+)\)$").unwrap();
        let re_unicodestring = regex::Regex::new(r"^unicodestring\((\d+)\)$").unwrap();

        let s = String::deserialize(deserializer)?.to_lowercase();
        if s == "boolean" {
            Ok(DataType::Boolean)
        } else if s == "int8" {
            Ok(DataType::Int8)
        } else if s == "int16" {
            Ok(DataType::Int16)
        } else if s == "int24" {
            Ok(DataType::Int24)
        } else if s == "int32" {
            Ok(DataType::Int32)
        } else if s == "int64" {
            Ok(DataType::Int64)
        } else if s == "uint8" {
            Ok(DataType::UInt8)
        } else if s == "uint16" {
            Ok(DataType::UInt16)
        } else if s == "uint24" {
            Ok(DataType::UInt24)
        } else if s == "uint32" {
            Ok(DataType::UInt32)
        } else if s == "uint64" {
            Ok(DataType::UInt64)
        } else if s == "real32" {
            Ok(DataType::Real32)
        } else if s == "real64" {
            Ok(DataType::Real64)
        } else if let Some(caps) = re_visiblestring.captures(&s) {
            let size: usize = caps[1].parse().map_err(|_| {
                D::Error::custom(format!("Invalid size for VisibleString: {}", &caps[1]))
            })?;
            Ok(DataType::VisibleString(size))
        } else if let Some(caps) = re_octetstring.captures(&s) {
            let size: usize = caps[1].parse().map_err(|_| {
                D::Error::custom(format!("Invalid size for OctetString: {}", &caps[1]))
            })?;
            Ok(DataType::OctetString(size))
        } else if let Some(caps) = re_unicodestring.captures(&s) {
            let size: usize = caps[1].parse().map_err(|_| {
                D::Error::custom(format!("Invalid size for UnicodeString: {}", &caps[1]))
            })?;
            Ok(DataType::UnicodeString(size))
        } else if s == "timeofday" {
            Ok(DataType::TimeOfDay)
        } else if s == "timedifference" {
            Ok(DataType::TimeDifference)
        } else if s == "domain" {
            Ok(DataType::Domain)
        } else {
            Err(D::Error::custom(format!("Invalid data type: {}", s)))
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::device_config::{DeviceConfig, LoadError};
    use assertables::assert_contains;
    #[test]
    fn test_duplicate_objects_errors() {
        const TOML: &str = r#"
            device_name = "test"
            [identity]
            vendor_id = 0
            product_code = 1
            revision_number = 2

            [[objects]]
            index = 0x2000
            parameter_name = "Test1"
            object_type = "var"
            data_type = "int16"
            access_type = "rw"

            [[objects]]
            index = 0x2000
            parameter_name = "Duplicate"
            object_type = "record"
        "#;

        let result = DeviceConfig::load_from_str(TOML);

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, LoadError::DuplicateObjectIds { id: 0x2000 }));
        assert_contains!(
            "Multiple definitions for object with index 0x2000",
            err.to_string().as_str()
        );
    }

    #[test]
    fn test_duplicate_sub_object_errors() {
        const TOML: &str = r#"
            device_name = "test"
            [identity]
            vendor_id = 0
            product_code = 1
            revision_number = 2


            [[objects]]
            index = 0x2000
            parameter_name = "Duplicate"
            object_type = "record"
            [[objects.subs]]
            sub_index = 1
            parameter_name = "Test1"
            data_type = "int16"
            access_type = "rw"
            [[objects.subs]]
            sub_index = 1
            parameter_name = "RepeatedTest1"
            data_type = "int16"
            access_type = "rw"
        "#;

        let result = DeviceConfig::load_from_str(TOML);

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(
            err,
            LoadError::DuplicateSubObjects {
                index: 0x2000,
                sub: 1
            }
        ));
        assert_contains!(
            "Multiple definitions of sub index 1 on object 0x2000",
            err.to_string().as_str()
        );
    }
}