Path: blob/master/gate-controller/src-tauri/src/relay/cp210x.rs
1091 views
use std::collections::HashMap;1use std::io::Write;2use std::sync::{Arc, Mutex};34use serialport::{self, SerialPort};56// ==============================7// ====== RELAY ACTION LOGIC ====8// ==============================910pub fn trigger_cp210x_action(11connections: &Arc<Mutex<HashMap<String, Box<dyn SerialPort + Send>>>>,12port_name: &str,13action: &str,14channel: u8,15) -> Result<(), String> {16let mut connections_guard = connections.lock().unwrap();17if !connections_guard.contains_key(port_name) {18let port = serialport::new(port_name, 9600)19.timeout(std::time::Duration::from_millis(500))20.open()21.map_err(|e| format!("Failed to open serial port '{}': {}", port_name, e))?;22connections_guard.insert(port_name.to_string(), port);23// Wait for the serial device to initialize24std::thread::sleep(std::time::Duration::from_millis(200));25}2627let serial_port = connections_guard.get_mut(port_name).unwrap();2829let action_val = if action == "on" { 1 } else { 0 };30let cmd_str = format!("AT+CH{}={}\r\n", channel, action_val);31let command = cmd_str.as_bytes();3233match serial_port.write_all(command) {34Ok(_) => Ok(()),35Err(e) => {36// Connection is likely stale. Remove it from the cache37// so the next attempt will try to reconnect.38connections_guard.remove(port_name);39Err(format!(40"Failed to write to serial port '{}': {}. It may have been disconnected.",41port_name, e42))43}44}45}464748