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
/// File auto-generated using xsd-parser-rs & IEEE 2030.5 sep-ordered-dep.xsd
/// Types should eventually be put in a module corresponding to their package
use anyhow::Context;
use bitflags::bitflags;
use std::fmt::Display;
use std::str::FromStr;
use yaserde::{DefaultYaSerde, HexBinaryYaSerde, PrimitiveYaSerde, YaDeserialize, YaSerialize};

use crate::traits::Validate;

use super::primitives::{
    HexBinary128, Int32, Int48, Int64, String32, String42, Uint16, Uint32, Uint48,
};

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "AccumulationBehaviourType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum AccumulationBehaviourType {
    #[default]
    /// (default, if not specified)
    NotApplicable = 0,
    /// The sum of the previous billing period values. Note: “Cumulative” is commonly used in conjunction with “demand.” Each demand reset causes the maximum demand value for the present billing period (since the last demand reset) to accumulate as an accumulative total of all maximum demands. So instead of “zeroing” the demand register, a demand reset has the affect of adding the present maximum demand to this accumulating total.
    Cumulative = 3,
    /// The difference between the value at the end of the prescribed interval and the beginning of the interval. This is used for incremental interval data.
    /// Note: One common application would be for load profile data, another use might be to report the number of events within an interval (such as the number of equipment energizations within the specified period of time.)
    DeltaData = 4,
    /// As if a needle is swung out on the meter face to a value to indicate the current value. (Note: An “indicating” value is typically measured over hundreds of milliseconds or greater, or may imply a “pusher” mechanism to capture a value. Compare this to “instantaneous” which is measured over a shorter period of time.)
    Indicating = 6,
    /// A form of accumulation which is selective with respect to time.
    /// Note : “Summation” could be considered a specialization of “Bulk Quantity” according to the rules of inheritance where “Summation” selectively accumulates pulses over a timing pattern, and “BulkQuantity” accumulates pulses all of the time.
    Summation = 9,
    /// Typically measured over the fastest period of time allowed by the definition of the metric (usually milliseconds or tens of milliseconds.) (Note: “Instantaneous” was moved to attribute #3 in 61968-9Ed2 from attribute #1 in 61968-9Ed1.)
    Instantaneous = 12,
    // ALL OTHERS RESERVED
}

impl Validate for AccumulationBehaviourType {}

#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, YaSerialize, YaDeserialize)]
#[yaserde(rename = "ApplianceLoadReductionType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum ApplianceLoadReductionType {
    #[default]
    /// Parameter requesting the appliance to respond by providing a moderate load reduction for the duration of a delay period.  Typically referring to a “non-emergency” event in which appliances can continue operating if already in a load consuming period.
    DelayApplianceLoad = 0,
    /// Parameter requesting the appliance to respond by providing an aggressive load reduction for a short time period.  Typically referring to an “emergency/spinning reserve” event in which an appliance should start shedding load if currently in a load consuming period.
    TemporaryApplianceLoadReduction = 1,
    // 2-255 reserved
    // * Full definition of how appliances react when receiving each parameter is document in the EPA document - ENERGY STAR® Program Requirements, Product Specification for Residential Refrigerators and Freezers, Eligibility Criteria 5, Draft 2 Version 5.0.
}

impl Validate for ApplianceLoadReductionType {}

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "CommodityType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub enum CommodityType {
    #[default]
    NotApplicable = 0, // (default, if not specified)
    ElectricitySecondaryMetered = 1, // metered value (a premises meter is typically on the low voltage, or secondary, side of a service transformer)
    ElectricityPrimaryMetered = 2, // metered value (measured on the high voltage, or primary, side of the service transformer)
    Air = 4,
    NaturalGas = 7,
    Propane = 8,
    PotableWater = 9,
    Steam = 10,
    WasteWater = 11,
    HeatingFluid = 12,
    CoolingFluid = 13,
    // All other values reserved
}

impl Validate for CommodityType {}

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "ConsumptionBlockType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum ConsumptionBlockType {
    #[default]
    NotApplicable = 0,
    Block1 = 1,
    Block2 = 2,
    Block3 = 3,
    Block4 = 4,
    Block5 = 5,
    Block6 = 6,
    Block7 = 7,
    Block8 = 8,
    Block9 = 9,
    Block10 = 10,
    Block11 = 11,
    Block12 = 12,
    Block13 = 13,
    Block14 = 14,
    Block15 = 15,
    Block16 = 16,
    // 17-255 RESERVED
}

impl Validate for ConsumptionBlockType {}

/// Follows codes defined in ISO 4217.
/// An exhaustive list is currently out of scope for this project
pub type CurrencyCode = Uint16;

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "DataQualifierType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum DataQualifierType {
    #[default]
    NotApplicable = 0,
    Average = 2,
    Maximum = 8,
    Minimum = 9,
    Normal = 12,
    StandardDeviationOfPopulation = 29,
    StandardDeviationOfSample = 30,
}

impl Validate for DataQualifierType {}

/// Interval of date and time.
#[derive(Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, YaSerialize, YaDeserialize)]
#[yaserde(rename = "DateTimeInterval")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct DateTimeInterval {
    /// Duration of the interval, in seconds.
    #[yaserde(rename = "duration")]
    pub duration: Uint32,

    /// Date and time of the start of the interval.
    #[yaserde(rename = "start")]
    pub start: TimeType,
}

impl Validate for DateTimeInterval {}

bitflags! {
    #[derive(Default, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Debug, HexBinaryYaSerde)]
    pub struct DeviceCategoryType: u32 { // HexBinary32
        const ProgrammableCommunicatingThermostat = 1;
        const StripHeaters = 2;
        const WaterHeater = 8;
        const PoolPump = 16;
        const Sauna = 32;
        const HotTub = 64;
        const SmartAppliance = 128;
        const IrrigationPump = 256;
        const ManagedCommercialAndIndustrialLoads = 512;
        const SimpleMiscLoads = 1024;
        const ExteriorLighting = 2048;
        const InteriorLighting = 4096;
        const LoadControlSwitch = 8192;
        const EnergyManagementSystem = 16384;
        const SmartEnergyModule = 32768;
        const ElectricVehicle = 65536;
        const EVSE = 131072;
        const VirutalOrMixedDer = 262144;
        const ReciprocatingEngine = 524288;
        const PhotovoltaicSystem = 2097152;
        const CombinedPvAndStorage = 8388608;
        const OtherGenerationSystem = 16777216;
        const OtherStorageSystem = 33554432;
    }
}

impl Validate for DeviceCategoryType {}

bitflags! {
    /// List of codes indicating the quality of the reading, using specification:
    #[derive(Default, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Debug, HexBinaryYaSerde)]
    pub struct QualityFlags: u16 { // HexBinary16
        /// Bit 0 - valid: data that has gone through all required validation checks
        /// and either passed them all or has been verified
        const Valid = 1;
        /// Bit 1 - manually edited: Replaced or approved by a human
        const ManuallyEdited = 2;
        /// Bit 2 - estimated using reference day: data value was replaced by a
        /// machine computed value based on analysis of historical data using the
        /// same type of measurement.
        const EstimatedRef = 8;
        /// Bit 3 - estimated using linear interpolation: data value was computed
        /// using linear interpolation based on the readings before and after it
        const EstimatedLinear = 16;
        /// Bit 4 - questionable: data that has failed one or more checks
        const Questionable = 32;
        /// Bit 5 - derived: data that has been calculated (using logic or
        /// mathematical operations), not necessarily measured directly
        const Derived = 64;
        /// Bit 6 - projected (forecast): data that has been calculated as a
        /// Projection or forecast of future readings
        const Projected = 128;
    }
}

#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, PrimitiveYaSerde)]
pub struct DstRuleType(u32);

impl Validate for DstRuleType {}

impl DstRuleType {
    const SECONDS_SHIFT: u32 = 0;
    const HOURS_SHIFT: u32 = 12;
    const DAY_OF_WEEK_SHIFT: u32 = 17;
    const DAY_OF_MONTH_SHIFT: u32 = 20;
    const OPERATOR_SHIFT: u32 = 25;
    const MONTH_SHIFT: u32 = 28;

    const SECONDS_MASK: u32 = 0xFFF << Self::SECONDS_SHIFT; // Bits 0-11
    const HOURS_MASK: u32 = 0x1F << Self::HOURS_SHIFT; // Bits 12-16
    const DAY_OF_WEEK_MASK: u32 = 0x7 << Self::DAY_OF_WEEK_SHIFT; // Bits 17-19
    const DAY_OF_MONTH_MASK: u32 = 0x1F << Self::DAY_OF_MONTH_SHIFT; // Bits 20-24
    const OPERATOR_MASK: u32 = 0x7 << Self::OPERATOR_SHIFT; // Bits 25-27
    const MONTH_MASK: u32 = 0xF << Self::MONTH_SHIFT; // Bits 28-31

    /// Create a complete DST Rule
    pub fn new(
        seconds: u32,
        hours: u32,
        day_of_week: u32,
        day_of_month: u32,
        operator: u32,
        month: u32,
    ) -> Self {
        let mut out = DstRuleType(0);
        out.set_seconds(seconds);
        out.set_hours(hours);
        out.set_day_of_week(day_of_week);
        out.set_day_of_month(day_of_month);
        out.set_operator(operator);
        out.set_month(month);
        out
    }

    /// Get the seconds (bits 0 - 11)
    pub fn seconds(&self) -> u32 {
        self.0 & Self::SECONDS_MASK
    }

    /// Set the seconds (bits 0 - 11)
    pub fn set_seconds(&mut self, seconds: u32) {
        self.0 = (self.0 & !Self::SECONDS_MASK) | (seconds & Self::SECONDS_MASK);
    }

    /// Get the hours (bits 12 - 16)
    pub fn hours(&self) -> u32 {
        (self.0 & Self::HOURS_MASK) >> Self::HOURS_SHIFT
    }

    /// Set the hours (bits 12 - 16)
    pub fn set_hours(&mut self, hours: u32) {
        self.0 = (self.0 & !Self::HOURS_MASK) | ((hours << Self::HOURS_SHIFT) & Self::HOURS_MASK);
    }

    /// Get the day of the week (bits 17 - 19)
    pub fn day_of_week(&self) -> u32 {
        (self.0 & Self::DAY_OF_WEEK_MASK) >> Self::DAY_OF_WEEK_SHIFT
    }

    /// Set the day of the week (bits 17 - 19)
    pub fn set_day_of_week(&mut self, day_of_week: u32) {
        self.0 = (self.0 & !Self::DAY_OF_WEEK_MASK)
            | ((day_of_week << Self::DAY_OF_WEEK_SHIFT) & Self::DAY_OF_WEEK_MASK);
    }

    /// Get the day of the month (bits 20 - 24)
    pub fn day_of_month(&self) -> u32 {
        (self.0 & Self::DAY_OF_MONTH_MASK) >> Self::DAY_OF_MONTH_SHIFT
    }

    /// Set the day of the month (bits 20 - 24)
    pub fn set_day_of_month(&mut self, day_of_month: u32) {
        self.0 = (self.0 & !Self::DAY_OF_MONTH_MASK)
            | ((day_of_month << Self::DAY_OF_MONTH_SHIFT) & Self::DAY_OF_MONTH_MASK);
    }

    /// Get the operator (bits 25 - 27)
    pub fn operator(&self) -> u32 {
        (self.0 & Self::OPERATOR_MASK) >> Self::OPERATOR_SHIFT
    }

    /// Set the operator (bits 25 - 27)
    pub fn set_operator(&mut self, operator: u32) {
        self.0 = (self.0 & !Self::OPERATOR_MASK)
            | ((operator << Self::OPERATOR_SHIFT) & Self::OPERATOR_MASK);
    }

    /// Get the month (bits 28 - 31)
    pub fn month(&self) -> u32 {
        (self.0 & Self::MONTH_MASK) >> Self::MONTH_SHIFT
    }

    /// Set the month (bits 28 - 31)
    pub fn set_month(&mut self, month: u32) {
        self.0 = (self.0 & !Self::MONTH_MASK) | ((month << Self::MONTH_SHIFT) & Self::MONTH_MASK);
    }
}

#[derive(Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, YaSerialize, YaDeserialize)]
#[yaserde(rename = "FlowDirectionType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum FlowDirectionType {
    #[default]
    NotApplicable = 0,
    /// Delivered to customer
    Forward = 1,
    /// Received from customer
    Reverse = 19,
}

impl Validate for FlowDirectionType {}

/// Specifies a GPS location, expressed in WGS 84 coordinates.
#[derive(Default, PartialEq, Eq, Debug, Clone, YaSerialize, YaDeserialize)]
#[yaserde(rename = "GPSLocationType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct GPSLocationType {
    /// Specifies the latitude from equator. -90 (south) to +90 (north) in
    /// decimal degrees.
    #[yaserde(rename = "lat")]
    pub lat: String32,

    /// Specifies the longitude from Greenwich Meridian. -180 (west) to +180
    /// (east) in decimal degrees.
    #[yaserde(rename = "lon")]
    pub lon: String32,
}

impl Validate for GPSLocationType {}

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "KindType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum KindType {
    #[default]
    NotApplicable = 0,
    Currency = 3,
    Demand = 8,
    Energy = 12,
    Power = 37,
}

impl Validate for KindType {}

/// IETF RFC 4646 identifier of a language-region.
/// An exhaustive list is currently out of scope for this project
pub type LocaleType = String42;

/// A Master Resource Identifier
pub type MRIDType = HexBinary128;

/// A signed time offset, typically applied to a Time value, expressed in seconds, with range −3600 to 3600
#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, DefaultYaSerde)]
pub struct OneHourRangeType(i16);

impl Validate for OneHourRangeType {}

impl OneHourRangeType {
    pub fn new(val: i16) -> Option<OneHourRangeType> {
        if !(-3600..=3600).contains(&val) {
            None
        } else {
            Some(OneHourRangeType(val))
        }
    }
    pub fn get(&self) -> i16 {
        self.0
    }
}
impl FromStr for OneHourRangeType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse()
            .ok()
            .and_then(OneHourRangeType::new)
            .context("OneHourRangeType value must be between -3600 and 3600")
    }
}

impl Display for OneHourRangeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// IANA Private Enterprise Number (PEN)
pub type PENType = Uint32;

/// Used for percentages, specified in hundredths of a percent, 0 to 10 000. (10 000 = 100%)
#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, DefaultYaSerde)]
pub struct Percent(u16);

impl Validate for Percent {}

impl Percent {
    pub fn new(val: u16) -> Option<Percent> {
        if val > 10_000 {
            None
        } else {
            Some(Percent(val))
        }
    }
    pub fn get(&self) -> u16 {
        self.0
    }
}

impl FromStr for Percent {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse()
            .ok()
            .and_then(Percent::new)
            .context("Percent value must be between 0 and 10000")
    }
}

impl Display for Percent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "PhaseCode")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum PhaseCode {
    #[default]
    NotApplicable = 0,
    PhaseC = 32,  // and S2
    PhaseCN = 33, // and S2N
    PhaseCA = 40,
    PhaseB = 64,
    PhaseBN = 65,
    PhaseBC = 66,
    PhaseA = 128,  // and S1
    PhaseAN = 129, // and S1N
    PhaseAB = 132,
    PhaseABC = 224,
    // ALL OTHERS RESERVED
}

impl Validate for PhaseCode {}

/// Six digit unsigned decimal integer (0 to 999999).
#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, DefaultYaSerde)]
pub struct PINType(u32);

impl Validate for PINType {}

impl PINType {
    pub fn new(val: u32) -> Option<PINType> {
        if val > 999_999 {
            None
        } else {
            Some(PINType(val))
        }
    }
    pub fn get(&self) -> u32 {
        self.0
    }
}
impl FromStr for PINType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse()
            .ok()
            .and_then(PINType::new)
            .context("PINType value must be between 0 and 999,999")
    }
}

impl Display for PINType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// For many variants there is no Internal System of Units designated prefix, and as such the number is used as a name instead.
#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "PowerOfTenMultiplierType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(i8)]
pub enum PowerOfTenMultiplierType {
    Nano = -9,
    NegativeEight = -8,
    NegativeSeven = -7,
    Micro = -6,
    NegativeFive = -5,
    NegativeFour = -4,
    Milli = -3,
    Centi = -2,
    Deci = -1,
    #[default]
    None = 0,
    Deca = 1,
    Hecto = 2,
    Kilo = 3,
    Four = 4,
    Five = 5,
    Mega = 6,
    Seven = 7,
    Eight = 8,
    Giga = 9,
}

impl Validate for PowerOfTenMultiplierType {}

#[derive(
    Default, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "PrimacyType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum PrimacyType {
    #[default]
    InHomeEnergyManagementSystem = 0,
    ContractedPremisesServiceProvider = 1,
    NonContractualServiceProvider = 2,
}

impl Validate for PrimacyType {}

/// Real electrical energy
#[derive(Default, PartialEq, Eq, Debug, Clone, YaSerialize, YaDeserialize)]
#[yaserde(rename = "RealEnergy")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct RealEnergy {
    /// Multiplier for 'unit'.
    #[yaserde(rename = "multiplier")]
    pub multiplier: PowerOfTenMultiplierType,

    /// Value of the energy in Watt-hours. (uom 72)
    #[yaserde(rename = "value")]
    pub value: Uint48,
}

impl Validate for RealEnergy {}

bitflags! {
    #[derive(Default, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Debug, HexBinaryYaSerde)]
    pub struct RoleFlagsType: u16 { // HexBinary16
        const IsMirror = 1;
        const IsPremiseAggregationPoint = 2;
        const IsPEV = 4;
        const IsDER = 8;
        const IsRevenueQuality = 16;
        const IsDC = 32;
        const IsSubmeter = 64;
    }
}

impl Validate for RoleFlagsType {}

#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, YaSerialize, YaDeserialize)]
#[yaserde(rename = "ServiceKind")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum ServiceKind {
    #[default]
    Electricity = 0,
    Gas = 1,
    Water = 2,
    Time = 3,
    Pressure = 4,
    Heat = 5,
    Cooling = 6,
}

impl Validate for ServiceKind {}

/// Unsigned integer, maximum inclusive 687194767359, which is 2^36 - 1 (68,719,476,735), with added check digit.
#[derive(Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, DefaultYaSerde)]
pub struct SFDIType(u64);

impl Validate for SFDIType {}

impl SFDIType {
    pub fn new(val: u64) -> Option<SFDIType> {
        if val > 1_099_511_627_775 {
            None
        } else {
            Some(SFDIType(val))
        }
    }
    pub fn get(&self) -> u64 {
        self.0
    }
}
impl FromStr for SFDIType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse()
            .ok()
            .and_then(SFDIType::new)
            .context("SFDIType value must be between -10,000 and 10,000")
    }
}

impl Display for SFDIType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Used for signed percentages, specified in hundredths of a percent, −10 000 to 10 000. (10 000 = 100%)
#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, DefaultYaSerde)]
pub struct SignedPercent(i16);

impl Validate for SignedPercent {}

impl SignedPercent {
    pub fn new(val: i16) -> Option<SignedPercent> {
        if !(-10_000..=10_000).contains(&val) {
            None
        } else {
            Some(SignedPercent(val))
        }
    }
    pub fn get(&self) -> i16 {
        self.0
    }
}
impl FromStr for SignedPercent {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse()
            .ok()
            .and_then(SignedPercent::new)
            .context("SignedPercent value must be between -10,000 and 10,000")
    }
}

impl Display for SignedPercent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Real electrical energy, signed.
#[derive(Default, PartialEq, Eq, Debug, Clone, YaSerialize, YaDeserialize)]
#[yaserde(rename = "SignedRealEnergy")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct SignedRealEnergy {
    /// Multiplier for 'unit'.
    #[yaserde(rename = "multiplier")]
    pub multiplier: PowerOfTenMultiplierType,

    /// Value of the energy in Watt-hours. (uom 72)
    #[yaserde(rename = "value")]
    pub value: Int48,
}

impl Validate for SignedRealEnergy {}

/// The subscribable values.
/// 0 - Resource does not support subscriptions
/// 1 - Resource supports non-conditional subscriptions
/// 2 - Resource supports conditional subscriptions
/// 3 - Resource supports both conditional and non-conditional subscriptions
/// All other values reserved.
#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, YaSerialize, YaDeserialize)]
#[repr(u8)]
pub enum SubscribableType {
    #[default]
    NoSubscriptionsSupported = 0,
    NonConditionalSubscriptions = 1,
    ConditionalSubscriptions = 2,
    AllSubscriptions = 3,
}

impl Validate for SubscribableType {}

/// A signed time offset, typically applied to a Time value, expressed in seconds.
pub type TimeOffsetType = Int32;

/// Time is a signed 64-bit value representing the number of seconds since 0 hours,
/// 0 minutes, 0 seconds, on 1 January 1970, in UTC, not counting leap seconds.
pub type TimeType = Int64;

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "TOUType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum TOUType {
    #[default]
    NotApplicable = 0,
    TouA = 1,
    TouB = 2,
    TouC = 3,
    TouD = 4,
    TouE = 5,
    TouF = 6,
    TouG = 7,
    TouH = 8,
    TouI = 9,
    TouJ = 10,
    TouK = 11,
    TouL = 12,
    TouM = 13,
    TouN = 14,
    TouO = 15,
}

impl Validate for TOUType {}

#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, YaSerialize, YaDeserialize)]
#[yaserde(rename = "UnitType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
#[allow(non_camel_case_types)]
pub enum UnitType {
    #[default]
    kWh = 0,
    kW = 1,
    Watts = 2,
    CubicMeters = 3,
    CubicFeet = 4,
    USGallons = 5,
    ImperialGallons = 6,
    BTU = 7,
    Liters = 8,
    kPAGauge = 9,
    kPAAbsolute = 10,
    Megajoule = 11,
    Unitless = 12,
}

impl Validate for UnitType {}

/// Type for specification of a specific value, with units and power of ten
/// multiplier.
#[derive(Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, YaSerialize, YaDeserialize)]
#[yaserde(rename = "UnitValueType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct UnitValueType {
    /// Multiplier for 'unit'.
    #[yaserde(rename = "multiplier")]
    pub multiplier: PowerOfTenMultiplierType,

    /// Unit in symbol
    #[yaserde(rename = "unit")]
    pub unit: UomType,

    /// Value in units specified
    #[yaserde(rename = "value")]
    pub value: Int32,
}

impl Validate for UnitValueType {}

#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(rename = "UomType")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum UomType {
    #[default]
    NotApplicable = 0,
    Amperes = 5,
    Kelvin = 6,
    DegreesCelsius = 23,
    Voltage = 29,
    Joule = 31,
    Hz = 33,
    W = 38,
    MtrCubed = 42,
    VA = 61,
    VAr = 63,
    CosTheta = 65,
    VSquared = 67,
    ASquared = 69,
    VAh = 71,
    Wh = 72,
    VArh = 73,
    Ah = 106,
    FtCubed = 119,
    FtCubedPerHour = 122,
    MCubedPerHour = 125,
    USGallons = 128,
    UGGallonsPerHour = 129,
    ImperialGallons = 130,
    ImperialGallonsPerHour = 131,
    BTU = 132,
    BTUPerHour = 133,
    Liter = 134,
    LiterPerHour = 137,
    PAGauge = 140,
    PAAbsolute = 155,
    Therm = 169,
}

impl Validate for UomType {}

/// Version SHALL indicate a distinct identifier for each revision of an IdentifiedObject. If not specified, a default version of "0" (initial version) SHALL be assumed. Upon modification of any IdentifiedObject, the mRID SHALL remain the same, but the version SHALL be incremented. Servers MAY NOT modify objects that they did not create, unless they were notified of the change from the entity controlling the object's PEN.
pub type VersionType = Uint16;

/// Binary Status Enum used in Metering & MirrorMetering
#[derive(Default, PartialEq, Eq, Debug, Clone, Copy, YaSerialize, YaDeserialize)]
#[yaserde(rename = "status")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum UsagePointStatus {
    #[default]
    Off,
    On,
}

#[test]
fn basic_dstruletype() {
    // Documentation example
    let rule = DstRuleType::new(2700, 1, 5, 0, 4, 3);
    assert_eq!(rule.seconds(), 2700);
    assert_eq!(rule.hours(), 1);
    assert_eq!(rule.day_of_week(), 5);
    assert_eq!(rule.day_of_month(), 0);
    assert_eq!(rule.operator(), 4);
    assert_eq!(rule.month(), 3);
}