cc_talk_core 0.0.4

A no-std implementation of the CCtalk 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
/// ccTalk fault codes as defined in the ccTalk Generic Specification
/// Table 3 - ccTalk Fault Code Table
///
/// These are status codes returned in response to a 'Perform self-check' command.
/// All non-zero fault codes are 'fatal' errors that prevent normal operation and
/// require service intervention. The device automatically inhibits operation when
/// a fault is detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FaultCode {
    /// No fault detected - normal operating condition
    Ok = 0,

    /// EEPROM checksum corrupted
    ///
    /// The coin acceptor found a mismatch between the checksum calculated from
    /// a coin data area and a stored checksum. Indicates possible EEPROM corruption.
    /// This checksum is not intended for use with program code/firmware.
    EepromChecksumCorrupted = 1,

    /// Fault on inductive coils
    ///
    /// A fault was detected with the coils for inductive coin validation.
    /// Optional extra info: Coil number
    InductiveCoilsFault = 2,

    /// Fault on credit sensor
    ///
    /// A fault was detected with the post-gate credit sensor. A serial credit
    /// can only be generated if the coin passes this sensor.
    CreditSensorFault = 3,

    /// Fault on piezo sensor
    ///
    /// A fault was detected on the piezo sensor used for slug rejection.
    PiezoSensorFault = 4,

    /// Fault on reflective sensor
    ///
    /// A fault was detected on an opto-reflective sensor for coin validation.
    ReflectiveSensorFault = 5,

    /// Fault on diameter sensor
    ///
    /// A fault was detected on a validation sensor specifically reserved for
    /// diameter resolution.
    DiameterSensorFault = 6,

    /// Fault on wake-up sensor
    ///
    /// A fault was detected on the sensor used to wake-up a coin acceptor from
    /// a sleeping or power-down state.
    WakeUpSensorFault = 7,

    /// Fault on sorter exit sensors
    ///
    /// A fault was detected on the sorter exit sensors. These sensors confirm
    /// that a coin has cleared the sorter flaps and perhaps to verify the path taken.
    /// Optional extra info: Sensor number
    SorterExitSensorsFault = 8,

    /// NVRAM checksum corrupted
    ///
    /// If battery-backed RAM is used then a corrupted checksum was discovered.
    NvramChecksumCorrupted = 9,

    /// Coin dispensing error (Obsolete)
    ///
    /// A fault was found during a hopper coin dispense operation.
    /// Note: This fault code is obsolete and was incorporated into the 'Test hopper' command.
    CoinDispensingError = 10,

    /// Low level sensor error (Obsolete)
    ///
    /// A fault was found on a hopper low level sensor.
    /// Note: This fault code is obsolete and was incorporated into the 'Test hopper' command.
    /// Optional extra info: Hopper or tube number
    LowLevelSensorError = 11,

    /// High level sensor error (Obsolete)
    ///
    /// A fault was found on a hopper high level sensor.
    /// Note: This fault code is obsolete and was incorporated into the 'Test hopper' command.
    /// Optional extra info: Hopper or tube number
    HighLevelSensorError = 12,

    /// Coin counting error (Obsolete)
    ///
    /// A fault was detected in the hopper 'dead reckoning' system. It probably ran out of coins.
    /// Note: This fault code is obsolete and was incorporated into the 'Test hopper' command.
    CoinCountingError = 13,

    /// Keypad error
    ///
    /// A fault was found on a keypad.
    /// Optional extra info: Key number
    KeypadError = 14,

    /// Button error
    ///
    /// A fault was found on a button.
    ButtonError = 15,

    /// Display error
    ///
    /// A fault was found on a display device.
    DisplayError = 16,

    /// Coin auditing error
    ///
    /// A fault was detected in the memory block used to record the number of
    /// inserted and accepted coins on a coin acceptor.
    CoinAuditingError = 17,

    /// Fault on reject sensor
    ///
    /// A fault was detected with the reject sensor. This is the sensor used to
    /// confirm a coin has left the reject path and has been returned to the customer.
    RejectSensorFault = 18,

    /// Fault on coin return mechanism
    ///
    /// A fault was detected in the flight deck mechanism used by the customer
    /// to clear coin jams in the entry or validation area.
    CoinReturnMechanismFault = 19,

    /// Fault on C.O.S. mechanism
    ///
    /// A fault was found on the 'Coin on String' sensor.
    CosMechanismFault = 20,

    /// Fault on rim sensor
    ///
    /// A fault was found on a coin rim validation sensor.
    RimSensorFault = 21,

    /// Fault on thermistor
    ///
    /// A fault was found on a thermistor used to measure ambient temperature.
    ThermistorFault = 22,

    /// Payout motor fault
    ///
    /// A fault was found on a hopper motor (used on changers).
    /// Optional extra info: Hopper number
    PayoutMotorFault = 23,

    /// Payout timeout (Obsolete)
    ///
    /// A coin was dispensed from a hopper but was not seen on the payout verification sensor.
    /// Note: This fault code is obsolete and was incorporated into the 'Test hopper' command.
    /// Optional extra info: Hopper or tube number
    PayoutTimeout = 24,

    /// Payout jammed (Obsolete)
    ///
    /// A jam was detected in a hopper.
    /// Note: This fault code is obsolete and was incorporated into the 'Test hopper' command.
    /// Optional extra info: Hopper or tube number
    PayoutJammed = 25,

    /// Payout sensor fault
    ///
    /// A fault was found on a hopper payout verification sensor (used on changers).
    /// Optional extra info: Hopper or tube number
    PayoutSensorFault = 26,

    /// Level sensor error
    ///
    /// A fault was found on a hopper level sensor.
    /// Optional extra info: Hopper or tube number
    LevelSensorError = 27,

    /// Personality module not fitted
    ///
    /// A personality or configuration module needed with some ccTalk peripherals was not fitted.
    PersonalityModuleNotFitted = 28,

    /// Personality checksum corrupted
    ///
    /// A data checksum on a personality or configuration module was corrupted.
    PersonalityChecksumCorrupted = 29,

    /// ROM checksum mismatch
    ///
    /// The device has found a mismatch between the checksum calculated from a program
    /// code area and a stored checksum. Possible flash memory/ROM corruption.
    /// Now used for any kind of application firmware checksum error.
    RomChecksumMismatch = 30,

    /// Missing slave device (Obsolete)
    ///
    /// A ccTalk peripheral did not find an attached slave device.
    /// Only of use in multi-master systems.
    /// Optional extra info: Slave address
    MissingSlaveDevice = 31,

    /// Internal comms bad
    ///
    /// A ccTalk peripheral could not access an internal serial device.
    /// Optional extra info: Slave address
    InternalCommsBad = 32,

    /// Supply voltage outside operating limits
    ///
    /// The ccTalk device is operating outside supply voltage limits defined
    /// in the product specification.
    SupplyVoltageOutsideLimits = 33,

    /// Temperature outside operating limits
    ///
    /// The ccTalk device is operating outside temperature limits defined
    /// in the product specification.
    TemperatureOutsideLimits = 34,

    /// D.C.E. fault
    ///
    /// A fault was found on the Dual Coin Entry chute.
    /// Optional extra info: 1 = coin, 2 = token
    DceFault = 35,

    /// Fault on bill validation sensor
    ///
    /// A fault was found on one of the bill validator validation sensors.
    /// Optional extra info: Sensor number
    BillValidationSensorFault = 36,

    /// Fault on bill transport motor
    ///
    /// A fault was found on the motor used to drive a bill through the bill validator.
    BillTransportMotorFault = 37,

    /// Fault on stacker
    ///
    /// A fault was found on the stacker attached to a bill validator.
    StackerFault = 38,

    /// Bill jammed
    ///
    /// A bill is stuck in the bill validator.
    BillJammed = 39,

    /// RAM test fail
    ///
    /// A read/write test cycle of the bill validator RAM has indicated a fault.
    RamTestFail = 40,

    /// Fault on string sensor
    ///
    /// A fault was found on a sensor used for detecting bills on a string.
    StringSensorFault = 41,

    /// Accept gate failed open
    ///
    /// The coin accept gate is stuck open due to a jam or fraud attempt.
    AcceptGateFailedOpen = 42,

    /// Accept gate failed closed
    ///
    /// The coin accept gate is stuck closed. Possible open-circuit fault on the solenoid driver.
    AcceptGateFailedClosed = 43,

    /// Stacker missing
    ///
    /// The stacker is not fitted and needs to be for notes to accept.
    StackerMissing = 44,

    /// Stacker full
    ///
    /// The stacker is full and needs emptying.
    StackerFull = 45,

    /// Flash memory erase fail
    ///
    /// The last flash memory erase cycle did not complete successfully.
    FlashMemoryEraseFail = 46,

    /// Flash memory write fail
    ///
    /// The last flash memory write cycle did not complete successfully.
    FlashMemoryWriteFail = 47,

    /// Slave device not responding
    ///
    /// If an attached device acts as a host to other slave devices then this fault
    /// code indicates a failure to communicate with those other devices.
    /// Optional extra info: Device number
    SlaveDeviceNotResponding = 48,

    /// Fault on opto sensor
    ///
    /// A fault was detected on an opto-electronic sensor.
    /// Optional extra info: Opto number
    OptoSensorFault = 49,

    /// Battery fault
    ///
    /// A system battery is missing or low on charge and requires replacing/recharging.
    BatteryFault = 50,

    /// Door open
    ///
    /// A door on the system was left in the open position. It must be shut to continue.
    DoorOpen = 51,

    /// Microswitch fault
    ///
    /// A fault was detected on a microswitch.
    MicroswitchFault = 52,

    /// RTC fault
    ///
    /// A fault was detected on the Real Time Clock.
    RtcFault = 53,

    /// Firmware error
    ///
    /// A non-checksum type error was detected in the firmware or the firmware of
    /// an attached peripheral. Self-calculated checksum errors should be reported
    /// in fault code 30.
    FirmwareError = 54,

    /// Initialisation error
    ///
    /// An initialisation error was detected in the peripheral on power-up.
    /// The optional extra info field can break this down further if required.
    InitialisationError = 55,

    /// Supply current outside operating limits
    ///
    /// The ccTalk device is operating outside supply current limits defined in
    /// the product specification. There may be a short or a faulty component.
    SupplyCurrentOutsideLimits = 56,

    /// Forced bootloader mode
    ///
    /// An external input was used to force the device into a bootloader mode.
    /// From here firmware can be re-programmed and the device reset. This is a
    /// special mode which stops the main application firmware from running.
    ForcedBootloaderMode = 57,

    /// Unspecified fault code
    ///
    /// Any fault code which does not fall into the above categories. Some manufacturers
    /// may wish to use the optional byte to specify a manufacturer-specific fault code.
    /// Optional extra info: Further information
    UnspecifiedFault = 255,
}

impl FaultCode {
    /// Returns true if this fault code can have optional extra information
    ///
    /// Some fault codes support an additional byte of information to provide
    /// more specific details about the fault (e.g., which sensor failed).
    #[must_use]
    pub const fn has_optional_info(&self) -> bool {
        matches!(
            self,
            Self::InductiveCoilsFault
                | Self::SorterExitSensorsFault
                | Self::LowLevelSensorError
                | Self::HighLevelSensorError
                | Self::KeypadError
                | Self::PayoutMotorFault
                | Self::PayoutTimeout
                | Self::PayoutJammed
                | Self::PayoutSensorFault
                | Self::LevelSensorError
                | Self::MissingSlaveDevice
                | Self::InternalCommsBad
                | Self::DceFault
                | Self::BillValidationSensorFault
                | Self::SlaveDeviceNotResponding
                | Self::OptoSensorFault
                | Self::UnspecifiedFault
        )
    }

    /// Returns true if this fault code is marked as obsolete in the specification
    ///
    /// Obsolete fault codes were incorporated into the 'Test hopper' command
    /// in a past revision of the protocol.
    #[must_use]
    pub const fn is_obsolete(&self) -> bool {
        matches!(
            self,
            Self::CoinDispensingError
                | Self::LowLevelSensorError
                | Self::HighLevelSensorError
                | Self::CoinCountingError
                | Self::PayoutTimeout
                | Self::PayoutJammed
                | Self::MissingSlaveDevice
        )
    }

    /// Returns true if this fault code indicates normal operation (no fault)
    #[must_use]
    pub const fn is_ok(&self) -> bool {
        matches!(self, Self::Ok)
    }

    /// Returns true if this fault code indicates a fatal error requiring service
    ///
    /// All non-zero fault codes are considered fatal and prevent normal operation.
    #[must_use]
    pub const fn is_fatal(&self) -> bool {
        !self.is_ok()
    }
}

impl TryFrom<u8> for FaultCode {
    type Error = InvalidFaultCode;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::Ok),
            1 => Ok(Self::EepromChecksumCorrupted),
            2 => Ok(Self::InductiveCoilsFault),
            3 => Ok(Self::CreditSensorFault),
            4 => Ok(Self::PiezoSensorFault),
            5 => Ok(Self::ReflectiveSensorFault),
            6 => Ok(Self::DiameterSensorFault),
            7 => Ok(Self::WakeUpSensorFault),
            8 => Ok(Self::SorterExitSensorsFault),
            9 => Ok(Self::NvramChecksumCorrupted),
            10 => Ok(Self::CoinDispensingError),
            11 => Ok(Self::LowLevelSensorError),
            12 => Ok(Self::HighLevelSensorError),
            13 => Ok(Self::CoinCountingError),
            14 => Ok(Self::KeypadError),
            15 => Ok(Self::ButtonError),
            16 => Ok(Self::DisplayError),
            17 => Ok(Self::CoinAuditingError),
            18 => Ok(Self::RejectSensorFault),
            19 => Ok(Self::CoinReturnMechanismFault),
            20 => Ok(Self::CosMechanismFault),
            21 => Ok(Self::RimSensorFault),
            22 => Ok(Self::ThermistorFault),
            23 => Ok(Self::PayoutMotorFault),
            24 => Ok(Self::PayoutTimeout),
            25 => Ok(Self::PayoutJammed),
            26 => Ok(Self::PayoutSensorFault),
            27 => Ok(Self::LevelSensorError),
            28 => Ok(Self::PersonalityModuleNotFitted),
            29 => Ok(Self::PersonalityChecksumCorrupted),
            30 => Ok(Self::RomChecksumMismatch),
            31 => Ok(Self::MissingSlaveDevice),
            32 => Ok(Self::InternalCommsBad),
            33 => Ok(Self::SupplyVoltageOutsideLimits),
            34 => Ok(Self::TemperatureOutsideLimits),
            35 => Ok(Self::DceFault),
            36 => Ok(Self::BillValidationSensorFault),
            37 => Ok(Self::BillTransportMotorFault),
            38 => Ok(Self::StackerFault),
            39 => Ok(Self::BillJammed),
            40 => Ok(Self::RamTestFail),
            41 => Ok(Self::StringSensorFault),
            42 => Ok(Self::AcceptGateFailedOpen),
            43 => Ok(Self::AcceptGateFailedClosed),
            44 => Ok(Self::StackerMissing),
            45 => Ok(Self::StackerFull),
            46 => Ok(Self::FlashMemoryEraseFail),
            47 => Ok(Self::FlashMemoryWriteFail),
            48 => Ok(Self::SlaveDeviceNotResponding),
            49 => Ok(Self::OptoSensorFault),
            50 => Ok(Self::BatteryFault),
            51 => Ok(Self::DoorOpen),
            52 => Ok(Self::MicroswitchFault),
            53 => Ok(Self::RtcFault),
            54 => Ok(Self::FirmwareError),
            55 => Ok(Self::InitialisationError),
            56 => Ok(Self::SupplyCurrentOutsideLimits),
            57 => Ok(Self::ForcedBootloaderMode),
            255 => Ok(Self::UnspecifiedFault),
            _ => Err(InvalidFaultCode(value)),
        }
    }
}

impl From<FaultCode> for u8 {
    fn from(fault: FaultCode) -> Self {
        fault as Self
    }
}

/// Error type for invalid fault codes
///
/// Returned when attempting to convert a u8 value that doesn't correspond
/// to a valid ccTalk fault code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct InvalidFaultCode(pub u8);

impl core::fmt::Display for InvalidFaultCode {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Invalid ccTalk fault code: {}", self.0)
    }
}

/// Represents a ccTalk fault with optional extra information
///
/// Some fault codes can include an additional byte of information to provide
/// more specific details about the fault condition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Fault {
    pub code: FaultCode,
    pub extra_info: Option<u8>,
}

impl Fault {
    /// Creates a new fault with no extra information
    #[must_use]
    pub const fn new(code: FaultCode) -> Self {
        Self {
            code,
            extra_info: None,
        }
    }

    /// Creates a new fault with extra information
    ///
    /// # Panics
    ///
    /// Panics if the fault code doesn't support optional extra information.
    /// Use `try_with_info` for a non-panicking version.
    #[must_use]
    pub fn with_info(code: FaultCode, info: u8) -> Self {
        assert!(
            code.has_optional_info(),
            "Fault code {code:?} does not support optional extra information",
        );
        Self {
            code,
            extra_info: Some(info),
        }
    }

    /// Attempts to create a new fault with extra information
    ///
    /// # Errors
    ///
    /// Returns `Err` if the fault code doesn't support optional extra information.
    pub const fn try_with_info(code: FaultCode, info: u8) -> Result<Self, &'static str> {
        if code.has_optional_info() {
            Ok(Self {
                code,
                extra_info: Some(info),
            })
        } else {
            Err("Fault code does not support optional extra information")
        }
    }

    /// Returns true if this fault indicates normal operation
    #[must_use]
    pub const fn is_ok(&self) -> bool {
        self.code.is_ok()
    }

    /// Returns true if this fault indicates a fatal error requiring service
    #[must_use]
    pub const fn is_fatal(&self) -> bool {
        self.code.is_fatal()
    }
}