ohea-lock 0.1.0

Rust library for controlling Ohea Lock BLE smart locks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Interactive hardware debugging tool for Ohea Lock.
//!
//! This example provides an interactive CLI for debugging and testing
//! Ohea Lock devices. It handles device discovery, pairing, and all
//! lock operations.
//!
//! # Usage
//!
//! ```bash
//! cargo run --example debug --features btleplug-support
//! ```

use btleplug::api::{Central, Manager as _, Peripheral as _, ScanFilter};
use btleplug::platform::{Adapter, Manager, Peripheral};
use ohea_lock::{BtleplugTransport, LockState, OheaLock, Result};
use std::io::{self, BufRead, Write};
use std::time::Duration;

// =============================================================================
// Configuration
// =============================================================================

const DEVICE_NAME: &str = "Ohea Lock";
const SCAN_TIMEOUT: Duration = Duration::from_secs(5);

// =============================================================================
// Main Entry Point
// =============================================================================

#[tokio::main]
async fn main() -> Result<()> {
    println!("\n╔══════════════════════════════════════╗");
    println!("║     Ohea Lock Debug Tool v0.1.0      ║");
    println!("╚══════════════════════════════════════╝\n");

    let adapter = get_adapter().await?;
    let peripheral = discover_and_select(&adapter).await?;
    let lock = connect_to_device(peripheral).await?;

    run_interactive_session(lock).await
}

// =============================================================================
// Bluetooth Adapter
// =============================================================================

async fn get_adapter() -> Result<Adapter> {
    print!("Initializing Bluetooth adapter... ");
    io::stdout().flush().ok();

    let manager = Manager::new().await?;
    let adapter = manager
        .adapters()
        .await?
        .into_iter()
        .next()
        .ok_or_else(|| ohea_lock::Error::Transport("No Bluetooth adapter found".into()))?;

    println!("✓");
    Ok(adapter)
}

// =============================================================================
// Device Discovery
// =============================================================================

async fn discover_and_select(adapter: &Adapter) -> Result<Peripheral> {
    println!("Scanning for {} devices ({:?})...", DEVICE_NAME, SCAN_TIMEOUT);

    adapter.start_scan(ScanFilter::default()).await?;
    tokio::time::sleep(SCAN_TIMEOUT).await;
    adapter.stop_scan().await?;

    let devices = find_ohea_locks(adapter).await?;

    if devices.is_empty() {
        println!("\n⚠ No {} found in scan results.", DEVICE_NAME);
        println!("  Ensure the device is powered on and in range.");
        println!("  If unpaired, the device may need to be in pairing mode.\n");

        if prompt_yes_no("Retry scan?")? {
            return Box::pin(discover_and_select(adapter)).await;
        }
        return Err(ohea_lock::Error::Transport("No device found".into()));
    }

    println!("\nFound {} device(s):\n", devices.len());

    for (i, device) in devices.iter().enumerate() {
        let props = device.properties().await?.unwrap_or_default();
        let name = props.local_name.as_deref().unwrap_or("Unknown");
        let addr = props.address;
        let rssi = props.rssi.map(|r| format!("{r} dBm")).unwrap_or_default();
        println!("  [{}] {} ({}) {}", i + 1, name, addr, rssi);
    }
    println!();

    let selection = if devices.len() == 1 {
        if prompt_yes_no(&format!("Connect to {}?", DEVICE_NAME))? {
            0
        } else {
            return Err(ohea_lock::Error::Transport("User cancelled".into()));
        }
    } else {
        prompt_number("Select device", 1, devices.len())? - 1
    };

    Ok(devices.into_iter().nth(selection).unwrap())
}

async fn find_ohea_locks(adapter: &Adapter) -> Result<Vec<Peripheral>> {
    let peripherals = adapter.peripherals().await?;
    let mut locks = Vec::new();

    for peripheral in peripherals {
        if let Some(props) = peripheral.properties().await? {
            if props.local_name.as_deref() == Some(DEVICE_NAME) {
                locks.push(peripheral);
            }
        }
    }

    Ok(locks)
}

// =============================================================================
// Service & Characteristic Discovery Display
// =============================================================================

async fn display_services_and_characteristics(peripheral: &Peripheral) -> Result<()> {
    use btleplug::api::CharPropFlags;

    let services = peripheral.services();

    println!("┌─────────────────────────────────────────────────────────────┐");
    println!("│ Discovered Services & Characteristics                       │");
    println!("└─────────────────────────────────────────────────────────────┘");

    for service in services {
        println!("\n📦 Service: {}", service.uuid);
        println!("   Primary: {}", if service.primary { "Yes" } else { "No" });

        if service.characteristics.is_empty() {
            println!("   └─ (no characteristics)");
        } else {
            for (idx, characteristic) in service.characteristics.iter().enumerate() {
                let is_last = idx == service.characteristics.len() - 1;
                let prefix = if is_last { "└─" } else { "├─" };

                println!("   {} 🔧 {}", prefix, characteristic.uuid);

                let props = characteristic.properties;
                let mut properties = Vec::new();
                if props.contains(CharPropFlags::READ) {
                    properties.push("Read");
                }
                if props.contains(CharPropFlags::WRITE) {
                    properties.push("Write");
                }
                if props.contains(CharPropFlags::WRITE_WITHOUT_RESPONSE) {
                    properties.push("WriteNoResp");
                }
                if props.contains(CharPropFlags::NOTIFY) {
                    properties.push("Notify");
                }
                if props.contains(CharPropFlags::INDICATE) {
                    properties.push("Indicate");
                }
                if props.contains(CharPropFlags::BROADCAST) {
                    properties.push("Broadcast");
                }

                if !properties.is_empty() {
                    let indent = if is_last { "      " } else { "   │  " };
                    println!("{}Properties: {}", indent, properties.join(", "));
                }

                // Display descriptors if any
                if !characteristic.descriptors.is_empty() {
                    let indent = if is_last { "      " } else { "   │  " };
                    println!("{}Descriptors: {} found", indent, characteristic.descriptors.len());
                    for descriptor in &characteristic.descriptors {
                        println!("{}  • {}", indent, descriptor.uuid);
                    }
                }
            }
        }
    }

    println!("\n─────────────────────────────────────────────────────────────\n");
    Ok(())
}

// =============================================================================
// Connection & Pairing
// =============================================================================

async fn connect_to_device(peripheral: Peripheral) -> Result<OheaLock<BtleplugTransport>> {
    let is_connected = peripheral.is_connected().await?;

    if is_connected {
        println!("Device already connected, discovering services...");
    } else {
        print!("Connecting... ");
        io::stdout().flush().ok();
        peripheral.connect().await?;
        println!("✓");

        print!("Discovering services (may trigger pairing)... ");
        io::stdout().flush().ok();
    }

    peripheral.discover_services().await?;
    println!("✓\n");

    // Display discovered services and characteristics
    display_services_and_characteristics(&peripheral).await?;

    let transport = BtleplugTransport::new(peripheral).await?;
    let mut lock = OheaLock::new(transport);

    print!("Initializing session... ");
    io::stdout().flush().ok();
    lock.initialize().await?;
    println!("✓\n");

    // Display device info
    display_device_info(&lock).await?;

    Ok(lock)
}

async fn display_device_info(lock: &OheaLock<BtleplugTransport>) -> Result<()> {
    let info = lock.get_device_info().await?;

    println!("┌─────────────────────────────────────┐");
    println!("│ Device Information                  │");
    println!("├─────────────────────────────────────┤");
    println!("│ Name:     {:<25} │", info.name);
    println!("│ Firmware: {:<25} │", info.firmware_version);
    println!("│ Battery:  {:<25} │", format!("{}%", info.battery_level));
    println!("└─────────────────────────────────────┘");
    println!();

    Ok(())
}

// =============================================================================
// Interactive Session
// =============================================================================

async fn run_interactive_session(lock: OheaLock<BtleplugTransport>) -> Result<()> {
    loop {
        let state = lock.get_lock_state().await?;
        let state_icon = match state {
            LockState::Locked => "🔒",
            LockState::Unlocked => "🔓",
        };

        println!("\nCurrent state: {} {:?}", state_icon, state);
        println!();
        println!("Commands:");
        println!("  [1] Lock");
        println!("  [2] Unlock");
        println!("  [3] Toggle");
        println!("  [4] Refresh state");
        println!("  [5] Show device info");
        println!("  [6] Read all characteristics");
        println!("  [q] Quit");
        println!();

        let input = prompt_string("Enter command")?;

        match input.trim().to_lowercase().as_str() {
            "1" | "lock" => {
                print!("Locking... ");
                io::stdout().flush().ok();
                lock.lock().await?;
                tokio::time::sleep(Duration::from_millis(300)).await;
                println!("✓");
            }
            "2" | "unlock" => {
                print!("Unlocking... ");
                io::stdout().flush().ok();
                lock.unlock().await?;
                tokio::time::sleep(Duration::from_millis(300)).await;
                println!("✓");
            }
            "3" | "toggle" => {
                let current = lock.get_lock_state().await?;
                let action = if current.is_locked() { "Unlocking" } else { "Locking" };
                print!("{}... ", action);
                io::stdout().flush().ok();

                if current.is_locked() {
                    lock.unlock().await?;
                } else {
                    lock.lock().await?;
                }
                tokio::time::sleep(Duration::from_millis(300)).await;
                println!("✓");
            }
            "4" | "refresh" | "r" => {
                println!("Refreshing...");
            }
            "5" | "info" | "i" => {
                display_device_info(&lock).await?;
            }
            "6" | "read" | "all" => {
                read_all_characteristics(&lock).await?;
            }
            "q" | "quit" | "exit" => {
                println!("Disconnecting...");
                break;
            }
            "" => continue,
            _ => {
                println!("Unknown command: {}", input.trim());
            }
        }
    }

    println!("Goodbye!\n");
    Ok(())
}

async fn read_all_characteristics(lock: &OheaLock<BtleplugTransport>) -> Result<()> {
    println!("\n┌─────────────────────────────────────┐");
    println!("│ All Readable Characteristics        │");
    println!("├─────────────────────────────────────┤");

    // Lock state
    match lock.get_lock_state().await {
        Ok(state) => println!("│ Lock State:    {:?}{} │", state, " ".repeat(14 - format!("{:?}", state).len())),
        Err(e) => println!("│ Lock State:    Error: {:<12} │", e.to_string().chars().take(12).collect::<String>()),
    }

    // Lock position
    match lock.get_lock_position().await {
        Ok(pos) => println!("│ Lock Position: {:#04x}{} │", pos, " ".repeat(17)),
        Err(e) => println!("│ Lock Position: Error: {:<12} │", e.to_string().chars().take(12).collect::<String>()),
    }

    // Battery
    match lock.get_battery_level().await {
        Ok(level) => println!("│ Battery:       {}%{} │", level, " ".repeat(if level < 10 { 19 } else if level < 100 { 18 } else { 17 })),
        Err(e) => println!("│ Battery:       Error: {:<12} │", e.to_string().chars().take(12).collect::<String>()),
    }

    // Firmware
    match lock.get_firmware_version().await {
        Ok(ver) => println!("│ Firmware:      {:<21} │", ver),
        Err(e) => println!("│ Firmware:      Error: {:<12} │", e.to_string().chars().take(12).collect::<String>()),
    }

    // Device name
    match lock.get_device_name().await {
        Ok(name) => println!("│ Device Name:   {:<21} │", name),
        Err(e) => println!("│ Device Name:   Error: {:<12} │", e.to_string().chars().take(12).collect::<String>()),
    }

    println!("└─────────────────────────────────────┘");
    Ok(())
}

// =============================================================================
// User Input Helpers
// =============================================================================

fn prompt_yes_no(question: &str) -> io::Result<bool> {
    print!("{} [y/N]: ", question);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().lock().read_line(&mut input)?;

    Ok(matches!(input.trim().to_lowercase().as_str(), "y" | "yes"))
}

fn prompt_number(prompt: &str, min: usize, max: usize) -> io::Result<usize> {
    loop {
        print!("{} [{}-{}]: ", prompt, min, max);
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().lock().read_line(&mut input)?;

        if let Ok(n) = input.trim().parse::<usize>() {
            if n >= min && n <= max {
                return Ok(n);
            }
        }
        println!("Please enter a number between {} and {}", min, max);
    }
}

fn prompt_string(prompt: &str) -> io::Result<String> {
    print!("{}: ", prompt);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().lock().read_line(&mut input)?;
    Ok(input)
}