uds_client/uds_client/
client.rs

1//! # UDS Client
2//!
3//! ## Overview
4//! The `UdsClient` provides an implementation for sending and receiving Unified Diagnostic Services (UDS) messages
5//! over a CAN bus interface. It facilitates communication with ECUs (Electronic Control Units) in an automotive
6//! network using UDS over CAN (ISO 14229).
7//!
8//! ## Features
9//! - Supports **sending UDS requests** and **receiving responses** from an ECU.
10//! - Implements **ISO-TP (ISO 15765-2) framing**, allowing for multi-frame messages.
11//! - Handles **CAN IDs** (standard and extended) to ensure correct communication.
12//! - Uses an **async-friendly design** to integrate with Rust's asynchronous runtime.
13//!
14//! ## Usage Example
15//! ```rust
16//! use embedded_can::{nb::Can, Frame, Id};
17//! use uds_client::{UdsClient, DiagError, ResponseSlot};
18//! use std::sync::Arc;
19//!
20//! async fn example_usage<T: Can>(channel: &mut T, resp_slot: &Arc<ResponseSlot>) -> Result<(), DiagError> {
21//!     let id = Id::Extended(ExtendedId::new(0x7DF).unwrap());
22//!     let mut client = UdsClient::new(channel, id, resp_slot);
23//!
24//!     // Example: Sending a diagnostic request
25//!     client.send_command(0x10, &[0x01, 0x02, 0x03]).await?;
26//!
27//!     // Example: Receiving a response
28//!     if let Ok(response) = client.receive().await {
29//!         println!("Received response: {:?}", response);
30//!     }
31//!
32//!     Ok(())
33//! }
34//! ```
35//!
36//! ## Errors
37//! The `UdsClient` may return the following errors:
38//! - `DiagError::Timeout`: When a response is not received within the expected time.
39//! - `DiagError::InvalidResponse`: When the received response does not match the expected UDS format.
40//! - `DiagError::HardwareError`: When there is an issue with the CAN bus or adapter.
41//!
42//! ## Structs
43//! - [`UdsClient`] - The main client struct for handling UDS communication.
44
45use crate::socket_can::CanSocketTx;
46
47use super::{DiagError, Response, ResponseSlot, response::UdsResponse};
48use embedded_can::{ExtendedId, Frame, Id};
49use log::debug;
50use std::sync::{Arc, LazyLock};
51
52pub struct UdsClient<'a, T: CanSocketTx> {
53    channel: T,
54    id: Id,
55    resp: &'a Arc<ResponseSlot>,
56}
57
58#[allow(dead_code)]
59impl<'a, T: CanSocketTx> UdsClient<'a, T> {
60    pub fn new(channel: T, id: u32, resp: &'a LazyLock<Arc<ResponseSlot>>) -> Self {
61        let id = Id::Extended(ExtendedId::new(id).unwrap());
62        Self { channel, id, resp }
63    }
64
65    /// Send a command without the response.
66    /// The frame includes <PCI> <CMD> <ARGS> as ISO 15765-2
67    pub fn send_command<P: Into<u8>, M: Into<u8>>(
68        &mut self,
69        pci: P,
70        cmd: M,
71        args: &[u8],
72    ) -> Result<(), DiagError> {
73        let mut data = vec![pci.into(), cmd.into()];
74        data.extend_from_slice(args);
75        self.send_raw(&data)
76    }
77
78    /// Send a command with the response.
79    /// The frame includes <PCI> <CMD> <ARGS> as ISO 15765-2
80    pub async fn send_command_with_response<P: Into<u8>, M: Into<u8>>(
81        &mut self,
82        pci: P,
83        cmd: M,
84        args: &[u8],
85    ) -> Result<UdsResponse, DiagError> {
86        let mut data = vec![pci.into(), cmd.into()];
87        data.extend_from_slice(args);
88        match self.send_raw_with_response(&data).await? {
89            Response::Ok(items) => {
90                debug!("got response: {:?}", items);
91                Ok(items)
92            }
93            Response::Error => Err(DiagError::Timeout),
94        }
95    }
96
97    /// Internal function: send raw data as bytes array to CAN bus.
98    fn send_raw(&mut self, data: &[u8]) -> Result<(), DiagError> {
99        let frame = T::Frame::new(self.id, data).unwrap();
100        println!("send raw data frame: {:?}", frame.data());
101        self.channel.transmit(&frame).unwrap();
102        Ok(())
103    }
104
105    /// Internal function: send raw data as bytes array to CAN bus and wait for a response.
106    async fn send_raw_with_response(&mut self, data: &[u8]) -> Result<Response, DiagError> {
107        let frame = T::Frame::new(self.id, data).unwrap();
108        self.channel.transmit(&frame).unwrap();
109        let response = self.resp.wait_for_response().await;
110        Ok(response)
111    }
112
113    /// Receive the frame from UDS server
114    pub async fn receive(&mut self) -> Response {
115        self.resp.wait_for_response().await
116    }
117
118    // pub fn send_raw_frame_with_response(&mut self, frame: T::Frame) -> Result<(), DiagError> {
119    //     if let Err(_) = self.channel.transmit(&frame) {
120    //         return Err(DiagError::NotSupported);
121    //     }
122    //     Ok(())
123    // }
124
125    // pub fn wait_response() -> Result<(), DiagError> {
126    //     Ok(())
127    // }
128}