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
use crate::traits::{
    SEAbstractDevice, SEList, SEResource, SESubscribableList, SESubscribableResource, Validate,
};
use sep2_common_derive::{
    SEAbstractDevice, SEList, SEResource, SESubscribableList, SESubscribableResource,
};

use yaserde::{YaDeserialize, YaSerialize};

#[cfg(test)]
use crate::serialize;

#[cfg(feature = "csip_aus")]
use super::conn_point::ConnectionPointLink;

use super::{
    links::{
        ConfigurationLink, DERListLink, DeviceInformationLink, DeviceStatusLink, FileStatusLink,
        FlowReservationRequestListLink, FlowReservationResponseListLink,
        FunctionSetAssignmentsListLink, IPInterfaceListLink, LoadShedAvailabilityListLink,
        LogEventListLink, PowerStatusLink, RegistrationLink, SubscriptionListLink, TimeLink,
    },
    primitives::{HexBinary160, Int16, Uint16, Uint32, Uint8},
    types::{
        DeviceCategoryType, PINType, PowerOfTenMultiplierType, SFDIType, SubscribableType, TimeType,
    },
};

#[derive(
    Default,
    PartialEq,
    Eq,
    Debug,
    Clone,
    YaSerialize,
    YaDeserialize,
    SESubscribableResource,
    SEResource,
    SEAbstractDevice,
)]
#[yaserde(rename = "AbstractDevice")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct AbstractDevice {
    #[yaserde(rename = "ConfigurationLink")]
    pub configuration_link: Option<ConfigurationLink>,

    #[yaserde(rename = "DERListLink")]
    pub der_list_link: Option<DERListLink>,

    /// This field is for use in devices that can adjust energy usage (e.g.,
    /// demand response, distributed energy resources). For devices that do not
    /// respond to EndDeviceControls or DERControls (for instance, an ESI), this
    /// field should not have any bits set.
    #[yaserde(rename = "deviceCategory")]
    pub device_category: Option<DeviceCategoryType>,

    #[yaserde(rename = "DeviceInformationLink")]
    pub device_information_link: Option<DeviceInformationLink>,

    #[yaserde(rename = "DeviceStatusLink")]
    pub device_status_link: Option<DeviceStatusLink>,

    #[yaserde(rename = "FileStatusLink")]
    pub file_status_link: Option<FileStatusLink>,

    #[yaserde(rename = "IPInterfaceListLink")]
    pub ip_interface_list_link: Option<IPInterfaceListLink>,

    /// Long form of device identifier. See the Security section for additional
    /// details.
    #[yaserde(rename = "lFDI")]
    pub lfdi: Option<HexBinary160>,

    #[yaserde(rename = "LoadShedAvailabilityListLink")]
    pub load_shed_availability_list_link: Option<LoadShedAvailabilityListLink>,

    #[yaserde(rename = "LogEventListLink")]
    pub log_event_list_link: Option<LogEventListLink>,

    #[yaserde(rename = "PowerStatusLink")]
    pub power_status_link: Option<PowerStatusLink>,

    /// Short form of device identifier, WITH the checksum digit. See the
    /// Security section for additional details.
    #[yaserde(rename = "sFDI")]
    pub sfdi: SFDIType,

    /// Indicates whether or not subscriptions are supported for this resource,
    /// and whether or not conditional (thresholds) are supported. If not
    /// specified, is "not subscribable" (0).
    #[yaserde(attribute, rename = "subscribable")]
    pub subscribable: Option<SubscribableType>,

    /// A reference to the resource address (URI). Required in a response to a
    /// GET, ignored otherwise.
    #[yaserde(attribute, rename = "href")]
    pub href: Option<String>,
}

impl Validate for AbstractDevice {}

#[derive(Default, PartialEq, Eq, Debug, Clone, YaSerialize, YaDeserialize, SEResource)]
#[yaserde(rename = "DeviceStatus")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct DeviceStatus {
    /// The time at which the reported values were recorded.
    #[yaserde(rename = "changedTime")]
    pub changed_time: TimeType,

    /// The number of times that the device has been turned on: Count of "device
    /// on" times, since the last time the counter was reset
    #[yaserde(rename = "onCount")]
    pub on_count: Option<Uint16>,

    /// Device operational state:
    /// 0 - Not applicable / Unknown
    /// 1 - Not operating
    /// 2 - Operating
    /// 3 - Starting up
    /// 4 - Shutting down
    /// 5 - At disconnect level
    /// 6 - kW ramping
    /// 7 - kVar ramping
    #[yaserde(rename = "opState")]
    pub op_state: Option<OpState>,

    /// Total time device has operated: re-settable: Accumulated time in seconds
    /// since the last time the counter was reset.
    #[yaserde(rename = "opTime")]
    pub op_time: Option<Uint32>,

    #[yaserde(rename = "Temperature")]
    pub temperature: Vec<Temperature>,

    #[yaserde(rename = "TimeLink")]
    pub time_link: Option<TimeLink>,

    /// The default polling rate for this function set (this resource and all
    /// resources below), in seconds. If not specified, a default of 900 seconds
    /// (15 minutes) is used. It is RECOMMENDED a client poll the resources of
    /// this function set every pollRate seconds.
    #[yaserde(attribute, rename = "pollRate")]
    pub poll_rate: Option<Uint32>,

    /// A reference to the resource address (URI). Required in a response to a
    /// GET, ignored otherwise.
    #[yaserde(attribute, rename = "href")]
    pub href: Option<String>,
}

impl Validate for DeviceStatus {}

#[allow(non_camel_case_types)]
#[derive(
    Default, PartialEq, PartialOrd, Eq, Ord, Debug, Clone, Copy, YaSerialize, YaDeserialize,
)]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[repr(u8)]
pub enum OpState {
    #[default]
    /// Or Unknown
    NotApplicable = 0,
    NotOperating = 1,
    Operating = 2,
    StartingUp = 3,
    ShuttingDown = 4,
    AtDisconnectLevel = 5,
    kWRamping = 6,
    kVarRamping = 7,
}

#[derive(
    Default,
    PartialEq,
    Eq,
    Debug,
    Clone,
    YaSerialize,
    YaDeserialize,
    SEAbstractDevice,
    SESubscribableResource,
    SEResource,
)]
#[yaserde(rename = "EndDevice")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[cfg_attr(
    feature = "csip_aus",
    yaserde(namespace = "csipaus: https://csipaus.org/ns")
)]
pub struct EndDevice {
    /// The time at which this resource was last modified or created.
    #[yaserde(rename = "changedTime")]
    pub changed_time: TimeType,

    /// This attribute indicates whether or not an EndDevice is enabled, or
    /// registered, on the server. If a server sets this attribute to false, the
    /// device is no longer registered. It should be noted that servers can
    /// delete EndDevice instances, but using this attribute for some time is
    /// more convenient for clients.
    #[yaserde(rename = "enabled")]
    pub enabled: Option<bool>,

    #[yaserde(rename = "FlowReservationRequestListLink")]
    pub flow_reservation_request_list_link: Option<FlowReservationRequestListLink>,

    #[yaserde(rename = "FlowReservationResponseListLink")]
    pub flow_reservation_response_list_link: Option<FlowReservationResponseListLink>,

    #[yaserde(rename = "FunctionSetAssignmentsListLink")]
    pub function_set_assignments_list_link: Option<FunctionSetAssignmentsListLink>,

    /// POST rate, or how often EndDevice and subordinate resources should be
    /// POSTed, in seconds. A client MAY indicate a preferred postRate when
    /// POSTing EndDevice. A server MAY add or modify postRate to indicate its
    /// preferred posting rate.
    #[yaserde(rename = "postRate")]
    pub post_rate: Option<Uint32>,

    #[yaserde(rename = "RegistrationLink")]
    pub registration_link: Option<RegistrationLink>,

    #[yaserde(rename = "SubscriptionListLink")]
    pub subscription_list_link: Option<SubscriptionListLink>,

    #[yaserde(rename = "ConfigurationLink")]
    pub configuration_link: Option<ConfigurationLink>,

    #[yaserde(rename = "DERListLink")]
    pub der_list_link: Option<DERListLink>,

    /// This field is for use in devices that can adjust energy usage (e.g.,
    /// demand response, distributed energy resources). For devices that do not
    /// respond to EndDeviceControls or DERControls (for instance, an ESI), this
    /// field should not have any bits set.
    #[yaserde(rename = "deviceCategory")]
    pub device_category: Option<DeviceCategoryType>,

    #[yaserde(rename = "DeviceInformationLink")]
    pub device_information_link: Option<DeviceInformationLink>,

    #[yaserde(rename = "DeviceStatusLink")]
    pub device_status_link: Option<DeviceStatusLink>,

    #[yaserde(rename = "FileStatusLink")]
    pub file_status_link: Option<FileStatusLink>,

    #[yaserde(rename = "IPInterfaceListLink")]
    pub ip_interface_list_link: Option<IPInterfaceListLink>,

    /// Long form of device identifier. See the Security section for additional
    /// details.
    #[yaserde(rename = "lFDI")]
    pub lfdi: Option<HexBinary160>,

    #[yaserde(rename = "LoadShedAvailabilityListLink")]
    pub load_shed_availability_list_link: Option<LoadShedAvailabilityListLink>,

    #[yaserde(rename = "LogEventListLink")]
    pub log_event_list_link: Option<LogEventListLink>,

    #[yaserde(rename = "PowerStatusLink")]
    pub power_status_link: Option<PowerStatusLink>,

    #[cfg(feature = "csip_aus")]
    #[yaserde(prefix = "csipaus", namespace = "csipaus: https://csipaus.org/ns")]
    #[yaserde(rename = "ConnectionPointLink ")]
    pub connection_point_link: Option<ConnectionPointLink>,

    /// Short form of device identifier, WITH the checksum digit. See the
    /// Security section for additional details.
    #[yaserde(rename = "sFDI")]
    pub sfdi: SFDIType,

    /// Indicates whether or not subscriptions are supported for this resource,
    /// and whether or not conditional (thresholds) are supported. If not
    /// specified, is "not subscribable" (0).
    #[yaserde(attribute, rename = "subscribable")]
    pub subscribable: Option<SubscribableType>,

    /// A reference to the resource address (URI). Required in a response to a
    /// GET, ignored otherwise.
    #[yaserde(attribute, rename = "href")]
    pub href: Option<String>,
}

impl PartialOrd for EndDevice {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EndDevice {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Primary Key - changedTime (descending)
        match self.changed_time.cmp(&other.changed_time).reverse() {
            core::cmp::Ordering::Equal => {}
            ord => return ord,
        }
        // Secondary Key - SFDI (ascending)
        match self.sfdi.cmp(&other.sfdi) {
            core::cmp::Ordering::Equal => {}
            ord => return ord,
        }
        // Tertiary Key - href (ascending)
        self.href.cmp(&other.href)
    }
}

impl Validate for EndDevice {}

#[derive(
    Default,
    PartialEq,
    Eq,
    Debug,
    Clone,
    YaSerialize,
    YaDeserialize,
    SESubscribableList,
    SEList,
    SESubscribableResource,
    SEResource,
)]
#[yaserde(rename = "EndDeviceList")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
#[cfg_attr(
    feature = "csip_aus",
    yaserde(namespace = "csipaus: https://csipaus.org/ns")
)]
pub struct EndDeviceList {
    #[yaserde(rename = "EndDevice")]
    pub end_device: Vec<EndDevice>,

    /// The default polling rate for this function set (this resource and all
    /// resources below), in seconds. If not specified, a default of 900 seconds
    /// (15 minutes) is used. It is RECOMMENDED a client poll the resources of
    /// this function set every pollRate seconds.
    #[yaserde(attribute, rename = "pollRate")]
    pub poll_rate: Option<Uint32>,

    /// The number specifying "all" of the items in the list. Required on GET,
    /// ignored otherwise.
    #[yaserde(attribute, rename = "all")]
    pub all: Uint32,

    /// Indicates the number of items in this page of results.
    #[yaserde(attribute, rename = "results")]
    pub results: Uint32,

    /// Indicates whether or not subscriptions are supported for this resource,
    /// and whether or not conditional (thresholds) are supported. If not
    /// specified, is "not subscribable" (0).
    #[yaserde(attribute, rename = "subscribable")]
    pub subscribable: Option<SubscribableType>,

    /// A reference to the resource address (URI). Required in a response to a
    /// GET, ignored otherwise.
    #[yaserde(attribute, rename = "href")]
    pub href: Option<String>,
}

impl Validate for EndDeviceList {}

#[derive(Default, PartialEq, Eq, Debug, Clone, YaSerialize, YaDeserialize, SEResource)]
#[yaserde(rename = "Registration")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct Registration {
    /// Contains the time at which this registration was created, by which
    /// clients MAY prioritize information providers with the most recent
    /// registrations, when no additional direction from the consumer is
    /// available.
    #[yaserde(rename = "dateTimeRegistered")]
    pub date_time_registered: TimeType,

    /// Contains the registration PIN number associated with the device,
    /// including the checksum digit.
    #[yaserde(rename = "pIN")]
    pub pin: PINType,

    /// The default polling rate for this function set (this resource and all
    /// resources below), in seconds. If not specified, a default of 900 seconds
    /// (15 minutes) is used. It is RECOMMENDED a client poll the resources of
    /// this function set every pollRate seconds.
    #[yaserde(attribute, rename = "pollRate")]
    pub poll_rate: Option<Uint32>,

    /// A reference to the resource address (URI). Required in a response to a
    /// GET, ignored otherwise.
    #[yaserde(attribute, rename = "href")]
    pub href: Option<String>,
}

impl Validate for Registration {}

#[derive(
    Default,
    PartialEq,
    Eq,
    Debug,
    Clone,
    YaSerialize,
    YaDeserialize,
    SEAbstractDevice,
    SESubscribableResource,
    SEResource,
)]
#[yaserde(rename = "SelfDevice")]
#[yaserde(namespace = "urn:ieee:std:2030.5:ns")]
pub struct SelfDevice {
    /// The default polling rate for this function set (this resource and all
    /// resources below), in seconds. If not specified, a default of 900 seconds
    /// (15 minutes) is used. It is RECOMMENDED a client poll the resources of
    /// this function set every pollRate seconds.
    #[yaserde(attribute, rename = "pollRate")]
    pub poll_rate: Option<Uint32>,

    #[yaserde(rename = "ConfigurationLink")]
    pub configuration_link: Option<ConfigurationLink>,

    #[yaserde(rename = "DERListLink")]
    pub der_list_link: Option<DERListLink>,

    /// This field is for use in devices that can adjust energy usage (e.g.,
    /// demand response, distributed energy resources). For devices that do not
    /// respond to EndDeviceControls or DERControls (for instance, an ESI), this
    /// field should not have any bits set.
    #[yaserde(rename = "deviceCategory")]
    pub device_category: Option<DeviceCategoryType>,

    #[yaserde(rename = "DeviceInformationLink")]
    pub device_information_link: Option<DeviceInformationLink>,

    #[yaserde(rename = "DeviceStatusLink")]
    pub device_status_link: Option<DeviceStatusLink>,

    #[yaserde(rename = "FileStatusLink")]
    pub file_status_link: Option<FileStatusLink>,

    #[yaserde(rename = "IPInterfaceListLink")]
    pub ip_interface_list_link: Option<IPInterfaceListLink>,

    /// Long form of device identifier. See the Security section for additional
    /// details.
    #[yaserde(rename = "lFDI")]
    pub lfdi: Option<HexBinary160>,

    #[yaserde(rename = "LoadShedAvailabilityListLink")]
    pub load_shed_availability_list_link: Option<LoadShedAvailabilityListLink>,

    #[yaserde(rename = "LogEventListLink")]
    pub log_event_list_link: Option<LogEventListLink>,

    #[yaserde(rename = "PowerStatusLink")]
    pub power_status_link: Option<PowerStatusLink>,

    /// Short form of device identifier, WITH the checksum digit. See the
    /// Security section for additional details.
    #[yaserde(rename = "sFDI")]
    pub sfdi: SFDIType,

    /// Indicates whether or not subscriptions are supported for this resource,
    /// and whether or not conditional (thresholds) are supported. If not
    /// specified, is "not subscribable" (0).
    #[yaserde(attribute, rename = "subscribable")]
    pub subscribable: Option<SubscribableType>,

    /// A reference to the resource address (URI). Required in a response to a
    /// GET, ignored otherwise.
    #[yaserde(attribute, rename = "href")]
    pub href: Option<String>,
}

impl Validate for SelfDevice {}

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

    /// The subject of the temperature measurement
    /// 0 - Enclosure
    /// 1 - Transformer
    /// 2 - HeatSink
    #[yaserde(rename = "subject")]
    pub subject: Uint8,

    /// Value in Degrees Celsius (uom 23).
    #[yaserde(rename = "value")]
    pub value: Int16,
}

impl Validate for Temperature {}

#[cfg(not(feature = "csip_aus"))]
#[test]
fn csip_aus_edev_no_namespace() {
    let expected = r#"<EndDevice xmlns="urn:ieee:std:2030.5:ns">
  <changedTime>0</changedTime>
  <sFDI>0</sFDI>
</EndDevice>"#;
    let edev = EndDevice::default();
    let out = serialize(&edev).unwrap();
    assert_eq!(expected, out);
}

#[cfg(feature = "csip_aus")]
#[test]
fn csip_aus_edev_namespace() {
    let expected = r#"<EndDevice xmlns="urn:ieee:std:2030.5:ns" xmlns:csipaus="https://csipaus.org/ns">
  <changedTime>0</changedTime>
  <sFDI>0</sFDI>
</EndDevice>"#;
    let edev = EndDevice::default();
    let out = serialize(&edev).unwrap();
    assert_eq!(expected, out);
}