ebds 0.4.2

Messages and related types for implementing the EBDS serial communication protocol
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
use alloc::string::String;

use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};

use crate::{
    status::{DeviceState, DeviceStateFlags},
    std::{self, fmt},
    Currency,
};

pub const ENV_BAU_DEVICE: &str = "SERIAL_PATH_BAU";
pub const ENV_CDU_DEVICE: &str = "SERIAL_PATH_CPU";
pub const DEFAULT_BAU_DEV_PATH: &str = "/dev/bau";
pub const DEFAULT_CDU_DEV_PATH: &str = "/dev/cdu";

/// HardwareComponent is a list of possible hardware components used on the platform
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
pub enum HardwareComponent {
    /// Cash dispenser unit
    CDU,
    /// Electronic payment process
    EPP,
    /// Stores interface unit
    SIU,
    /// Remote pickup unit
    RPU,
    /// Magnetic card reader
    MCR,
    /// Bill acceptor unit
    BAU,
    /// Bill acceptor 2?
    BA2,
    /// Bar code scanner?
    BCS,
    /// Camera
    CAM,
    /// Universal power supply
    UPS,
}

impl HardwareComponent {
    pub const fn default() -> Self {
        Self::BAU
    }
}

impl From<HardwareComponent> for &'static str {
    fn from(h: HardwareComponent) -> Self {
        match h {
            HardwareComponent::CDU => "CDU",
            HardwareComponent::EPP => "EPP",
            HardwareComponent::SIU => "SIU",
            HardwareComponent::RPU => "RPU",
            HardwareComponent::MCR => "MCR",
            HardwareComponent::BAU => "BAU",
            HardwareComponent::BA2 => "BA2",
            HardwareComponent::BCS => "BCS",
            HardwareComponent::CAM => "CAM",
            HardwareComponent::UPS => "UPS",
        }
    }
}

impl From<&HardwareComponent> for &'static str {
    fn from(h: &HardwareComponent) -> Self {
        (*h).into()
    }
}

impl fmt::Display for HardwareComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", <&'static str>::from(self))
    }
}

/// HardwareState represents the different states hardware can be in
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
#[serde(field_identifier, rename_all = "UPPERCASE")]
pub enum HardwareState {
    /// Everything is running properly
    OK,
    /// The hardware is missing
    Missing,
    /// The hardware emitted a warning
    Warning,
    /// The hardware emitted an error
    Error,
}

impl HardwareState {
    pub const fn default() -> Self {
        Self::OK
    }
}

impl Serialize for HardwareState {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            Self::OK => serializer.serialize_unit_variant("HardwareState", 0, "OK"),
            Self::Missing => serializer.serialize_unit_variant("HardwareState", 1, "MISSING"),
            Self::Warning => serializer.serialize_unit_variant("HardwareState", 2, "WARNING"),
            Self::Error => serializer.serialize_unit_variant("HardwareState", 3, "ERROR"),
        }
    }
}

impl From<DeviceState> for HardwareState {
    fn from(dev_state: DeviceState) -> Self {
        Self::from(DeviceStateFlags::from(dev_state))
    }
}

impl From<DeviceStateFlags> for HardwareState {
    fn from(dev_state: DeviceStateFlags) -> Self {
        match dev_state {
            DeviceStateFlags::Disconnected | DeviceStateFlags::CashBoxRemoved => Self::Warning,
            DeviceStateFlags::PowerUp
            | DeviceStateFlags::Initialize
            | DeviceStateFlags::Download
            | DeviceStateFlags::Idle
            | DeviceStateFlags::HostDisabled
            | DeviceStateFlags::BusyCalculation
            | DeviceStateFlags::Escrowed
            | DeviceStateFlags::Accepting
            | DeviceStateFlags::Stacking
            | DeviceStateFlags::Returning
            | DeviceStateFlags::Paused
            | DeviceStateFlags::Calibration
            | DeviceStateFlags::Dispensing
            | DeviceStateFlags::FloatingDown
            | DeviceStateFlags::IdleInEscrowSession
            | DeviceStateFlags::HostDisabledInEscrowSession
            | DeviceStateFlags::PatternRecovering => Self::OK,
            DeviceStateFlags::Cheated
            | DeviceStateFlags::StackerFull
            | DeviceStateFlags::TransportOpened
            | DeviceStateFlags::EscrowStorageFull
            | DeviceStateFlags::UnknownDocumentsDetected => Self::Warning,
            DeviceStateFlags::Jammed
            | DeviceStateFlags::Failure
            | DeviceStateFlags::Stalled
            | DeviceStateFlags::DisabledAndJammed
            | DeviceStateFlags::Disabled => Self::Error,
            _ => Self::Error,
        }
    }
}

impl From<HardwareState> for &'static str {
    fn from(h: HardwareState) -> Self {
        match h {
            HardwareState::OK => "OK",
            HardwareState::Missing => "MISSING",
            HardwareState::Warning => "WARNING",
            HardwareState::Error => "ERROR",
        }
    }
}

impl From<&HardwareState> for &'static str {
    fn from(h: &HardwareState) -> Self {
        (*h).into()
    }
}

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

/// BillAcceptorStatusDetails represents detailed information about the bill acceptor hardware
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct BillAcceptorStatusDetails {
    // Was the cashbox removed, or has the field not been set
    cashbox_removed: Option<bool>,
    // The firmware version
    firmware_version: Option<String>,
    // ISO string for the type of currency
    currency: Option<Currency>,
    // Is the bill acceptor jammed, or has the field not been set
    jammed: Option<bool>,
}

impl BillAcceptorStatusDetails {
    /// Create a new BillAcceptorStatusDetails
    pub const fn new(
        cashbox_removed: Option<bool>,
        firmware_version: Option<String>,
        currency: Option<Currency>,
        jammed: Option<bool>,
    ) -> Self {
        Self {
            cashbox_removed,
            firmware_version,
            currency,
            jammed,
        }
    }

    pub const fn default() -> Self {
        Self {
            cashbox_removed: None,
            firmware_version: None,
            currency: None,
            jammed: None,
        }
    }

    /// Builder function to include cashbox removed status
    pub fn with_cashbox_removed(mut self, cashbox_removed: bool) -> Self {
        self.cashbox_removed = Some(cashbox_removed);
        self
    }

    /// Builder function to include firmware version
    pub fn with_firmware_version(mut self, firmware_version: &str) -> Self {
        self.firmware_version = Some(firmware_version.into());
        self
    }

    /// Builder function to include currency status
    pub fn with_currency(mut self, currency: Currency) -> Self {
        self.currency = Some(currency);
        self
    }

    /// Builder function to include jammed status
    pub fn with_jammed(mut self, jammed: bool) -> Self {
        self.jammed = Some(jammed);
        self
    }

    /// Get whether the cashbox is removed
    ///
    /// If none is set, returns false
    pub fn cashbox_removed(&self) -> bool {
        self.cashbox_removed.unwrap_or_default()
    }

    /// Set whether the cashbox is removed
    pub fn set_cashbox_removed(&mut self, removed: bool) {
        self.cashbox_removed = Some(removed);
    }

    /// Unset the cashbox removed status
    pub fn unset_cashbox_removed(&mut self) {
        self.cashbox_removed = None;
    }

    /// Get the firmware version
    ///
    /// If none is set, returns the empty string
    pub fn firmware_version(&self) -> &str {
        if let Some(ret) = self.firmware_version.as_ref() {
            ret
        } else {
            ""
        }
    }

    /// Set the firmware version
    pub fn set_firmware_version<S>(&mut self, version: S)
    where
        S: Into<String>,
    {
        self.firmware_version = Some(version.into());
    }

    /// Unset the firmware version
    pub fn unset_firmware_version(&mut self) {
        self.firmware_version = None
    }

    /// Get the BAU currency
    ///
    /// If none is set, returns the default currency (USD)
    pub fn currency(&self) -> Currency {
        if let Some(ret) = self.currency {
            ret
        } else {
            Currency::USD
        }
    }

    /// Set the BAU currency
    pub fn set_currency(&mut self, currency: Currency) {
        self.currency = Some(currency);
    }

    /// Unset the BAU currency
    pub fn unset_currency(&mut self) {
        self.currency = None;
    }

    /// Get whether the BAU is jammed
    ///
    /// If none is set, returns false
    pub fn jammed(&self) -> bool {
        self.jammed.unwrap_or_default()
    }

    /// Set whether the BAU is jammed
    pub fn set_jammed(&mut self, jammed: bool) {
        self.jammed = Some(jammed);
    }

    /// Unset the jammed status
    pub fn unset_jammed(&mut self) {
        self.jammed = None;
    }
}

impl fmt::Display for BillAcceptorStatusDetails {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut has_field = false;
        write!(f, "{{")?;
        if let Some(ret) = self.cashbox_removed {
            write!(f, r#""cashbox_removed":{ret}"#)?;
            has_field = true;
        }
        if let Some(ret) = self.firmware_version.as_ref() {
            if has_field {
                write!(f, ",")?;
            }
            write!(f, r#""firmware_version":"{ret}""#)?;
            has_field = true;
        }
        if let Some(ret) = self.currency {
            if has_field {
                write!(f, ",")?;
            }
            write!(f, r#""currency":{ret}"#)?;
            has_field = true;
        }
        if let Some(ret) = self.jammed {
            if has_field {
                write!(f, ",")?;
            }
            write!(f, r#""jammed":{ret}"#)?;
        }
        write!(f, "}}")
    }
}

impl Serialize for BillAcceptorStatusDetails {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut bau_status = serializer.serialize_struct("BillAcceptorStatusDetails", 4)?;

        bau_status.serialize_field("cashbox_removed", &self.cashbox_removed)?;
        bau_status.serialize_field("firmware_version", &self.firmware_version)?;
        bau_status.serialize_field("currency", &self.currency)?;
        bau_status.serialize_field("jammed", &self.jammed)?;

        bau_status.end()
    }
}

/// HardwareStatusDetails represents the type of hardware details are provided for in
/// HardwareStatus
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
pub enum HardwareStatusDetails {
    NULL,
    BAU,
}

impl Default for HardwareStatusDetails {
    fn default() -> Self {
        Self::NULL
    }
}

impl From<HardwareStatusDetails> for &'static str {
    fn from(h: HardwareStatusDetails) -> Self {
        match h {
            HardwareStatusDetails::NULL => "NULL",
            HardwareStatusDetails::BAU => "BAU",
        }
    }
}

impl From<&HardwareStatusDetails> for &'static str {
    fn from(h: &HardwareStatusDetails) -> &'static str {
        (*h).into()
    }
}

impl fmt::Display for HardwareStatusDetails {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", <&'static str>::from(self))
    }
}

/// HardwareStatus represents basics information about the current status of hardware
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct HardwareStatus {
    // Hardware component type
    component: HardwareComponent,
    // Current state of the hardware
    state: HardwareState,
    // Basic description of the hardware status
    description: String,
    // Details of the BAU status
    details: BillAcceptorStatusDetails,
}

impl HardwareStatus {
    pub const fn new(
        component: HardwareComponent,
        state: HardwareState,
        description: String,
        details: BillAcceptorStatusDetails,
    ) -> Self {
        Self {
            component,
            state,
            description,
            details,
        }
    }

    pub const fn default() -> Self {
        Self {
            component: HardwareComponent::default(),
            state: HardwareState::default(),
            description: String::new(),
            details: BillAcceptorStatusDetails::default(),
        }
    }

    /// Get the hardware component
    pub fn component(&self) -> HardwareComponent {
        self.component
    }

    /// Set the hardware component
    pub fn set_component(&mut self, component: HardwareComponent) {
        self.component = component;
    }

    /// Get the hardware state
    pub fn state(&self) -> HardwareState {
        self.state
    }

    /// Set the hardware state
    pub fn set_state(&mut self, state: HardwareState) {
        self.state = state;
    }

    /// Set the "worst" state for the HardwareStatus
    /// (e.g. [HardwareState::Error](HardwareState) takes precedence over [HardwareState::OK](HardwareState))
    pub fn set_priority_state(&mut self, proposed: HardwareState) {
        if (proposed as u32) > (self.state as u32) {
            self.state = proposed;
        }
    }

    /// Get the hardware description
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Set the hardware description
    pub fn set_description<S>(&mut self, description: S)
    where
        S: Into<String>,
    {
        self.description = description.into();
    }

    /// Get the BAU status details
    pub fn details(&self) -> &BillAcceptorStatusDetails {
        &self.details
    }

    /// Get a mutable reference to the BAU status details
    pub fn details_mut(&mut self) -> &mut BillAcceptorStatusDetails {
        &mut self.details
    }

    /// Set the BAU status details
    pub fn set_details(&mut self, details: BillAcceptorStatusDetails) {
        self.details = details;
    }
}

impl fmt::Display for HardwareStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let component = self.component();
        let state = self.state();
        let description = self.description();
        let details = self.details();

        write!(f, "{{")?;
        write!(f, r#""component":"{component}","#)?;
        write!(f, r#""state":{state},"#)?;
        write!(f, r#""description":"{description}","#)?;
        write!(f, r#""details":{details}"#)?;
        write!(f, "}}")
    }
}

#[cfg(feature = "std")]
/// Get the device path from the environment, or return the default path
pub fn get_device_path(env_key: &str, default_path: &str) -> String {
    std::env::var(env_key).unwrap_or(default_path.into())
}

#[cfg(not(feature = "std"))]
pub fn get_device_path(_env_key: &str, default_path: &str) -> String {
    default_path.into()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{self, Result};

    #[test]
    fn test_hardware_component_serde() -> Result<()> {
        assert_eq!(serde_json::to_string(&HardwareComponent::CDU)?, r#""CDU""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::EPP)?, r#""EPP""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::SIU)?, r#""SIU""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::RPU)?, r#""RPU""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::MCR)?, r#""MCR""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::BAU)?, r#""BAU""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::BA2)?, r#""BA2""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::BCS)?, r#""BCS""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::CAM)?, r#""CAM""#);
        assert_eq!(serde_json::to_string(&HardwareComponent::UPS)?, r#""UPS""#);

        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""CDU""#)?,
            HardwareComponent::CDU
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""EPP""#)?,
            HardwareComponent::EPP
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""SIU""#)?,
            HardwareComponent::SIU
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""RPU""#)?,
            HardwareComponent::RPU
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""MCR""#)?,
            HardwareComponent::MCR
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""BAU""#)?,
            HardwareComponent::BAU
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""BA2""#)?,
            HardwareComponent::BA2
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""BCS""#)?,
            HardwareComponent::BCS
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""CAM""#)?,
            HardwareComponent::CAM
        );
        assert_eq!(
            serde_json::from_str::<HardwareComponent>(r#""UPS""#)?,
            HardwareComponent::UPS
        );

        Ok(())
    }

    #[test]
    fn test_hardware_state_serde() -> Result<()> {
        assert_eq!(serde_json::to_string(&HardwareState::OK)?, r#""OK""#);
        assert_eq!(
            serde_json::to_string(&HardwareState::Missing)?,
            r#""MISSING""#
        );
        assert_eq!(
            serde_json::to_string(&HardwareState::Warning)?,
            r#""WARNING""#
        );
        assert_eq!(serde_json::to_string(&HardwareState::Error)?, r#""ERROR""#);

        Ok(())
    }

    #[test]
    fn test_bill_acceptor_status_details_serde() -> Result<()> {
        let bau_status_filled = BillAcceptorStatusDetails {
            cashbox_removed: Some(true),
            firmware_version: Some("version-1.0".into()),
            currency: Some(Currency::USD),
            jammed: Some(false),
        };

        let expected = r#"{"cashbox_removed":true,"firmware_version":"version-1.0","currency":"USD","jammed":false}"#;

        assert_eq!(serde_json::to_string(&bau_status_filled)?, expected);

        let des_filled: BillAcceptorStatusDetails = serde_json::from_str(expected)?;

        assert_eq!(des_filled, bau_status_filled);

        let bau_status_sparse = BillAcceptorStatusDetails {
            cashbox_removed: None,
            firmware_version: Some("version-1.0".into()),
            currency: Some(Currency::USD),
            jammed: None,
        };

        let expected = r#"{"cashbox_removed":null,"firmware_version":"version-1.0","currency":"USD","jammed":null}"#;

        assert_eq!(serde_json::to_string(&bau_status_sparse)?, expected);

        let sparse_json = r#"{"firmware_version":"version-1.0","currency":"USD"}"#;
        let des_sparse: BillAcceptorStatusDetails = serde_json::from_str(sparse_json)?;
        assert_eq!(des_sparse, bau_status_sparse);

        Ok(())
    }
}