rust-patlite-beacon 0.1.1

A Rust library and CLI tool for controlling USB PATLITE beacon devices
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use anyhow::{anyhow, Result};
use rusb::{Device, DeviceHandle, GlobalContext};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use thiserror::Error;
use tokio::time::sleep;

const VENDOR_ID: u16 = 0x191A;
const DEVICE_ID: u16 = 0x6001;
const COMMAND_VERSION: u8 = 0x0;
const COMMAND_ID_CONTROL: u8 = 0x0;
const COMMAND_ID_SETTING: u8 = 0x1;
const COMMAND_ID_GETSTATE: u8 = 0x80;
const ENDPOINT_ADDRESS: u8 = 0x01;
const ENDPOINT_ADDRESS_GET: u8 = 0x81;
const SEND_TIMEOUT: Duration = Duration::from_millis(1000);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum LedColor {
    Off = 0,
    Red = 1,
    Green = 2,
    Yellow = 3,
    Blue = 4,
    Purple = 5,
    LightBlue = 6,
    White = 7,
    Keep = 0xF,
}

impl LedColor {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "off" => Some(LedColor::Off),
            "red" => Some(LedColor::Red),
            "green" => Some(LedColor::Green),
            "yellow" => Some(LedColor::Yellow),
            "blue" => Some(LedColor::Blue),
            "purple" => Some(LedColor::Purple),
            "lightblue" | "light-blue" | "skyblue" | "sky-blue" => Some(LedColor::LightBlue),
            "white" => Some(LedColor::White),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum LedPattern {
    Off = 0x0,
    On = 0x1,
    Pattern1 = 0x2,
    Pattern2 = 0x3,
    Pattern3 = 0x4,
    Pattern4 = 0x5,
    Pattern5 = 0x6,
    Pattern6 = 0x7,
    Keep = 0xF,
}

impl LedPattern {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "off" => Some(LedPattern::Off),
            "on" | "solid" => Some(LedPattern::On),
            "pattern1" | "1" => Some(LedPattern::Pattern1),
            "pattern2" | "2" => Some(LedPattern::Pattern2),
            "pattern3" | "3" => Some(LedPattern::Pattern3),
            "pattern4" | "4" => Some(LedPattern::Pattern4),
            "pattern5" | "5" => Some(LedPattern::Pattern5),
            "pattern6" | "6" => Some(LedPattern::Pattern6),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum BuzzerPattern {
    Off = 0x0,
    On = 0x1,
    Sweep = 0x2,
    Intermittent = 0x3,
    WeakAttention = 0x4,
    StrongAttention = 0x5,
    ShiningStar = 0x6,
    LondonBridge = 0x7,
    Keep = 0xF,
}

impl BuzzerPattern {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "off" => Some(BuzzerPattern::Off),
            "on" | "continuous" => Some(BuzzerPattern::On),
            "sweep" => Some(BuzzerPattern::Sweep),
            "intermittent" => Some(BuzzerPattern::Intermittent),
            "weak" | "weak-attention" => Some(BuzzerPattern::WeakAttention),
            "strong" | "strong-attention" => Some(BuzzerPattern::StrongAttention),
            "shining-star" => Some(BuzzerPattern::ShiningStar),
            "london-bridge" => Some(BuzzerPattern::LondonBridge),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuzzerCount(u8);

impl BuzzerCount {
    pub const CONTINUOUS: Self = Self(0x0);
    pub const KEEP: Self = Self(0xF);

    pub fn times(count: u8) -> Option<Self> {
        if count >= 1 && count <= 14 {
            Some(Self(count))
        } else {
            None
        }
    }

    pub fn value(&self) -> u8 {
        self.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuzzerVolume(u8);

impl BuzzerVolume {
    pub const OFF: Self = Self(0x0);
    pub const MAX: Self = Self(0xA);
    pub const KEEP: Self = Self(0xF);

    pub fn level(level: u8) -> Option<Self> {
        if level <= 0xA {
            Some(Self(level))
        } else {
            None
        }
    }

    pub fn value(&self) -> u8 {
        self.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Setting {
    Off = 0x0,
    On = 0x1,
}

#[derive(Debug, Error)]
pub enum BeaconError {
    #[error("USB error: {0}")]
    Usb(#[from] rusb::Error),
    
    #[error("Device not found")]
    DeviceNotFound,
    
    #[error("Failed to send command")]
    SendFailed,
    
    #[error("Invalid parameter")]
    InvalidParameter,
}

pub struct Beacon {
    handle: DeviceHandle<GlobalContext>,
    _device: Device<GlobalContext>,
}

impl Beacon {
    pub fn open() -> Result<Self> {
        let devices = rusb::devices()?;
        
        for device in devices.iter() {
            let device_desc = device.device_descriptor()?;
            
            if device_desc.vendor_id() == VENDOR_ID && device_desc.product_id() == DEVICE_ID {
                let handle = device.open()?;
                
                // Detach kernel driver if necessary
                if let Ok(active) = handle.kernel_driver_active(0) {
                    if active {
                        handle.detach_kernel_driver(0)?;
                    }
                }
                
                // Set configuration
                handle.set_active_configuration(1)?;
                
                // Claim interface
                handle.claim_interface(0)?;
                
                return Ok(Beacon {
                    handle,
                    _device: device,
                });
            }
        }
        
        Err(anyhow!("Device not found"))
    }

    pub fn scan() -> Result<Vec<(u8, u8, u16, u16)>> {
        let devices = rusb::devices()?;
        let mut found = Vec::new();
        
        for device in devices.iter() {
            let device_desc = device.device_descriptor()?;
            
            if device_desc.vendor_id() == VENDOR_ID && device_desc.product_id() == DEVICE_ID {
                found.push((
                    device.bus_number(),
                    device.address(),
                    device_desc.vendor_id(),
                    device_desc.product_id(),
                ));
            }
        }
        
        Ok(found)
    }

    fn send_command(&self, data: &[u8]) -> Result<()> {
        let bytes_written = self.handle.write_bulk(ENDPOINT_ADDRESS, data, SEND_TIMEOUT)?;
        
        if bytes_written != data.len() {
            return Err(anyhow!("Failed to send complete command"));
        }
        
        Ok(())
    }

    pub fn set_light(&self, color: LedColor, pattern: LedPattern) -> Result<()> {
        let buzzer_control = (BuzzerCount::KEEP.value() << 4) | BuzzerPattern::Keep as u8;
        let led_control = ((color as u8) << 4) | (pattern as u8);
        
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_CONTROL,
            buzzer_control,
            BuzzerVolume::KEEP.value(),
            led_control,
            0, 0, 0,
        ];
        
        self.send_command(&data)
    }

    pub fn set_buzzer(&self, pattern: BuzzerPattern, count: BuzzerCount) -> Result<()> {
        let buzzer_control = (count.value() << 4) | (pattern as u8);
        let led_control = ((LedColor::Keep as u8) << 4) | (LedPattern::Keep as u8);
        
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_CONTROL,
            buzzer_control,
            BuzzerVolume::KEEP.value(),
            led_control,
            0, 0, 0,
        ];
        
        self.send_command(&data)
    }

    pub fn set_volume(&self, volume: BuzzerVolume) -> Result<()> {
        let buzzer_control = (BuzzerCount::KEEP.value() << 4) | (BuzzerPattern::Keep as u8);
        let led_control = ((LedColor::Keep as u8) << 4) | (LedPattern::Keep as u8);
        
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_CONTROL,
            buzzer_control,
            volume.value(),
            led_control,
            0, 0, 0,
        ];
        
        self.send_command(&data)
    }

    pub fn set_buzzer_ex(&self, pattern: BuzzerPattern, count: BuzzerCount, volume: BuzzerVolume) -> Result<()> {
        let buzzer_control = (count.value() << 4) | (pattern as u8);
        let led_control = ((LedColor::Keep as u8) << 4) | (LedPattern::Keep as u8);
        
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_CONTROL,
            buzzer_control,
            volume.value(),
            led_control,
            0, 0, 0,
        ];
        
        self.send_command(&data)
    }

    pub fn set_setting(&self, setting: Setting) -> Result<()> {
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_SETTING,
            setting as u8,
            0, 0, 0, 0, 0,
        ];
        
        self.send_command(&data)
    }

    pub fn get_touch_sensor_state(&self) -> Result<bool> {
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_GETSTATE,
            0, 0, 0, 0, 0, 0,
        ];
        
        self.send_command(&data)?;
        
        let mut response = [0u8; 2];
        self.handle.read_bulk(ENDPOINT_ADDRESS_GET, &mut response, SEND_TIMEOUT)?;
        
        Ok((response[1] & 1) == 1)
    }

    pub fn reset(&self) -> Result<()> {
        let buzzer_control = (BuzzerCount::KEEP.value() << 4) | (BuzzerPattern::Off as u8);
        let led_control = ((LedColor::Off as u8) << 4) | (LedPattern::Off as u8);
        
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_CONTROL,
            buzzer_control,
            BuzzerVolume::KEEP.value(),
            led_control,
            0, 0, 0,
        ];
        
        self.send_command(&data)
    }

    pub fn wait_for_touch_sync(&self) -> Result<()> {
        let initial_state = self.get_touch_sensor_state()?;
        
        if initial_state {
            while self.get_touch_sensor_state()? {
                std::thread::sleep(Duration::from_millis(50));
            }
        }
        
        while !self.get_touch_sensor_state()? {
            std::thread::sleep(Duration::from_millis(50));
        }
        
        Ok(())
    }

    pub fn wait_for_touch_with_callback_sync<F>(&self, mut callback: F) -> Result<()>
    where
        F: FnMut(bool),
    {
        let initial_state = self.get_touch_sensor_state()?;
        let mut last_state = initial_state;
        callback(last_state);
        
        if initial_state {
            while self.get_touch_sensor_state()? {
                std::thread::sleep(Duration::from_millis(50));
            }
            last_state = false;
            callback(last_state);
        }
        
        while !self.get_touch_sensor_state()? {
            std::thread::sleep(Duration::from_millis(50));
        }
        callback(true);
        
        Ok(())
    }

    pub fn poll_touch_sensor_sync<F>(&self, mut callback: F, poll_interval: Duration) -> Result<()>
    where
        F: FnMut(bool) -> bool,
    {
        loop {
            let state = self.get_touch_sensor_state()?;
            if !callback(state) {
                break;
            }
            std::thread::sleep(poll_interval);
        }
        Ok(())
    }

}

pub struct AsyncBeacon {
    beacon: Arc<Mutex<Beacon>>,
}

impl AsyncBeacon {
    pub fn new(beacon: Beacon) -> Self {
        Self {
            beacon: Arc::new(Mutex::new(beacon)),
        }
    }

    pub async fn wait_for_touch(&self) -> Result<()> {
        let initial_state = {
            let beacon = self.beacon.lock().unwrap();
            beacon.get_touch_sensor_state()?
        };
        
        if initial_state {
            loop {
                let state = {
                    let beacon = self.beacon.lock().unwrap();
                    beacon.get_touch_sensor_state()?
                };
                if !state {
                    break;
                }
                sleep(Duration::from_millis(50)).await;
            }
        }
        
        loop {
            let state = {
                let beacon = self.beacon.lock().unwrap();
                beacon.get_touch_sensor_state()?
            };
            if state {
                break;
            }
            sleep(Duration::from_millis(50)).await;
        }
        
        Ok(())
    }

    pub async fn wait_for_touch_with_callback<F>(&self, mut callback: F) -> Result<()>
    where
        F: FnMut(bool),
    {
        let initial_state = {
            let beacon = self.beacon.lock().unwrap();
            beacon.get_touch_sensor_state()?
        };
        let mut last_state = initial_state;
        callback(last_state);
        
        if initial_state {
            loop {
                let state = {
                    let beacon = self.beacon.lock().unwrap();
                    beacon.get_touch_sensor_state()?
                };
                if !state {
                    last_state = false;
                    callback(last_state);
                    break;
                }
                sleep(Duration::from_millis(50)).await;
            }
        }
        
        loop {
            let state = {
                let beacon = self.beacon.lock().unwrap();
                beacon.get_touch_sensor_state()?
            };
            if state {
                callback(true);
                break;
            }
            sleep(Duration::from_millis(50)).await;
        }
        
        Ok(())
    }

    pub async fn poll_touch_sensor<F>(&self, mut callback: F, poll_interval: Duration) -> Result<()>
    where
        F: FnMut(bool) -> bool,
    {
        loop {
            let state = {
                let beacon = self.beacon.lock().unwrap();
                beacon.get_touch_sensor_state()?
            };
            if !callback(state) {
                break;
            }
            sleep(poll_interval).await;
        }
        Ok(())
    }
}

impl Drop for Beacon {
    fn drop(&mut self) {
        // Release the interface when dropping
        let _ = self.handle.release_interface(0);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_led_color_from_str() {
        assert_eq!(LedColor::from_str("off"), Some(LedColor::Off));
        assert_eq!(LedColor::from_str("red"), Some(LedColor::Red));
        assert_eq!(LedColor::from_str("RED"), Some(LedColor::Red));
        assert_eq!(LedColor::from_str("green"), Some(LedColor::Green));
        assert_eq!(LedColor::from_str("yellow"), Some(LedColor::Yellow));
        assert_eq!(LedColor::from_str("blue"), Some(LedColor::Blue));
        assert_eq!(LedColor::from_str("purple"), Some(LedColor::Purple));
        assert_eq!(LedColor::from_str("lightblue"), Some(LedColor::LightBlue));
        assert_eq!(LedColor::from_str("light-blue"), Some(LedColor::LightBlue));
        assert_eq!(LedColor::from_str("skyblue"), Some(LedColor::LightBlue));
        assert_eq!(LedColor::from_str("sky-blue"), Some(LedColor::LightBlue));
        assert_eq!(LedColor::from_str("white"), Some(LedColor::White));
        assert_eq!(LedColor::from_str("invalid"), None);
    }

    #[test]
    fn test_led_color_values() {
        assert_eq!(LedColor::Off as u8, 0);
        assert_eq!(LedColor::Red as u8, 1);
        assert_eq!(LedColor::Green as u8, 2);
        assert_eq!(LedColor::Yellow as u8, 3);
        assert_eq!(LedColor::Blue as u8, 4);
        assert_eq!(LedColor::Purple as u8, 5);
        assert_eq!(LedColor::LightBlue as u8, 6);
        assert_eq!(LedColor::White as u8, 7);
        assert_eq!(LedColor::Keep as u8, 0xF);
    }

    #[test]
    fn test_led_pattern_from_str() {
        assert_eq!(LedPattern::from_str("off"), Some(LedPattern::Off));
        assert_eq!(LedPattern::from_str("on"), Some(LedPattern::On));
        assert_eq!(LedPattern::from_str("solid"), Some(LedPattern::On));
        assert_eq!(LedPattern::from_str("pattern1"), Some(LedPattern::Pattern1));
        assert_eq!(LedPattern::from_str("1"), Some(LedPattern::Pattern1));
        assert_eq!(LedPattern::from_str("pattern2"), Some(LedPattern::Pattern2));
        assert_eq!(LedPattern::from_str("2"), Some(LedPattern::Pattern2));
        assert_eq!(LedPattern::from_str("pattern3"), Some(LedPattern::Pattern3));
        assert_eq!(LedPattern::from_str("3"), Some(LedPattern::Pattern3));
        assert_eq!(LedPattern::from_str("pattern4"), Some(LedPattern::Pattern4));
        assert_eq!(LedPattern::from_str("4"), Some(LedPattern::Pattern4));
        assert_eq!(LedPattern::from_str("pattern5"), Some(LedPattern::Pattern5));
        assert_eq!(LedPattern::from_str("5"), Some(LedPattern::Pattern5));
        assert_eq!(LedPattern::from_str("pattern6"), Some(LedPattern::Pattern6));
        assert_eq!(LedPattern::from_str("6"), Some(LedPattern::Pattern6));
        assert_eq!(LedPattern::from_str("PATTERN1"), Some(LedPattern::Pattern1));
        assert_eq!(LedPattern::from_str("invalid"), None);
    }

    #[test]
    fn test_led_pattern_values() {
        assert_eq!(LedPattern::Off as u8, 0x0);
        assert_eq!(LedPattern::On as u8, 0x1);
        assert_eq!(LedPattern::Pattern1 as u8, 0x2);
        assert_eq!(LedPattern::Pattern2 as u8, 0x3);
        assert_eq!(LedPattern::Pattern3 as u8, 0x4);
        assert_eq!(LedPattern::Pattern4 as u8, 0x5);
        assert_eq!(LedPattern::Pattern5 as u8, 0x6);
        assert_eq!(LedPattern::Pattern6 as u8, 0x7);
        assert_eq!(LedPattern::Keep as u8, 0xF);
    }

    #[test]
    fn test_buzzer_pattern_from_str() {
        assert_eq!(BuzzerPattern::from_str("off"), Some(BuzzerPattern::Off));
        assert_eq!(BuzzerPattern::from_str("on"), Some(BuzzerPattern::On));
        assert_eq!(BuzzerPattern::from_str("continuous"), Some(BuzzerPattern::On));
        assert_eq!(BuzzerPattern::from_str("sweep"), Some(BuzzerPattern::Sweep));
        assert_eq!(BuzzerPattern::from_str("intermittent"), Some(BuzzerPattern::Intermittent));
        assert_eq!(BuzzerPattern::from_str("weak"), Some(BuzzerPattern::WeakAttention));
        assert_eq!(BuzzerPattern::from_str("weak-attention"), Some(BuzzerPattern::WeakAttention));
        assert_eq!(BuzzerPattern::from_str("strong"), Some(BuzzerPattern::StrongAttention));
        assert_eq!(BuzzerPattern::from_str("strong-attention"), Some(BuzzerPattern::StrongAttention));
        assert_eq!(BuzzerPattern::from_str("shining-star"), Some(BuzzerPattern::ShiningStar));
        assert_eq!(BuzzerPattern::from_str("london-bridge"), Some(BuzzerPattern::LondonBridge));
        assert_eq!(BuzzerPattern::from_str("SWEEP"), Some(BuzzerPattern::Sweep));
        assert_eq!(BuzzerPattern::from_str("invalid"), None);
    }

    #[test]
    fn test_buzzer_pattern_values() {
        assert_eq!(BuzzerPattern::Off as u8, 0x0);
        assert_eq!(BuzzerPattern::On as u8, 0x1);
        assert_eq!(BuzzerPattern::Sweep as u8, 0x2);
        assert_eq!(BuzzerPattern::Intermittent as u8, 0x3);
        assert_eq!(BuzzerPattern::WeakAttention as u8, 0x4);
        assert_eq!(BuzzerPattern::StrongAttention as u8, 0x5);
        assert_eq!(BuzzerPattern::ShiningStar as u8, 0x6);
        assert_eq!(BuzzerPattern::LondonBridge as u8, 0x7);
        assert_eq!(BuzzerPattern::Keep as u8, 0xF);
    }

    #[test]
    fn test_buzzer_count_times() {
        assert_eq!(BuzzerCount::times(0), None);
        assert_eq!(BuzzerCount::times(1), Some(BuzzerCount(1)));
        assert_eq!(BuzzerCount::times(7), Some(BuzzerCount(7)));
        assert_eq!(BuzzerCount::times(14), Some(BuzzerCount(14)));
        assert_eq!(BuzzerCount::times(15), None);
        assert_eq!(BuzzerCount::times(100), None);
    }

    #[test]
    fn test_buzzer_count_constants() {
        assert_eq!(BuzzerCount::CONTINUOUS.value(), 0x0);
        assert_eq!(BuzzerCount::KEEP.value(), 0xF);
    }

    #[test]
    fn test_buzzer_count_value() {
        let count = BuzzerCount::times(5).unwrap();
        assert_eq!(count.value(), 5);
    }

    #[test]
    fn test_buzzer_volume_level() {
        assert_eq!(BuzzerVolume::level(0), Some(BuzzerVolume(0)));
        assert_eq!(BuzzerVolume::level(5), Some(BuzzerVolume(5)));
        assert_eq!(BuzzerVolume::level(10), Some(BuzzerVolume(10)));
        assert_eq!(BuzzerVolume::level(11), None);
        assert_eq!(BuzzerVolume::level(100), None);
    }

    #[test]
    fn test_buzzer_volume_constants() {
        assert_eq!(BuzzerVolume::OFF.value(), 0x0);
        assert_eq!(BuzzerVolume::MAX.value(), 0xA);
        assert_eq!(BuzzerVolume::KEEP.value(), 0xF);
    }

    #[test]
    fn test_buzzer_volume_value() {
        let volume = BuzzerVolume::level(7).unwrap();
        assert_eq!(volume.value(), 7);
    }

    #[test]
    fn test_setting_values() {
        assert_eq!(Setting::Off as u8, 0x0);
        assert_eq!(Setting::On as u8, 0x1);
    }

    #[test]
    fn test_command_byte_generation_led() {
        let color = LedColor::Red as u8;
        let pattern = LedPattern::Pattern1 as u8;
        let led_control = (color << 4) | pattern;
        assert_eq!(led_control, 0x12);

        let color = LedColor::Green as u8;
        let pattern = LedPattern::On as u8;
        let led_control = (color << 4) | pattern;
        assert_eq!(led_control, 0x21);

        let color = LedColor::Keep as u8;
        let pattern = LedPattern::Keep as u8;
        let led_control = (color << 4) | pattern;
        assert_eq!(led_control, 0xFF);
    }

    #[test]
    fn test_command_byte_generation_buzzer() {
        let count = BuzzerCount::times(3).unwrap().value();
        let pattern = BuzzerPattern::Sweep as u8;
        let buzzer_control = (count << 4) | pattern;
        assert_eq!(buzzer_control, 0x32);

        let count = BuzzerCount::CONTINUOUS.value();
        let pattern = BuzzerPattern::On as u8;
        let buzzer_control = (count << 4) | pattern;
        assert_eq!(buzzer_control, 0x01);

        let count = BuzzerCount::KEEP.value();
        let pattern = BuzzerPattern::Keep as u8;
        let buzzer_control = (count << 4) | pattern;
        assert_eq!(buzzer_control, 0xFF);
    }

    #[test]
    fn test_full_command_construction() {
        let buzzer_count = BuzzerCount::times(2).unwrap().value();
        let buzzer_pattern = BuzzerPattern::Intermittent as u8;
        let buzzer_control = (buzzer_count << 4) | buzzer_pattern;
        
        let led_color = LedColor::Blue as u8;
        let led_pattern = LedPattern::Pattern3 as u8;
        let led_control = (led_color << 4) | led_pattern;
        
        let volume = BuzzerVolume::level(5).unwrap().value();
        
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_CONTROL,
            buzzer_control,
            volume,
            led_control,
            0, 0, 0,
        ];
        
        assert_eq!(data[0], 0x0);
        assert_eq!(data[1], 0x0);
        assert_eq!(data[2], 0x23);
        assert_eq!(data[3], 0x5);
        assert_eq!(data[4], 0x44); 
    }

    #[test]
    fn test_touch_sensor_command_construction() {
        let data = [
            COMMAND_VERSION,
            COMMAND_ID_GETSTATE,
            0, 0, 0, 0, 0, 0,
        ];
        
        assert_eq!(data[0], 0x0);
        assert_eq!(data[1], 0x80);
        assert_eq!(data.len(), 8);
    }

    #[test]
    fn test_async_beacon_creation() {
        // This test verifies that AsyncBeacon can be created
        // Real device testing would require hardware
        
        // We can't create a real Beacon without hardware, but we can
        // verify the type system works
        fn _type_check() {
            // This function is never called, just type-checked
            fn create_async_beacon(beacon: Beacon) -> AsyncBeacon {
                AsyncBeacon::new(beacon)
            }
        }
    }

    #[test]
    fn test_poll_interval_duration() {
        use std::time::Duration;
        
        // Test that Duration creation works correctly for polling
        let poll_interval = Duration::from_millis(50);
        assert_eq!(poll_interval.as_millis(), 50);
        
        let poll_interval = Duration::from_millis(100);
        assert_eq!(poll_interval.as_millis(), 100);
    }
}