blight 0.8.0

A hassle-free CLI backlight utility/library for Linux.
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
//! Abstractions and functions for controlling LEDs using the `/sys/class/leds` Linux interface
//!
//! Once an instance of the [`Led`] type has been initialized, the interface for controlling it
//! is identical to a backlight device. However, LEDs that only support `0` and `1` as valid
//! brightness values are considered as `non-dimmable` and hence any functionality related to
//! dimming is not available on those types. This is statically enforced by the type system.
//!
//! # Usage
//! ```no_run
//! use blight::{Delay, Light, led};
//!
//! fn main() -> blight::Result<()> {
//!     led::set_led_state("target::led::name", true)?; // Turn an LED on
//!
//!     let leds = led::led_names()?; // Read all LED names from `/sys/class/leds`
//!     // Print all the info determined just by parsing the names of the LEDs
//!     for led in &leds {
//!         println!(
//!             "Full name: {}, parsed name: {:?}, color: {:?}, function: {:?}",
//!             led.raw_name(),
//!             led.parsed_name(),
//!             led.color(),
//!             led.function()
//!         );
//!     }
//!     // Find Capslock LED and alter its state
//!     if let Some(caps) = leds
//!         .into_iter()
//!         .find(|n| n.function() == led::Function::Capslock)
//!     {
//!         // This is the same as `led::Led::from_name(caps)?`
//!         match caps.initialize()? {
//!             // Dimmable LEDs offer more functionality (same as a backlight device)
//!             // Note: Capslock is almost always non-dimmable, this line of code is only
//!             // to illustrate the general usage of the interface.
//!             led::LedType::Dimmable(mut led) => led.sweep_write(0, Delay::default()),
//!             // Non-dimmable LEDs support only 0 and 1 as their brightness values,
//!             // and can only be turned on/off (using `toggle` or `write_value` methods)
//!             led::LedType::NonDimmable(mut led) => led.toggle(),
//!         }?
//!     }
//!     // Initialize a known LED by its name
//!     match led::Led::new("platform::kbd_backlight".into())? {
//!         led::LedType::Dimmable(mut led) => led.write_value(led.max()), // set it to max brightness
//!         led::LedType::NonDimmable(mut led) => led.write_value(0),      // turn off the LED
//!     }?;
//!     Ok(())
//! }
//! ```
use std::{
    borrow::Cow,
    fs::File,
    marker::PhantomData,
    path::{Path, PathBuf},
    str::FromStr,
};

use crate::{
    err::{Error, ErrorKind},
    private, utils, Light,
};

/// Linux LED interface directory
#[cfg(not(test))]
pub const LEDDIR: &str = "/sys/class/leds";
#[cfg(test)]
pub const LEDDIR: &str = "testbldir";

/// Distinguish between a dimmable and a non-dimmable LED
///
/// See [module][self] level docs for usage examples.
#[derive(Debug)]
pub enum LedType {
    /// LED that supports multiple brightness values
    Dimmable(Led<Dimmable>),
    /// LED that supports only 1 (on) and 0 (off) brightness values
    NonDimmable(Led<NonDimmable>),
}

/// Marker type used with [`Led`] to enable dimmable LED specific functionality
#[derive(Debug)]
pub struct Dimmable;

/// Marker type used with [`Led`] to restrict LED functionality to simple on/off toggle
#[derive(Debug)]
pub struct NonDimmable;

/// Abstraction of an LED device from `/sys/class/leds`
///
/// An LED can either be dimmable or non-dimmable. Non-dimmable LED instances only provide the [`Light::toggle`]
/// and [`Light::write_value`] method to change the state of the device. Dimmable LEDs, on the other hand, enable
/// access to all the methods provided by the [`Light`] trait. These constraints are statically enforced by the type system.
///
/// For usage examples, see [module][self] level docs.
#[derive(Debug)]
pub struct Led<Type> {
    name: LedName<'static>,
    max: u8,
    current: u8,
    path: PathBuf,
    brightness: File,
    marker: PhantomData<Type>,
}

impl Led<()> {
    /// Create a new instance of an Led
    ///
    /// An instance will be created only if an LED of the provided name exists and the max and current brightness values are successfully read.
    ///
    /// Note: The initialized Led will only contain additional `function` and `color` information if the name of the LED
    /// is in accordance with the device naming convention described in <https://www.kernel.org/doc/html/latest/leds/leds-class.html#led-device-naming>.
    ///
    /// # Errors
    /// - [`ErrorKind::NotFound`] - an LED dir of the given name is not found
    /// - [`ErrorKind::ReadMax`] - failure to read the max brightness value
    /// - [`ErrorKind::ReadCurrent`] - failure to read the current brightness value
    pub fn new(name: Cow<str>) -> crate::Result<LedType> {
        Self::new_inner(LedName::parse(name), None)
    }

    /// Create a new instance of an Led with an exclusive lock on the brightness file
    ///
    /// An instance will be created only if an LED of the provided name exists and the max and current brightness values are successfully read.
    /// If `blocking` is set `true`, this call will block until an exclusive lock is acquired on the brightness file.
    ///
    /// Note: The initialized Led will only contain additional `function` and `color` information if the name of the LED
    /// is in accordance with the device naming convention described in <https://www.kernel.org/doc/html/latest/leds/leds-class.html#led-device-naming>.
    ///
    /// # Errors
    /// - [`ErrorKind::NotFound`] - an LED dir of the given name is not found
    /// - [`ErrorKind::ReadMax`] - failure to read the max brightness value
    /// - [`ErrorKind::ReadCurrent`] - failure to read the current brightness value
    /// - [`ErrorKind::LockError`] - failure to acquire an exclusive file lock
    #[cfg(feature = "locking")]
    pub fn new_locked(name: Cow<str>, blocking: bool) -> crate::Result<LedType> {
        Self::new_inner(
            LedName::parse(name),
            Some(if blocking {
                utils::Lock::Blocking
            } else {
                utils::Lock::NonBlocking
            }),
        )
    }

    fn new_inner(name: LedName, lock: Option<utils::Lock>) -> crate::Result<LedType> {
        let utils::Info {
            current,
            max,
            brightness,
            path,
        } = utils::read_info(LEDDIR, &name.raw, lock)?;
        #[allow(clippy::cast_possible_truncation)]
        let (max, current) = (max as _, current as _);
        let name = name.into_owned();
        let led = if max == 1 {
            LedType::NonDimmable(Led {
                name,
                max,
                current,
                path,
                brightness,
                marker: PhantomData,
            })
        } else {
            LedType::Dimmable(Led {
                name,
                max,
                current,
                path,
                brightness,
                marker: PhantomData,
            })
        };

        Ok(led)
    }

    /// Create an instance of an [`Led`] from an existing [`LedName`]
    ///
    /// An instance will be created only if an LED of the provided name exists and the max and current brightness values are successfully read.
    ///
    /// Note: The initialized Led will only contain additional `function` and `color` information if the name of the LED
    /// is in accordance with the device naming convention described in <https://www.kernel.org/doc/html/latest/leds/leds-class.html#led-device-naming>.
    ///
    /// # Errors
    /// - `NotFound` - an LED dir of the given name is not found
    /// - `ReadMax` - failure to read the max brightness value
    /// - `ReadCurrent` - failure to read the current brightness value
    pub fn from_name(name: LedName) -> crate::Result<LedType> {
        Self::new_inner(name, None)
    }
}

impl<Type> Led<Type> {
    /// Supported color of the LED
    ///
    /// See type level docs of [`LedName`] for additional details on parsing
    pub fn color(&self) -> Color {
        self.name.color
    }

    /// Function of the LED, such as Capslock and Numlock
    ///
    /// See type level docs of [`LedName`] for additional details on parsing
    pub fn function(&self) -> Function {
        self.name.function
    }

    /// Name of the LED that was parsed from the full device name using the standard Linux LED naming convention
    ///
    /// See type level docs of [`LedName`] for additional details on parsing
    pub fn parsed_name(&self) -> Option<&str> {
        self.name.parsed_name()
    }
}

impl<Type> private::Sealed for Led<Type> {}

impl super::Dimmable for Led<Dimmable> {}

impl super::Toggleable for Led<Dimmable> {}

impl super::Toggleable for Led<NonDimmable> {}

impl<Type> Light for Led<Type> {
    type Value = u8;

    /// Full name of the LED device
    ///
    /// Use [`Led::parsed_name`] to get the parsed name (if available)
    fn name(&self) -> &str {
        self.name.raw_name()
    }

    fn current(&self) -> Self::Value {
        self.current
    }

    fn max(&self) -> Self::Value {
        self.max
    }

    #[doc(hidden)]
    fn set_current(&mut self, _: crate::private::Internal, current: Self::Value) {
        self.current = current;
    }

    #[doc(hidden)]
    fn brightness_file(&mut self, _: crate::private::Internal) -> &mut File {
        &mut self.brightness
    }

    /// Returns absolute path that points to the device directory in `/sys/class/leds`
    fn device_path(&self) -> &Path {
        &self.path
    }
}

/// Abstraction that represents the name of an LED device
///
/// If [`LedName`] was initialized with a an LED name formatted according to the
/// device naming convention described in <https://www.kernel.org/doc/html/latest/leds/leds-class.html#led-device-naming>/,
/// the resulting instance can be inspected to get additional details of an LED device, such as [`Self::color`], [`Self::function`], and [`Self::parsed_name`].
///
/// Note: the aforementioned methods are also directly available on the [`Led`] type.
#[derive(Debug, Clone, PartialEq)]
pub struct LedName<'a> {
    raw: Cow<'a, str>,
    len: usize,
    color: Color,
    function: Function,
}

impl<'a> LedName<'a> {
    /// Parse a string containing an LED interface name
    ///
    /// This function is infallible, which means any string will be accepted.
    /// However, only names formatted according to the Linux LED naming convention will be parsed correctly
    /// to get color, name and function information. See [type][LedName] level docs for additional details.
    pub fn parse(name: Cow<'a, str>) -> Self {
        let mut name = Self {
            raw: name,
            len: 0,
            color: Color::default(),
            function: Function::default(),
        };
        let Some((rem, fun)) = name.raw.rsplit_once(':') else {
            return name;
        };
        let Ok(fun): Result<Function, _> = fun.parse();
        name.function = fun;
        // If no string slice was encountered here
        // it means the name didn't contain `:` making it invalid
        let Some((rem, clr)) = rem.rsplit_once(':') else {
            return name;
        };
        let Ok(clr): Result<Color, _> = clr.parse();
        name.color = clr;
        name.len = rem.len();
        name
    }

    /// Color of the LED which was parsed from the name
    ///
    /// See type level docs for details on LED naming convention.
    pub fn color(&self) -> Color {
        self.color
    }

    /// Function of the LED which was parsed from the name (Capslock, Scrollock, Numlock, etc)
    ///
    /// See type level docs for details on LED naming convention.
    pub fn function(&self) -> Function {
        self.function
    }

    /// The full unparsed name of the LED (same as the string used to initialize the `LedName`)
    ///
    /// See type level docs for details on LED naming convention.
    pub fn raw_name(&self) -> &str {
        &self.raw
    }

    /// Parsed name of the LED
    ///
    /// See type level docs for details on LED naming convention.
    pub fn parsed_name(&self) -> Option<&str> {
        (self.len != 0).then_some(&self.raw[..self.len])
    }

    /// Initialize an instance of [`Led`] using `self`
    ///
    /// This is identical to calling [`Led::from_name`] and passing self to it (which is exactly what this method does).
    ///
    /// # Errors
    /// - All possible errors returned by [`Led::from_name`] or [`Led::new`]
    pub fn initialize(self) -> crate::Result<LedType> {
        Led::from_name(self)
    }

    /// Convert an LED name containing borrowed data into an owned instance
    pub fn into_owned(self) -> LedName<'static> {
        LedName {
            raw: self.raw.into_owned().into(),
            ..self
        }
    }
}

/// Supported color of an LED
///
/// Use [`LedName`] to parse an LED name (string) to inspect its supported color. The same is also
/// done automatically when initializing an LED with [`Led::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Color {
    White = 0,
    Red = 1,
    Green = 2,
    Blue = 3,
    Amber = 4,
    Violet = 5,
    Yellow = 6,
    Ir = 7,
    Multi = 8,
    Rgb = 9,
    Purple = 10,
    Orange = 11,
    Pink = 12,
    Cyan = 13,
    Lime = 14,
    Max = 15,
    #[default]
    Unknown,
}

impl FromStr for Color {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let clr = match s {
            "white" => Color::White,
            "red" => Color::Red,
            "green" => Color::Green,
            "blue" => Color::Blue,
            "amber" => Color::Amber,
            "violet" => Color::Violet,
            "yellow" => Color::Yellow,
            "ir" => Color::Ir,
            "multi" => Color::Multi,
            "rgb" => Color::Rgb,
            "purple" => Color::Purple,
            "orange" => Color::Orange,
            "pink" => Color::Pink,
            "cyan" => Color::Cyan,
            "lime" => Color::Lime,
            "max" => Color::Max,
            _ => Color::default(),
        };
        Ok(clr)
    }
}

/// Function of an LED
///
/// Use [`LedName`] to parse an LED name (string) to inspect its function. The same is also
/// done automatically when initializing an LED with [`Led::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Function {
    Capslock,
    Scrolllock,
    Numlock,
    Fnlock,
    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,
    Mobile,
    Mtd,
    Panic,
    Programming,
    Rx,
    Sd,
    SpeedLan,
    SpeedWan,
    Standby,
    Torch,
    Tx,
    Usb,
    Wan,
    WanOnline,
    Wlan,
    Wlan2ghz,
    Wlan5ghz,
    Wlan6ghz,
    Wps,
    #[default]
    Unknown,
}

impl FromStr for Function {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        #[allow(clippy::enum_glob_use)]
        use Function::*;
        let func = match s {
            "capslock" => Capslock,
            "scrolllock" => Scrolllock,
            "numlock" => Numlock,
            "fnlock" => Fnlock,
            "kbd_backlight" => KbdBacklight,
            "power" => Power,
            "disk" => Disk,
            "charging" => Charging,
            "status" => Status,
            "micmute" => Micmute,
            "mute" => Mute,
            "player-1" => Player1,
            "player-2" => Player2,
            "player-3" => Player3,
            "player-4" => Player4,
            "player-5" => Player5,
            "activity" => Activity,
            "alarm" => Alarm,
            "backlight" => Backlight,
            "bluetooth" => Bluetooth,
            "boot" => Boot,
            "cpu" => Cpu,
            "debug" => Debug,
            "disk-activity" => DiskActivity,
            "disk-err" => DiskErr,
            "disk-read" => DiskRead,
            "disk-write" => DiskWrite,
            "fault" => Fault,
            "flash" => Flash,
            "heartbeat" => Heartbeat,
            "indicator" => Indicator,
            "lan" => Lan,
            "mail" => Mail,
            "mobile" => Mobile,
            "mtd" => Mtd,
            "panic" => Panic,
            "programming" => Programming,
            "rx" => Rx,
            "sd" => Sd,
            "speed-lan" => SpeedLan,
            "speed-wan" => SpeedWan,
            "standby" => Standby,
            "torch" => Torch,
            "tx" => Tx,
            "usb" => Usb,
            "wan" => Wan,
            "wan-online" => WanOnline,
            "wlan" => Wlan,
            "wlan-2ghz" => Wlan2ghz,
            "wlan-5ghz" => Wlan5ghz,
            "wlan-6ghz" => Wlan6ghz,
            "wps" => Wps,
            _ => Unknown,
        };
        Ok(func)
    }
}

/// Helper function to read all the LED names available in `/sys/class/leds`
///
/// The name can be used to inspect the color and function of an LED (if parsed correctly),
/// without initializing an instance of [`Led`].
///
/// # Errors
/// - `ReadDir` - failure to read [`LEDDIR`] (usually due to missing permissions)
pub fn led_names() -> crate::Result<Vec<LedName<'static>>> {
    let read_dir_err = |err| Error::from(ErrorKind::ReadDir { dir: LEDDIR }).with_source(err);
    let mut names = vec![];
    for d in std::fs::read_dir(LEDDIR).map_err(read_dir_err)? {
        let is_dir = d.as_ref().is_ok_and(|inr| inr.path().is_dir());
        if is_dir {
            let entry = d.map_err(read_dir_err)?;
            names.push(LedName::parse(entry.file_name().to_string_lossy()).into_owned());
        }
    }
    Ok(names)
}

/// Helper function to initialize all the LED devices available in `/sys/class/leds`
///
/// This function will return an error if any single LED fails to initialize.
///
/// # Errors
/// - All possible errors returned by [`led_names`]
/// - All possible errors returned by [`Led::from_name`]
pub fn leds() -> crate::Result<Vec<LedType>> {
    led_names().and_then(|names| names.into_iter().map(Led::from_name).collect())
}

/// Helper function to initialize all LEDs from an iterator over [`LedName`]s
///
/// This function will return an error if any single LED fails to initialize.
///
/// # Examples
/// ```no_run
/// # fn main() -> blight::Result<()> {
/// let leds = blight::led::leds_from_names(
///     blight::led::led_names()?
///         .into_iter()
///         .filter(|n| n.color() == blight::led::Color::Rgb),
/// )?;
/// for led in leds {
/// // do something here
/// }
/// #   Ok(())
/// # }
/// ```
///
/// # Errors
/// - All possible errors returned by [`Led::from_name`]
pub fn leds_from_names<'a>(
    names: impl IntoIterator<Item = LedName<'a>>,
) -> crate::Result<Vec<LedType>> {
    names.into_iter().map(Led::from_name).collect()
}

/// Helper function to turn an LED on/off
///
/// `State`: true = on (brightness = max), false = off (brightness = 0)
///
/// # Errors
/// - All possible errors returned by [`Led::new`] and [`Light::write_value`]
pub fn set_led_state(led_name: &str, state: bool) -> crate::Result<()> {
    match Led::new(led_name.into())? {
        LedType::Dimmable(mut led) => led.write_value(if state { led.max() } else { 0 }),
        LedType::NonDimmable(mut led) => led.write_value(u8::from(state)),
    }
}

/// Helper function to get LED state
///
/// `State`: true = on (brightness != 0), false = off (brightness == 0)
///
/// # Errors
/// - All possible errors returned by [`Led::new`]
pub fn get_led_state(led_name: &str) -> crate::Result<bool> {
    let state = match Led::new(led_name.into())? {
        LedType::Dimmable(led) => led.current(),
        LedType::NonDimmable(led) => led.current(),
    };
    Ok(state != 0)
}

/// Helper function to set LED brightness value
///
/// # Errors
/// - All possible errors returned by [`Led::new`] and [`Led::write_value`]
pub fn set_led_value(led_name: &str, value: u8) -> crate::Result<()> {
    match Led::new(led_name.into())? {
        LedType::Dimmable(mut led) => led.write_value(value),
        LedType::NonDimmable(mut led) => led.write_value(value),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::{clean_up, setup_test_env};

    #[test]
    fn parse_name() {
        let cases = [
            (
                "platform:white:kbd_backlight",
                LedName {
                    raw: "platform:white:kbd_backlight".into(),
                    len: 8,
                    color: Color::White,
                    function: Function::KbdBacklight,
                },
                Some("platform"),
            ),
            (
                "input13::capslock",
                LedName {
                    raw: "input13::capslock".into(),
                    len: 7,
                    color: Color::Unknown,
                    function: Function::Capslock,
                },
                Some("input13"),
            ),
            (
                "input7::numlock",
                LedName {
                    raw: "input7::numlock".into(),
                    len: 6,
                    color: Color::Unknown,
                    function: Function::Numlock,
                },
                Some("input7"),
            ),
            (
                "name::",
                LedName {
                    raw: "name::".into(),
                    len: 4,
                    color: Color::Unknown,
                    function: Function::Unknown,
                },
                Some("name"),
            ),
            (
                "unknown",
                LedName {
                    raw: "unknown".into(),
                    len: 0,
                    color: Color::Unknown,
                    function: Function::Unknown,
                },
                None,
            ),
        ];
        for (i, (string, expected, expected_name)) in cases.into_iter().enumerate() {
            let name: LedName = LedName::parse(string.into());
            assert_eq!(name, expected, "Case {i} failed");
            assert_eq!(name.parsed_name(), expected_name, "case {i} failed");
        }
    }

    #[test]
    fn initialize_dimmable() {
        clean_up();
        let name = "generic";
        setup_test_env(&[name], 10, 100);
        let led = Led::new(name.into()).expect("failed to initialize LED");
        assert!(
            matches!(led, LedType::Dimmable(_)),
            "Initialized LED is not of dimmable type"
        );
        clean_up();
    }

    #[test]
    fn initialize_non_dimmable() {
        clean_up();
        let name = "generic";
        setup_test_env(&[name], 1, 1);
        let led = Led::new(name.into()).expect("failed to initialize LED");
        assert!(
            matches!(led, LedType::NonDimmable(_)),
            "Initialized LED is not of dimmable type"
        );
        clean_up();
    }

    #[test]
    fn names() {
        clean_up();
        let names = ["led1", "led2", "led3"];
        setup_test_env(&names, 0, 1);
        let mut names_read: Vec<_> = led_names()
            .expect("failed to get LED names")
            .into_iter()
            .map(|n| n.raw.into_owned())
            .collect();
        names_read.sort_unstable();
        let names_read: Vec<&str> = names_read.iter().map(String::as_str).collect();
        assert_eq!(
            names.as_ref(),
            &names_read,
            "LED names read from the dir do not match"
        );
        clean_up();
    }

    #[test]
    fn set_state() {
        clean_up();
        let name = "generic";
        setup_test_env(&[name], 0, 1);
        // Turn LED on
        set_led_state(name, true).expect("failed to turn on LED");
        let LedType::NonDimmable(mut led) = Led::new(name.into()).unwrap() else {
            unreachable!()
        };
        assert_eq!(led.current(), 1, "LED is not turned on");
        // Turn LED off
        set_led_state(name, false).expect("failed to turn off LED");
        led.reload();
        assert_eq!(led.current(), 0, "LED is not turned off");
        clean_up();
    }

    #[test]
    fn get_state_on() {
        clean_up();
        let name = "generic";
        setup_test_env(&[name], 1, 1);
        assert!(
            super::get_led_state(name).unwrap(),
            "led state should return true, but returned false"
        );
        clean_up();
    }

    #[test]
    fn get_state_off() {
        clean_up();
        let name = "generic";
        setup_test_env(&[name], 0, 1);
        assert!(
            !super::get_led_state(name).unwrap(),
            "led state should return false, but returned true"
        );
        clean_up();
    }

    #[test]
    fn set_value() {
        clean_up();
        let name = "generic";
        setup_test_env(&[name], 0, 255);
        let LedType::Dimmable(mut led) = Led::new(name.into()).expect("failed to initialize LED")
        else {
            unreachable!()
        };
        let values = [0, 1, 2, 3, u8::MAX];
        for val in values {
            set_led_value(name, val).expect("failed to set led value");
            led.reload();
            assert_eq!(led.current(), val);
        }
        clean_up();
    }
}