status_test/
status_test.rs

1use std::io::{self, Write};
2use std::time::Duration;
3
4use tokio;
5
6use catprinter::ble::{connect, scan};
7
8/// Example: Query CatPrinter status and battery in a loop
9/// - Scans for BLE printers
10/// - Lets user select device
11/// - Queries status/battery 10 times
12#[tokio::main]
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    println!("Scanning for CatPrinter-compatible BLE devices for 3 seconds...");
15    let devices = scan(Duration::from_secs(3)).await?;
16    if devices.is_empty() {
17        println!(
18            "No devices found. Make sure your Bluetooth adapter is up and the printer is powered on and advertising."
19        );
20        return Ok(());
21    }
22
23    println!("Found devices:");
24    for (i, d) in devices.iter().enumerate() {
25        println!("  {}) id={} name={:?}", i + 1, d.id, d.name);
26    }
27
28    // Ask user to pick a device
29    let mut input = String::new();
30    let chosen = loop {
31        print!("Select device number to connect to (1-{}): ", devices.len());
32        io::stdout().flush()?;
33        input.clear();
34        io::stdin().read_line(&mut input)?;
35        if let Ok(n) = input.trim().parse::<usize>() {
36            if n >= 1 && n <= devices.len() {
37                break &devices[n - 1];
38            }
39        }
40        println!("Invalid selection.");
41    };
42
43    println!("Connecting to device id={} name={:?} ...", chosen.id, chosen.name);
44    let printer = match connect(&chosen.id, Duration::from_secs(10)).await {
45        Ok(p) => {
46            println!("Connected successfully.");
47            p
48        }
49        Err(e) => {
50            eprintln!("Failed to connect: {}", e);
51            return Ok(());
52        }
53    };
54
55    // Query status and battery 10 times, 1s apart
56    println!("Starting status/battery query loop (10 iterations, 1s apart)...");
57    for i in 0..10 {
58        println!("Query {}:", i + 1);
59        match printer.get_status(Duration::from_secs(10)).await {
60            Ok(s) => {
61                println!(
62                    "Status (0xA1) -> battery: {:?}, temperature: {:?}, state: {:?}",
63                    s.battery_percent, s.temperature, s.state
64                );
65            }
66            Err(e) => {
67                eprintln!("Failed to get status: {}", e);
68            }
69        }
70        match printer.get_battery(Duration::from_secs(10)).await {
71            Ok(b) => {
72                println!("Battery (0xAB) -> battery percent: {}", b);
73            }
74            Err(e) => {
75                eprintln!("Failed to get battery: {}", e);
76            }
77        }
78        tokio::time::sleep(Duration::from_secs(1)).await;
79    }
80    println!("Status/battery query loop finished.");
81    Ok(())
82}