oze_canopen/
interface.rs

1use crate::{canopen::RxMessage, sdo_client::SdoClient, transmitter::TxPacket};
2use std::{collections::HashMap, sync::Arc};
3use tokio::sync::{broadcast, mpsc, Mutex};
4
5/// Timeout duration for sending messages.
6pub const SEND_TIMOUT: u64 = 20;
7
8/// Struct representing CANopen information.
9#[derive(Debug, Default, Clone)]
10pub struct CanOpenInfo {
11    /// Number of received bits.
12    pub rx_bits: usize,
13    /// Status of the transmitter socket.
14    pub transmitter_socket: bool,
15    /// Status of the receiver socket.
16    pub receiver_socket: bool,
17}
18
19/// Struct representing a CAN connection.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Connection {
22    /// Name of the CAN interface.
23    pub can_name: String,
24    /// Bitrate of the CAN interface.
25    pub bitrate: Option<u32>,
26}
27
28/// Struct representing a CANopen interface.
29pub struct CanOpenInterface {
30    /// Connection details.
31    pub connection: Arc<Mutex<Connection>>,
32    /// Transmitter channel.
33    pub tx: mpsc::Sender<TxPacket>,
34    /// Receiver channel.
35    pub rx: broadcast::Receiver<RxMessage>,
36    /// Map of SDO clients.
37    pub sdo_clients: HashMap<u8, Arc<Mutex<SdoClient>>>,
38    /// CANopen information.
39    pub info: Arc<Mutex<CanOpenInfo>>,
40    /// CANopen information.
41    pub(crate) close: Arc<Mutex<bool>>,
42}
43
44impl CanOpenInterface {
45    /// Retrieves an SDO client for a given node ID.
46    ///
47    /// # Arguments
48    ///
49    /// * `node_id` - The ID of the node.
50    ///
51    /// # Returns
52    ///
53    /// An `Option` containing an `Arc<Mutex<SdoClient>>` if found, otherwise `None`.
54    ///
55    /// # Examples
56    ///
57    /// ```
58    /// let client = can_interface.get_sdo_client(2).unwrap();
59    /// client.lock().await.download(0x1801, 2, &[1u8]).await;
60    /// ```
61    pub fn get_sdo_client(&self, node_id: u8) -> Option<Arc<Mutex<SdoClient>>> {
62        let v = self.sdo_clients.get(&node_id)?;
63        Some(v.clone())
64    }
65
66    pub async fn close() {}
67}
68
69impl Clone for CanOpenInterface {
70    /// Clones the `CanOpenInterface`.
71    fn clone(&self) -> Self {
72        Self {
73            connection: self.connection.clone(),
74            tx: self.tx.clone(),
75            rx: self.rx.resubscribe(),
76            sdo_clients: self.sdo_clients.clone(),
77            info: self.info.clone(),
78            close: self.close.clone(),
79        }
80    }
81}