1#![cfg_attr(docsrs, feature(doc_cfg))]
2use bitflags::bitflags;
5use bytes::{Buf, Bytes};
6use thiserror::Error;
7
8pub const HEADER_SIZE: usize = 8;
10
11bitflags! {
12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
14 pub struct CommandFlags: u16 {
15 const ACK_REQUIRED = 0x0001;
17 const BROADCAST = 0x8000;
19 const SCHEDULED_ACTION = 0x0002;
24 }
25}
26
27pub mod command_id {
34 pub const READMEM_CMD: u16 = 0x0800;
36 pub const READMEM_ACK: u16 = 0x0801;
38 pub const WRITEMEM_CMD: u16 = 0x0802;
40 pub const WRITEMEM_ACK: u16 = 0x0803;
42 pub const PENDING_ACK: u16 = 0x0805;
44 pub const EVENT_CMD: u16 = 0x0C00;
46 pub const EVENT_ACK: u16 = 0x0C01;
48}
49
50pub mod ccd_flags {
56 pub const REQUEST_ACK: u16 = 1 << 14;
58 pub const COMMAND_RESEND: u16 = 1 << 15;
60}
61
62pub const PENDING_ACK_COMMAND: u16 = command_id::PENDING_ACK;
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum OpCode {
79 ReadRegister,
81 WriteRegister,
83 ReadMem,
85 WriteMem,
87}
88
89impl OpCode {
90 pub const fn command_code(self) -> u16 {
92 match self {
93 OpCode::ReadRegister => 0x0080,
94 OpCode::WriteRegister => 0x0082,
95 OpCode::ReadMem => 0x0084,
96 OpCode::WriteMem => 0x0086,
97 }
98 }
99
100 pub const fn ack_code(self) -> u16 {
102 self.command_code() + 1
103 }
104
105 #[allow(dead_code)]
106 fn from_command(code: u16) -> Result<Self, GenCpError> {
107 match code {
108 0x0080 => Ok(OpCode::ReadRegister),
109 0x0082 => Ok(OpCode::WriteRegister),
110 0x0084 => Ok(OpCode::ReadMem),
111 0x0086 => Ok(OpCode::WriteMem),
112 _ => Err(GenCpError::UnknownOpcode(code)),
113 }
114 }
115
116 fn from_ack(code: u16) -> Result<Self, GenCpError> {
117 match code {
118 0x0081 => Ok(OpCode::ReadRegister),
119 0x0083 => Ok(OpCode::WriteRegister),
120 0x0085 => Ok(OpCode::ReadMem),
121 0x0087 => Ok(OpCode::WriteMem),
122 _ => Err(GenCpError::UnknownOpcode(code)),
123 }
124 }
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
146#[non_exhaustive]
147pub enum StatusCode {
148 Success,
150 NotImplemented,
152 InvalidParameter,
154 InvalidAddress,
156 WriteProtect,
160 BadAlignment,
162 AccessDenied,
168 Busy,
172 InvalidHeader,
175 WrongConfig,
178 GenericError,
180}
181
182impl StatusCode {
183 pub const fn from_raw(raw: u16) -> Option<Self> {
186 Some(match raw {
187 0x0000 => StatusCode::Success,
188 0x8001 => StatusCode::NotImplemented,
189 0x8002 => StatusCode::InvalidParameter,
190 0x8003 => StatusCode::InvalidAddress,
191 0x8004 => StatusCode::WriteProtect,
192 0x8005 => StatusCode::BadAlignment,
193 0x8006 => StatusCode::AccessDenied,
194 0x8007 => StatusCode::Busy,
195 0x800E => StatusCode::InvalidHeader,
196 0x800F => StatusCode::WrongConfig,
197 0x8FFF => StatusCode::GenericError,
198 _ => return None,
199 })
200 }
201
202 pub const fn to_raw(self) -> u16 {
204 match self {
205 StatusCode::Success => 0x0000,
206 StatusCode::NotImplemented => 0x8001,
207 StatusCode::InvalidParameter => 0x8002,
208 StatusCode::InvalidAddress => 0x8003,
209 StatusCode::WriteProtect => 0x8004,
210 StatusCode::BadAlignment => 0x8005,
211 StatusCode::AccessDenied => 0x8006,
212 StatusCode::Busy => 0x8007,
213 StatusCode::InvalidHeader => 0x800E,
214 StatusCode::WrongConfig => 0x800F,
215 StatusCode::GenericError => 0x8FFF,
216 }
217 }
218
219 pub const fn name(self) -> &'static str {
221 match self {
222 StatusCode::Success => "SUCCESS",
223 StatusCode::NotImplemented => "NOT_IMPLEMENTED",
224 StatusCode::InvalidParameter => "INVALID_PARAMETER",
225 StatusCode::InvalidAddress => "INVALID_ADDRESS",
226 StatusCode::WriteProtect => "WRITE_PROTECT",
227 StatusCode::BadAlignment => "BAD_ALIGNMENT",
228 StatusCode::AccessDenied => "ACCESS_DENIED",
229 StatusCode::Busy => "BUSY",
230 StatusCode::InvalidHeader => "INVALID_HEADER",
231 StatusCode::WrongConfig => "WRONG_CONFIG",
232 StatusCode::GenericError => "ERROR",
233 }
234 }
235
236 pub const fn is_retryable(self) -> bool {
241 matches!(self, StatusCode::Busy)
242 }
243}
244
245impl std::fmt::Display for StatusCode {
252 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253 write!(f, "{} (0x{:04X})", self.name(), self.to_raw())
254 }
255}
256
257#[macro_export]
263#[doc(hidden)]
264macro_rules! transport_status {
265 (
266 $(#[$meta:meta])*
267 $vis:vis enum $name:ident {
268 $(
269 $(#[$variant_meta:meta])*
270 $variant:ident = $raw:literal, $spec:literal;
271 )*
272 }
273 ) => {
274 $(#[$meta])*
275 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
276 #[non_exhaustive]
277 $vis enum $name {
278 Common($crate::StatusCode),
281 $(
282 $(#[$variant_meta])*
283 $variant,
284 )*
285 Unknown(u16),
288 }
289
290 impl $name {
291 pub const fn from_raw(raw: u16) -> Self {
293 match raw {
294 $($raw => $name::$variant,)*
295 _ => match $crate::StatusCode::from_raw(raw) {
296 Some(common) => $name::Common(common),
297 None => $name::Unknown(raw),
298 },
299 }
300 }
301
302 pub const fn to_raw(self) -> u16 {
304 match self {
305 $name::Common(common) => common.to_raw(),
306 $($name::$variant => $raw,)*
307 $name::Unknown(raw) => raw,
308 }
309 }
310
311 pub const fn name(self) -> &'static str {
313 match self {
314 $name::Common(common) => common.name(),
315 $($name::$variant => $spec,)*
316 $name::Unknown(_) => "unknown status",
317 }
318 }
319
320 pub const fn common(self) -> Option<$crate::StatusCode> {
323 match self {
324 $name::Common(common) => Some(common),
325 _ => None,
326 }
327 }
328
329 pub const fn is_success(self) -> bool {
331 matches!(self, $name::Common($crate::StatusCode::Success))
332 }
333
334 pub const fn is_retryable(self) -> bool {
337 matches!(self, $name::Common($crate::StatusCode::Busy))
338 }
339 }
340
341 impl From<$crate::StatusCode> for $name {
342 fn from(common: $crate::StatusCode) -> Self {
343 $name::Common(common)
344 }
345 }
346
347 impl ::std::fmt::Display for $name {
349 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
350 write!(f, "{} (0x{:04X})", self.name(), self.to_raw())
351 }
352 }
353 };
354}
355
356#[derive(Debug, Error)]
358#[non_exhaustive]
359pub enum GenCpError {
360 #[error("invalid packet: {0}")]
361 InvalidPacket(&'static str),
363 #[error("unknown opcode: {0:#06x}")]
364 UnknownOpcode(u16),
366 #[error("io: {0}")]
367 Io(#[from] std::io::Error),
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub struct AckHeader {
374 pub status: u16,
378 pub opcode: OpCode,
380 pub length: u16,
382 pub request_id: u16,
384}
385
386#[derive(Debug, Clone)]
388pub struct GenCpAck {
389 pub header: AckHeader,
391 pub payload: Bytes,
393}
394
395pub fn decode_ack(buf: &[u8]) -> Result<GenCpAck, GenCpError> {
397 if buf.len() < HEADER_SIZE {
398 return Err(GenCpError::InvalidPacket("too short"));
399 }
400 let mut cursor = buf;
401 let status_raw = cursor.get_u16();
402 let opcode_raw = cursor.get_u16();
403 let length = cursor.get_u16();
404 let request_id = cursor.get_u16();
405
406 let expected = HEADER_SIZE + length as usize;
407 if buf.len() != expected {
408 return Err(GenCpError::InvalidPacket("length mismatch"));
409 }
410
411 let opcode = OpCode::from_ack(opcode_raw)?;
412
413 let payload = Bytes::copy_from_slice(&buf[HEADER_SIZE..]);
414 Ok(GenCpAck {
415 header: AckHeader {
416 status: status_raw,
417 opcode,
418 length,
419 request_id,
420 },
421 payload,
422 })
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428 use bytes::{BufMut, BytesMut};
429
430 const SPEC_STATUS_TABLE: &[(u16, StatusCode, &str)] = &[
435 (0x0000, StatusCode::Success, "SUCCESS"),
436 (0x8001, StatusCode::NotImplemented, "NOT_IMPLEMENTED"),
437 (0x8002, StatusCode::InvalidParameter, "INVALID_PARAMETER"),
438 (0x8003, StatusCode::InvalidAddress, "INVALID_ADDRESS"),
439 (0x8004, StatusCode::WriteProtect, "WRITE_PROTECT"),
440 (0x8005, StatusCode::BadAlignment, "BAD_ALIGNMENT"),
441 (0x8006, StatusCode::AccessDenied, "ACCESS_DENIED"),
442 (0x8007, StatusCode::Busy, "BUSY"),
443 (0x800E, StatusCode::InvalidHeader, "INVALID_HEADER"),
444 (0x800F, StatusCode::WrongConfig, "WRONG_CONFIG"),
445 (0x8FFF, StatusCode::GenericError, "ERROR"),
446 ];
447
448 #[test]
449 fn status_table_matches_the_specification() {
450 for &(raw, expected, name) in SPEC_STATUS_TABLE {
451 assert_eq!(
452 StatusCode::from_raw(raw),
453 Some(expected),
454 "decoding {raw:#06x} ({name})"
455 );
456 assert_eq!(expected.to_raw(), raw, "re-encoding {name}");
457 assert_eq!(expected.name(), name);
458 }
459 }
460
461 #[test]
462 fn regression_the_three_codes_we_used_to_mislabel() {
463 assert_eq!(StatusCode::from_raw(0x8004), Some(StatusCode::WriteProtect));
466 assert!(!StatusCode::WriteProtect.is_retryable());
467
468 assert_eq!(StatusCode::from_raw(0x8005), Some(StatusCode::BadAlignment));
470
471 assert_eq!(StatusCode::from_raw(0x8006), Some(StatusCode::AccessDenied));
474 assert_eq!(StatusCode::from_raw(32774), Some(StatusCode::AccessDenied));
475
476 assert!(StatusCode::Busy.is_retryable());
478 assert!(!StatusCode::Success.is_retryable());
479 }
480
481 #[test]
482 fn display_carries_both_the_name_and_the_raw_value() {
483 assert_eq!(
484 StatusCode::AccessDenied.to_string(),
485 "ACCESS_DENIED (0x8006)"
486 );
487 }
488
489 #[test]
490 fn transport_specific_codes_are_not_in_the_shared_core() {
491 assert_eq!(StatusCode::from_raw(0x800B), None);
496 assert_eq!(StatusCode::from_raw(0x800C), None);
499 assert_eq!(StatusCode::from_raw(0xA001), None);
500 }
501
502 #[allow(unreachable_pub)]
505 mod example {
506 transport_status! {
507 pub(crate) enum Example {
509 Mine = 0x800B, "MINE";
511 }
512 }
513 }
514 use example::Example;
515
516 #[test]
517 fn a_transport_status_wraps_the_core_and_keeps_the_rest() {
518 assert_eq!(Example::from_raw(0x800B), Example::Mine);
519 assert_eq!(
520 Example::from_raw(0x8006),
521 Example::Common(StatusCode::AccessDenied)
522 );
523 assert_eq!(Example::from_raw(0x8123), Example::Unknown(0x8123));
524 for raw in [0x0000, 0x800B, 0x8006, 0x8123] {
525 assert_eq!(Example::from_raw(raw).to_raw(), raw, "{raw:#06x}");
526 }
527 assert_eq!(Example::Mine.to_string(), "MINE (0x800B)");
528 assert_eq!(
529 Example::Unknown(0x8123).to_string(),
530 "unknown status (0x8123)"
531 );
532 assert!(Example::from_raw(0x8007).is_retryable());
533 assert!(Example::from_raw(0).is_success());
534 assert_eq!(Example::Mine.common(), None);
535 }
536
537 #[test]
538 fn pending_ack_is_a_command_id_not_a_status() {
539 assert_eq!(PENDING_ACK_COMMAND, 0x0805);
541 assert_ne!(PENDING_ACK_COMMAND, StatusCode::AccessDenied.to_raw());
542 assert_eq!(OpCode::ReadMem.command_code(), 0x0084);
544 assert_eq!(OpCode::WriteMem.command_code(), 0x0086);
545 }
546
547 #[test]
548 fn decode_read_register_ack() {
549 let value = 0x0000_0002u32;
550 let mut buf = BytesMut::with_capacity(HEADER_SIZE + 4);
551 buf.put_u16(0x0000);
552 buf.put_u16(0x0081);
553 buf.put_u16(4);
554 buf.put_u16(0x4141);
555 buf.put_u32(value);
556
557 let ack = decode_ack(&buf).expect("decode");
558 assert_eq!(ack.header.status, StatusCode::Success.to_raw());
559 assert_eq!(ack.header.opcode, OpCode::ReadRegister);
560 assert_eq!(ack.header.length, 4);
561 assert_eq!(ack.header.request_id, 0x4141);
562 assert_eq!(&ack.payload[..], &value.to_be_bytes());
563 }
564
565 #[test]
566 fn decode_write_register_ack() {
567 let index = 1u32;
568 let mut buf = BytesMut::with_capacity(HEADER_SIZE + 4);
569 buf.put_u16(0x0000);
570 buf.put_u16(0x0083);
571 buf.put_u16(4);
572 buf.put_u16(0x4343);
573 buf.put_u32(index);
574
575 let ack = decode_ack(&buf).expect("decode");
576 assert_eq!(ack.header.status, StatusCode::Success.to_raw());
577 assert_eq!(ack.header.opcode, OpCode::WriteRegister);
578 assert_eq!(ack.header.length, 4);
579 assert_eq!(ack.header.request_id, 0x4343);
580 assert_eq!(&ack.payload[..], &index.to_be_bytes());
581 }
582
583 #[test]
584 fn decode_read_mem_ack() {
585 let payload = vec![0xAA; 4];
586 let mut buf = BytesMut::with_capacity(HEADER_SIZE + payload.len());
587 buf.put_u16(0x0000);
588 buf.put_u16(0x0085);
589 buf.put_u16(payload.len() as u16);
590 buf.put_u16(0x4242);
591 buf.extend_from_slice(&payload);
592
593 let ack = decode_ack(&buf).expect("decode");
594 assert_eq!(ack.header.status, StatusCode::Success.to_raw());
595 assert_eq!(ack.header.opcode, OpCode::ReadMem);
596 assert_eq!(ack.header.length as usize, payload.len());
597 assert_eq!(ack.header.request_id, 0x4242);
598 assert_eq!(&ack.payload[..], &payload[..]);
599 }
600
601 #[test]
602 fn decode_write_mem_ack() {
603 let payload: Vec<u8> = Vec::new();
604 let mut buf = BytesMut::with_capacity(HEADER_SIZE + payload.len());
605 buf.put_u16(0x0000);
606 buf.put_u16(0x0087);
607 buf.put_u16(0);
608 buf.put_u16(0x1001);
609 let ack = decode_ack(&buf).expect("decode");
610 assert_eq!(ack.header.opcode, OpCode::WriteMem);
611 assert_eq!(ack.header.status, StatusCode::Success.to_raw());
612 assert_eq!(ack.payload.len(), 0);
613 }
614
615 const GOLDEN_READ_REGISTER_ACK: [u8; 12] = [
635 0x00, 0x00, 0x00, 0x81, 0x00, 0x04, 0x12, 0x34, 0x00, 0x00, 0x3E, 0xF2, ];
641
642 #[test]
643 fn ack_header_fields_sit_at_the_specified_offsets() {
644 let b = &GOLDEN_READ_REGISTER_ACK;
645 assert_eq!(u16::from_be_bytes([b[0], b[1]]), 0x0000, "status at 0");
646 assert_eq!(u16::from_be_bytes([b[2], b[3]]), 0x0081, "ack id at 2");
647 assert_eq!(u16::from_be_bytes([b[4], b[5]]), 4, "length at 4");
648 assert_eq!(u16::from_be_bytes([b[6], b[7]]), 0x1234, "request id at 6");
649 assert_eq!(HEADER_SIZE, 8, "the payload begins at offset 8");
650
651 let ack = decode_ack(b).expect("decode the golden ack");
652 assert_eq!(ack.header.status, StatusCode::Success.to_raw());
653 assert_eq!(ack.header.opcode, OpCode::ReadRegister);
654 assert_eq!(ack.header.length, 4);
655 assert_eq!(ack.header.request_id, 0x1234);
656 assert_eq!(&ack.payload[..], &[0x00, 0x00, 0x3E, 0xF2]);
657 }
658
659 #[test]
665 fn ack_length_counts_the_payload_only() {
666 let mut counts_the_header = GOLDEN_READ_REGISTER_ACK;
667 counts_the_header[4..6].copy_from_slice(&12u16.to_be_bytes());
668 assert!(
669 decode_ack(&counts_the_header).is_err(),
670 "a length of 12 describes a 20-byte datagram, not this one"
671 );
672
673 let mut over_promises = GOLDEN_READ_REGISTER_ACK;
675 over_promises[4..6].copy_from_slice(&8u16.to_be_bytes());
676 assert!(decode_ack(&over_promises).is_err());
677 }
678
679 #[test]
682 fn ack_ids_are_command_ids_plus_one() {
683 for (cmd, ack) in [
684 (0x0080u16, 0x0081u16),
685 (0x0082, 0x0083),
686 (0x0084, 0x0085),
687 (0x0086, 0x0087),
688 ] {
689 assert_eq!(
690 OpCode::from_command(cmd).expect("command id").ack_code(),
691 ack
692 );
693 assert!(
694 OpCode::from_ack(cmd).is_err(),
695 "{cmd:#06x} is a command id, not an acknowledgement"
696 );
697 }
698 }
699
700 #[test]
704 fn pending_ack_is_not_a_normal_acknowledgement() {
705 let mut pending = GOLDEN_READ_REGISTER_ACK;
706 pending[2..4].copy_from_slice(&PENDING_ACK_COMMAND.to_be_bytes());
707 assert_eq!(
708 u16::from_be_bytes([pending[0], pending[1]]),
709 0x0000,
710 "a pending-ack reports SUCCESS — the status cannot be the signal"
711 );
712 assert!(
713 decode_ack(&pending).is_err(),
714 "0x0805 is not an acknowledgement command id"
715 );
716 }
717}