Skip to main content

xcp_core/
response.rs

1//! CTO response parsing: RES (`0xFF`), ERR (`0xFE`), EV (`0xFD`), SERV
2//! (`0xFC`).
3//!
4//! A positive (`RES`) response carries no echo of the command that
5//! produced it — the layout is known only from the *outstanding* command.
6//! [`parse_response_with`] takes that expectation explicitly
7//! ([`Expect`]); [`parse_response`] infers it with a documented
8//! exact-length heuristic (see its rustdoc for the collision table).
9
10use crate::byteorder::{AddressGranularity, ByteOrder};
11use crate::error::XcpError;
12use crate::resource::{ResourceMode, SessionStatus};
13use alloc::vec::Vec;
14
15/// The response PID classes.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17#[allow(clippy::exhaustive_enums)]
18pub enum Pid {
19    /// `0xFF` — positive response (RES).
20    Res,
21    /// `0xFE` — error response (ERR).
22    Err,
23    /// `0xFD` — asynchronous event (EV).
24    Ev,
25    /// `0xFC` — service request (SERV).
26    Serv,
27}
28
29impl Pid {
30    /// Decode a response PID byte.
31    #[must_use]
32    pub const fn from_code(code: u8) -> Option<Self> {
33        Some(match code {
34            0xFF => Self::Res,
35            0xFE => Self::Err,
36            0xFD => Self::Ev,
37            0xFC => Self::Serv,
38            _ => return None,
39        })
40    }
41}
42
43/// The command whose response to expect — disambiguates `RES` layouts.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
45#[allow(clippy::exhaustive_enums)]
46pub enum Expect {
47    /// Response to CONNECT.
48    Connect,
49    /// Response to GET_STATUS.
50    GetStatus,
51    /// Response to GET_VERSION.
52    GetVersion,
53    /// Response to GET_ID.
54    GetId,
55    /// Response to UPLOAD / SHORT_UPLOAD (payload is the uploaded data).
56    Upload,
57    /// Response to START_STOP_DAQ_LIST (first PID of the list).
58    StartStopDaqList,
59    /// Response to GET_DAQ_CLOCK (free-running slave timestamp).
60    GetDaqClock,
61    /// No known outstanding command: apply the documented inference
62    /// heuristic.
63    #[default]
64    Generic,
65}
66
67/// A parsed XCP CTO response packet.
68#[derive(Debug, Clone, PartialEq, Eq)]
69#[allow(clippy::exhaustive_enums)]
70pub enum XcpResponse {
71    /// Positive CONNECT response: resource availability, basic comm mode,
72    /// `MAX_CTO`/`MAX_DTO`, protocol and transport layer versions.
73    Connect(ConnectInfo),
74    /// Positive GET_STATUS response.
75    GetStatus(StatusInfo),
76    /// Positive GET_VERSION response (XCP ≥ 1.1).
77    GetVersion(VersionInfo),
78    /// Positive GET_ID response (identification string length; the string
79    /// itself follows via UPLOAD in block mode).
80    GetId(IdInfo),
81    /// Positive UPLOAD / SHORT_UPLOAD response: the uploaded bytes.
82    Upload(Vec<u8>),
83    /// Positive START_STOP_DAQ_LIST response: the first PID assigned to
84    /// the DAQ list's ODTs.
85    StartStopDaqList {
86        /// First packet identifier the slave assigned to the list.
87        first_pid: u8,
88    },
89    /// Positive GET_DAQ_CLOCK response: the free-running slave timestamp.
90    GetDaqClock {
91        /// Slave DAQ clock in the slave's timestamp unit.
92        timestamp: u32,
93    },
94    /// Any other positive response (DISCONNECT, SET_MTA, DOWNLOAD acks,
95    /// GET_CAL_PAGE, …) with the bytes after the PID preserved — empty for
96    /// a bare ack.
97    Generic {
98        /// Payload bytes after the RES PID.
99        data: Vec<u8>,
100    },
101    /// Asynchronous slave event (EV, PID `0xFD`).
102    Event {
103        /// Event code (e.g. `0x06` DAQ overload, `0x05` CMD_PENDING).
104        code: u8,
105        /// Payload bytes after the event code.
106        data: Vec<u8>,
107    },
108    /// Service request from the slave (SERV, PID `0xFC`).
109    Service {
110        /// Service code (e.g. `0x01` request reset).
111        code: u8,
112        /// Payload bytes after the service code.
113        data: Vec<u8>,
114    },
115}
116
117/// The CONNECT response payload.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119pub struct ConnectInfo {
120    /// Resources the slave offers (CAL/PAG, DAQ, STIM, PGM, DBG).
121    pub resource: ResourceMode,
122    /// Basic communication mode: byte order, address granularity, block
123    /// mode support.
124    pub comm_mode: CommModeBasic,
125    /// Maximum CTO (command/response) packet size in bytes — 8 for classic
126    /// XCP on CAN.
127    pub max_cto: u8,
128    /// Maximum DTO (DAQ/STIM) packet size in bytes.
129    pub max_dto: u16,
130    /// XCP protocol layer version (major, minor) — the CONNECT response
131    /// carries only the major; minor is `0`.
132    pub protocol_version: (u8, u8),
133    /// XCP transport layer version (major, minor) — `(1, 0)` for XCP on
134    /// CAN; the response carries only the major.
135    pub transport_version: (u8, u8),
136}
137
138/// The `COMM_MODE_BASIC` byte of the CONNECT response.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140pub struct CommModeBasic {
141    /// Byte order for all multi-byte fields (Intel = little-endian /
142    /// Motorola = big-endian).
143    pub byte_order: ByteOrder,
144    /// Address granularity (byte / word / dword).
145    pub address_granularity: AddressGranularity,
146    /// Slave block mode supported on the current transport.
147    pub slave_block_mode: bool,
148    /// `true` when the slave supports GET_COMM_MODE_INFO (optional info
149    /// available).
150    pub optional_info: bool,
151}
152
153impl CommModeBasic {
154    /// Decode from the raw `COMM_MODE_BASIC` byte.
155    #[must_use]
156    pub const fn from_raw(raw: u8) -> Self {
157        Self {
158            byte_order: ByteOrder::from_bit(raw),
159            address_granularity: AddressGranularity::from_bits(raw),
160            slave_block_mode: raw & 0x40 != 0,
161            optional_info: raw & 0x80 != 0,
162        }
163    }
164
165    /// Encode to the raw `COMM_MODE_BASIC` byte.
166    #[must_use]
167    pub const fn to_raw(self) -> u8 {
168        self.byte_order.to_bit()
169            | (self.address_granularity.to_bits() << 1)
170            | if self.slave_block_mode { 0x40 } else { 0 }
171            | if self.optional_info { 0x80 } else { 0 }
172    }
173}
174
175/// The GET_STATUS response payload.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177pub struct StatusInfo {
178    /// Session status flags (store/clear requests, DAQ running, resume).
179    pub session_status: SessionStatus,
180    /// Resources currently protected (seed & key required to unlock).
181    pub protection_status: ResourceMode,
182    /// Slave session configuration ID.
183    pub session_cfg_id: u16,
184}
185
186/// The GET_VERSION response payload.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub struct VersionInfo {
189    /// XCP protocol layer version (major, minor).
190    pub protocol_version: (u8, u8),
191    /// XCP transport layer version (major, minor).
192    pub transport_version: (u8, u8),
193}
194
195/// The GET_ID response payload.
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
197pub struct IdInfo {
198    /// Echo of the request mode (`0` = ASCII text).
199    pub mode: u8,
200    /// Length of the identification data in bytes; retrieve with UPLOAD.
201    pub length: u32,
202}
203
204/// Parse an XCP CTO response packet with Intel (little-endian) byte order
205/// and no outstanding-command context — the inference heuristic of
206/// [`Expect::Generic`].
207///
208/// Prefer [`parse_response_with`] when the outstanding command is known;
209/// the heuristic is length-based and documented in [`Expect`].
210///
211/// # Errors
212///
213/// - [`XcpError::BufferTooShort`] — the packet is empty, or an ERR/EV/
214///   SERV packet without its code byte, or a `RES` payload too short for
215///   the expected layout.
216/// - [`XcpError::UnknownPid`] — the first byte is not a response PID.
217/// - Any slave ERR code variant ([`XcpError::CmdUnknown`], …) — the slave
218///   answered with a negative response.
219pub fn parse_response(bytes: &[u8]) -> Result<XcpResponse, XcpError> {
220    parse_response_with(ByteOrder::Intel, Expect::Generic, bytes)
221}
222
223/// Parse an XCP CTO response packet with explicit byte order and the
224/// outstanding command ([`Expect`]).
225///
226/// The parser is **total**: trailing bytes beyond a layout are tolerated
227/// (CAN frames may carry DLC padding), and every input resolves to a
228/// typed response or a typed error.
229///
230/// # Errors
231///
232/// See [`parse_response`].
233pub fn parse_response_with(
234    byte_order: ByteOrder,
235    expect: Expect,
236    bytes: &[u8],
237) -> Result<XcpResponse, XcpError> {
238    let Some((&pid, rest)) = bytes.split_first() else {
239        return Err(XcpError::BufferTooShort { need: 1, have: 0 });
240    };
241    match pid {
242        0xFF => parse_res(byte_order, expect, rest),
243        0xFE => Err(crate::error::slave_error(rest)?),
244        0xFD => {
245            let Some((&code, data)) = rest.split_first() else {
246                return Err(XcpError::BufferTooShort { need: 2, have: 1 });
247            };
248            Ok(XcpResponse::Event {
249                code,
250                data: Vec::from(data),
251            })
252        }
253        0xFC => {
254            let Some((&code, data)) = rest.split_first() else {
255                return Err(XcpError::BufferTooShort { need: 2, have: 1 });
256            };
257            Ok(XcpResponse::Service {
258                code,
259                data: Vec::from(data),
260            })
261        }
262        other => Err(XcpError::UnknownPid(other)),
263    }
264}
265
266/// Parse a positive (RES, `0xFF`) payload according to `expect`, or by
267/// heuristic when [`Expect::Generic`].
268fn parse_res(byte_order: ByteOrder, expect: Expect, rest: &[u8]) -> Result<XcpResponse, XcpError> {
269    let short = |need: usize| XcpError::BufferTooShort {
270        need,
271        have: rest.len() + 1,
272    };
273    match expect {
274        Expect::Connect => connect_info(byte_order, rest)
275            .map(XcpResponse::Connect)
276            .ok_or_else(|| short(8)),
277        Expect::GetStatus => status_info(byte_order, rest)
278            .map(XcpResponse::GetStatus)
279            .ok_or_else(|| short(6)),
280        Expect::GetVersion => version_info(rest)
281            .map(XcpResponse::GetVersion)
282            .ok_or_else(|| short(6)),
283        Expect::GetId => id_info(byte_order, rest)
284            .map(XcpResponse::GetId)
285            .ok_or_else(|| short(8)),
286        Expect::Upload => Ok(XcpResponse::Upload(Vec::from(rest))),
287        Expect::StartStopDaqList => match rest.first_chunk::<1>() {
288            Some(&[first_pid]) => Ok(XcpResponse::StartStopDaqList { first_pid }),
289            None => Err(short(2)),
290        },
291        Expect::GetDaqClock => daq_clock(byte_order, rest)
292            .map(|timestamp| XcpResponse::GetDaqClock { timestamp })
293            .ok_or_else(|| short(8)),
294        Expect::Generic => Ok(generic_res(byte_order, rest)),
295    }
296}
297
298/// The documented inference heuristic for context-free RES packets:
299///
300/// | total length | inferred response | collision risk |
301/// |---|---|---|
302/// | 8 | CONNECT ([`ConnectInfo`]) | UPLOAD of 7 bytes, GET_ID, GET_DAQ_CLOCK |
303/// | 6, first payload byte `0x00` | GET_VERSION | UPLOAD of 5 zero bytes |
304/// | 6 | GET_STATUS | UPLOAD of 5 bytes |
305/// | anything else | `Generic { data }` | bare acks, small uploads |
306///
307/// The first payload byte of a GET_VERSION response is the reserved
308/// `0x00`, which a GET_STATUS `SESSION_STATUS` byte never is when any
309/// flag is set. Masters driving GET_ID, GET_DAQ_CLOCK, or large UPLOADs
310/// should use [`Expect`] instead of the heuristic.
311fn generic_res(byte_order: ByteOrder, rest: &[u8]) -> XcpResponse {
312    let generic = || XcpResponse::Generic {
313        data: Vec::from(rest),
314    };
315    match rest.len() {
316        7 => connect_info(byte_order, rest).map_or_else(generic, XcpResponse::Connect),
317        5 => match rest.first() {
318            Some(0x00) => version_info(rest).map_or_else(generic, XcpResponse::GetVersion),
319            _ => status_info(byte_order, rest).map_or_else(generic, XcpResponse::GetStatus),
320        },
321        _ => generic(),
322    }
323}
324
325/// Decode the CONNECT payload (7 bytes after the PID).
326fn connect_info(byte_order: ByteOrder, rest: &[u8]) -> Option<ConnectInfo> {
327    let &[resource, cmb, max_cto, d0, d1, pver, tver] = rest.first_chunk::<7>()?;
328    Some(ConnectInfo {
329        resource: ResourceMode::from_raw(resource),
330        comm_mode: CommModeBasic::from_raw(cmb),
331        max_cto,
332        max_dto: word16(byte_order, d0, d1),
333        protocol_version: (pver, 0),
334        transport_version: (tver, 0),
335    })
336}
337
338/// Decode the GET_STATUS payload (5 bytes after the PID).
339fn status_info(byte_order: ByteOrder, rest: &[u8]) -> Option<StatusInfo> {
340    let &[session, protection, _reserved, c0, c1] = rest.first_chunk::<5>()?;
341    Some(StatusInfo {
342        session_status: SessionStatus::from_raw(session),
343        protection_status: ResourceMode::from_raw(protection),
344        session_cfg_id: word16(byte_order, c0, c1),
345    })
346}
347
348/// Decode the GET_VERSION payload (5 bytes after the PID: reserved, then
349/// the four version bytes).
350fn version_info(rest: &[u8]) -> Option<VersionInfo> {
351    let &[_reserved, pmaj, pmin, tmaj, tmin] = rest.first_chunk::<5>()?;
352    Some(VersionInfo {
353        protocol_version: (pmaj, pmin),
354        transport_version: (tmaj, tmin),
355    })
356}
357
358/// Decode the GET_ID payload (7 bytes after the PID).
359fn id_info(byte_order: ByteOrder, rest: &[u8]) -> Option<IdInfo> {
360    let &[mode, _r0, _r1, a0, a1, a2, a3] = rest.first_chunk::<7>()?;
361    Some(IdInfo {
362        mode,
363        length: word32(byte_order, [a0, a1, a2, a3]),
364    })
365}
366
367/// Decode the GET_DAQ_CLOCK payload (7 bytes after the PID: three
368/// reserved, then the timestamp).
369fn daq_clock(byte_order: ByteOrder, rest: &[u8]) -> Option<u32> {
370    let &[_r0, _r1, _r2, t0, t1, t2, t3] = rest.first_chunk::<7>()?;
371    Some(word32(byte_order, [t0, t1, t2, t3]))
372}
373
374/// Assemble a `u16` from its wire bytes in the given order.
375const fn word16(byte_order: ByteOrder, b0: u8, b1: u8) -> u16 {
376    match byte_order {
377        ByteOrder::Intel => u16::from_le_bytes([b0, b1]),
378        ByteOrder::Motorola => u16::from_be_bytes([b0, b1]),
379    }
380}
381
382/// Assemble a `u32` from its wire bytes in the given order.
383const fn word32(byte_order: ByteOrder, b: [u8; 4]) -> u32 {
384    match byte_order {
385        ByteOrder::Intel => u32::from_le_bytes(b),
386        ByteOrder::Motorola => u32::from_be_bytes(b),
387    }
388}