freemdu 0.1.0

Communicate with Miele appliances via their proprietary diagnostic interface.
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
//! Communicate with Miele appliances via their proprietary diagnostic interface.
//!
//! # Overview
//!
//! The `freemdu` crate implements the proprietary Miele diagnostic protocol.
//! It offers an asynchronous, platform-agnostic API for communicating
//! with Miele appliances via the diagnostic interface.
//!
//! Depending on your needs, you can:
//!
//! - Use the high-level [`device`] module to query diagnostic properties and trigger actions.
//! - Instantiate device implementations (e.g. [`device::id629`]) to access model-specific methods.
//! - Work directly with the low-level diagnostic [`Interface`].
//!
//! # Getting started
//!
//! Most Miele appliances expose a diagnostic UART on their control board.
//! To communicate with it, you need a UART interface configured as follows:
//!
//! - **Baud rate:** 2400
//! - **Parity:** Even
//! - **Data bits:** 8
//! - **Stop bits:** 1
//!
//! If you enable the `native-serial` feature, you can obtain a compatible
//! serial port instance using [`serial::open`]:
//!
//! ```no_run
//! # #[tokio::main]
//! # async fn main() -> freemdu::device::Result<(), freemdu::serial::PortError> {
//! let mut port = freemdu::serial::open("/dev/ttyACM0")?;
//! # Ok(())
//! # }
//! ```
//!
//! The UART connection can be provided by a USB–UART adapter.
//! In that case, the adapter's RX, TX and GND lines must be connected to
//! the corresponding pins on the appliance's control board.
//!
//! <div class="warning">
//! Because the control board is typically not galvanically isolated,
//! working on it may expose you to dangerous voltages.
//! Always take appropriate safety precautions!
//! </div>
//!
//! Alternatively, you can access the interface through a compatible
//! **optical communication adapter**.
//! Instructions for building a simple adapter are available on the
//! [FreeMDU project page](https://github.com/medusalix/FreeMDU).
//!
//! # Examples
//!
//! The following examples demonstrate the primary ways to communicate with devices:
//!
//! ## Querying device properties using the high-level [`device`] module
//!
//! The recommended way to connect to a device is via [`device::connect`],
//! which identifies the device and provides access to its properties and actions:
//!
//! ```no_run
//! # #[tokio::main]
//! # async fn main() -> freemdu::device::Result<(), freemdu::serial::PortError> {
//! # let mut port = freemdu::serial::open("/dev/ttyACM0")?;
//! let mut dev = freemdu::device::connect(&mut port).await?;
//!
//! for prop in dev.properties() {
//!    let val = dev.query_property(prop).await?;
//!
//!    println!("{prop:?}: {val:?}");
//! }
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## Working with a specific device implementation
//!
//! For model-specific access, a corresponding device instance has to be instantiated directly.
//! This provides additional methods beyond the general [`device::Device`] trait:
//!
//! ```no_run
//! use freemdu::device::{Device, id629::WashingMachine};
//!
//! # #[tokio::main]
//! # async fn main() -> freemdu::device::Result<(), freemdu::serial::PortError> {
//! # let mut port = freemdu::serial::open("/dev/ttyACM0")?;
//! let mut machine = WashingMachine::connect(&mut port).await?;
//!
//! println!("Program type: {}", machine.query_program_type().await?);
//! println!("Program options: {}", machine.query_program_options().await?);
//!
//! machine.start_program().await?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## Low-level diagnostic access using [`Interface`]
//!
//! Advanced users can interact with the raw diagnostic protocol through the
//! low-level [`Interface`]:
//!
//! ```no_run
//! # #[tokio::main]
//! # async fn main() -> freemdu::Result<(), freemdu::serial::PortError> {
//! # let mut port = freemdu::serial::open("/dev/ttyACM0")?;
//! let mut intf = freemdu::Interface::new(port);
//!
//! println!("Software ID: {}", intf.query_software_id().await?);
//!
//! intf.unlock_read_access(0x1234).await?;
//! intf.unlock_full_access(0x5678).await?;
//!
//! let mem: [u8; 16] = intf.read_memory(0x0000).await?;
//!
//! println!("Memory contents: {:x?}", mem);
//!
//! # Ok(())
//! # }
//! ```
//!
//! # Protocol details
//!
//! The diagnostic interface is protected by two **16-bit keys**.
//! Each appliance model or electronics board typically has
//! its own unique keys required to unlock the diagnostic interface.
//! The supported devices are listed on the
//! [FreeMDU project page](https://github.com/medusalix/FreeMDU).
//!
//! Once fully unlocked, the appliance accepts all diagnostic commands.
//! However, the interface automatically locks again after 3 seconds
//! of inactivity, so tools must send commands periodically to maintain access.

#![no_std]
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate alloc;

pub mod device;

#[cfg(feature = "native-serial")]
#[cfg_attr(docsrs, doc(cfg(feature = "native-serial")))]
pub mod serial;

pub use embedded_io_async;

use core::{
    fmt::{Debug, Display, Formatter},
    num::Wrapping,
};
use embedded_io_async::{Read, ReadExactError, Write};
use log::debug;
use strum::FromRepr;

/// A specialized [`Result`] type for [`Interface`] operations.
///
/// Uses [`Error<E>`] as the error variant, which can include port-specific errors.
pub type Result<T, E> = core::result::Result<T, Error<E>>;

/// Error type for [`Interface`] operations.
///
/// The generic parameter `E` allows the error type to carry a port-specific error.
///
/// This enum is marked `#[non_exhaustive]` to allow for future variants.
#[non_exhaustive]
#[derive(PartialEq, Eq, Debug)]
pub enum Error<E> {
    /// The provided argument is invalid.
    InvalidArgument,
    /// Data received by or from the device has an incorrect checksum.
    IncorrectChecksum,
    /// The device received an invalid command.
    InvalidCommand,
    /// The device responded with an unknown response code.
    UnknownResponseCode,
    /// The port encountered an unexpected end-of-file.
    UnexpectedEof,
    /// A port-specific input/output error.
    Io(E),
}

impl<E: core::error::Error> Display for Error<E> {
    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
        match self {
            Self::InvalidArgument => write!(f, "invalid argument"),
            Self::IncorrectChecksum => write!(f, "incorrect checksum"),
            Self::InvalidCommand => write!(f, "invalid command"),
            Self::UnknownResponseCode => write!(f, "unknown response code"),
            Self::UnexpectedEof => write!(f, "unexpected end-of-file"),
            Self::Io(err) => write!(f, "input/output error: {err}"),
        }
    }
}

impl<E: core::error::Error> core::error::Error for Error<E> {}

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

impl<E> From<ReadExactError<E>> for Error<E> {
    fn from(err: ReadExactError<E>) -> Self {
        match err {
            ReadExactError::UnexpectedEof => Self::UnexpectedEof,
            ReadExactError::Other(err) => Self::Io(err),
        }
    }
}

/// Command code used by the diagnostic interface.
#[derive(Debug)]
#[repr(u8)]
enum Command {
    Lock = 0x10,
    QuerySoftwareId = 0x11,
    UnlockReadAccess = 0x20,
    ReadMemory = 0x30,
    ReadEeprom = 0x31,
    UnlockFullAccess = 0x32,
    WriteMemory = 0x40,
    WriteEeprom = 0x41,
    JumpToSubroutine = 0x42,
    Halt = 0x45,
    SetBaudRate2400 = 0x46,
    SetBaudRate9600 = 0x47,
}

/// Request message sent to the diagnostic interface.
///
/// A checksum must be appended to the serialized message using [`compute_checksum`].
#[derive(Debug)]
struct Request {
    cmd: Command,
    param: u16,
    len: u8,
}

impl Request {
    pub fn new(cmd: Command, param: u16, len: u8) -> Self {
        let req = Self { cmd, param, len };

        debug!("New request: {req:x?}");

        req
    }
}

impl From<Request> for Payload<4> {
    fn from(req: Request) -> Self {
        let mut buf = [0x00; 4];

        buf[0] = req.cmd as u8;
        buf[1..3].copy_from_slice(&req.param.to_le_bytes());
        buf[3] = req.len;

        Self(buf)
    }
}

/// Diagnostic interface response code.
///
/// Used in communication with the device, both when
/// sending requests and when interpreting responses.
#[derive(FromRepr, Debug)]
#[repr(u8)]
enum ResponseCode {
    Success,
    IncorrectChecksum,
    InvalidCommand,
}

/// Diagnostic interface payload.
///
/// Wraps a fixed-size byte array used for communication with the device.
/// When sent or received through an [`Interface`], the payload is automatically
/// split or reassembled into chunks.
///
/// Several [`From`] implementations are provided to convert between `Payload`
/// and common primitive types.
#[derive(Debug)]
pub struct Payload<const N: usize>([u8; N]);

impl<const N: usize> From<[u8; N]> for Payload<N> {
    fn from(data: [u8; N]) -> Self {
        Self(data)
    }
}

impl From<u8> for Payload<1> {
    fn from(val: u8) -> Self {
        Self(val.to_le_bytes())
    }
}

impl From<u16> for Payload<2> {
    fn from(val: u16) -> Self {
        Self(val.to_le_bytes())
    }
}

impl From<u32> for Payload<4> {
    fn from(val: u32) -> Self {
        Self(val.to_le_bytes())
    }
}

impl<const N: usize> From<Payload<N>> for [u8; N] {
    fn from(payload: Payload<N>) -> Self {
        payload.0
    }
}

impl From<Payload<1>> for u8 {
    fn from(payload: Payload<1>) -> Self {
        Self::from_le_bytes(payload.0)
    }
}

impl From<Payload<2>> for u16 {
    fn from(payload: Payload<2>) -> Self {
        Self::from_le_bytes(payload.0)
    }
}

impl From<Payload<4>> for u32 {
    fn from(payload: Payload<4>) -> Self {
        Self::from_le_bytes(payload.0)
    }
}

fn compute_checksum(data: &[u8]) -> u8 {
    data.iter().map(|&x| Wrapping(x)).sum::<Wrapping<_>>().0
}

/// Asynchronous diagnostic protocol interface.
///
/// Requires a port that implements [`Read`] and [`Write`] for communication.
///
/// Most users should access devices through the [`device`] module:
///
/// - Use [`device::connect`] to obtain a [`device::Device`] trait object with
///   high-level methods for querying properties and triggering actions.
/// - Alternatively, use one of the [`device`] submodules directly if you only need
///   support for a specific device.
///
/// [`Interface`] is only intended for advanced use cases where direct,
/// low-level access to the diagnostic protocol is required.
///
/// # Examples
///
/// ```no_run
/// # async fn example() -> freemdu::Result<(), freemdu::serial::PortError> {
/// let mut port = freemdu::serial::open("/dev/ttyACM0")?;
/// let mut intf = freemdu::Interface::new(port);
///
/// println!("Software ID: {}", intf.query_software_id().await?);
///
/// intf.unlock_read_access(0x1234).await?;
/// intf.unlock_full_access(0x5678).await?;
///
/// let mem: [u8; 16] = intf.read_memory(0x0000).await?;
///
/// println!("Memory: {:x?}", mem);
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Interface<P> {
    port: P,
    send_dummy_bytes: bool,
}

impl<P: Read + Write> Interface<P> {
    /// Constructs a new diagnostic interface.
    pub fn new(port: P) -> Self {
        Self {
            port,
            send_dummy_bytes: false,
        }
    }

    /// Enables transmission of dummy bytes during communication.
    ///
    /// Some older devices require dummy bytes as part of the
    /// diagnostic protocol (e.g. devices with software ID 419).
    /// Calling this method ensures that these bytes are automatically sent when needed.
    ///
    /// The first dummy bytes are sent immediately as a response
    /// to the query software ID command.
    pub async fn enable_dummy_bytes(&mut self) -> Result<(), P::Error> {
        self.send_dummy_bytes = true;
        self.write(&[0x00, 0x00, 0x00, 0x00]).await
    }

    /// Locks the diagnostic interface.
    ///
    /// This command resets the device's diagnostic access level.
    /// After locking, any further diagnostic operations require
    /// repeating the full unlock sequence.
    pub async fn lock(&mut self) -> Result<(), P::Error> {
        self.send(Request::new(Command::Lock, 0x0000, 0x00).into())
            .await
    }

    /// Queries the software ID of the device.
    ///
    /// This number identifies the software/firmware running on the device.
    /// Note that different electronics boards can share the same software ID.
    ///
    /// This must be called first as part of the unlock sequence.
    /// See [`Interface::unlock_read_access`] for the next step.
    pub async fn query_software_id(&mut self) -> Result<u16, P::Error> {
        self.send(Request::new(Command::QuerySoftwareId, 0x0000, 0x02).into())
            .await?;

        Ok(self.receive().await?.into())
    }

    /// Unlocks read-only diagnostic access.
    ///
    /// Before calling this function, the software ID must be
    /// queried using [`Interface::query_software_id`].
    /// Diagnostic access requires a key, which is typically unique for each software ID.
    ///
    /// Successfully unlocking read access enables the following functions:
    ///
    /// - [`Interface::read_memory`]
    /// - [`Interface::read_eeprom`]
    pub async fn unlock_read_access(&mut self, key: u16) -> Result<(), P::Error> {
        self.send(Request::new(Command::UnlockReadAccess, key, 0x00).into())
            .await
    }

    /// Reads data from the device's memory.
    ///
    /// The requested payload length cannot exceed 255 bytes.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidArgument`] if the payload length is greater than 255 bytes.
    pub async fn read_memory<L: From<Payload<N>>, const N: usize>(
        &mut self,
        addr: u16,
    ) -> Result<L, P::Error> {
        let Ok(len) = N.try_into() else {
            return Err(Error::InvalidArgument);
        };

        self.send(Request::new(Command::ReadMemory, addr, len).into())
            .await?;

        Ok(self.receive().await?.into())
    }

    /// Reads data from the device's EEPROM.
    ///
    /// The address must be specified in words, not bytes.
    /// For example, to read a byte at address `0x64`, provide the word address `0x32`.
    /// The payload length must be even and cannot exceed 255 bytes.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidArgument`] if the payload length is not a multiple of two or exceeds 255 bytes.
    pub async fn read_eeprom<L: From<Payload<N>>, const N: usize>(
        &mut self,
        addr: u16,
    ) -> Result<L, P::Error> {
        let len = match N.try_into() {
            Ok(n) if n % 2 == 0 => n,
            _ => return Err(Error::InvalidArgument),
        };

        self.send(Request::new(Command::ReadEeprom, addr, len).into())
            .await?;

        Ok(self.receive().await?.into())
    }

    /// Unlocks full diagnostic access.
    ///
    /// Before calling this function, read-only access has to be
    /// unlocked using [`Interface::unlock_read_access`].
    /// Diagnostic access requires a key, which is typically unique for each software ID.
    ///
    /// Successfully unlocking full access enables the following functions:
    ///
    /// - [`Interface::write_memory`]
    /// - [`Interface::write_eeprom`]
    /// - [`Interface::jump_to_subroutine`]
    /// - [`Interface::halt`]
    /// - [`Interface::set_baud_rate_2400`]
    /// - [`Interface::set_baud_rate_9600`]
    pub async fn unlock_full_access(&mut self, key: u16) -> Result<(), P::Error> {
        self.send(Request::new(Command::UnlockFullAccess, key, 0x00).into())
            .await
    }

    /// Writes data to the device's memory.
    ///
    /// The payload length cannot exceed 255 bytes.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidArgument`] if the payload length is greater than 255 bytes.
    pub async fn write_memory<L: Into<Payload<N>>, const N: usize>(
        &mut self,
        addr: u16,
        payload: L,
    ) -> Result<(), P::Error> {
        let Ok(len) = N.try_into() else {
            return Err(Error::InvalidArgument);
        };

        self.send(Request::new(Command::WriteMemory, addr, len).into())
            .await?;
        self.send(payload.into()).await
    }

    /// Writes data to the device's EEPROM.
    ///
    /// The address must be specified in words, not bytes.
    /// For example, to write a byte at address `0x64`, provide the word address `0x32`.
    /// The payload length must be even and cannot exceed 255 bytes.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidArgument`] if the payload length is not a multiple of two or exceeds 255 bytes.
    pub async fn write_eeprom<L: Into<Payload<N>>, const N: usize>(
        &mut self,
        addr: u16,
        payload: L,
    ) -> Result<(), P::Error> {
        let len = match N.try_into() {
            Ok(n) if n % 2 == 0 => n,
            _ => return Err(Error::InvalidArgument),
        };

        self.send(Request::new(Command::WriteEeprom, addr, len).into())
            .await?;
        self.send(payload.into()).await
    }

    /// Jumps to a specified subroutine and waits for it to return.
    ///
    /// This resets the device's diagnostic access level.
    /// The interface must be unlocked again after this operation
    /// to perform further diagnostic commands.
    pub async fn jump_to_subroutine(&mut self, addr: u16) -> Result<(), P::Error> {
        // Response is sent once subroutine returns
        self.send(Request::new(Command::JumpToSubroutine, addr, 0x00).into())
            .await?;
        self.read(&mut [0x00]).await
    }

    /// Halts the device's normal operation.
    ///
    /// Causes the device to enter an infinite loop.
    pub async fn halt(&mut self) -> Result<(), P::Error> {
        self.send(Request::new(Command::Halt, 0x0000, 0x00).into())
            .await
    }

    /// Sets the device's baud rate to 2400.
    ///
    /// This resets the device's diagnostic access level.
    /// The interface must be unlocked again after this operation
    /// to perform further diagnostic commands.
    ///
    /// Note that this does not change the baud rate of the current port instance.
    /// A new [`Interface`] must be created with a port configured for 2400 baud.
    pub async fn set_baud_rate_2400(&mut self) -> Result<(), P::Error> {
        self.send(Request::new(Command::SetBaudRate2400, 0x0000, 0x00).into())
            .await
    }

    /// Sets the device's baud rate to 9600.
    ///
    /// This resets the device's diagnostic access level.
    /// The interface must be unlocked again after this operation
    /// to perform further diagnostic commands.
    ///
    /// Note that this does not change the baud rate of the current port instance.
    /// A new [`Interface`] must be created with a port configured for 9600 baud.
    pub async fn set_baud_rate_9600(&mut self) -> Result<(), P::Error> {
        self.send(Request::new(Command::SetBaudRate9600, 0x0000, 0x00).into())
            .await
    }

    /// Sends a payload to the port.
    ///
    /// The payload is split into chunks with an appended checksum.
    /// Chunks are sent sequentially, verifying the response code for every transmission.
    async fn send<const N: usize>(&mut self, payload: Payload<N>) -> Result<(), P::Error> {
        for chunk in payload.0.chunks(4) {
            let checksum = compute_checksum(chunk);
            let mut resp = [0xff];

            self.write(chunk).await?;
            self.write(&[checksum]).await?;
            self.read(&mut resp).await?;

            match ResponseCode::from_repr(resp[0]) {
                Some(ResponseCode::Success) => Ok(()),
                Some(ResponseCode::IncorrectChecksum) => Err(Error::IncorrectChecksum),
                Some(ResponseCode::InvalidCommand) => Err(Error::InvalidCommand),
                None => Err(Error::UnknownResponseCode),
            }?;

            if self.send_dummy_bytes {
                self.write(&[0x00]).await?;
            }
        }

        Ok(())
    }

    /// Receives a payload from the port.
    ///
    /// Chunks of the payload are read and their checksums verified.
    /// A response code is sent for every received chunk.
    async fn receive<const N: usize>(&mut self) -> Result<Payload<N>, P::Error> {
        let mut payload = Payload([0x00; N]);

        for chunk in payload.0.chunks_mut(4) {
            let mut checksum = [0x00];

            self.read(chunk).await?;
            self.read(&mut checksum).await?;

            if checksum[0] != compute_checksum(chunk) {
                return Err(Error::IncorrectChecksum);
            }

            if self.send_dummy_bytes {
                for _ in 0..=chunk.len() {
                    self.write(&[0x00]).await?;
                }
            }

            // Acknowledge reception of chunk
            // Sending other response codes here aborts the transfer
            self.write(&[ResponseCode::Success as u8]).await?;
        }

        Ok(payload)
    }

    /// Reads data from the port into the provided buffer.
    async fn read(&mut self, buf: &mut [u8]) -> Result<(), P::Error> {
        self.port.read_exact(buf).await?;
        debug!("Read from port: {buf:02x?}");

        Ok(())
    }

    /// Writes the provided buffer to the port.
    async fn write(&mut self, buf: &[u8]) -> Result<(), P::Error> {
        debug!("Write to port: {buf:02x?}");
        self.port.write_all(buf).await?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::collections::vec_deque::VecDeque;
    use core::convert::Infallible;

    pub fn init_logger() {
        let _ = env_logger::builder()
            .filter_level(log::LevelFilter::max())
            .is_test(true)
            .try_init();
    }

    #[tokio::test]
    async fn enable_dummy_bytes() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00, 0xa3, 0x01, 0xa4, 0x00, 0x11, 0x22, 0x33]);
        let mut intf = Interface::new(&mut deque);
        let id = intf.query_software_id().await?;

        intf.enable_dummy_bytes().await?;

        let data: [u8; 2] = intf.read_memory(0xabcd).await?;

        assert_eq!(id, 419, "software ID should be correct");
        assert_eq!(
            deque,
            [
                0x11, 0x00, 0x00, 0x02, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xcd, 0xab, 0x02,
                0xaa, 0x00, 0x00, 0x00, 0x00, 0x00
            ],
            "deque contents should be correct"
        );

        assert_eq!(data, [0x11, 0x22], "memory contents should be correct");

        Ok(())
    }

    #[tokio::test]
    async fn lock() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.lock().await?;

        assert_eq!(
            deque,
            [0x10, 0x00, 0x00, 0x00, 0x10],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn query_software_id() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00, 0x75, 0x02, 0x77]);
        let mut intf = Interface::new(&mut deque);
        let id = intf.query_software_id().await?;

        assert_eq!(id, 629, "software ID should be correct");
        assert_eq!(
            deque,
            [0x11, 0x00, 0x00, 0x02, 0x13, 0x00],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn unlock_read_access() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.unlock_read_access(0xabcd).await?;

        assert_eq!(
            deque,
            [0x20, 0xcd, 0xab, 0x00, 0x98],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn read_memory() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([
            0x00, 0x11, 0x22, 0x33, 0x44, 0xaa, 0xab, 0xcd, 0xef, 0x99, 0x00, 0xde, 0xad, 0x8b,
        ]);
        let mut intf = Interface::new(&mut deque);
        let data: [u8; 10] = intf.read_memory(0xabcd).await?;

        assert_eq!(
            deque,
            [0x30, 0xcd, 0xab, 0x0a, 0xb2, 0x00, 0x00, 0x00],
            "deque contents should be correct"
        );

        assert_eq!(
            data,
            [0x11, 0x22, 0x33, 0x44, 0xab, 0xcd, 0xef, 0x99, 0xde, 0xad],
            "memory contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn read_eeprom() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([
            0x00, 0x11, 0x22, 0x33, 0x44, 0xaa, 0xab, 0xcd, 0xef, 0x99, 0x00, 0xde, 0xad, 0x8b,
        ]);
        let mut intf = Interface::new(&mut deque);
        let data: [u8; 10] = intf.read_eeprom(0xabcd).await?;

        assert_eq!(
            deque,
            [0x31, 0xcd, 0xab, 0x0a, 0xb3, 0x00, 0x00, 0x00],
            "deque contents should be correct"
        );

        assert_eq!(
            data,
            [0x11, 0x22, 0x33, 0x44, 0xab, 0xcd, 0xef, 0x99, 0xde, 0xad],
            "EEPROM contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn unlock_full_access() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.unlock_full_access(0xabcd).await?;

        assert_eq!(
            deque,
            [0x32, 0xcd, 0xab, 0x00, 0xaa],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn write_memory() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00, 0x00, 0x00, 0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.write_memory(
            0xabcd,
            [0x11, 0x22, 0x33, 0x44, 0xab, 0xcd, 0xef, 0x99, 0xde, 0xad],
        )
        .await?;

        assert_eq!(
            deque,
            [
                0x40, 0xcd, 0xab, 0x0a, 0xc2, 0x11, 0x22, 0x33, 0x44, 0xaa, 0xab, 0xcd, 0xef, 0x99,
                0x00, 0xde, 0xad, 0x8b
            ],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn write_eeprom() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00, 0x00, 0x00, 0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.write_eeprom(
            0xabcd,
            [0x11, 0x22, 0x33, 0x44, 0xab, 0xcd, 0xef, 0x99, 0xde, 0xad],
        )
        .await?;

        assert_eq!(
            deque,
            [
                0x41, 0xcd, 0xab, 0x0a, 0xc3, 0x11, 0x22, 0x33, 0x44, 0xaa, 0xab, 0xcd, 0xef, 0x99,
                0x00, 0xde, 0xad, 0x8b
            ],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn jump_to_subroutine() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00, 0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.jump_to_subroutine(0xabcd).await?;

        assert_eq!(
            deque,
            [0x42, 0xcd, 0xab, 0x00, 0xba],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn halt() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.halt().await?;

        assert_eq!(
            deque,
            [0x45, 0x00, 0x00, 0x00, 0x45],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn set_baud_rate_2400() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.set_baud_rate_2400().await?;

        assert_eq!(
            deque,
            [0x46, 0x00, 0x00, 0x00, 0x46],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn set_baud_rate_9600() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00]);
        let mut intf = Interface::new(&mut deque);

        intf.set_baud_rate_9600().await?;

        assert_eq!(
            deque,
            [0x47, 0x00, 0x00, 0x00, 0x47],
            "deque contents should be correct"
        );

        Ok(())
    }

    #[tokio::test]
    async fn error_invalid_argument() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([]);
        let mut intf = Interface::new(&mut deque);
        let res: Result<[u8; 256], _> = intf.read_memory(0xabcd).await;

        assert_eq!(
            res.unwrap_err(),
            Error::InvalidArgument,
            "result should be invalid argument error"
        );

        let res: Result<u8, _> = intf.read_eeprom(0xabcd).await;

        assert_eq!(
            res.unwrap_err(),
            Error::InvalidArgument,
            "result should be invalid argument error"
        );

        let res = intf.write_memory(0xabcd, [0x00; 256]).await;

        assert_eq!(
            res.unwrap_err(),
            Error::InvalidArgument,
            "result should be invalid argument error"
        );

        let res = intf.write_eeprom(0xabcd, 0x11u8).await;

        assert_eq!(
            res.unwrap_err(),
            Error::InvalidArgument,
            "result should be invalid argument error"
        );

        Ok(())
    }

    #[tokio::test]
    async fn error_incorrect_checksum() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x01, 0x00, 0x11, 0xff]);
        let mut intf = Interface::new(&mut deque);
        let res = intf.lock().await;

        assert_eq!(
            res.unwrap_err(),
            Error::IncorrectChecksum,
            "result should be incorrect checksum error"
        );

        let res: Result<u8, _> = intf.read_memory(0xabcd).await;

        assert_eq!(
            res.unwrap_err(),
            Error::IncorrectChecksum,
            "result should be incorrect checksum error"
        );

        Ok(())
    }

    #[tokio::test]
    async fn error_invalid_command() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x02]);
        let mut intf = Interface::new(&mut deque);
        let res = intf.lock().await;

        assert_eq!(
            res.unwrap_err(),
            Error::InvalidCommand,
            "result should be invalid command error"
        );

        Ok(())
    }

    #[tokio::test]
    async fn error_unknown_response_code() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0xff]);
        let mut intf = Interface::new(&mut deque);
        let res = intf.halt().await;

        assert_eq!(
            res.unwrap_err(),
            Error::UnknownResponseCode,
            "result should be unknown response code error"
        );

        Ok(())
    }

    #[tokio::test]
    async fn error_unexpected_eof() -> Result<(), Infallible> {
        init_logger();

        let mut deque = VecDeque::from([0x00]);
        let mut intf = Interface::new(&mut deque);
        let res: Result<[u8; 5], _> = intf.read_memory(0xabcd).await;

        assert_eq!(
            res.unwrap_err(),
            Error::UnexpectedEof,
            "result should be unexpected end-of-file error"
        );

        Ok(())
    }
}