br_serial/
lib.rs

1use std::sync::{mpsc, Mutex};
2use std::collections::HashMap;
3use std::str::FromStr;
4use std::sync::mpsc::{Receiver, Sender};
5use std::thread;
6use std::time::Duration;
7use lazy_static::lazy_static;
8use log::info;
9use serialport::{available_ports, SerialPortType};
10
11mod usb;
12pub mod protocol;
13lazy_static! {
14    /// 全局串口变量
15    pub static ref DEVICES: Mutex<HashMap<String,Device>> =Mutex::new(HashMap::new());
16    /// 无法连接的设备
17    pub static ref BLACKLIST: Mutex<HashMap<String,String>> =Mutex::new(HashMap::new());
18}
19
20/// 主设备
21#[derive(Clone, Debug)]
22pub struct Devices {}
23
24impl Devices {
25    pub fn new() -> Receiver<SubDevice> {
26
27        // 创建通道
28        let (tx, rx) = mpsc::channel();
29
30        thread::spawn(move || {
31            Devices::listen_device();
32        });
33        let tx2 = tx.clone();
34        thread::spawn(move || {
35            Devices::start(tx2.clone());
36        });
37        return rx;
38    }
39    /// 监听usb设备
40    pub fn listen_device() {
41        loop {
42            let mut devices = HashMap::new();
43            match available_ports() {
44                Ok(ports) => {
45                    for p in ports {
46                        match p.port_type {
47                            SerialPortType::UsbPort(info) => {
48                                let is_none = BLACKLIST.lock().unwrap().get(&*p.port_name.to_string()).is_none();
49                                if !is_none {
50                                    continue;
51                                }
52                                devices.insert(p.port_name.to_string(), info);
53                                continue;
54                            }
55                            _ => {}
56                        }
57                    }
58                }
59                Err(_) => {}
60            }
61            for (com, device) in devices.iter() {
62                let is_none = DEVICES.lock().unwrap().get(&*com.clone()).is_none();
63                if !is_none {
64                    continue;
65                }
66                let uuid = format!("{}_{}", device.vid, device.pid);
67                info!("检测到设备: {}",uuid);
68                let device = Device {
69                    uuid: uuid.clone(),
70                    com: com.clone(),
71                    supplier: "".to_string().clone(),
72                    manufacturer: device.manufacturer.as_ref().map_or("", String::as_str).to_string(),
73                    vid: device.vid,
74                    pid: device.pid,
75                    serial_number: device.serial_number.as_ref().map_or("", String::as_str).to_string(),
76                    product_name: device.product.as_ref().map_or("", String::as_str).to_string(),
77                    state: 0,
78                    device_id: "".to_string(),
79                    sub_device: HashMap::new(),
80                    rate: 115200,
81                    reconnect: 0,
82                };
83                DEVICES.lock().unwrap().insert(com.clone(), device.clone());
84            }
85            thread::sleep(Duration::from_secs(1));
86        }
87    }
88    pub fn start(sender: Sender<SubDevice>) {
89        loop {
90            let mut devices = DEVICES.lock().unwrap().clone();
91            let mut sub_devices = HashMap::new();
92            for (com, device) in devices.iter_mut() {
93                match device.state {
94                    0 => {
95                        usb::Usb { com: com.clone(), step: 0, tx: sender.clone() }.connect();
96                    }
97                    _ => {
98                        for (x, y) in device.sub_device.iter() {
99                            sub_devices.insert(x.clone(), y.clone());
100                        }
101                    }
102                }
103            }
104            thread::sleep(Duration::from_secs(1));
105        }
106    }
107}
108
109/// 主设备
110#[derive(Clone, Debug)]
111pub struct Device {
112    /// 设备id
113    pub device_id: String,
114    /// 端口地址
115    pub com: String,
116    /// 全局唯一ID
117    pub uuid: String,
118    /// 供应商
119    pub supplier: String,
120    /// 制造商
121    pub manufacturer: String,
122    /// 生产厂商ID
123    pub vid: u16,
124    /// 产品ID
125    pub pid: u16,
126    /// 序列号
127    pub serial_number: String,
128    /// 产品名称
129    pub product_name: String,
130    /// 连接状态
131    pub state: usize,
132    /// 子设备
133    pub sub_device: HashMap<String, SubDevice>,
134    /// 波特率
135    pub rate: u32,
136    /// 重连次数
137    pub reconnect: usize,
138}
139
140impl Device {
141    pub fn save_data(&mut self) {
142        DEVICES.lock().unwrap().insert(self.com.clone(), self.clone());
143    }
144}
145
146/// 子设备
147#[derive(Clone, Debug)]
148pub struct SubDevice {
149    pub mode: String,
150    // 子设备ID
151    pub id: String,
152    // 子设备名称
153    pub name: String,
154    // 子设备连接状态
155    pub state: i32,
156    // 主设备 接收状态
157    pub device: bool,
158    /// usb的uuid
159    pub device_id: String,
160    /// 数据模式
161    pub data_mode: String,
162    /// 数据类型
163    pub data_type: String,
164
165    pub value: f64,
166}
167
168impl FromStr for SubDevice {
169    type Err = ();
170
171    fn from_str(s: &str) -> Result<Self, Self::Err> {
172        let sub = json::parse(s).unwrap();
173        Ok(SubDevice {
174            mode: "USB".to_string(),
175            id: sub["id"].to_string(),
176            name: sub["name"].to_string(),
177            state: sub["state"].as_i32().unwrap(),
178            device: sub["device"].as_bool().unwrap(),
179            device_id: sub["device_id"].to_string(),
180            data_mode: sub["data_mode"].to_string(),
181            data_type: sub["data_type"].to_string(),
182            value: sub["value"].as_f64().unwrap(),
183        })
184    }
185}