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/cp210x.rs
1091 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
// ==============================
8
// ====== RELAY ACTION LOGIC ====
9
// ==============================
10
11
pub fn trigger_cp210x_action(
12
connections: &Arc<Mutex<HashMap<String, Box<dyn SerialPort + Send>>>>,
13
port_name: &str,
14
action: &str,
15
channel: u8,
16
) -> Result<(), String> {
17
let mut connections_guard = connections.lock().unwrap();
18
if !connections_guard.contains_key(port_name) {
19
let port = serialport::new(port_name, 9600)
20
.timeout(std::time::Duration::from_millis(500))
21
.open()
22
.map_err(|e| format!("Failed to open serial port '{}': {}", port_name, e))?;
23
connections_guard.insert(port_name.to_string(), port);
24
// Wait for the serial device to initialize
25
std::thread::sleep(std::time::Duration::from_millis(200));
26
}
27
28
let serial_port = connections_guard.get_mut(port_name).unwrap();
29
30
let action_val = if action == "on" { 1 } else { 0 };
31
let cmd_str = format!("AT+CH{}={}\r\n", channel, action_val);
32
let command = cmd_str.as_bytes();
33
34
match serial_port.write_all(command) {
35
Ok(_) => Ok(()),
36
Err(e) => {
37
// Connection is likely stale. Remove it from the cache
38
// so the next attempt will try to reconnect.
39
connections_guard.remove(port_name);
40
Err(format!(
41
"Failed to write to serial port '{}': {}. It may have been disconnected.",
42
port_name, e
43
))
44
}
45
}
46
}
47
48