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
#[cfg(not(feature = "std"))]
use alloc::string::String;

use crate::std;
use std::{fmt, result};

use serde::{Deserialize, Serialize};

pub type Result<T> = result::Result<T, Error>;
pub type JsonRpcResult<T> = result::Result<T, JsonRpcError>;

/// Result status for HAL function calls
#[repr(u16)]
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
pub enum HalResult {
    Success = 0,
    Failure = 1,
    LogicFailure = 2,
    RuntimeFailure = 3,
    InvalidArgumentFailure = 4,
    OutOfRangeFailure = 5,
    NakResponse = 6,
    IllegalCall = 7,
    AsyncInterrupted = 8,
    InsufficientException = 9,
    TimeOut = 10,
    ErrorInvalidArguments = 4105,
    InvalidHandle = 4112,
    IncompleteArguments = 4113,
}

impl From<u16> for HalResult {
    fn from(res: u16) -> Self {
        match res {
            0 => Self::Success,
            1 => Self::Failure,
            2 => Self::LogicFailure,
            3 => Self::RuntimeFailure,
            4 => Self::InvalidArgumentFailure,
            5 => Self::OutOfRangeFailure,
            6 => Self::NakResponse,
            7 => Self::IllegalCall,
            8 => Self::AsyncInterrupted,
            9 => Self::InsufficientException,
            10 => Self::TimeOut,
            4105 => Self::ErrorInvalidArguments,
            4112 => Self::InvalidHandle,
            4113 => Self::IncompleteArguments,
            _ => Self::Failure,
        }
    }
}

impl From<HalResult> for &'static str {
    fn from(res: HalResult) -> Self {
        match res {
            HalResult::Success => "success",
            HalResult::Failure => "failure",
            HalResult::LogicFailure => "logic failure",
            HalResult::RuntimeFailure => "runtime failure",
            HalResult::InvalidArgumentFailure => "invalid argument failure",
            HalResult::OutOfRangeFailure => "out of range failure",
            HalResult::NakResponse => "NAK response",
            HalResult::IllegalCall => "illegal call",
            HalResult::AsyncInterrupted => "async interrupted",
            HalResult::InsufficientException => "insufficient exception",
            HalResult::TimeOut => "time out",
            HalResult::ErrorInvalidArguments => "error invalid arguments",
            HalResult::InvalidHandle => "invalid handle",
            HalResult::IncompleteArguments => "incomplete arguments",
        }
    }
}

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

impl fmt::Display for HalResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = <&'static str>::from(self);
        let code = (*self) as u16;

        write!(f, "{s}: {code}")
    }
}

/// HAL error codes
#[repr(i16)]
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
pub enum HalError {
    LicenseKeyAuthFailure = -18,
    BillPresentInEscrow = -15,
    BillNotPresentInEscrow = -14,
    BillReject = -13,
    PrintImageErr = -12,
    OpenSerialPortFailure = -11,
    BufferOverflow = -10,
    DeviceTimeout = -9,
    LibraryInternalErr = -8,
    DeviceAlreadyOpen = -7,
    DeviceNotReady = -6,
    Cancelled = -5,
    InvalidData = -3,
    DeviceBusy = -2,
    DeviceFailure = -1,
    RequestFieldInvalid = 1,
    InternalErr = 2,
    InternalValidationErr = 3,
    ComponentNotImplemented = 4,
    PreconditionFailed = 5,
    ApplicationTimeout = 6,
    InvalidDenomination = 7,
    ApplicationBusy = 8,
    DeviceCommErr = 9,
    FirmwareErr = 10,
    PhysicalTamper = 11,
    SystemErr = 12,
    MethodNotImplemented = 13,
    DecodingErr = 14,
}

impl From<HalError> for &'static str {
    fn from(err: HalError) -> Self {
        match err {
            HalError::LicenseKeyAuthFailure => "license key auth failure",
            HalError::BillPresentInEscrow => "bill present in escrow",
            HalError::BillNotPresentInEscrow => "bill not present in escrow",
            HalError::BillReject => "bill reject",
            HalError::PrintImageErr => "print image err",
            HalError::OpenSerialPortFailure => "open serial port failure",
            HalError::BufferOverflow => "buffer overflow",
            HalError::DeviceTimeout => "device timeout",
            HalError::LibraryInternalErr => "library internal err",
            HalError::DeviceAlreadyOpen => "device already open",
            HalError::DeviceNotReady => "device not ready",
            HalError::Cancelled => "cancelled",
            HalError::InvalidData => "invalid data",
            HalError::DeviceBusy => "device busy",
            HalError::DeviceFailure => "device failure",
            HalError::RequestFieldInvalid => "request field invalid",
            HalError::InternalErr => "internal err",
            HalError::InternalValidationErr => "internal validation err",
            HalError::ComponentNotImplemented => "component not implemented",
            HalError::PreconditionFailed => "precondition failed",
            HalError::ApplicationTimeout => "application timeout",
            HalError::InvalidDenomination => "invalid denomination",
            HalError::ApplicationBusy => "application busy",
            HalError::DeviceCommErr => "device comm err",
            HalError::FirmwareErr => "firmware err",
            HalError::PhysicalTamper => "physical tamper",
            HalError::SystemErr => "system err",
            HalError::MethodNotImplemented => "method not implemented",
            HalError::DecodingErr => "decoding err",
        }
    }
}

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

impl fmt::Display for HalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s: &'static str = self.into();
        let code = (*self) as i32;

        write!(f, "{s}: {code}")
    }
}

#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum JsonRpcErrorCode {
    HalResult(HalResult),
    HalError(HalError),
    IoError(String),
    JsonError(String),
    SerialError(String),
    GenericError(i64),
    Stop,
}

impl From<HalResult> for JsonRpcErrorCode {
    fn from(err: HalResult) -> Self {
        Self::HalResult(err)
    }
}

impl From<HalError> for JsonRpcErrorCode {
    fn from(err: HalError) -> Self {
        Self::HalError(err)
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for JsonRpcErrorCode {
    fn from(err: std::io::Error) -> Self {
        Self::IoError(format!("{err}"))
    }
}

impl From<serde_json::Error> for JsonRpcErrorCode {
    fn from(err: serde_json::Error) -> Self {
        Self::JsonError(format!("{err}"))
    }
}

impl From<i64> for JsonRpcErrorCode {
    fn from(err: i64) -> Self {
        Self::GenericError(err)
    }
}

impl fmt::Display for JsonRpcErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HalResult(err) => write!(f, "Hal result: {err}"),
            Self::HalError(err) => write!(f, "Hal error: {err}"),
            Self::IoError(err) => write!(f, "I/O error: {err}"),
            Self::JsonError(err) => write!(f, "JSON error: {err}"),
            Self::SerialError(err) => write!(f, "Serial error: {err}"),
            Self::GenericError(err) => write!(f, "Generic error: {err}"),
            Self::Stop => write!(f, "Stop"),
        }
    }
}

/// Basic error type for JSON-RPC messages
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct JsonRpcError {
    /// Error code (if present)
    pub(crate) code: JsonRpcErrorCode,
    /// Error message (if present)
    pub(crate) message: String,
}

impl JsonRpcError {
    /// Create a JsonRpcError
    pub fn new<C, S>(code: C, message: S) -> Self
    where
        C: Into<JsonRpcErrorCode>,
        S: Into<String>,
    {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }

    /// Create a JsonRpcError with a generic failure code
    pub fn failure<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self::new(-1i64, message)
    }

    pub fn stop() -> Self {
        Self::new(JsonRpcErrorCode::Stop, "")
    }

    /// Get the error code
    pub fn code(&self) -> &JsonRpcErrorCode {
        &self.code
    }

    /// Set the error code
    pub fn set_code<C>(&mut self, code: C)
    where
        C: Into<JsonRpcErrorCode>,
    {
        self.code = code.into();
    }

    /// Get the error message
    pub fn message(&self) -> &str {
        &self.message
    }

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

impl fmt::Display for JsonRpcError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "code[{}]: {}", self.code, self.message)
    }
}

impl From<HalResult> for JsonRpcError {
    fn from(res: HalResult) -> Self {
        match res {
            HalResult::Success => Self {
                code: res.into(),
                message: String::new(),
            },
            HalResult::InvalidHandle => Self {
                code: HalError::PreconditionFailed.into(),
                message: "Device handle is invalid".into(),
            },
            HalResult::ErrorInvalidArguments => Self {
                code: HalError::InternalValidationErr.into(),
                message: "One of the passed arguments is NULL".into(),
            },
            HalResult::IncompleteArguments => Self {
                code: HalError::InternalValidationErr.into(),
                message: "One of the passed arguments is incomplete (wrong length)".into(),
            },
            hal_result => Self {
                code: hal_result.into(),
                message: String::new(),
            },
        }
    }
}

#[cfg(feature = "std")]
impl From<JsonRpcError> for std::io::Error {
    fn from(err: JsonRpcError) -> Self {
        Self::new(std::io::ErrorKind::Other, format!("{err}"))
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for JsonRpcError {
    fn from(err: std::io::Error) -> Self {
        Self {
            code: err.into(),
            message: String::new(),
        }
    }
}

impl From<serde_json::Error> for JsonRpcError {
    fn from(err: serde_json::Error) -> Self {
        Self {
            code: err.into(),
            message: String::new(),
        }
    }
}

impl From<std::str::Utf8Error> for JsonRpcError {
    fn from(err: std::str::Utf8Error) -> Self {
        Self::failure(format!("{err}"))
    }
}

/// Basic error type for serial communication
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Error {
    code: ErrorCode,
    message: String,
}

impl Error {
    /// Create a generic failure Error
    pub fn failure<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            code: ErrorCode::Failure,
            message: message.into(),
        }
    }

    /// Create a serial port failure Error
    pub fn serial<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            code: ErrorCode::SerialPort,
            message: message.into(),
        }
    }

    /// Create a JSON-RPC failure Error
    pub fn json_rpc<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            code: ErrorCode::JsonRpc,
            message: message.into(),
        }
    }

    /// Get the error code
    pub fn code(&self) -> ErrorCode {
        self.code
    }

    /// Get the error message
    pub fn message(&self) -> &str {
        self.message.as_str()
    }
}

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

#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Self {
            code: ErrorCode::Failure,
            message: format!("I/O error: {}", err),
        }
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(err: std::str::Utf8Error) -> Self {
        Self {
            code: ErrorCode::Failure,
            message: format!("Utf8 error: {}", err),
        }
    }
}

impl From<serialport::Error> for Error {
    fn from(err: serialport::Error) -> Self {
        Self {
            code: ErrorCode::SerialPort,
            message: format!("Serial port error: {err}"),
        }
    }
}

#[cfg(feature = "std")]
impl<T> From<std::sync::mpsc::SendError<T>> for Error {
    fn from(err: std::sync::mpsc::SendError<T>) -> Self {
        Self::failure(format!("failed to send an item to the queue: {err}"))
    }
}

impl From<&Error> for JsonRpcError {
    fn from(err: &Error) -> Self {
        Self::new(err.code(), err.message())
    }
}

impl From<Error> for JsonRpcError {
    fn from(err: Error) -> Self {
        Self::from(&err)
    }
}

impl From<JsonRpcError> for Error {
    fn from(err: JsonRpcError) -> Self {
        Self::from(&err)
    }
}

impl From<&JsonRpcError> for Error {
    fn from(err: &JsonRpcError) -> Self {
        Self::json_rpc(format!("code[{}]: {}", err.code(), err.message()))
    }
}

/// Error codes for returned errors from acceptor device
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
// FIXME: fill out with more error codes
pub enum ErrorCode {
    /// Generic failure code
    Failure = -1,
    /// Failure code originating from the serial port connection
    SerialPort = -2,
    /// JSON-RPC failure code
    JsonRpc = -3,
}

impl From<ErrorCode> for &'static str {
    fn from(e: ErrorCode) -> Self {
        match e {
            ErrorCode::Failure => "failure",
            ErrorCode::SerialPort => "serial port",
            ErrorCode::JsonRpc => "JSON-RPC",
        }
    }
}

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

impl From<ErrorCode> for JsonRpcErrorCode {
    fn from(e: ErrorCode) -> Self {
        JsonRpcErrorCode::SerialError(format!("{e}"))
    }
}

impl From<&ErrorCode> for JsonRpcErrorCode {
    fn from(e: &ErrorCode) -> Self {
        (*e).into()
    }
}

impl From<JsonRpcErrorCode> for ErrorCode {
    fn from(_e: JsonRpcErrorCode) -> Self {
        Self::JsonRpc
    }
}

impl From<&JsonRpcErrorCode> for ErrorCode {
    fn from(_e: &JsonRpcErrorCode) -> Self {
        Self::JsonRpc
    }
}

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