Skip to main content

at_cryptoauth/
datalink.rs

1use embedded_hal::delay::DelayNs;
2
3// for this implementation of I2C with CryptoAuth chips, txdata is assumed to
4// have ATCAPacket format Devices such as ATECCx08A require a word address value
5// pre-pended to the packet txdata[0] is using _reserved byte of the ATCAPacket
6use super::error::{Error, ErrorKind};
7use super::packet::{Packet, Response};
8use core::fmt::Debug;
9use core::slice::from_ref;
10const WAKE_RESPONSE_EXPECTED: &[u8] = &[0x04, 0x11, 0x33, 0x43];
11const WAKE_SELFTEST_FAILED: &[u8] = &[0x04, 0x07, 0xC4, 0x40];
12
13/// Default I2C address of ATECC608 (0xC0 >> 1 = 0x60)
14const DEFAULT_ADDRESS: u8 = 0xc0 >> 1;
15/// Default time in us that takes for ATECC608 device to wake up.
16const DEFAULT_WAKE_DELAY_US: u32 = 1500;
17
18// By default, wake up sequence is repeated up to 20 times until it succeeds.
19// Multiply by 2, otherwise you see RxFail on wake up. It happens when you try
20// to write a word to the config zone on Raspberry Pi's I2C. This behavior might
21// be specific to linux HAL. What's worse, GenKey command from Raspberry Pi
22// needs to retry 20 * 15 times until it succeeds.
23#[cfg(target_os = "none")]
24const DEFAULT_MAX_RETRIES: usize = 20;
25#[cfg(not(target_os = "none"))]
26const DEFAULT_MAX_RETRIES: usize = 20 * 15;
27
28/// Configuration for I2C communication with ATECC608
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct I2cConfig {
31    /// I2C address (default: 0x60)
32    pub address: u8,
33    /// Wake-up delay in microseconds (default: 1500)
34    pub wake_delay_us: u32,
35    /// Maximum retry count for communication attempts
36    pub max_retries: usize,
37}
38
39impl Default for I2cConfig {
40    fn default() -> Self {
41        Self {
42            address: DEFAULT_ADDRESS,
43            wake_delay_us: DEFAULT_WAKE_DELAY_US,
44            max_retries: DEFAULT_MAX_RETRIES,
45        }
46    }
47}
48
49/// So-called "word address".
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub(crate) enum Transaction {
52    Reset = 0x00,
53    Sleep = 0x01,
54    Idle = 0x02,
55    Command = 0x03,
56    #[allow(dead_code)]
57    Reserved = 0xff,
58}
59
60pub(crate) struct I2c<PHY> {
61    phy: PHY,
62    config: I2cConfig,
63}
64
65impl<PHY> I2c<PHY> {
66    pub(crate) fn with_config(phy: PHY, config: I2cConfig) -> Self {
67        Self { phy, config }
68    }
69}
70
71impl<PHY> I2c<PHY>
72where
73    PHY: embedded_hal_async::i2c::I2c,
74{
75    /// Wakes up device, sends the packet, waits for command completion,
76    /// receives response, and puts the device into the idle state.
77    pub(crate) async fn execute<'a>(
78        &mut self,
79        buffer: &'a mut [u8],
80        packet: Packet,
81        exec_time: Option<u32>,
82    ) -> Result<Response<'a>, Error> {
83        self.wake().await?;
84        self.send(packet.buffer(buffer)).await?;
85        // Wait for the device to finish its job.
86        embassy_time::Timer::after(embassy_time::Duration::from_micros(
87            (exec_time.unwrap_or(1) * 1000) as u64,
88        ))
89        .await;
90        let response_buffer = self.receive(buffer).await?;
91        self.idle().await?;
92        Response::new(response_buffer)
93    }
94
95    async fn send(&mut self, bytes: &[u8]) -> Result<(), Error> {
96        self.phy
97            .write(self.config.address, bytes)
98            .await
99            .map_err(|_| ErrorKind::TxFail.into())
100    }
101
102    /// Returns response buffer for later processing.
103    async fn receive<'a>(&mut self, buffer: &'a mut [u8]) -> Result<&'a mut [u8], Error> {
104        // Reset indicates the beginning of transaction.
105        let word_address = Transaction::Reset as u8;
106
107        let mut count = 0;
108        loop {
109            let result = self
110                .phy
111                .write(self.config.address, from_ref(&word_address))
112                .await;
113
114            if result.is_ok() {
115                break;
116            } else {
117                if count > self.config.max_retries {
118                    return Err(Error::from(ErrorKind::TxFail));
119                }
120                count += 1;
121            }
122        }
123
124        let min_resp_size = 4;
125        self.phy
126            .read(self.config.address, &mut buffer[0..2])
127            .await
128            .map_err(|_| Error::from(ErrorKind::RxFail))?;
129
130        let length_to_read = match buffer[0] {
131            // A single byte has already read.
132            1 => return Ok(buffer[0..1].as_mut()),
133            // Buffer cannot contain the response to come. Abort.
134            length if buffer.len() < length as usize => return Err(ErrorKind::CommFail.into()),
135            // The coming response is malformed. Abort.
136            length if length < min_resp_size => return Err(ErrorKind::CommFail.into()),
137            length => length as usize,
138        };
139
140        self.phy
141            .read(self.config.address, buffer[2..length_to_read].as_mut())
142            .await
143            .map(move |()| buffer[..length_to_read].as_mut())
144            .map_err(|_| ErrorKind::RxFail.into())
145    }
146
147    async fn wake(&mut self) -> Result<(), Error> {
148        // Send a single null byte to an absent address.
149        //
150        // Ignore errors as this will error if the device is not awake yet.
151        self.phy
152            .write(self.config.address, from_ref(&0x00))
153            .await
154            .ok();
155
156        // Wait for the device to wake up.
157        embassy_time::Timer::after(embassy_time::Duration::from_micros(
158            self.config.wake_delay_us as u64,
159        ))
160        .await;
161
162        let buffer = &mut [0x00, 0x00, 0x00, 0x00];
163
164        let mut count = 0;
165        loop {
166            let result = self.phy.read(self.config.address, buffer.as_mut()).await;
167
168            if result.is_ok() {
169                break;
170            } else {
171                if count > self.config.max_retries {
172                    return Err(Error::from(ErrorKind::RxFail));
173                }
174                count += 1;
175            }
176        }
177
178        match buffer.as_ref() {
179            WAKE_RESPONSE_EXPECTED => Ok(()),
180            WAKE_SELFTEST_FAILED => Err(ErrorKind::WakeFailed.into()),
181            _ => Err(ErrorKind::WakeFailed.into()),
182        }
183    }
184
185    async fn idle(&mut self) -> Result<(), Error> {
186        let word_address = Transaction::Idle as u8;
187        self.phy
188            .write(self.config.address, from_ref(&word_address))
189            .await
190            .map_err(|_| ErrorKind::TxFail.into())
191    }
192
193    pub(crate) async fn sleep(&mut self) -> Result<(), Error> {
194        let word_address = Transaction::Sleep as u8;
195        // Wait for the I2C bus to be ready.
196        embassy_time::Timer::after(embassy_time::Duration::from_micros(30)).await;
197        self.phy
198            .write(self.config.address, from_ref(&word_address))
199            .await
200            .map_err(|_| ErrorKind::TxFail.into())
201    }
202}
203
204impl<PHY> I2c<PHY>
205where
206    PHY: embedded_hal::i2c::I2c,
207{
208    /// Wakes up device, sends the packet, waits for command completion,
209    /// receives response, and puts the device into the idle state.
210    pub(crate) fn execute_blocking<'a>(
211        &mut self,
212        buffer: &'a mut [u8],
213        packet: Packet,
214        exec_time: Option<u32>,
215    ) -> Result<Response<'a>, Error> {
216        self.wake_blocking()?;
217        self.send_blocking(packet.buffer(buffer))?;
218        // Wait for the device to finish its job.
219        embassy_time::Delay.delay_us(exec_time.unwrap_or(1) * 1000);
220        let response_buffer = self.receive_blocking(buffer)?;
221        self.idle_blocking()?;
222        Response::new(response_buffer)
223    }
224
225    fn send_blocking(&mut self, bytes: &[u8]) -> Result<(), Error> {
226        self.phy
227            .write(self.config.address, bytes)
228            .map_err(|_| ErrorKind::TxFail.into())
229    }
230
231    /// Returns response buffer for later processing.
232    fn receive_blocking<'a>(&mut self, buffer: &'a mut [u8]) -> Result<&'a mut [u8], Error> {
233        // Reset indicates the beginning of transaction.
234        let word_address = Transaction::Reset as u8;
235
236        let mut count = 0;
237        loop {
238            let result = self.phy.write(self.config.address, from_ref(&word_address));
239
240            if result.is_ok() {
241                break;
242            } else {
243                if count > self.config.max_retries {
244                    return Err(Error::from(ErrorKind::TxFail));
245                }
246                count += 1;
247            }
248        }
249
250        let min_resp_size = 4;
251        self.phy
252            .read(self.config.address, &mut buffer[0..2])
253            .map_err(|_| Error::from(ErrorKind::RxFail))?;
254
255        let length_to_read = match buffer[0] {
256            // A single byte has already read.
257            1 => return Ok(buffer[0..1].as_mut()),
258            // Buffer cannot contain the response to come. Abort.
259            length if buffer.len() < length as usize => return Err(ErrorKind::CommFail.into()),
260            // The coming response is malformed. Abort.
261            length if length < min_resp_size => return Err(ErrorKind::CommFail.into()),
262            length => length as usize,
263        };
264
265        self.phy
266            .read(self.config.address, buffer[2..length_to_read].as_mut())
267            .map(move |()| buffer[..length_to_read].as_mut())
268            .map_err(|_| ErrorKind::RxFail.into())
269    }
270
271    fn wake_blocking(&mut self) -> Result<(), Error> {
272        // Send a single null byte to an absent address.
273        //
274        // Ignore errors as this will error if the device is not awake yet.
275        self.phy.write(self.config.address, from_ref(&0x00)).ok();
276
277        // Wait for the device to wake up.
278        embassy_time::Delay.delay_us(self.config.wake_delay_us);
279
280        let buffer = &mut [0x00, 0x00, 0x00, 0x00];
281
282        let mut count = 0;
283        loop {
284            let result = self.phy.read(self.config.address, buffer.as_mut());
285
286            if result.is_ok() {
287                break;
288            } else {
289                if count > self.config.max_retries {
290                    return Err(Error::from(ErrorKind::RxFail));
291                }
292                count += 1;
293            }
294        }
295
296        match buffer.as_ref() {
297            WAKE_RESPONSE_EXPECTED => Ok(()),
298            WAKE_SELFTEST_FAILED => Err(ErrorKind::WakeFailed.into()),
299            _ => Err(ErrorKind::WakeFailed.into()),
300        }
301    }
302
303    fn idle_blocking(&mut self) -> Result<(), Error> {
304        let word_address = Transaction::Idle as u8;
305        self.phy
306            .write(self.config.address, from_ref(&word_address))
307            .map_err(|_| ErrorKind::TxFail.into())
308    }
309
310    pub(crate) fn sleep_blocking(&mut self) -> Result<(), Error> {
311        let word_address = Transaction::Sleep as u8;
312        // Wait for the I2C bus to be ready.
313        embassy_time::Delay.delay_us(30);
314
315        self.phy
316            .write(self.config.address, from_ref(&word_address))
317            .map_err(|_| ErrorKind::TxFail.into())
318    }
319}