rs_can/
device.rs

1use crate::{
2    error::Error,
3    frame::{Frame, Id},
4};
5use derive_getters::Getters;
6use serde::{Deserialize, Serialize};
7use std::{
8    any::{type_name, Any},
9    collections::HashMap,
10    hash::Hash,
11};
12
13#[cfg(not(feature = "async"))]
14pub type CanResult<R, E> = Result<R, E>;
15#[cfg(feature = "async")]
16pub type CanResult<R, E> = impl std::future::Future<Output = Result<R, E>>;
17
18pub trait Listener<C, F: Frame>: Send {
19    fn as_any(&self) -> &dyn Any;
20    /// Callback when frame transmitting.
21    fn on_frame_transmitting(&self, channel: C, frame: &F);
22    /// Callback when frame transmit success.
23    fn on_frame_transmitted(&self, channel: C, id: Id);
24    /// Callback when frames received.
25    fn on_frame_received(&self, channel: C, frames: &[F]);
26}
27
28pub trait Device: Clone + TryFrom<DeviceBuilder<Self::Channel>, Error = Error> {
29    type Channel: Hash + Eq;
30    type Frame: Frame<Channel = Self::Channel>;
31    #[inline]
32    fn is_closed(&self) -> bool {
33        self.opened_channels().is_empty()
34    }
35    /// get all channels that has opened
36    fn opened_channels(&self) -> Vec<Self::Channel>;
37    /// Transmit a CAN or CAN-FD Frame.
38    fn transmit(&self, msg: Self::Frame, timeout: Option<u32>) -> CanResult<(), Error>;
39    /// Receive CAN and CAN-FD Frames.
40    fn receive(
41        &self,
42        channel: Self::Channel,
43        timeout: Option<u32>,
44    ) -> CanResult<Vec<Self::Frame>, Error>;
45    /// Close CAN device.
46    fn shutdown(&mut self);
47}
48
49#[derive(Debug, Default, Deserialize, Serialize, Getters)]
50pub struct ChannelConfig {
51    #[getter(copy)]
52    bitrate: u32,
53    #[getter(copy)]
54    dbitrate: Option<u32>,
55    #[getter(copy)]
56    resistance: Option<bool>,
57    #[serde(skip)]
58    others: HashMap<String, Box<dyn Any>>,
59}
60
61impl ChannelConfig {
62    pub fn new(bitrate: u32) -> Self {
63        Self {
64            bitrate,
65            ..Default::default()
66        }
67    }
68
69    pub fn set_data_bitrate(&mut self, bitrate: u32) -> &mut Self {
70        self.dbitrate = Some(bitrate);
71        self
72    }
73
74    pub fn set_resistance(&mut self, resistance: bool) -> &mut Self {
75        self.resistance = Some(resistance);
76        self
77    }
78
79    pub fn add_other(&mut self, name: &str, other: Box<dyn Any>) -> &mut Self {
80        self.others.insert(name.into(), other);
81        self
82    }
83
84    pub fn get_other<T: Clone + 'static>(&self, name: &str) -> Result<Option<T>, Error> {
85        get_other(&self.others, name)
86    }
87}
88
89#[derive(Debug, Default, Getters)]
90pub struct DeviceBuilder<K: Hash + Eq> {
91    #[getter(rename = "channel_configs")]
92    configs: HashMap<K, ChannelConfig>,
93    others: HashMap<String, Box<dyn Any>>,
94}
95
96impl<K: Hash + Eq + Default> DeviceBuilder<K> {
97    pub fn new() -> Self {
98        Self::default()
99    }
100
101    pub fn add_config(&mut self, channel: K, cfg: ChannelConfig) -> &mut Self {
102        self.configs.insert(channel.into(), cfg);
103        self
104    }
105
106    pub fn add_other(&mut self, name: &str, cfg: Box<dyn Any>) -> &mut Self {
107        self.others.insert(name.into(), cfg);
108        self
109    }
110
111    pub fn get_other<T: Clone + 'static>(&self, name: &str) -> Result<Option<T>, Error> {
112        get_other(&self.others, name)
113    }
114
115    pub fn build<T: Device<Channel = K>>(self) -> Result<T, Error> {
116        self.try_into()
117    }
118}
119
120#[inline(always)]
121fn get_other<T: Clone + 'static>(
122    others: &HashMap<String, Box<dyn Any>>,
123    name: &str,
124) -> Result<Option<T>, Error> {
125    match others.get(name) {
126        Some(v) => Ok(Some(
127            v.downcast_ref::<T>()
128                .ok_or(Error::OtherError(format!(
129                    "type mismatched for `{}` expected: `{}`",
130                    name,
131                    type_name::<T>()
132                )))?
133                .clone(),
134        )),
135        None => Ok(None),
136    }
137}