### Rust: Synchronous Serial Device Communication Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md This example demonstrates how to establish a synchronous connection to a serial device, perform relative mouse movements, clicks, and wheel scrolls, and then disconnect. It requires a serial port path, baud rate, and a timeout duration for connection. ```rust use makcu_rs::{Device, MouseButton}; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("/dev/ttyUSB0", 115200, Duration::from_millis(100)); dev.connect()?; dev.move_rel(100, 0)?; dev.click(MouseButton::Left)?; dev.wheel(-2)?; dev.disconnect(); Ok(()) } ``` ```rust let dev = Device::new("COM3", 115200, Duration::from_millis(100)); dev.connect()?; dev.click(MouseButton::Left)?; dev.disconnect(); ``` -------------------------------- ### Rust: Sending a command and tracking response Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md This example demonstrates how to send a serial command and wait for a response with an optional timeout. It uses the `set_serial` method which returns the received response. ```rust let response = dev.set_serial("ABC123")?; println!("Response: {response}"); ``` -------------------------------- ### Complete Automation Script using makcu-rs in Rust Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt This example showcases a full automation workflow using the `makcu-rs` library in Rust. It covers device initialization, connection, setting up button callbacks for event monitoring, querying device information, and executing a sequence of mouse and scroll operations. The script also demonstrates the use of the batch API for efficient command execution and prints performance statistics. ```rust use makcu_rs::{Device, MouseButton, MouseButtonStates}; use std::time::Duration; fn main() -> anyhow::Result<()> { // Initialize device let dev = Device::new("/dev/ttyUSB0", 115200, Duration::from_millis(100)); dev.connect()?; println!("Connected to device"); // Setup button monitoring dev.set_button_callback(Some(|states: MouseButtonStates| { if states.side1 && states.side2 { println!("Emergency stop: both side buttons pressed"); } })); // Query device serial number match dev.set_serial("") { Ok(serial) => println!("Device serial: {}", serial), Err(_) => println!("Could not read serial"), } // Execute automation sequence println!("Starting automation sequence..."); // Move to starting position dev.move_rel(500, 300)?; std::thread::sleep(Duration::from_millis(100)); // Perform drag operation dev.batch() .press(MouseButton::Left) .move_rel(200, 0) .move_rel(0, 150) .release(MouseButton::Left) .run()?; // Context menu and selection dev.click(MouseButton::Right)?; std::thread::sleep(Duration::from_millis(200)); dev.move_rel(50, 80)?; dev.click(MouseButton::Left)?; // Scroll through content for _ in 0..5 { dev.wheel(-3)?; std::thread::sleep(Duration::from_millis(100)); } // Print performance statistics let stats = Device::profiler_stats(); if !stats.is_empty() { println!("\nPerformance Statistics:"); for (op, metrics) in stats.iter() { if let Some(avg) = metrics.get("avg_us") { println!(" {}: {:.2}µs average", op, avg); } } } // Cleanup dev.disconnect(); println!("Automation complete"); Ok(()) } ``` -------------------------------- ### Rust: Asynchronous Serial Device Communication Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md This example shows how to set up an asynchronous serial device connection using tokio. It includes performing relative mouse movements, clicks, and wheel scrolls asynchronously. The function requires a serial port path and baud rate. ```rust #[tokio::main] async fn main() -> std::io::Result<()> { use makcu_rs::{DeviceAsync, MouseButton}; let dev = DeviceAsync::new("/dev/ttyUSB0", 115200).await?; dev.move_rel(50, 0).await?; dev.click(MouseButton::Right).await?; dev.wheel(1).await?; Ok(()) } ``` ```rust let dev = DeviceAsync::new("COM3", 115200).await?; dev.press(MouseButton::Middle).await?; ``` -------------------------------- ### Rust: Accessing profiler statistics Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md If the 'profile' feature is enabled, this example shows how to retrieve performance statistics collected by the library. The `profiler_stats` function returns a data structure containing timing information for various operations. ```rust let stats = makcu_rs::Device::profiler_stats(); dbg!(stats); ``` -------------------------------- ### Rust: Adding makcu-rs to Cargo.toml Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md This snippet shows how to add the makcu-rs library as a dependency to a Rust project's Cargo.toml file. It includes examples for the basic dependency and for enabling optional features like 'async', 'mockserial', and 'profile'. ```toml [dependencies] makcu-rs = "0.1" ``` ```toml makcu-rs = { version = "0.1", features = ["async", "mockserial", "profile"] } ``` -------------------------------- ### Bash: Building with optional features Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md This bash command demonstrates how to compile the makcu-rs library with specific optional features enabled, such as 'profile' and 'mockserial', by passing them to the `cargo build` command. ```bash cargo build --features "profile mockserial" ``` -------------------------------- ### Rust: Executing batch commands Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md This code snippet illustrates how to chain multiple serial operations (like mouse movement, clicks, and wheel scrolls) into a single batch command using a fluent API. The `run` method executes all accumulated commands. ```rust dev.batch() .move_rel(100, 20) .click(MouseButton::Left) .wheel(-1) .run()?; ``` -------------------------------- ### Create and Connect Device (Sync) Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Initializes a synchronous device connection to a serial port. It requires the port name, baud rate, and a connection timeout. The connect method spawns necessary reader/writer threads. ```rust use makcu_rs::Device; use std::time::Duration; fn main() -> anyhow::Result<()> { // Create device for COM3 at 115200 baud with 100ms timeout let dev = Device::new("COM3", 115200, Duration::from_millis(100)); // Connect to the serial port (spawns reader/writer threads) dev.connect()?; // Device is now ready for operations println!("Connected successfully"); // Always disconnect when done to clean up threads dev.disconnect(); Ok(()) } ``` -------------------------------- ### Mouse Clicks (Sync) Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Simulates mouse button clicks, including single press-and-release operations for standard buttons and individual press/release calls for custom timing. ```rust use makcu_rs::{Device, MouseButton}; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("COM3", 115200, Duration::from_millis(100)); dev.connect()?; // Single click operations (press + release) dev.click(MouseButton::Left)?; dev.click(MouseButton::Right)?; dev.click(MouseButton::Middle)?; dev.click(MouseButton::Side1)?; dev.click(MouseButton::Side2)?; // Individual press/release for custom timing dev.press(MouseButton::Left)?; std::thread::sleep(Duration::from_millis(50)); dev.release(MouseButton::Left)?; dev.disconnect(); Ok(()) } ``` -------------------------------- ### Create and Connect Device (Async) Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Initializes an asynchronous device connection using tokio-serial for non-blocking operations. This method automatically opens the connection and is suitable for async Rust applications. ```rust use makcu_rs::{DeviceAsync, MouseButton}; #[tokio::main] async fn main() -> std::io::Result<()> { // Create async device - automatically opens connection let dev = DeviceAsync::new("/dev/ttyUSB0", 115200).await?; // Perform async operations dev.move_rel(100, 50).await?; dev.click(MouseButton::Left).await?; println!("Async operations completed"); Ok(()) } ``` -------------------------------- ### Mock Serial Implementation for Testing in Rust Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt This snippet demonstrates how to use the `MockSerial` implementation for unit testing serial communication without requiring actual hardware. It utilizes the `mockserial` feature of the `makcu-rs` crate. The `MockSerial` simulates serial port behavior, responding to tracked commands and allowing the standard `Device` API to function seamlessly. ```rust // Cargo.toml: makcu-rs = { version = "0.1", features = ["mockserial"] } #[cfg(feature = "mockserial")] use makcu_rs::mockserial::MockSerial; use makcu_rs::Device; use std::time::Duration; #[cfg(feature = "mockserial")] fn main() -> anyhow::Result<()> { // Create mock serial port for testing let mock = MockSerial::new(Duration::from_millis(10)); // Use mock in tests to simulate serial behavior // Mock automatically responds to tracked commands println!("Mock serial created for testing"); // Regular Device API works with mock serial backend let dev = Device::new("MOCK", 115200, Duration::from_millis(100)); // All operations succeed without real hardware // Response simulation built-in for tracked commands Ok(()) } #[cfg(not(feature = "mockserial"))] fn main() { println!("Build with --features mockserial to enable"); } ``` -------------------------------- ### Batch Operations (Sync) Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Chains multiple mouse control commands (move, click, scroll, press, release) into a single batch for execution. This is done using a fluent API and sending them as one operation to reduce overhead. ```rust use makcu_rs::{Device, MouseButton}; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("COM3", 115200, Duration::from_millis(100)); dev.connect()?; // Build and execute a batch of operations dev.batch() .move_rel(100, 20) .click(MouseButton::Left) .move_rel(50, 0) .wheel(-2) .press(MouseButton::Right) .release(MouseButton::Right) .run()?; // Batch operations reduce overhead compared to individual calls println!("Batch completed"); dev.disconnect(); Ok(()) } ``` -------------------------------- ### TOML: Enabling mockserial feature Source: https://github.com/whatzwastaken/makcu-rs/blob/main/README.md This TOML snippet shows how to enable the 'mockserial' feature for the makcu-rs crate within a project's Cargo.toml file, typically used for unit testing by simulating serial port behavior. ```toml [features] mockserial = [] ``` -------------------------------- ### Mouse Movement (Sync) Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Simulates relative mouse cursor movements using synchronous calls. Accepts positive values for right/down and negative values for left/up. ```rust use makcu_rs::Device; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("/dev/ttyUSB0", 115200, Duration::from_millis(100)); dev.connect()?; // Move right 150 pixels, down 75 pixels dev.move_rel(150, 75)?; // Move left 50 pixels, up 25 pixels (negative values) dev.move_rel(-50, -25)?; // No movement on x-axis, move down 100 pixels dev.move_rel(0, 100)?; dev.disconnect(); Ok(()) } ``` -------------------------------- ### Register Button State Callbacks Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Sets up a callback function to receive real-time updates on mouse button states. The callback is invoked whenever a button state changes, allowing for immediate reactions. It can be removed by setting the callback to `None`. ```rust use makcu_rs::{Device, MouseButtonStates}; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("COM3", 115200, Duration::from_millis(100)); dev.connect()?; // Set callback to monitor button states dev.set_button_callback(Some(|states: MouseButtonStates| { println!("Button states - Left: {}, Right: {}, Middle: {}, Side1: {}, Side2: {}", states.left, states.right, states.middle, states.side1, states.side2); // React to specific button combinations if states.left && states.right { println!("Both left and right buttons pressed!"); } })); // Button state updates will trigger callback automatically std::thread::sleep(Duration::from_secs(10)); // Remove callback dev.set_button_callback(None::); dev.disconnect(); Ok(()) } ``` -------------------------------- ### Execute Asynchronous Batch Operations Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Chains multiple asynchronous mouse and button operations for non-blocking execution. This is useful for performing a sequence of actions without halting the main thread. It requires the `tokio` runtime. ```rust use makcu_rs::{DeviceAsync, MouseButton}; #[tokio::main] async fn main() -> std::io::Result<()> { let dev = DeviceAsync::new("/dev/ttyUSB0", 115200).await?; // Build async batch dev.batch() .press(MouseButton::Left) .move_rel(50, 30) .release(MouseButton::Left) .wheel(-120) .click(MouseButton::Right) .run() .await?; println!("Async batch completed"); Ok(()) } ``` -------------------------------- ### Collect Performance Profiling Statistics Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Enables performance profiling by collecting timing statistics for each operation when the `profile` feature is enabled during compilation. The collected data includes the number of calls, total time, and average time for each operation. These statistics can be retrieved and displayed. ```rust use makcu_rs::{Device, MouseButton}; use std::time::Duration; fn main() -> anyhow::Result<()> { // Build with: cargo build --features "profile" let dev = Device::new("/dev/ttyUSB0", 115200, Duration::from_millis(100)); dev.connect()?; // Perform various operations for _ in 0..100 { dev.move_rel(10, 0)?; dev.click(MouseButton::Left)?; dev.wheel(-1)?; } // Retrieve profiler statistics let stats = Device::profiler_stats(); // Display timing information for (operation, metrics) in stats.iter() { let count = metrics.get("count").unwrap_or(&0.0); let total = metrics.get("total_us").unwrap_or(&0.0); let avg = metrics.get("avg_us").unwrap_or(&0.0); println!("{}: {} calls, {:.2}µs total, {:.2}µs avg", operation, count, total, avg); } dev.disconnect(); Ok(()) } ``` -------------------------------- ### Send Tracked Commands with Timeout Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Sends commands to the device that expect a response and implements a timeout mechanism. This allows for graceful handling of commands that might not receive an acknowledgment within a specified period. It's used for operations like setting or querying the device's serial number. ```rust use makcu_rs::Device; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("/dev/ttyUSB0", 115200, Duration::from_millis(100)); dev.connect()?; // Send serial command and wait for response (1 second timeout) match dev.set_serial("ABC123") { Ok(response) => println!("Device responded: {}", response), Err(e) => eprintln!("Command failed: {}", e), } // Empty string to query current serial match dev.set_serial("") { Ok(serial) => println!("Current device serial: {}", serial), Err(e) => eprintln!("Query failed: {}", e), } dev.disconnect(); Ok(()) } ``` -------------------------------- ### Mouse Wheel Scrolling (Sync) Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Controls the mouse wheel scrolling. Positive values scroll up, and negative values scroll down. Supports large scroll distances. ```rust use makcu_rs::Device; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("/dev/ttyUSB0", 115200, Duration::from_millis(100)); dev.connect()?; // Scroll up (positive values) dev.wheel(3)?; // Scroll down (negative values) dev.wheel(-5)?; // Large scroll distance dev.wheel(-120)?; dev.disconnect(); Ok(()) } ``` -------------------------------- ### Lock Mouse Axes and Buttons Source: https://context7.com/whatzwastaken/makcu-rs/llms.txt Provides functionality to lock specific mouse axes (X and Y) and buttons (Left, Right, Middle, Side1, Side2) to prevent hardware input from affecting them. This is useful for isolating input or preventing accidental actions. Controls can be unlocked by setting the corresponding lock function to `false`. ```rust use makcu_rs::Device; use std::time::Duration; fn main() -> anyhow::Result<()> { let dev = Device::new("COM3", 115200, Duration::from_millis(100)); dev.connect()?; // Lock horizontal mouse movement dev.lock_mouse_x(true)?; // Lock vertical mouse movement dev.lock_mouse_y(true)?; // Lock specific buttons dev.lock_left(true)?; dev.lock_right(true)?; dev.lock_middle(true)?; dev.lock_side1(true)?; dev.lock_side2(true)?; println!("All controls locked"); std::thread::sleep(Duration::from_secs(5)); // Unlock all controls dev.lock_mouse_x(false)?; dev.lock_mouse_y(false)?; dev.lock_left(false)?; dev.lock_right(false)?; dev.lock_middle(false)?; println!("Controls unlocked"); dev.disconnect(); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.