bulbb 0.0.3

Bulbb is a library to manage backlight brightness.
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
/*
Copyright 2021 David Karrick

Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
<LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
option. This file may not be copied, modified, or distributed
except according to those terms.
*/
use std::{fmt, fs, path::Path};

use super::LEDS_DIR;
use crate::{
    error::Error,
    utils::{read_sys_led, SysBacklightInterface},
};

#[cfg(not(feature = "dbus"))]
use std::{fs::OpenOptions, io::prelude::*};

#[cfg(feature = "dbus")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "dbus")]
use zbus::Connection;

#[derive(Clone, Copy, Debug)]
pub struct LedFilterable<'a> {
    device_name: Option<&'a str>,
    color: Option<LedColor>,
    function: Option<LedFunction>,
}

impl<'a> LedFilterable<'a> {
    fn new() -> LedFilterable<'a> {
        LedFilterable {
            device_name: None,
            color: None,
            function: None,
        }
    }
    fn with_device_name(&'a mut self, device_name: &'a str) -> &'a mut LedFilterable {
        self.device_name = Some(device_name);
        self
    }
    fn with_color(&'a mut self, color: LedColor) -> &'a mut LedFilterable {
        self.color = Some(color);
        self
    }
    fn with_function(&'a mut self, function: LedFunction) -> &'a mut LedFilterable {
        self.function = Some(function);
        self
    }
    fn finish(&'a mut self) -> LedFilterable {
        *(self)
    }
    fn filter_by_device_name(&'a self, to_be_filtered: &str) -> bool {
        if let Some(device_name) = &self.device_name {
            to_be_filtered.contains(device_name)
        } else {
            false
        }
    }
    fn filter_by_color(&'a self, to_be_filtered: &str) -> bool {
        if let Some(color) = &self.color {
            to_be_filtered.contains(color.to_string().as_str())
        } else {
            false
        }
    }
    fn filter_by_function(&'a self, pre_filter: &str) -> bool {
        if let Some(function) = &self.function {
            pre_filter.contains(function.to_string().as_str())
        } else {
            false
        }
    }
    fn filter(&'a self, to_be_filtered: &str) -> bool {
        self.filter_by_device_name(to_be_filtered)
            || self.filter_by_color(to_be_filtered)
            || self.filter_by_function(to_be_filtered)
    }
}

fn multi_filter_led(filters: &[LedFilterable], to_be_filtered: &str) -> bool {
    let mut status = false;
    for f in filters {
        if f.filter(to_be_filtered) {
            status = true;
        }
    }
    status
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "dbus", derive(Serialize, Deserialize))]
/// LED device information
///
/// Devices are extracted from the `/sys/class/leds/` directory.
pub struct LedDevice {
    pub info: LedInfo,
    /** Set the brightness of the LED.

    Most LEDs don't have hardware brightness support, so will
    just be turned on for non-zero brightness settings.

    # Note

    > For multicolor LEDs, writing to this file will update all
    > LEDs within the group to a calculated percentage of what
    > each color LED intensity is set to.
    >
    > The percentage is calculated for each grouped LED via
    > the equation below::
    >
    > `led_brightness = brightness * multi_intensity/max_brightness`
    >
    > For additional details please refer to
    > [Multicolor LED handling under Linux](https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html).

    The value is between 0 and [max_brightness](struct.LedDevice.html#structfield.max_brightness).

    Writing 0 to this file clears active trigger.

    Writing non-zero to this file while trigger is active changes the
    top brightness trigger is going to use. */
    pub brightness: u32,
    /** Maximum brightness level for this LED, default is 255 (LED_FULL).

    If the LED does not support different brightness levels, this
    should be 1. */
    pub max_brightness: u32,
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "dbus", derive(Serialize, Deserialize))]
/// LED Information.
pub struct LedInfo {
    /// **LED Device Naming**
    ///
    /// Is currently of the form:
    ///
    /// > “devicename:color:function”
    pub device: String,
    /**
    This should refer to a unique identifier created by the kernel,
    like e.g. phyN for network devices or inputN for input devices,
    rather than to the hardware. The information related to the product
    and the bus to which given device is hooked is available in sysfs.
    Generally this section is expected mostly for LEDs that are somehow associated with other devices.*/
    pub device_name: Option<String>,
    /// One of LED_COLOR_ID_* definitions from the header
    /// [include/dt-bindings/leds/common.h](https://github.com/torvalds/linux/blob/master/include/dt-bindings/leds/common.h).
    pub color: Option<LedColor>,
    /// One of LED_FUNCTION_* definitions from the header
    /// [include/dt-bindings/leds/common.h](https://github.com/torvalds/linux/blob/master/include/dt-bindings/leds/common.h).
    pub function: Option<LedFunction>,
}

impl LedDevice {
    pub fn get_led_devices_with_filter(f: LedFilterable) -> Result<Vec<LedDevice>, Error> {
        if Path::new(LEDS_DIR).is_dir() {
            fs::read_dir(LEDS_DIR)
                .unwrap()
                .into_iter()
                .filter(|r| r.is_ok()) // Get rid of Err variants for Result<DirEntry>
                .map(|r| r.unwrap().file_name().into_string()) // This is safe, since we only have the Ok variants
                .filter(|r| r.is_ok())
                .map(|r| r.unwrap()) // This is safe, since we only have the Ok variants
                // Get rid of Err variants for Result<DirEntry>
                .filter(|e| {
                    f.filter_by_device_name(e) || f.filter_by_color(e) || f.filter_by_function(e)
                })
                .map(LedDevice::get_led_device)
                .collect::<Result<Vec<LedDevice>, Error>>()
        } else {
            Ok(Vec::new())
        }
    }

    pub fn get_led_devices_with_multi_filter(f: &[LedFilterable]) -> Result<Vec<LedDevice>, Error> {
        if Path::new(LEDS_DIR).is_dir() {
            fs::read_dir(LEDS_DIR)
                .unwrap()
                .into_iter()
                .filter(|r| r.is_ok()) // Get rid of Err variants for Result<DirEntry>
                .map(|r| r.unwrap().file_name().into_string()) // This is safe, since we only have the Ok variants
                .filter(|r| r.is_ok())
                .map(|r| r.unwrap()) // This is safe, since we only have the Ok variants
                // Get rid of Err variants for Result<DirEntry>
                .filter(|e| multi_filter_led(f, e))
                .map(LedDevice::get_led_device)
                .collect::<Result<Vec<LedDevice>, Error>>()
        } else {
            Ok(Vec::new())
        }
    }
    /// Get LED by device name.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let device_name = format!("asus::kbd_backlight");
    /// let led_device = LedDevice::get_led_device(device_name.clone()).unwrap();
    /// assert_eq!(led_device.get_device_name(), device_name);
    /// ```
    pub fn get_led_device(device: String) -> Result<LedDevice, Error> {
        if Path::new(format!("{}/{}", LEDS_DIR, &device).as_str()).is_dir() {
            let brightness =
                read_sys_led(&device, SysBacklightInterface::Brightness)?.parse::<u32>()?;
            let max_brightness =
                read_sys_led(&device, SysBacklightInterface::MaxBrightness)?.parse::<u32>()?;
            let info = LedInfo::from_string(device);

            Ok(LedDevice {
                info,
                brightness,
                max_brightness,
            })
        } else {
            Err(Error::InvalidDeviceName { device })
        }
    }

    /// Get all LED devices.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let led_devices = LedDevice::get_all_led_devices().unwrap();
    /// for ld in led_devices {
    ///     println!("LED Device: {:?}", ld);
    /// }
    /// ```
    pub fn get_all_led_devices() -> Result<Vec<LedDevice>, Error> {
        let mut leds = Vec::with_capacity(1);

        if Path::new(LEDS_DIR).is_dir() {
            for device in fs::read_dir(LEDS_DIR)? {
                let device = device?;
                let device_name = device.file_name().into_string().unwrap();

                match LedDevice::get_led_device(device_name) {
                    Ok(dev) => leds.push(dev),
                    Err(e) => return Err(e),
                }
            }
        }

        Ok(leds)
    }

    /// Get all keyboards devices.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let keyboards = LedDevice::get_all_keyboard_devices().unwrap();
    /// for keyboard in keyboards {
    ///     println!("Keyboard: {:?}", keyboard);
    /// }
    /// ```
    pub fn get_all_keyboard_devices() -> Result<Vec<LedDevice>, Error> {
        LedDevice::get_led_devices_with_filter(LedFilterable {
            device_name: None,
            color: None,
            function: Some(LedFunction::KbdBacklight),
        })
    }

    /// Get name of LED device.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let led_devices = LedDevice::get_all_led_devices().unwrap();
    /// for led_device in led_devices {
    ///     let max_brightness = led_device.get_max_brightness();
    ///     let device = led_device.get_device_name();
    ///     println!("Device: {}", device);
    ///     assert!(!device.is_empty())
    /// }
    /// ```
    pub fn get_device_name(&self) -> &str {
        &self.info.device
    }

    /// Get brightness of LED.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let led_devices = LedDevice::get_all_led_devices().unwrap();
    /// for led_device in led_devices {
    ///     let max_brightness = led_device.get_max_brightness();
    ///     let brightness = led_device.get_brightness();
    ///     println!("Brightness: {}", brightness);
    ///     assert!(brightness >= 0 && brightness <= max_brightness)
    /// }
    /// ```
    pub fn get_brightness(&self) -> u32 {
        self.brightness
    }

    /// Get the maximum brightness value of LED.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let led_devices = LedDevice::get_all_led_devices().unwrap();
    /// for led_device in led_devices {
    ///     let max_brightness = led_device.get_max_brightness();
    ///     println!("Max Brightness: {}", max_brightness);
    ///     assert!(max_brightness > 0)
    /// }
    /// ```
    pub fn get_max_brightness(&self) -> u32 {
        self.max_brightness
    }

    /// Set brightness of LED.
    ///
    /// ### Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let keyboard = LedDevice::get_all_led_devices().unwrap();
    /// keyboard[0].set_brightness(20);
    /// ```
    #[cfg(feature = "dbus")]
    pub fn set_brightness(&self, level: u32) -> Result<(), Error> {
        if level <= self.max_brightness {
            let sd_bus = Connection::new_system().unwrap();
            match sd_bus.call_method(
                Some("org.freedesktop.login1"),
                "/org/freedesktop/login1/session/auto",
                Some("org.freedesktop.login1.Session"),
                "SetBrightness",
                &("leds", &self.info.device, level),
            ) {
                Ok(_) => Ok(()),
                Err(e) => Err(Error::SetBrightnessDBusError(e)),
            }
        } else {
            Err(Error::InvalidBrightnessLevel {
                given: level,
                max: self.max_brightness,
            })
        }
    }

    /// Set brightness of led device.
    ///
    /// ### NOTE
    ///
    /// This method writes to `/sys/class/leds/<led>/brightness`
    /// and will fail if user is not root (even when executed with sudo).
    /// It is recommended to create a udev rule to allow user of a certain
    /// group to write to the file. The example below will allow all users in
    /// the `input` group to change the brightness of all devices in `/sys/class/leds/`.
    ///
    /// ```ignore
    /// ACTION=="add", SUBSYSTEM=="leds", RUN+="/bin/chgrp input /sys/class/leds/%k/brightness"
    /// ACTION=="add", SUBSYSTEM=="leds", RUN+="/bin/chmod g+w /sys/class/leds/%k/brightness"
    /// ```
    ///
    /// ### Examples
    ///
    /// ```
    /// use bulbb::misc::LedDevice;
    ///
    /// let keyboard = LedDevice::get_all_led_devices().unwrap();
    /// keyboard[0].set_brightness(20);
    /// ```
    #[cfg(not(feature = "dbus"))]
    pub fn set_brightness(&self, level: u32) -> Result<(), Error> {
        if level <= self.max_brightness {
            // write to /sys/class/leds/<led>/brightness
            let mut brightness = OpenOptions::new()
                .write(true)
                .open(format!("{}/{}/brightness", LEDS_DIR, &self.info.device))?;
            match brightness.write_all(level.to_string().as_bytes()) {
                Ok(_) => Ok(()),
                Err(e) => Err(Error::Io(e)),
            }
        } else {
            Err(Error::InvalidBrightnessLevel {
                given: level,
                max: self.max_brightness,
            })
        }
    }
}

impl LedInfo {
    /// Trys to parse string into LedInfo.
    pub fn from_string(s: String) -> LedInfo {
        let device = s.clone();
        let mut led_info = s.split(':').collect::<Vec<&str>>();
        led_info.retain(|&x| !x.is_empty());

        if led_info.len() == 3 {
            LedInfo {
                device,
                device_name: Some(led_info[0].to_string()),
                color: LedColor::from_id(led_info[1]),
                function: LedFunction::from_id(led_info[2]),
            }
        } else {
            let mut device_name: Option<String> = None;
            let mut color: Option<LedColor> = None;
            let mut function: Option<LedFunction> = None;

            let mut idx = 0_usize;
            while idx <= led_info.len() && !led_info.is_empty() {
                if LedColor::from_id(led_info[idx]).is_some() {
                    color = LedColor::from_id(led_info.remove(idx))
                } else if LedFunction::from_id(led_info[idx]).is_some() {
                    function = LedFunction::from_id(led_info.remove(idx))
                } else if !led_info.is_empty() {
                    device_name = Some(led_info.remove(idx).to_string())
                } else {
                    idx += 1
                }
            }

            LedInfo {
                device,
                device_name,
                color,
                function,
            }
        }
    }
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "dbus", derive(Serialize, Deserialize))]
/// Color of LED.
pub enum LedColor {
    White,
    Red,
    Green,
    Blue,
    Amber,
    Violet,
    Yellow,
    Ir,
    Multi,
    Rgb,
    Max,
}

impl LedColor {
    /// Trys to parse str into LedColor.
    pub fn from_id(s: &str) -> Option<Self> {
        match s {
            "white" => Some(LedColor::White),
            "red" => Some(LedColor::Red),
            "green" => Some(LedColor::Green),
            "blue" => Some(LedColor::Blue),
            "amber" => Some(LedColor::Amber),
            "violet" => Some(LedColor::Violet),
            "yellow" => Some(LedColor::Yellow),
            "ir" => Some(LedColor::Ir),
            "multi" => Some(LedColor::Multi),
            "rgb" => Some(LedColor::Rgb),
            "max" => Some(LedColor::Max),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "dbus", derive(Serialize, Deserialize))]
/// Function of the LED.
pub enum LedFunction {
    CapsLock,
    ScrollLock,
    NumLock,
    KbdBacklight,
    Power,
    Disk,
    Charging,
    Status,
    MicMute,
    Mute,
    Player1,
    Player2,
    Player3,
    Player4,
    Player5,
    Activity,
    Alarm,
    Backlight,
    Bluetooth,
    Boot,
    Cpu,
    Debug,
    DiskActivity,
    DiskErr,
    DiskRead,
    DiskWrite,
    Fault,
    Flash,
    Heartbeat,
    Indicator,
    Lan,
    Mail,
    Mtd,
    Panic,
    Programming,
    Rx,
    Sd,
    Standby,
    Torch,
    Tx,
    Usb,
    Wan,
    Wlan,
    Wps,
}

impl From<LedColor> for &str {
    fn from(val: LedColor) -> &'static str {
        match val {
            LedColor::White => "white",
            LedColor::Red => "red",
            LedColor::Green => "green",
            LedColor::Blue => "blue",
            LedColor::Amber => "amber",
            LedColor::Violet => "violet",
            LedColor::Yellow => "yellow",
            LedColor::Ir => "ir",
            LedColor::Multi => "multi",
            LedColor::Rgb => "rgb",
            LedColor::Max => "max",
        }
    }
}

impl From<&LedColor> for &str {
    fn from(val: &LedColor) -> &'static str {
        match val {
            LedColor::White => "white",
            LedColor::Red => "red",
            LedColor::Green => "green",
            LedColor::Blue => "blue",
            LedColor::Amber => "amber",
            LedColor::Violet => "violet",
            LedColor::Yellow => "yellow",
            LedColor::Ir => "ir",
            LedColor::Multi => "multi",
            LedColor::Rgb => "rgb",
            LedColor::Max => "max",
        }
    }
}

impl From<LedColor> for String {
    fn from(val: LedColor) -> String {
        match val {
            LedColor::White => String::from("white"),
            LedColor::Red => String::from("red"),
            LedColor::Green => String::from("green"),
            LedColor::Blue => String::from("blue"),
            LedColor::Amber => String::from("amber"),
            LedColor::Violet => String::from("violet"),
            LedColor::Yellow => String::from("yellow"),
            LedColor::Ir => String::from("ir"),
            LedColor::Multi => String::from("multi"),
            LedColor::Rgb => String::from("rgb"),
            LedColor::Max => String::from("max"),
        }
    }
}

impl From<&LedColor> for String {
    fn from(val: &LedColor) -> String {
        match val {
            LedColor::White => String::from("white"),
            LedColor::Red => String::from("red"),
            LedColor::Green => String::from("green"),
            LedColor::Blue => String::from("blue"),
            LedColor::Amber => String::from("amber"),
            LedColor::Violet => String::from("violet"),
            LedColor::Yellow => String::from("yellow"),
            LedColor::Ir => String::from("ir"),
            LedColor::Multi => String::from("multi"),
            LedColor::Rgb => String::from("rgb"),
            LedColor::Max => String::from("max"),
        }
    }
}

impl fmt::Display for LedColor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            LedColor::White => write!(f, "white"),
            LedColor::Red => write!(f, "red"),
            LedColor::Green => write!(f, "green"),
            LedColor::Blue => write!(f, "blue"),
            LedColor::Amber => write!(f, "amber"),
            LedColor::Violet => write!(f, "violet"),
            LedColor::Yellow => write!(f, "yellow"),
            LedColor::Ir => write!(f, "ir"),
            LedColor::Multi => write!(f, "multi"),
            LedColor::Rgb => write!(f, "rgb"),
            LedColor::Max => write!(f, "max"),
        }
    }
}

impl LedFunction {
    /// Trys to parse str into LedFunction.
    pub fn from_id(s: &str) -> Option<Self> {
        match s {
            "capslock" => Some(LedFunction::CapsLock),
            "scrolllock" => Some(LedFunction::ScrollLock),
            "numlock" => Some(LedFunction::NumLock),
            "kbd_backlight" => Some(LedFunction::KbdBacklight),
            "power" => Some(LedFunction::Power),
            "disk" => Some(LedFunction::Disk),
            "charging" => Some(LedFunction::Charging),
            "status" => Some(LedFunction::Status),
            "micmute" => Some(LedFunction::MicMute),
            "mute" => Some(LedFunction::Mute),
            "player-1" => Some(LedFunction::Player1),
            "player-2" => Some(LedFunction::Player2),
            "player-3" => Some(LedFunction::Player3),
            "player-4" => Some(LedFunction::Player4),
            "player-5" => Some(LedFunction::Player5),
            "activity" => Some(LedFunction::Activity),
            "alarm" => Some(LedFunction::Alarm),
            "backlight" => Some(LedFunction::Backlight),
            "bluetooth" => Some(LedFunction::Bluetooth),
            "boot" => Some(LedFunction::Boot),
            "cpu" => Some(LedFunction::Cpu),
            "debug" => Some(LedFunction::Debug),
            "disk-activity" => Some(LedFunction::DiskActivity),
            "disk-err" => Some(LedFunction::DiskErr),
            "disk-read" => Some(LedFunction::DiskRead),
            "disk-write" => Some(LedFunction::DiskWrite),
            "fault" => Some(LedFunction::Fault),
            "flash" => Some(LedFunction::Flash),
            "heartbeat" => Some(LedFunction::Heartbeat),
            "indicator" => Some(LedFunction::Indicator),
            "lan" => Some(LedFunction::Lan),
            "mail" => Some(LedFunction::Mail),
            "mtd" => Some(LedFunction::Mtd),
            "panic" => Some(LedFunction::Panic),
            "programming" => Some(LedFunction::Programming),
            "rx" => Some(LedFunction::Rx),
            "sd" => Some(LedFunction::Sd),
            "standby" => Some(LedFunction::Standby),
            "torch" => Some(LedFunction::Torch),
            "tx" => Some(LedFunction::Tx),
            "usb" => Some(LedFunction::Usb),
            "wan" => Some(LedFunction::Wan),
            "wlan" => Some(LedFunction::Wlan),
            "wps" => Some(LedFunction::Wps),
            _ => None,
        }
    }
}

impl From<&LedFunction> for &str {
    fn from(val: &LedFunction) -> &'static str {
        match val {
            LedFunction::CapsLock => "capslock",
            LedFunction::ScrollLock => "scrolllock",
            LedFunction::NumLock => "numlock",
            LedFunction::KbdBacklight => "kbd_backlight",
            LedFunction::Power => "power",
            LedFunction::Disk => "disk",
            LedFunction::Charging => "charging",
            LedFunction::Status => "status",
            LedFunction::MicMute => "micmute",
            LedFunction::Mute => "mute",
            LedFunction::Player1 => "player-1",
            LedFunction::Player2 => "player-2",
            LedFunction::Player3 => "player-3",
            LedFunction::Player4 => "player-4",
            LedFunction::Player5 => "player-5",
            LedFunction::Activity => "activity",
            LedFunction::Alarm => "alarm",
            LedFunction::Backlight => "backlight",
            LedFunction::Bluetooth => "bluetooth",
            LedFunction::Boot => "boot",
            LedFunction::Cpu => "cpu",
            LedFunction::Debug => "debug",
            LedFunction::DiskActivity => "disk-activity",
            LedFunction::DiskErr => "disk-err",
            LedFunction::DiskRead => "disk-read",
            LedFunction::DiskWrite => "disk-write",
            LedFunction::Fault => "fault",
            LedFunction::Flash => "flash",
            LedFunction::Heartbeat => "heartbeat",
            LedFunction::Indicator => "indicator",
            LedFunction::Lan => "lan",
            LedFunction::Mail => "mail",
            LedFunction::Mtd => "mtd",
            LedFunction::Panic => "panic",
            LedFunction::Programming => "programming",
            LedFunction::Rx => "rx",
            LedFunction::Sd => "sd",
            LedFunction::Standby => "standby",
            LedFunction::Torch => "torch",
            LedFunction::Tx => "tx",
            LedFunction::Usb => "usb",
            LedFunction::Wan => "wan",
            LedFunction::Wlan => "wlan",
            LedFunction::Wps => "wps",
        }
    }
}

impl From<LedFunction> for &str {
    fn from(val: LedFunction) -> &'static str {
        match val {
            LedFunction::CapsLock => "capslock",
            LedFunction::ScrollLock => "scrolllock",
            LedFunction::NumLock => "numlock",
            LedFunction::KbdBacklight => "kbd_backlight",
            LedFunction::Power => "power",
            LedFunction::Disk => "disk",
            LedFunction::Charging => "charging",
            LedFunction::Status => "status",
            LedFunction::MicMute => "micmute",
            LedFunction::Mute => "mute",
            LedFunction::Player1 => "player-1",
            LedFunction::Player2 => "player-2",
            LedFunction::Player3 => "player-3",
            LedFunction::Player4 => "player-4",
            LedFunction::Player5 => "player-5",
            LedFunction::Activity => "activity",
            LedFunction::Alarm => "alarm",
            LedFunction::Backlight => "backlight",
            LedFunction::Bluetooth => "bluetooth",
            LedFunction::Boot => "boot",
            LedFunction::Cpu => "cpu",
            LedFunction::Debug => "debug",
            LedFunction::DiskActivity => "disk-activity",
            LedFunction::DiskErr => "disk-err",
            LedFunction::DiskRead => "disk-read",
            LedFunction::DiskWrite => "disk-write",
            LedFunction::Fault => "fault",
            LedFunction::Flash => "flash",
            LedFunction::Heartbeat => "heartbeat",
            LedFunction::Indicator => "indicator",
            LedFunction::Lan => "lan",
            LedFunction::Mail => "mail",
            LedFunction::Mtd => "mtd",
            LedFunction::Panic => "panic",
            LedFunction::Programming => "programming",
            LedFunction::Rx => "rx",
            LedFunction::Sd => "sd",
            LedFunction::Standby => "standby",
            LedFunction::Torch => "torch",
            LedFunction::Tx => "tx",
            LedFunction::Usb => "usb",
            LedFunction::Wan => "wan",
            LedFunction::Wlan => "wlan",
            LedFunction::Wps => "wps",
        }
    }
}

impl From<&LedFunction> for String {
    fn from(val: &LedFunction) -> String {
        match val {
            LedFunction::CapsLock => String::from("capslock"),
            LedFunction::ScrollLock => String::from("scrolllock"),
            LedFunction::NumLock => String::from("numlock"),
            LedFunction::KbdBacklight => String::from("kbd_backlight"),
            LedFunction::Power => String::from("power"),
            LedFunction::Disk => String::from("disk"),
            LedFunction::Charging => String::from("charging"),
            LedFunction::Status => String::from("status"),
            LedFunction::MicMute => String::from("micmute"),
            LedFunction::Mute => String::from("mute"),
            LedFunction::Player1 => String::from("player-1"),
            LedFunction::Player2 => String::from("player-2"),
            LedFunction::Player3 => String::from("player-3"),
            LedFunction::Player4 => String::from("player-4"),
            LedFunction::Player5 => String::from("player-5"),
            LedFunction::Activity => String::from("activity"),
            LedFunction::Alarm => String::from("alarm"),
            LedFunction::Backlight => String::from("backlight"),
            LedFunction::Bluetooth => String::from("bluetooth"),
            LedFunction::Boot => String::from("boot"),
            LedFunction::Cpu => String::from("cpu"),
            LedFunction::Debug => String::from("debug"),
            LedFunction::DiskActivity => String::from("disk-activity"),
            LedFunction::DiskErr => String::from("disk-err"),
            LedFunction::DiskRead => String::from("disk-read"),
            LedFunction::DiskWrite => String::from("disk-write"),
            LedFunction::Fault => String::from("fault"),
            LedFunction::Flash => String::from("flash"),
            LedFunction::Heartbeat => String::from("heartbeat"),
            LedFunction::Indicator => String::from("indicator"),
            LedFunction::Lan => String::from("lan"),
            LedFunction::Mail => String::from("mail"),
            LedFunction::Mtd => String::from("mtd"),
            LedFunction::Panic => String::from("panic"),
            LedFunction::Programming => String::from("programming"),
            LedFunction::Rx => String::from("rx"),
            LedFunction::Sd => String::from("sd"),
            LedFunction::Standby => String::from("standby"),
            LedFunction::Torch => String::from("torch"),
            LedFunction::Tx => String::from("tx"),
            LedFunction::Usb => String::from("usb"),
            LedFunction::Wan => String::from("wan"),
            LedFunction::Wlan => String::from("wlan"),
            LedFunction::Wps => String::from("wps"),
        }
    }
}

impl From<LedFunction> for String {
    fn from(val: LedFunction) -> String {
        match val {
            LedFunction::CapsLock => String::from("capslock"),
            LedFunction::ScrollLock => String::from("scrolllock"),
            LedFunction::NumLock => String::from("numlock"),
            LedFunction::KbdBacklight => String::from("kbd_backlight"),
            LedFunction::Power => String::from("power"),
            LedFunction::Disk => String::from("disk"),
            LedFunction::Charging => String::from("charging"),
            LedFunction::Status => String::from("status"),
            LedFunction::MicMute => String::from("micmute"),
            LedFunction::Mute => String::from("mute"),
            LedFunction::Player1 => String::from("player-1"),
            LedFunction::Player2 => String::from("player-2"),
            LedFunction::Player3 => String::from("player-3"),
            LedFunction::Player4 => String::from("player-4"),
            LedFunction::Player5 => String::from("player-5"),
            LedFunction::Activity => String::from("activity"),
            LedFunction::Alarm => String::from("alarm"),
            LedFunction::Backlight => String::from("backlight"),
            LedFunction::Bluetooth => String::from("bluetooth"),
            LedFunction::Boot => String::from("boot"),
            LedFunction::Cpu => String::from("cpu"),
            LedFunction::Debug => String::from("debug"),
            LedFunction::DiskActivity => String::from("disk-activity"),
            LedFunction::DiskErr => String::from("disk-err"),
            LedFunction::DiskRead => String::from("disk-read"),
            LedFunction::DiskWrite => String::from("disk-write"),
            LedFunction::Fault => String::from("fault"),
            LedFunction::Flash => String::from("flash"),
            LedFunction::Heartbeat => String::from("heartbeat"),
            LedFunction::Indicator => String::from("indicator"),
            LedFunction::Lan => String::from("lan"),
            LedFunction::Mail => String::from("mail"),
            LedFunction::Mtd => String::from("mtd"),
            LedFunction::Panic => String::from("panic"),
            LedFunction::Programming => String::from("programming"),
            LedFunction::Rx => String::from("rx"),
            LedFunction::Sd => String::from("sd"),
            LedFunction::Standby => String::from("standby"),
            LedFunction::Torch => String::from("torch"),
            LedFunction::Tx => String::from("tx"),
            LedFunction::Usb => String::from("usb"),
            LedFunction::Wan => String::from("wan"),
            LedFunction::Wlan => String::from("wlan"),
            LedFunction::Wps => String::from("wps"),
        }
    }
}

impl fmt::Display for LedFunction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            LedFunction::CapsLock => write!(f, "capslock"),
            LedFunction::ScrollLock => write!(f, "scrolllock"),
            LedFunction::NumLock => write!(f, "numlock"),
            LedFunction::KbdBacklight => write!(f, "kbd_backlight"),
            LedFunction::Power => write!(f, "power"),
            LedFunction::Disk => write!(f, "disk"),
            LedFunction::Charging => write!(f, "charging"),
            LedFunction::Status => write!(f, "status"),
            LedFunction::MicMute => write!(f, "micmute"),
            LedFunction::Mute => write!(f, "mute"),
            LedFunction::Player1 => write!(f, "player-1"),
            LedFunction::Player2 => write!(f, "player-2"),
            LedFunction::Player3 => write!(f, "player-3"),
            LedFunction::Player4 => write!(f, "player-4"),
            LedFunction::Player5 => write!(f, "player-5"),
            LedFunction::Activity => write!(f, "activity"),
            LedFunction::Alarm => write!(f, "alarm"),
            LedFunction::Backlight => write!(f, "backlight"),
            LedFunction::Bluetooth => write!(f, "bluetooth"),
            LedFunction::Boot => write!(f, "boot"),
            LedFunction::Cpu => write!(f, "cpu"),
            LedFunction::Debug => write!(f, "debug"),
            LedFunction::DiskActivity => write!(f, "disk-activity"),
            LedFunction::DiskErr => write!(f, "disk-err"),
            LedFunction::DiskRead => write!(f, "disk-read"),
            LedFunction::DiskWrite => write!(f, "disk-write"),
            LedFunction::Fault => write!(f, "fault"),
            LedFunction::Flash => write!(f, "flash"),
            LedFunction::Heartbeat => write!(f, "heartbeat"),
            LedFunction::Indicator => write!(f, "indicator"),
            LedFunction::Lan => write!(f, "lan"),
            LedFunction::Mail => write!(f, "mail"),
            LedFunction::Mtd => write!(f, "mtd"),
            LedFunction::Panic => write!(f, "panic"),
            LedFunction::Programming => write!(f, "programming"),
            LedFunction::Rx => write!(f, "rx"),
            LedFunction::Sd => write!(f, "sd"),
            LedFunction::Standby => write!(f, "standby"),
            LedFunction::Torch => write!(f, "torch"),
            LedFunction::Tx => write!(f, "tx"),
            LedFunction::Usb => write!(f, "usb"),
            LedFunction::Wan => write!(f, "wan"),
            LedFunction::Wlan => write!(f, "wlan"),
            LedFunction::Wps => write!(f, "wps"),
        }
    }
}

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

    use crate::utils::format_led_device;

    #[test]
    fn parse_led_device_names() {
        let devices = vec![
            "asus::kbd_backlight",
            "input13::capslock",
            "input13::compose",
            "input13::kana",
            "input13::numlock",
            "input13::scrolllock",
            "input2::capslock",
            "input2::numlock",
            "input2::scrolllock",
            "phy0-led",
        ];
        for dev in devices {
            let led_info = LedInfo::from_string(dev.to_string());
            let led_c = if let Some(c) = led_info.color {
                c.to_string()
            } else {
                String::from("")
            };
            let led_f = if let Some(f) = led_info.function {
                f.to_string()
            } else {
                String::from("")
            };

            println!(
                "Device: {}\nDevice Name: {}\nColor: {}\nFunction: {}\n",
                led_info.device,
                led_info.device_name.unwrap_or_else(|| String::from("")),
                led_c,
                led_f
            )
        }
    }

    #[test]
    fn get_all_led_devices() {
        let leds = LedDevice::get_all_led_devices().unwrap();
        for led in leds {
            format_led_device(led)
        }
    }

    #[test]
    fn get_all_keyboard_devices() {
        let keyboards = LedDevice::get_all_keyboard_devices().unwrap();
        for kbd in keyboards {
            format_led_device(kbd)
        }
    }

    #[test]
    fn filter() {
        let filter1 = LedFilterable {
            device_name: Some("dev"),
            color: None,
            function: None,
        };

        let mut filter2 = LedFilterable::new();
        let filter2 = filter2.with_device_name("dev").finish();
        assert_eq!(filter1.device_name, filter2.device_name);
        assert_eq!(filter1.color.is_none(), filter2.color.is_none());
        assert_eq!(filter1.function.is_none(), filter2.function.is_none());
    }
}