opentitanlib/test_utils/
i2c_target.rs

1// Copyright lowRISC contributors (OpenTitan project).
2// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3// SPDX-License-Identifier: Apache-2.0
4
5use anyhow::Result;
6use std::time::Duration;
7
8use crate::io::uart::Uart;
9use crate::test_utils::e2e_command::TestCommand;
10use crate::test_utils::rpc::{ConsoleRecv, ConsoleSend};
11use crate::test_utils::status::Status;
12
13// Bring in the auto-generated sources.
14include!(env!("i2c_target"));
15
16impl I2cTargetAddress {
17    pub fn write(&self, uart: &dyn Uart) -> Result<()> {
18        TestCommand::I2cTargetAddress.send_with_crc(uart)?;
19        self.send_with_crc(uart)?;
20        Status::recv(uart, Duration::from_secs(300), false)?;
21        Ok(())
22    }
23}
24
25impl I2cTransferStart {
26    pub fn new(address: u8, content: &[u8], stop: bool) -> Self {
27        let mut a = arrayvec::ArrayVec::<u8, 256>::new();
28        a.try_extend_from_slice(content)
29            .expect("fewer than 256 bytes");
30        Self {
31            length: a.len() as u8,
32            address,
33            stop,
34            data: a,
35        }
36    }
37
38    pub fn execute_read<F>(&self, uart: &dyn Uart, f: F) -> Result<()>
39    where
40        F: FnOnce() -> Result<()>,
41    {
42        TestCommand::I2cStartTransferRead.send_with_crc(uart)?;
43        self.send_with_crc(uart)?;
44        f()?;
45        Status::recv(uart, Duration::from_secs(300), false)?;
46        Ok(())
47    }
48
49    pub fn execute_write<F>(uart: &dyn Uart, f: F) -> Result<Self>
50    where
51        F: FnOnce() -> Result<()>,
52    {
53        TestCommand::I2cStartTransferWrite.send_with_crc(uart)?;
54        f()?;
55        Self::recv(uart, Duration::from_secs(300), false)
56    }
57
58    pub fn execute_write_slow<F>(uart: &dyn Uart, f: F) -> Result<Self>
59    where
60        F: FnOnce() -> Result<()>,
61    {
62        TestCommand::I2cStartTransferWriteSlow.send_with_crc(uart)?;
63        f()?;
64        Self::recv(uart, Duration::from_secs(300), false)
65    }
66
67    pub fn execute_write_read<F>(&self, uart: &dyn Uart, f: F) -> Result<Self>
68    where
69        F: FnOnce() -> Result<()>,
70    {
71        TestCommand::I2cStartTransferWriteRead.send_with_crc(uart)?;
72        self.send_with_crc(uart)?;
73        f()?;
74        Self::recv(uart, Duration::from_secs(300), false)
75    }
76}
77
78impl I2cTestConfig {
79    pub fn write(&self, uart: &dyn Uart) -> Result<()> {
80        TestCommand::I2cTestConfig.send_with_crc(uart)?;
81        self.send_with_crc(uart)?;
82        Status::recv(uart, Duration::from_secs(300), false)?;
83        Ok(())
84    }
85}