kmbox/
lib.rs

1use colored::*;
2use serialport::SerialPortType;
3use std::io::Write;
4use std::time::Duration;
5
6/// Finds and returns the COM port that matches the description "USB-SERIAL CH340".
7///
8/// # Returns
9/// An `Option<String>` containing the port name if found, otherwise `None`.
10pub fn find_port() -> Option<String> {
11    let description = "USB-SERIAL CH340";
12    
13    let ports = match serialport::available_ports() {
14        Ok(ports) => ports,
15        Err(e) => {
16            eprintln!("{}", "Failed to list available ports:".red());
17            eprintln!("{}", e.to_string().red());
18            return None;
19        }
20    };
21
22    ports.iter().find_map(|p| match &p.port_type {
23        SerialPortType::UsbPort(info) => {
24            if info.product.as_deref().map_or(false, |desc| desc.contains(description)) {
25                Some(p.port_name.clone())
26            } else {
27                None
28            }
29        }
30        _ => None,
31    })
32}
33
34/// Sends a movement command to the KMBox through the specified serial port.
35///
36/// # Parameters
37/// - `port_name`: The name of the COM port to use.
38/// - `x`: The x-coordinate to move to.
39/// - `y`: The y-coordinate to move to.
40///
41/// # Returns
42/// A Result indicating success or failure with a descriptive error message.
43pub fn move_command(port_name: String, x: i32, y: i32) -> Result<(), String> {
44    let mut port = match serialport::new(&port_name, 115_200)
45        .timeout(Duration::from_millis(10))
46        .open() {
47        Ok(port) => port,
48        Err(e) => {
49            let error_message = format!("Failed to open port {}: {}", port_name, e);
50            eprintln!("{}", "ERROR:".red().bold());
51            eprintln!("{}", error_message.red());
52            return Err(error_message);
53        }
54    };
55    
56    println!("{}", "[+] KMBox Connected on".green().bold());
57    println!("{}", port_name.green());
58
59    let command = format!("km.move({}, {})\r\n", x, y);
60    if let Err(e) = port.write(command.as_bytes()) {
61        let error_message = format!("Failed to write to serial port: {}", e);
62        eprintln!("{}", "ERROR:".red().bold());
63        eprintln!("{}", error_message.red());
64        return Err(error_message);
65    }
66
67    println!("{}", "Move command sent:".green().bold());
68    println!("{}", command.green());
69    Ok(())
70}
71
72fn mouse_click() {
73    todo!()
74}