Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
parkpow
GitHub Repository: parkpow/deep-license-plate-recognition
Path: blob/master/gate-controller/src-tauri/src/relay/ch340.rs
1085 views
1
use std::collections::HashMap;
2
use std::io::Write;
3
use std::sync::{Arc, Mutex};
4
5
use serialport::{self, SerialPort};
6
7
use super::ConnectionManager;
8
9
// ==============================
10
// ====== RELAY ACTION LOGIC ====
11
// ==============================
12
13
pub fn trigger_ch340_action(
14
connections: &Arc<Mutex<HashMap<String, Box<dyn SerialPort + Send>>>>,
15
port_name: &str,
16
action: &str,
17
channel: u8,
18
) -> Result<(), String> {
19
let mut connections_guard = connections.lock().unwrap();
20
if !connections_guard.contains_key(port_name) {
21
let port = serialport::new(port_name, 9600)
22
.timeout(std::time::Duration::from_millis(100))
23
.open()
24
.map_err(|e| format!("Failed to open serial port '{}': {}", port_name, e))?;
25
connections_guard.insert(port_name.to_string(), port);
26
// Wait for the serial device to initialize
27
std::thread::sleep(std::time::Duration::from_millis(200));
28
}
29
30
let serial_port = connections_guard.get_mut(port_name).unwrap();
31
32
let action_val = if action == "on" { 0x01 } else { 0x00 };
33
let checksum = (0xA0u8 as u16 + channel as u16 + action_val as u16) as u8;
34
let command = [0xA0, channel, action_val, checksum];
35
36
match serial_port.write_all(&command) {
37
Ok(_) => Ok(()),
38
Err(e) => {
39
// Connection is likely stale. Remove it from the cache
40
// so the next attempt will try to reconnect.
41
connections_guard.remove(port_name);
42
Err(format!(
43
"Failed to write to serial port '{}': {}. It may have been disconnected.",
44
port_name, e
45
))
46
}
47
}
48
}
49
50