Path: blob/master/gate-controller/src-tauri/src/relay/ch340.rs
1085 views
use std::collections::HashMap;1use std::io::Write;2use std::sync::{Arc, Mutex};34use serialport::{self, SerialPort};56use super::ConnectionManager;78// ==============================9// ====== RELAY ACTION LOGIC ====10// ==============================1112pub fn trigger_ch340_action(13connections: &Arc<Mutex<HashMap<String, Box<dyn SerialPort + Send>>>>,14port_name: &str,15action: &str,16channel: u8,17) -> Result<(), String> {18let mut connections_guard = connections.lock().unwrap();19if !connections_guard.contains_key(port_name) {20let port = serialport::new(port_name, 9600)21.timeout(std::time::Duration::from_millis(100))22.open()23.map_err(|e| format!("Failed to open serial port '{}': {}", port_name, e))?;24connections_guard.insert(port_name.to_string(), port);25// Wait for the serial device to initialize26std::thread::sleep(std::time::Duration::from_millis(200));27}2829let serial_port = connections_guard.get_mut(port_name).unwrap();3031let action_val = if action == "on" { 0x01 } else { 0x00 };32let checksum = (0xA0u8 as u16 + channel as u16 + action_val as u16) as u8;33let command = [0xA0, channel, action_val, checksum];3435match serial_port.write_all(&command) {36Ok(_) => Ok(()),37Err(e) => {38// Connection is likely stale. Remove it from the cache39// so the next attempt will try to reconnect.40connections_guard.remove(port_name);41Err(format!(42"Failed to write to serial port '{}': {}. It may have been disconnected.",43port_name, e44))45}46}47}484950