ocpp-kit 0.5.0

Open Charge Point Protocol (OCPP 1.6J, 2.0.1, 2.1) toolkit for Rust: typed messages, OCPP-J framing, a sans-I/O protocol engine, and transports for charging stations, CSMS and local controllers.
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
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
//! The OCPP 2.x device model: components, variables, attributes and monitors.
//!
//! The device model is the part of OCPP 2.x that replaced 1.6's flat configuration keys, and
//! it is where most of the work of `GetVariables`, `SetVariables`, `GetBaseReport`,
//! `GetReport`, `SetVariableMonitoring` and `NotifyEvent` lives. The registry here is
//! version-neutral — 2.0.1 and 2.1 model it identically — and converts into either version's
//! generated types.
//!
//! ```
//! use ocpp_kit::station::device_model::{
//!     Attribute, DataType, DeviceModel, Mutability, SetStatus, VariableSpec,
//! };
//!
//! let mut model = DeviceModel::with_defaults();
//! model.declare(
//!     "SampleCtrlr",
//!     VariableSpec::new("Enabled", DataType::Boolean)
//!         .mutability(Mutability::ReadWrite)
//!         .value("true"),
//! );
//!
//! assert_eq!(model.set("SampleCtrlr", "Enabled", Attribute::Actual, "false"), SetStatus::Accepted);
//! // A value the declared type cannot hold is rejected, not stored.
//! assert_eq!(model.set("SampleCtrlr", "Enabled", Attribute::Actual, "yes"), SetStatus::Rejected);
//! ```

use alloc::borrow::ToOwned;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use alloc::vec::Vec;

use crate::types::Decimal;
use core::fmt;

/// Which attribute of a variable is meant.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Attribute {
    /// The value in effect. The default when a request omits the attribute.
    #[default]
    Actual,
    /// The value the operator wants to reach.
    Target,
    /// The lower bound of the accepted range.
    MinSet,
    /// The upper bound of the accepted range.
    MaxSet,
}

impl Attribute {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Attribute::Actual => "Actual",
            Attribute::Target => "Target",
            Attribute::MinSet => "MinSet",
            Attribute::MaxSet => "MaxSet",
        }
    }

    /// Parses a wire value.
    #[must_use]
    pub fn from_wire(value: &str) -> Option<Self> {
        Some(match value {
            "Actual" => Attribute::Actual,
            "Target" => Attribute::Target,
            "MinSet" => Attribute::MinSet,
            "MaxSet" => Attribute::MaxSet,
            _ => return None,
        })
    }
}

impl fmt::Display for Attribute {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Whether a variable can be written.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mutability {
    /// Reads only.
    #[default]
    ReadOnly,
    /// Writes only — passwords and keys, which are never reported back.
    WriteOnly,
    /// Reads and writes.
    ReadWrite,
}

impl Mutability {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Mutability::ReadOnly => "ReadOnly",
            Mutability::WriteOnly => "WriteOnly",
            Mutability::ReadWrite => "ReadWrite",
        }
    }

    /// Whether the value may be reported.
    #[must_use]
    pub const fn readable(self) -> bool {
        !matches!(self, Mutability::WriteOnly)
    }

    /// Whether the value may be written.
    #[must_use]
    pub const fn writable(self) -> bool {
        !matches!(self, Mutability::ReadOnly)
    }
}

/// The `DataEnumType` of a variable — what its string value has to parse as.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataType {
    /// Free text.
    #[default]
    String,
    /// A decimal number.
    Decimal,
    /// A whole number.
    Integer,
    /// An RFC 3339 timestamp.
    DateTime,
    /// `true` or `false`.
    Boolean,
    /// One of `values_list`.
    OptionList,
    /// A comma-separated subset of `values_list`.
    SequenceList,
    /// A comma-separated list of values from `values_list`, in any order.
    MemberList,
}

impl DataType {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            DataType::String => "string",
            DataType::Decimal => "decimal",
            DataType::Integer => "integer",
            DataType::DateTime => "dateTime",
            DataType::Boolean => "boolean",
            DataType::OptionList => "OptionList",
            DataType::SequenceList => "SequenceList",
            DataType::MemberList => "MemberList",
        }
    }

    /// Parses a `DataEnumType` value, as the schemas and the appendix spell it.
    #[must_use]
    pub fn from_wire(value: &str) -> Option<Self> {
        Some(match value {
            "string" => DataType::String,
            "decimal" => DataType::Decimal,
            "integer" => DataType::Integer,
            "dateTime" => DataType::DateTime,
            "boolean" => DataType::Boolean,
            "OptionList" => DataType::OptionList,
            "SequenceList" => DataType::SequenceList,
            "MemberList" => DataType::MemberList,
            _ => return None,
        })
    }

    /// Whether `value` is a valid instance of this type, given the declared `values_list`.
    #[must_use]
    pub fn accepts(self, value: &str, values_list: &[String]) -> bool {
        match self {
            DataType::String => true,
            DataType::Boolean => matches!(value, "true" | "false"),
            DataType::Integer => value.parse::<i64>().is_ok(),
            DataType::Decimal => value.parse::<Decimal>().is_ok(),
            DataType::DateTime => crate::types::DateTime::parse(value).is_ok(),
            DataType::OptionList => {
                values_list.is_empty() || values_list.iter().any(|v| v == value)
            }
            DataType::SequenceList | DataType::MemberList => {
                values_list.is_empty()
                    || value
                        .split(',')
                        .map(str::trim)
                        .all(|item| values_list.iter().any(|v| v == item))
            }
        }
    }
}

/// Identifies one component instance.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ComponentKey {
    /// Component name, e.g. `OCPPCommCtrlr`.
    pub name: String,
    /// Instance discriminator, when several instances exist.
    pub instance: Option<String>,
    /// EVSE the component belongs to.
    pub evse: Option<u32>,
    /// Connector within the EVSE.
    pub connector: Option<u32>,
}

impl ComponentKey {
    /// A component with no instance and no EVSE.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            instance: None,
            evse: None,
            connector: None,
        }
    }

    /// Adds an instance discriminator.
    #[must_use]
    pub fn instance(mut self, instance: impl Into<String>) -> Self {
        self.instance = Some(instance.into());
        self
    }

    /// Binds the component to an EVSE, and optionally to a connector.
    #[must_use]
    pub fn evse(mut self, evse: u32, connector: Option<u32>) -> Self {
        self.evse = Some(evse);
        self.connector = connector;
        self
    }
}

impl ComponentKey {
    /// Whether this component answers a `GetReport` `componentVariable.component` criterion.
    ///
    /// B08.FR.22–25 (2.0.1 edition 4): the name must match; each of instance, EVSE and
    /// connector narrows the match only when the request gives it — no `evse.id` is every EVSE
    /// and the station level (B08.FR.23), an `evse.id` without a connector is every connector
    /// of that EVSE (B08.FR.22), and no instance is every instance or none (B08.FR.25).
    #[must_use]
    pub fn matches(&self, criterion: &ComponentKey) -> bool {
        self.name == criterion.name
            && criterion
                .instance
                .as_ref()
                .is_none_or(|instance| self.instance.as_ref() == Some(instance))
            && criterion.evse.is_none_or(|evse| self.evse == Some(evse))
            && criterion
                .connector
                .is_none_or(|connector| self.connector == Some(connector))
    }
}

impl From<&str> for ComponentKey {
    fn from(name: &str) -> Self {
        ComponentKey::new(name)
    }
}

impl fmt::Display for ComponentKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.name)?;
        if let Some(instance) = &self.instance {
            write!(f, "({instance})")?;
        }
        if let Some(evse) = self.evse {
            write!(f, "@evse{evse}")?;
            if let Some(connector) = self.connector {
                write!(f, ".{connector}")?;
            }
        }
        Ok(())
    }
}

/// Identifies one variable within a component.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VariableKey {
    /// Variable name, e.g. `HeartbeatInterval`.
    pub name: String,
    /// Instance discriminator.
    pub instance: Option<String>,
}

impl VariableKey {
    /// A variable with no instance.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            instance: None,
        }
    }

    /// Adds an instance discriminator — how `MessageAttempts[TransactionEvent]` is modelled.
    #[must_use]
    pub fn instance(mut self, instance: impl Into<String>) -> Self {
        self.instance = Some(instance.into());
        self
    }
}

impl From<&str> for VariableKey {
    fn from(name: &str) -> Self {
        VariableKey::new(name)
    }
}

impl fmt::Display for VariableKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.name)?;
        if let Some(instance) = &self.instance {
            write!(f, "[{instance}]")?;
        }
        Ok(())
    }
}

/// How a variable is declared.
#[derive(Clone, Debug)]
pub struct VariableSpec {
    key: VariableKey,
    data_type: DataType,
    mutability: Mutability,
    unit: Option<String>,
    values_list: Vec<String>,
    min_limit: Option<Decimal>,
    max_limit: Option<Decimal>,
    persistent: bool,
    constant: bool,
    /// Whether a write only takes effect after a reboot — the 2.x equivalent of 1.6's
    /// `RebootRequired` configuration status.
    reboot_required: bool,
    /// The attribute types this variable supports, whether or not they have a value.
    ///
    /// B07.FR.11: "All attribute types of a variable, that are supported by the Charging
    /// Station, SHALL be reported, **even if they have no value (are unset)**" — so support
    /// and value are two different facts and the model has to keep them apart.
    supported: BTreeSet<Attribute>,
    values: BTreeMap<Attribute, String>,
}

impl VariableSpec {
    /// Declares a variable.
    #[must_use]
    pub fn new(name: impl Into<String>, data_type: DataType) -> Self {
        Self {
            key: VariableKey::new(name),
            data_type,
            mutability: Mutability::ReadOnly,
            unit: None,
            values_list: Vec::new(),
            min_limit: None,
            max_limit: None,
            persistent: true,
            constant: false,
            reboot_required: false,
            // Every variable has an Actual; the rest are declared as they are added.
            supported: BTreeSet::from([Attribute::Actual]),
            values: BTreeMap::new(),
        }
    }

    /// Adds an instance discriminator.
    #[must_use]
    pub fn instance(mut self, instance: impl Into<String>) -> Self {
        self.key.instance = Some(instance.into());
        self
    }

    /// Sets whether the variable can be written.
    #[must_use]
    pub fn mutability(mut self, mutability: Mutability) -> Self {
        self.mutability = mutability;
        self
    }

    /// Sets the unit, e.g. `s` or `Wh`.
    #[must_use]
    pub fn unit(mut self, unit: impl Into<String>) -> Self {
        self.unit = Some(unit.into());
        self
    }

    /// Restricts the accepted values.
    #[must_use]
    pub fn values(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.values_list = values.into_iter().map(Into::into).collect();
        self
    }

    /// Restricts a numeric variable to a range.
    ///
    /// The bounds are exact decimals, so a limit of `0.1` rejects exactly what it says it
    /// rejects — the device model's values are decimal *text* on the wire, and comparing
    /// them through a float is how a conforming value comes to be refused.
    #[must_use]
    pub fn limits(mut self, min: Option<Decimal>, max: Option<Decimal>) -> Self {
        self.min_limit = min;
        self.max_limit = max;
        self
    }

    /// Marks the variable as one a write only takes effect on after a reboot.
    #[must_use]
    pub fn reboot_required(mut self) -> Self {
        self.reboot_required = true;
        self
    }

    /// Marks the variable as constant — reported, never written, never persisted.
    #[must_use]
    pub fn constant(mut self) -> Self {
        self.constant = true;
        self.mutability = Mutability::ReadOnly;
        self
    }

    /// Sets the `Actual` value.
    #[must_use]
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.values.insert(Attribute::Actual, value.into());
        self
    }

    /// Sets one attribute's value, declaring it supported.
    #[must_use]
    pub fn attribute(mut self, attribute: Attribute, value: impl Into<String>) -> Self {
        self.supported.insert(attribute);
        self.values.insert(attribute, value.into());
        self
    }

    /// Declares an attribute type supported without giving it a value (B07.FR.11).
    ///
    /// A `MaxSet` a station honours but has not been given is still something the CSMS needs
    /// to know it may write.
    #[must_use]
    pub fn supports(mut self, attribute: Attribute) -> Self {
        self.supported.insert(attribute);
        self
    }

    /// The attribute types this variable supports.
    pub fn supported(&self) -> impl Iterator<Item = Attribute> + '_ {
        self.supported.iter().copied()
    }
}

/// The result of a `GetVariables` entry (`GetVariableStatusEnumType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum GetStatus {
    /// The value is returned.
    Accepted,
    /// No such component.
    UnknownComponent,
    /// No such variable in that component.
    UnknownVariable,
    /// The variable exists but not that attribute.
    NotSupportedAttributeType,
    /// The variable is write-only.
    Rejected,
}

/// The result of a `SetVariables` entry (`SetVariableStatusEnumType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "a rejected write left the variable unchanged; the CSMS has to be told which \
              status it got, not `Accepted`"]
pub enum SetStatus {
    /// Stored and in effect.
    Accepted,
    /// Stored, but only in effect after a reboot.
    RebootRequired,
    /// No such component.
    UnknownComponent,
    /// No such variable in that component.
    UnknownVariable,
    /// The variable exists but not that attribute.
    NotSupportedAttributeType,
    /// The variable is read-only, or the value does not satisfy its declared type or limits.
    Rejected,
}

/// One line of a `NotifyReport` / `GetBaseReport` inventory.
#[derive(Clone, Debug, PartialEq)]
pub struct ReportDatum {
    /// Which component.
    pub component: ComponentKey,
    /// Which variable.
    pub variable: VariableKey,
    /// The variable's attributes and their values. A write-only variable reports its
    /// attributes with no value.
    pub attributes: Vec<(Attribute, Mutability, Option<String>)>,
    /// Whether the variable can be written.
    pub mutability: Mutability,
    /// The declared type.
    pub data_type: DataType,
    /// The unit, if any.
    pub unit: Option<String>,
    /// The accepted values, if restricted.
    pub values_list: Vec<String>,
    /// The lower numeric bound, if any.
    pub min_limit: Option<Decimal>,
    /// The upper numeric bound, if any.
    pub max_limit: Option<Decimal>,
    /// Whether the value survives a reboot.
    pub persistent: bool,
    /// Whether the value can never change.
    pub constant: bool,
}

/// Which slice of the inventory a report covers (`ReportBaseEnumType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReportBase {
    /// Every component, variable and attribute, with all characteristics.
    FullInventory,
    /// Only what the Charging Station supports configuring.
    ConfigurationInventory,
    /// Only what is needed to summarise the station.
    SummaryInventory,
}

/// The registry of components and variables.
#[derive(Clone, Debug, Default)]
pub struct DeviceModel {
    components: BTreeMap<ComponentKey, BTreeMap<VariableKey, VariableSpec>>,
}

impl DeviceModel {
    /// An empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// A registry pre-populated with the standard controllers and the variables an OCPP 2.x
    /// Charging Station must expose to pass the Core certification profile.
    ///
    /// Values are placeholders; override them with [`declare`](Self::declare).
    #[must_use]
    pub fn with_defaults() -> Self {
        let mut model = Self::new();
        for (component, spec) in defaults() {
            model.declare(component, spec);
        }
        model
    }

    /// Declares every variable the specification associates with one standardized component.
    ///
    /// The appendix's list is a *vocabulary*, not a requirement — a Charging Station
    /// implements the part of it that it actually has. Declaring a component from the
    /// catalogue gets the names, data types and units right for free; override the ones you
    /// mean to support with [`declare`](Self::declare) and remove the rest.
    ///
    /// Returns how many variables were declared, or `None` if the component is not one the
    /// specification standardizes.
    ///
    /// The appendix gives names, data types and units. It does *not* give mutability, so a
    /// variable declared this way starts read-only until you say otherwise.
    ///
    /// ```
    /// use ocpp_kit::station::device_model::{
    ///     Attribute, DataType, DeviceModel, Mutability, SetStatus, VariableSpec,
    /// };
    ///
    /// let mut model = DeviceModel::new();
    /// let declared = model.declare_standard("OCPPCommCtrlr").expect("a standard component");
    /// assert!(declared > 0);
    ///
    /// // Supported but not yet set, so it reads back empty (B06.FR.13) and refuses a write.
    /// assert_eq!(
    ///     model.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Actual),
    ///     Ok(String::new()),
    /// );
    /// assert_eq!(
    ///     model.set("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Actual, "300"),
    ///     SetStatus::Rejected,
    /// );
    ///
    /// // Say which ones the station actually lets the CSMS write.
    /// model.declare(
    ///     "OCPPCommCtrlr",
    ///     VariableSpec::new("HeartbeatInterval", DataType::Integer)
    ///         .mutability(Mutability::ReadWrite)
    ///         .value("300"),
    /// );
    /// assert_eq!(
    ///     model.set("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Actual, "600"),
    ///     SetStatus::Accepted,
    /// );
    /// // …and the declared type is still enforced.
    /// assert_eq!(
    ///     model.set("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Actual, "soon"),
    ///     SetStatus::Rejected,
    /// );
    /// ```
    pub fn declare_standard(&mut self, component: &str) -> Option<usize> {
        let standard = crate::standard::components::component(component)?;
        let key = ComponentKey::new(standard.name);
        let mut declared = 0;
        for variable in standard.variables {
            let data_type = variable
                .data_type
                .and_then(DataType::from_wire)
                .unwrap_or(DataType::String);
            let mut spec = VariableSpec::new(variable.name, data_type);
            if let Some(instance) = variable.instance {
                spec = spec.instance(instance);
            }
            if let Some(unit) = variable.unit {
                spec = spec.unit(unit);
            }
            // The appendix's `(Attribute)` suffix names an attribute of the variable, not a
            // variable of its own, so it becomes a *supported* attribute rather than a new
            // entry. Supported and unset, not supported with an empty value: B07.FR.11 keeps
            // those apart, `report` lists what is supported, and B06.FR.13 makes an unset one
            // read back as an empty string anyway.
            match variable.attribute.and_then(Attribute::from_wire) {
                Some(attribute) if attribute != Attribute::Actual => {
                    if let Some(existing) = self
                        .components
                        .get_mut(&key)
                        .and_then(|variables| variables.get_mut(&spec.key))
                    {
                        existing.supported.insert(attribute);
                        continue;
                    }
                    spec = spec.supports(attribute);
                }
                _ => {}
            }
            self.declare(key.clone(), spec);
            declared += 1;
        }
        Some(declared)
    }

    /// Declares (or replaces) a variable.
    pub fn declare(&mut self, component: impl Into<ComponentKey>, spec: VariableSpec) {
        self.components
            .entry(component.into())
            .or_default()
            .insert(spec.key.clone(), spec);
    }

    /// How many variables are declared.
    #[must_use]
    pub fn len(&self) -> usize {
        self.components.values().map(BTreeMap::len).sum()
    }

    /// Whether the registry is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Every declared component.
    pub fn components(&self) -> impl Iterator<Item = &ComponentKey> {
        self.components.keys()
    }

    /// Reads one attribute.
    pub fn get(
        &self,
        component: impl Into<ComponentKey>,
        variable: impl Into<VariableKey>,
        attribute: Attribute,
    ) -> Result<String, GetStatus> {
        let component = component.into();
        let variable = variable.into();
        let Some(variables) = self.components.get(&component) else {
            return Err(GetStatus::UnknownComponent);
        };
        let Some(spec) = variables.get(&variable) else {
            return Err(GetStatus::UnknownVariable);
        };
        // B06.FR.09 — a WriteOnly variable is `Rejected`, not returned.
        if !spec.mutability.readable() {
            return Err(GetStatus::Rejected);
        }
        // B06.FR.08 reserves `NotSupportedAttributeType` for an attribute type that is
        // *unknown* for this variable. Support and value are two facts (B07.FR.11), so an
        // attribute that is supported but unset is not "not supported".
        if !spec.supported.contains(&attribute) {
            return Err(GetStatus::NotSupportedAttributeType);
        }
        // B06.FR.13 names this case exactly: "the Charging Station has no attributeValue for
        // the requested attributeType … SHALL return an empty string as attributeValue. Note:
        // this can happen, for example, when the attributeType Target has not yet been set,
        // even though it is supported."
        Ok(spec.values.get(&attribute).cloned().unwrap_or_default())
    }

    /// Writes one attribute, enforcing mutability, the declared type and the declared limits.
    pub fn set(
        &mut self,
        component: impl Into<ComponentKey>,
        variable: impl Into<VariableKey>,
        attribute: Attribute,
        value: &str,
    ) -> SetStatus {
        let component = component.into();
        let variable = variable.into();
        let Some(variables) = self.components.get_mut(&component) else {
            return SetStatus::UnknownComponent;
        };
        let Some(spec) = variables.get_mut(&variable) else {
            return SetStatus::UnknownVariable;
        };
        if !spec.mutability.writable() || spec.constant {
            return SetStatus::Rejected;
        }
        // B05.FR.06 — as for reads, `NotSupportedAttributeType` means the attribute type is
        // unknown for this variable, not that it happens to have no value yet.
        if !spec.supported.contains(&attribute) {
            return SetStatus::NotSupportedAttributeType;
        }
        if !spec.data_type.accepts(value, &spec.values_list) {
            return SetStatus::Rejected;
        }
        if matches!(spec.data_type, DataType::Integer | DataType::Decimal) {
            if let Ok(number) = value.parse::<Decimal>() {
                if spec.min_limit.is_some_and(|min| number < min)
                    || spec.max_limit.is_some_and(|max| number > max)
                {
                    return SetStatus::Rejected;
                }
            }
        }
        spec.values.insert(attribute, value.to_owned());
        if spec.reboot_required {
            SetStatus::RebootRequired
        } else {
            SetStatus::Accepted
        }
    }

    /// Builds an inventory report.
    ///
    /// `component_filter` and `variable_filter` implement `GetReport`'s
    /// `componentVariable` criteria; pass `None` for `GetBaseReport`.
    #[must_use]
    pub fn report(
        &self,
        base: ReportBase,
        component_filter: Option<&str>,
        variable_filter: Option<&str>,
    ) -> Vec<ReportDatum> {
        let criterion = component_filter.map(ComponentKey::new);
        self.report_matching(base, criterion.as_ref(), variable_filter)
    }

    /// As [`report`](Self::report), with a full `component` criterion: instance, EVSE and
    /// connector narrow the match where the `GetReportRequest` gives them
    /// ([`ComponentKey::matches`], B08.FR.22–25).
    #[must_use]
    pub fn report_matching(
        &self,
        base: ReportBase,
        component_filter: Option<&ComponentKey>,
        variable_filter: Option<&str>,
    ) -> Vec<ReportDatum> {
        let mut out = Vec::new();
        for (component, variables) in &self.components {
            if component_filter.is_some_and(|criterion| !component.matches(criterion)) {
                continue;
            }
            for (variable, spec) in variables {
                if variable_filter.is_some_and(|name| name != variable.name) {
                    continue;
                }
                let include = match base {
                    ReportBase::FullInventory => true,
                    // B07.FR.07: "all component-variables that can be set by the operator".
                    ReportBase::ConfigurationInventory => spec.mutability.writable(),
                    // B07.FR.09 is specific, and it is not "the interesting ones": the
                    // availability of the Charging Station, its EVSEs and its Connectors,
                    // plus the condition variables of anything in an abnormal state.
                    ReportBase::SummaryInventory => is_summary_variable(&variable.name),
                };
                if !include {
                    continue;
                }
                out.push(ReportDatum {
                    component: component.clone(),
                    variable: variable.clone(),
                    // B07.FR.11: every *supported* attribute type is reported, with or
                    // without a value; B07.FR.03: a WriteOnly variable's value is not.
                    attributes: spec
                        .supported
                        .iter()
                        .map(|attribute| {
                            let value = spec
                                .mutability
                                .readable()
                                .then(|| spec.values.get(attribute).cloned())
                                .flatten();
                            (*attribute, spec.mutability, value)
                        })
                        .collect(),
                    mutability: spec.mutability,
                    data_type: spec.data_type,
                    unit: spec.unit.clone(),
                    values_list: spec.values_list.clone(),
                    min_limit: spec.min_limit,
                    max_limit: spec.max_limit,
                    persistent: spec.persistent,
                    constant: spec.constant,
                });
            }
        }
        out
    }

    /// Splits a report into `NotifyReport`-sized pages.
    ///
    /// A full inventory does not fit in one message, so 2.x pages it with `seqNo` and `tbc`.
    /// Each returned page is `(seq_no, to_be_continued, data)`.
    #[must_use]
    pub fn paginate(data: &[ReportDatum], per_page: usize) -> Vec<(i32, bool, Vec<ReportDatum>)> {
        let per_page = per_page.max(1);
        let total = data.len().div_ceil(per_page).max(1);
        let mut pages = Vec::with_capacity(total);
        let mut chunks = data.chunks(per_page).peekable();
        let mut seq = 0;
        if chunks.peek().is_none() {
            return alloc::vec![(0, false, Vec::new())];
        }
        while let Some(chunk) = chunks.next() {
            pages.push((seq, chunks.peek().is_some(), chunk.to_vec()));
            seq += 1;
        }
        pages
    }
}

/// Whether a variable belongs in a `SummaryInventory` report (B07.FR.09).
///
/// The specification enumerates them: `AvailabilityState` for the Charging Station, each EVSE
/// and each Connector, and — "for all Components in an abnormal State" — the `Active`,
/// `Problem`, `Tripped`, `Overload` and `Fallback` variables. A summary that instead guessed
/// from mutability would report the heartbeat interval and omit the one thing the CSMS asked
/// for.
fn is_summary_variable(name: &str) -> bool {
    matches!(
        name,
        "AvailabilityState" | "Active" | "Problem" | "Tripped" | "Overload" | "Fallback"
    )
}

/// The standard controllers and the variables a Core-profile station must expose.
///
/// Trimmed to the ones the protocol itself reads — the engine's timeouts, the retry
/// schedule, the heartbeat interval, the security profile — plus the identifying constants.
#[allow(clippy::too_many_lines)]
fn defaults() -> Vec<(ComponentKey, VariableSpec)> {
    use DataType::{Boolean, Integer, String as Str};
    let seconds = |name: &str| VariableSpec::new(name, Integer).unit("s");
    alloc::vec![
        // --- OCPPCommCtrlr: everything the RPC layer is parameterised by ----------
        (
            ComponentKey::new("OCPPCommCtrlr"),
            seconds("HeartbeatInterval")
                .mutability(Mutability::ReadWrite)
                .value("300"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            seconds("MessageTimeout").instance("Default").value("30"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            VariableSpec::new("MessageAttempts", Integer)
                .instance("TransactionEvent")
                .mutability(Mutability::ReadWrite)
                .value("3"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            seconds("MessageAttemptInterval")
                .instance("TransactionEvent")
                .mutability(Mutability::ReadWrite)
                .value("60"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            seconds("WebSocketPingInterval")
                .mutability(Mutability::ReadWrite)
                .value("60"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            seconds("RetryBackOffWaitMinimum")
                .mutability(Mutability::ReadWrite)
                .value("10"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            seconds("RetryBackOffRandomRange")
                .mutability(Mutability::ReadWrite)
                .value("10"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            VariableSpec::new("RetryBackOffRepeatTimes", Integer)
                .mutability(Mutability::ReadWrite)
                .value("3"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            seconds("OfflineThreshold")
                .mutability(Mutability::ReadWrite)
                .value("600"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            VariableSpec::new("QueueAllMessages", Boolean)
                .mutability(Mutability::ReadWrite)
                .value("false"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            VariableSpec::new("NetworkConfigurationPriority", Str)
                .mutability(Mutability::ReadWrite)
                .value("0"),
        ),
        (
            ComponentKey::new("OCPPCommCtrlr"),
            VariableSpec::new("NetworkProfileConnectionAttempts", Integer)
                .mutability(Mutability::ReadWrite)
                .value("3"),
        ),
        // --- SecurityCtrlr -------------------------------------------------------
        (
            ComponentKey::new("SecurityCtrlr"),
            VariableSpec::new("SecurityProfile", Integer)
                .limits(Some(Decimal::from(1)), Some(Decimal::from(3)))
                .value("1"),
        ),
        (
            ComponentKey::new("SecurityCtrlr"),
            VariableSpec::new("BasicAuthPassword", Str).mutability(Mutability::WriteOnly),
        ),
        (
            ComponentKey::new("SecurityCtrlr"),
            VariableSpec::new("Identity", Str).constant(),
        ),
        (
            ComponentKey::new("SecurityCtrlr"),
            VariableSpec::new("OrganizationName", Str).mutability(Mutability::ReadWrite),
        ),
        // --- TxCtrlr -------------------------------------------------------------
        (
            ComponentKey::new("TxCtrlr"),
            VariableSpec::new("TxStartPoint", DataType::MemberList)
                .mutability(Mutability::ReadWrite)
                .values([
                    "ParkingBayOccupancy",
                    "EVConnected",
                    "Authorized",
                    "DataSigned",
                    "PowerPathClosed",
                    "EnergyTransfer"
                ])
                .value("PowerPathClosed"),
        ),
        (
            ComponentKey::new("TxCtrlr"),
            VariableSpec::new("TxStopPoint", DataType::MemberList)
                .mutability(Mutability::ReadWrite)
                .values([
                    "ParkingBayOccupancy",
                    "EVConnected",
                    "Authorized",
                    "DataSigned",
                    "PowerPathClosed",
                    "EnergyTransfer"
                ])
                .value("EVConnected"),
        ),
        (
            ComponentKey::new("TxCtrlr"),
            VariableSpec::new("StopTxOnInvalidId", Boolean)
                .mutability(Mutability::ReadWrite)
                .value("true"),
        ),
        // --- AuthCtrlr / AuthCacheCtrlr / LocalAuthListCtrlr ---------------------
        (
            ComponentKey::new("AuthCtrlr"),
            VariableSpec::new("AuthorizeRemoteStart", Boolean)
                .mutability(Mutability::ReadWrite)
                .value("false"),
        ),
        (
            ComponentKey::new("AuthCtrlr"),
            VariableSpec::new("LocalPreAuthorize", Boolean)
                .mutability(Mutability::ReadWrite)
                .value("false"),
        ),
        (
            ComponentKey::new("AuthCacheCtrlr"),
            VariableSpec::new("Enabled", Boolean)
                .mutability(Mutability::ReadWrite)
                .value("true"),
        ),
        (
            ComponentKey::new("LocalAuthListCtrlr"),
            VariableSpec::new("Enabled", Boolean)
                .mutability(Mutability::ReadWrite)
                .value("true"),
        ),
        (
            ComponentKey::new("LocalAuthListCtrlr"),
            VariableSpec::new("Entries", Integer).value("0"),
        ),
        // --- ClockCtrlr ----------------------------------------------------------
        (
            ComponentKey::new("ClockCtrlr"),
            VariableSpec::new("TimeSource", DataType::SequenceList)
                .mutability(Mutability::ReadWrite)
                .values([
                    "Heartbeat",
                    "NTP",
                    "GPS",
                    "RealTimeClock",
                    "MobileNetwork",
                    "RadioTimeTransmitter"
                ])
                .value("Heartbeat"),
        ),
        (
            ComponentKey::new("ClockCtrlr"),
            VariableSpec::new("DateTime", DataType::DateTime),
        ),
        // --- DeviceDataCtrlr -----------------------------------------------------
        (
            ComponentKey::new("DeviceDataCtrlr"),
            VariableSpec::new("ItemsPerMessage", Integer)
                .instance("GetReport")
                .value("25"),
        ),
        (
            ComponentKey::new("DeviceDataCtrlr"),
            VariableSpec::new("BytesPerMessage", Integer)
                .instance("GetReport")
                .value("65536"),
        ),
    ]
}

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

    #[test]
    fn mutability_and_type_are_enforced_on_write() {
        let mut model = DeviceModel::with_defaults();
        assert_eq!(
            model.set(
                "OCPPCommCtrlr",
                "HeartbeatInterval",
                Attribute::Actual,
                "600"
            ),
            SetStatus::Accepted
        );
        assert_eq!(
            model
                .get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Actual)
                .unwrap(),
            "600"
        );

        // Not an integer.
        assert_eq!(
            model.set(
                "OCPPCommCtrlr",
                "HeartbeatInterval",
                Attribute::Actual,
                "soon"
            ),
            SetStatus::Rejected
        );
        // Read-only.
        assert_eq!(
            model.set("SecurityCtrlr", "Identity", Attribute::Actual, "CS-1"),
            SetStatus::Rejected
        );
        // Outside the declared limits.
        assert_eq!(
            model.set("SecurityCtrlr", "SecurityProfile", Attribute::Actual, "9"),
            SetStatus::Rejected
        );
        assert_eq!(
            model.set("Nope", "Whatever", Attribute::Actual, "1"),
            SetStatus::UnknownComponent
        );
        assert_eq!(
            model.set("SecurityCtrlr", "Whatever", Attribute::Actual, "1"),
            SetStatus::UnknownVariable
        );
    }

    /// B07.FR.11 makes "supported" and "has a value" two different facts, and the read and
    /// write paths have to agree with the report about which is which. B05.FR.06 and
    /// B06.FR.08 both reserve `NotSupportedAttributeType` for an attribute type that is
    /// *unknown* for the variable; B06.FR.13 says a supported attribute with no value yet
    /// reads back as an empty string — naming `Target` as the example.
    #[test]
    fn a_supported_attribute_with_no_value_is_readable_and_writable_b06_fr_13() {
        let mut model = DeviceModel::new();
        model.declare(
            "OCPPCommCtrlr",
            VariableSpec::new("HeartbeatInterval", DataType::Integer)
                .mutability(Mutability::ReadWrite)
                .value("300")
                .supports(Attribute::Target),
        );

        // The report says `Target` is supported and has no value.
        let data = model.report(ReportBase::FullInventory, None, None);
        let entry = data
            .iter()
            .find(|d| d.variable.name == "HeartbeatInterval")
            .expect("declared");
        let target = entry
            .attributes
            .iter()
            .find(|(attribute, _, _)| *attribute == Attribute::Target)
            .expect("B07.FR.11: a supported attribute is reported even when unset");
        assert_eq!(target.2, None, "…and it is reported without a value");

        // So reading it must not claim it is unsupported (B06.FR.08), and B06.FR.13 makes
        // the answer an empty string rather than an error.
        assert_eq!(
            model.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Target),
            Ok(String::new())
        );

        // And writing it must not claim it is unsupported either (B05.FR.06).
        assert_eq!(
            model.set(
                "OCPPCommCtrlr",
                "HeartbeatInterval",
                Attribute::Target,
                "60"
            ),
            SetStatus::Accepted
        );
        assert_eq!(
            model.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Target),
            Ok("60".to_owned())
        );

        // An attribute type the variable never declared is the case those two rules are for.
        assert_eq!(
            model.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::MinSet),
            Err(GetStatus::NotSupportedAttributeType)
        );
        assert_eq!(
            model.set("OCPPCommCtrlr", "HeartbeatInterval", Attribute::MinSet, "1"),
            SetStatus::NotSupportedAttributeType
        );
    }

    #[test]
    fn a_write_only_variable_is_never_read_back() {
        let mut model = DeviceModel::with_defaults();
        assert_eq!(
            model.set(
                "SecurityCtrlr",
                "BasicAuthPassword",
                Attribute::Actual,
                "0123456789abcdef"
            ),
            SetStatus::Accepted
        );
        assert_eq!(
            model.get("SecurityCtrlr", "BasicAuthPassword", Attribute::Actual),
            Err(GetStatus::Rejected)
        );
        let report = model.report(
            ReportBase::FullInventory,
            Some("SecurityCtrlr"),
            Some("BasicAuthPassword"),
        );
        assert_eq!(
            report[0].attributes[0].2, None,
            "the value is withheld from reports too"
        );
    }

    /// B08.FR.22–25: instance, EVSE and connector narrow a `GetReport` only when given.
    #[test]
    fn a_report_criterion_matches_instance_evse_and_connector_where_given() {
        let station = ComponentKey::new("Connector");
        let evse1 = ComponentKey::new("Connector").evse(1, Some(1));
        let evse2 = ComponentKey::new("Connector").evse(2, Some(1));
        let named = ComponentKey::new("Connector")
            .instance("A")
            .evse(1, Some(2));

        let any = ComponentKey::new("Connector");
        assert!(station.matches(&any) && evse1.matches(&any) && named.matches(&any)); // FR.23/25

        let on_evse1 = ComponentKey::new("Connector").evse(1, None); // FR.22
        assert!(evse1.matches(&on_evse1) && named.matches(&on_evse1));
        assert!(!evse2.matches(&on_evse1) && !station.matches(&on_evse1));

        let instance_a = ComponentKey::new("Connector").instance("A"); // FR.24
        assert!(named.matches(&instance_a) && !evse1.matches(&instance_a));

        assert!(!ComponentKey::new("EVSE").matches(&any));
    }

    #[test]
    fn instances_distinguish_variables_of_the_same_name() {
        let model = DeviceModel::with_defaults();
        let attempts = model
            .get(
                "OCPPCommCtrlr",
                VariableKey::new("MessageAttempts").instance("TransactionEvent"),
                Attribute::Actual,
            )
            .unwrap();
        assert_eq!(attempts, "3");
        assert_eq!(
            model.get("OCPPCommCtrlr", "MessageAttempts", Attribute::Actual),
            Err(GetStatus::UnknownVariable)
        );
    }

    #[test]
    fn a_configuration_inventory_reports_only_writable_variables() {
        let model = DeviceModel::with_defaults();
        let full = model.report(ReportBase::FullInventory, None, None);
        let config = model.report(ReportBase::ConfigurationInventory, None, None);
        assert!(config.len() < full.len());
        assert!(config.iter().all(|datum| datum.mutability.writable()));
    }

    #[test]
    fn the_standard_catalogue_declares_a_component_with_its_types_and_units() {
        let mut model = DeviceModel::new();
        let declared = model
            .declare_standard("OCPPCommCtrlr")
            .expect("a standard component");
        assert!(
            declared >= 15,
            "the appendix lists at least 15 OCPPCommCtrlr variables"
        );

        // Types and units come from the appendix, not from a hand-written table.
        let report = model.report(
            ReportBase::FullInventory,
            Some("OCPPCommCtrlr"),
            Some("HeartbeatInterval"),
        );
        assert_eq!(report[0].data_type, DataType::Integer);
        assert_eq!(report[0].unit.as_deref(), Some("s"));

        assert!(model.declare_standard("NotAComponent").is_none());
    }

    #[test]
    fn a_physical_component_gets_its_types_from_the_standardized_variable_list() {
        let mut model = DeviceModel::new();
        model
            .declare_standard("EVSE")
            .expect("EVSE is standardized");
        // The physical-component tables have no Type column; chapter 4 supplies it.
        let report = model.report(ReportBase::FullInventory, Some("EVSE"), Some("ACVoltage"));
        assert_eq!(report[0].data_type, DataType::Decimal);
        assert_eq!(report[0].unit.as_deref(), Some("V"));
    }

    /// B07.FR.09 names exactly what a summary contains: availability and condition. Choosing
    /// by mutability instead — as this once did — reports `HeartbeatInterval` and omits
    /// `AvailabilityState`, which is the one thing the CSMS asked for.
    #[test]
    fn a_summary_inventory_reports_availability_and_condition_b07_fr_09() {
        let mut model = DeviceModel::new();
        model.declare(
            ComponentKey::new("ChargingStation"),
            VariableSpec::new("AvailabilityState", DataType::OptionList).value("Available"),
        );
        model.declare(
            ComponentKey::new("Connector").evse(1, Some(1)),
            VariableSpec::new("Problem", DataType::Boolean).value("false"),
        );
        model.declare(
            ComponentKey::new("OCPPCommCtrlr"),
            VariableSpec::new("HeartbeatInterval", DataType::Integer)
                .mutability(Mutability::ReadWrite)
                .value("300"),
        );

        let summary = model.report(ReportBase::SummaryInventory, None, None);
        let names: Vec<&str> = summary
            .iter()
            .map(|datum| datum.variable.name.as_str())
            .collect();
        assert!(names.contains(&"AvailabilityState"), "{names:?}");
        assert!(names.contains(&"Problem"), "{names:?}");
        assert!(
            !names.contains(&"HeartbeatInterval"),
            "a configuration variable is not a summary: {names:?}"
        );

        // …and it is still in the full and configuration inventories.
        let full = model.report(ReportBase::FullInventory, None, None);
        assert_eq!(full.len(), 3);
    }

    /// B07.FR.11: "All attribute types of a variable, that are supported by the Charging
    /// Station, SHALL be reported, even if they have no value (are unset)." Reporting only
    /// the ones that happen to hold a value tells the CSMS a `MaxSet` it may write does not
    /// exist.
    #[test]
    fn a_supported_but_unset_attribute_is_still_reported_b07_fr_11() {
        let mut model = DeviceModel::new();
        model.declare(
            ComponentKey::new("SmartChargingCtrlr"),
            VariableSpec::new("Entries", DataType::Integer)
                .mutability(Mutability::ReadWrite)
                .value("10")
                .supports(Attribute::MaxSet),
        );

        let report = model.report(ReportBase::FullInventory, None, None);
        let attributes = &report[0].attributes;
        let max_set = attributes
            .iter()
            .find(|(attribute, _, _)| *attribute == Attribute::MaxSet)
            .expect("MaxSet is supported, so it is reported");
        assert_eq!(max_set.2, None, "…with no value, which is the point");
        assert!(
            attributes
                .iter()
                .any(|(attribute, _, value)| *attribute == Attribute::Actual
                    && value.as_deref() == Some("10"))
        );
    }

    #[test]
    fn reports_are_paginated_with_a_to_be_continued_flag() {
        let model = DeviceModel::with_defaults();
        let pages = DeviceModel::paginate(&model.report(ReportBase::FullInventory, None, None), 10);
        assert!(pages.len() > 1);
        assert_eq!(pages[0].0, 0);
        assert!(pages[0].1, "every page but the last is `tbc`");
        assert!(!pages.last().unwrap().1);
        let total: usize = pages.iter().map(|(_, _, data)| data.len()).sum();
        assert_eq!(
            total,
            model.report(ReportBase::FullInventory, None, None).len()
        );
    }
}