iso15765_2/
core.rs

1#![allow(deprecated)]
2
3use crate::{
4    constants::{
5        TIMEOUT_AR_ISO15765_2, TIMEOUT_AS_ISO15765_2, TIMEOUT_BR_ISO15765_2, TIMEOUT_BS_ISO15765_2,
6        TIMEOUT_CR_ISO15765_2, TIMEOUT_CS_ISO15765_2,
7    },
8    error::Error,
9};
10use bitflags::bitflags;
11use bytes::{Bytes, BytesMut};
12use std::{
13    collections::VecDeque,
14    fmt::{Display, Formatter},
15    sync::Arc,
16};
17use tokio::sync::Mutex;
18
19bitflags! {
20    /// ISO 15765-2 state.
21    #[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
22    pub struct State: u8 {
23        const Idle = 0b0000_0000;
24        #[deprecated]
25        const WaitSingle = 0b0000_0001;
26        #[deprecated]
27        const WaitFirst = 0b0000_0010;
28        const WaitFlowCtrl = 0b0000_0100;
29        #[deprecated]
30        const WaitData = 0b0000_1000;
31        const WaitBusy = 0b0001_0000;
32        #[deprecated]
33        const ResponsePending = 0b0010_0000;
34        const Sending = 0b0100_0000;
35        const Error = 0b1000_0000;
36    }
37}
38
39impl Display for State {
40    #[allow(deprecated)]
41    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
42        let mut idle = true;
43        let mut first = true;
44        if self.contains(State::WaitSingle) {
45            write!(f, "WaitSingle")?;
46            idle = false;
47            first = false;
48        }
49        if self.contains(State::WaitFirst) {
50            write!(
51                f,
52                "{}",
53                format_args!("{}WaitFirst", if first { "" } else { " | " })
54            )?;
55            idle = false;
56            first = false;
57        }
58        if self.contains(State::WaitFlowCtrl) {
59            write!(
60                f,
61                "{}",
62                format_args!("{}WaitFlowCtrl", if first { "" } else { " | " })
63            )?;
64            idle = false;
65            first = false;
66        }
67        if self.contains(State::WaitData) {
68            write!(
69                f,
70                "{}",
71                format_args!("{}WaitData", if first { "" } else { " | " })
72            )?;
73            idle = false;
74            first = false;
75        }
76        if self.contains(State::WaitBusy) {
77            write!(
78                f,
79                "{}",
80                format_args!("{}WaitBusy", if first { "" } else { " | " })
81            )?;
82            idle = false;
83            first = false;
84        }
85        if self.contains(State::ResponsePending) {
86            write!(
87                f,
88                "{}",
89                format_args!("{}ResponsePending", if first { "" } else { " | " })
90            )?;
91            idle = false;
92            first = false;
93        }
94        if self.contains(State::Sending) {
95            write!(
96                f,
97                "{}",
98                format_args!("{}Sending", if first { "" } else { " | " })
99            )?;
100            idle = false;
101            first = false;
102        }
103        if self.contains(State::Error) {
104            write!(
105                f,
106                "{}",
107                format_args!("{}Error", if first { "" } else { " | " })
108            )?;
109            idle = false;
110        }
111        if idle {
112            write!(f, "Idle")?;
113        }
114
115        Ok(())
116    }
117}
118
119#[derive(Debug, Clone)]
120pub enum Event {
121    Wait,
122    FirstFrameReceived,
123    // FrameReceived(FrameType),
124    DataReceived(Bytes),
125    ErrorOccurred(Error),
126}
127unsafe impl Send for Event {}
128unsafe impl Sync for Event {}
129
130#[async_trait::async_trait]
131pub trait EventListener {
132    async fn buffer_data(&self) -> Option<Event>;
133    async fn clear_buffer(&self);
134    async fn on_iso_tp_event(&self, event: Event);
135    // async fn update_p2_ctx(&self, p2: u16, p2_star: u32);
136}
137
138/// Flow control type define.
139#[repr(u8)]
140#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
141pub enum FlowControlState {
142    #[default]
143    Continues = 0x00,
144    Wait = 0x01,
145    Overload = 0x02,
146}
147
148impl TryFrom<u8> for FlowControlState {
149    type Error = Error;
150    fn try_from(value: u8) -> Result<Self, Self::Error> {
151        match value {
152            0x00 => Ok(Self::Continues),
153            0x01 => Ok(Self::Wait),
154            0x02 => Ok(Self::Overload),
155            v => Err(Error::InvalidParam(format!("`state` ({})", v))),
156        }
157    }
158}
159
160impl From<FlowControlState> for u8 {
161    #[inline]
162    fn from(val: FlowControlState) -> Self {
163        val as u8
164    }
165}
166
167/// Flow control frame context.
168#[derive(Debug, Default, Copy, Clone)]
169pub struct FlowControlContext {
170    pub(crate) state: FlowControlState,
171    pub(crate) block_size: u8,
172    /// Use milliseconds (ms) for values in the range 00 to 7F (0 ms to 127 ms).
173    /// If st_min is 0, set to default value. See [`ST_MIN_ISO15765_2`]
174    /// and [`ST_MIN_ISO15765_4`]
175    ///
176    /// Use microseconds (μs) for values in the range F1 to F9 (100 μs to 900 μs).
177    ///
178    /// Values in the ranges 80 to F0 and FA to FF are reserved.
179    pub(crate) st_min: u8,
180}
181
182impl FlowControlContext {
183    #[inline]
184    pub fn new(state: FlowControlState, block_size: u8, st_min: u8) -> Result<Self, Error> {
185        match st_min {
186            0x80..=0xF0 | 0xFA..=0xFF => Err(Error::InvalidStMin(st_min)),
187            v => Ok(Self {
188                state,
189                block_size,
190                st_min: v,
191            }),
192        }
193    }
194    #[inline]
195    pub fn state(&self) -> FlowControlState {
196        self.state
197    }
198    #[inline]
199    pub fn block_size(&self) -> u8 {
200        self.block_size
201    }
202    #[inline]
203    pub fn st_min(&self) -> u8 {
204        self.st_min
205    }
206    #[inline]
207    pub fn st_min_us(&self) -> u32 {
208        match self.st_min {
209            // 0x00 => 1000 * 10,
210            ..=0x7F => 1000 * (self.st_min as u32),
211            0x80..=0xF0 | 0xFA..=0xFF => {
212                // should not enter
213                let message = format!("ISO 15765-2 - got an invalid st_min: {}", self.st_min);
214                rsutil::error!("{}", message);
215                unreachable!("{}", message) // panic is dangerous
216            }
217            0xF1..=0xF9 => 100 * (self.st_min & 0x0F) as u32,
218        }
219    }
220}
221
222/// Consecutive frame data context.
223#[derive(Debug, Default, Clone)]
224pub(crate) struct Consecutive {
225    pub(crate) sequence: Option<u8>,
226    pub(crate) length: Option<u32>,
227    pub(crate) buffer: BytesMut,
228}
229
230#[derive(Debug, Default, Clone)]
231pub(crate) struct Buffer {
232    inner: Arc<Mutex<VecDeque<Event>>>,
233}
234
235impl Buffer {
236    #[inline(always)]
237    pub async fn clear(&self) {
238        self.inner.lock().await.clear();
239    }
240
241    #[inline(always)]
242    pub async fn set(&self, event: Event) {
243        self.inner.lock().await.push_back(event);
244    }
245
246    #[inline(always)]
247    pub async fn get(&self) -> Option<Event> {
248        self.inner.lock().await.pop_front()
249    }
250}
251
252#[derive(Debug, Clone)]
253pub(crate) struct Timeout {
254    /// Network Layer Acknowledgement Time by Receiver
255    pub(crate) n_ar: Arc<Mutex<u64>>,
256    /// Network Layer Acknowledgement Time by Sender
257    pub(crate) n_as: Arc<Mutex<u64>>,
258    /// Network Layer Block Time by Receiver
259    pub(crate) n_br: Arc<Mutex<u64>>,
260    /// Network Layer Block Time by Sender
261    pub(crate) n_bs: Arc<Mutex<u64>>,
262    /// Network Layer Next Consecutive Frame Time by Sender
263    pub(crate) n_cs: Arc<Mutex<u64>>,
264    /// Network Layer Consecutive Frame Time by Receiver
265    pub(crate) n_cr: Arc<Mutex<u64>>,
266}
267
268impl Default for Timeout {
269    fn default() -> Self {
270        Self {
271            n_ar: Arc::new(Mutex::new(TIMEOUT_AR_ISO15765_2 as u64)),
272            n_as: Arc::new(Mutex::new(TIMEOUT_AS_ISO15765_2 as u64)),
273            n_br: Arc::new(Mutex::new(TIMEOUT_BR_ISO15765_2 as u64)),
274            n_bs: Arc::new(Mutex::new(TIMEOUT_BS_ISO15765_2 as u64)),
275            n_cs: Arc::new(Mutex::new(TIMEOUT_CR_ISO15765_2 as u64)),
276            n_cr: Arc::new(Mutex::new(TIMEOUT_CS_ISO15765_2 as u64)),
277        }
278    }
279}