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