zephyr/device/
led.rs

1//! Device wrappers for Zephyr LED controllers.
2
3use super::{NoStatic, Unique};
4use crate::{error::to_result_void, raw, Result};
5
6/// A Zephyr LED controller device.
7#[allow(dead_code)]
8pub struct LedController {
9    pub(crate) device: *const raw::device,
10}
11
12impl LedController {
13    /// Constructor, intended to be called by devicetree generated code.
14    #[allow(dead_code)]
15    pub(crate) unsafe fn new(
16        unique: &Unique,
17        _static: &NoStatic,
18        device: *const raw::device,
19    ) -> Option<LedController> {
20        if !unique.once() {
21            return None;
22        }
23
24        Some(LedController { device })
25    }
26
27    /// Verify that the underlying LED controller is ready for use.
28    pub fn is_ready(&self) -> bool {
29        unsafe { raw::device_is_ready(self.device) }
30    }
31}
32
33/// A single logical LED exposed by a Zephyr LED controller.
34///
35/// This wrapper maps to Zephyr's `led_*` API. Devicetree child nodes of a `pwm-leds` controller
36/// become instances of this type.
37#[allow(dead_code)]
38pub struct Led {
39    pub(crate) device: *const raw::device,
40    pub(crate) index: u32,
41}
42
43impl core::fmt::Debug for Led {
44    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
45        f.debug_struct("Led")
46            .field("device", &self.device)
47            .field("index", &self.index)
48            .finish()
49    }
50}
51
52// SAFETY: `Led` holds a raw device pointer and an LED index with no thread-affine Rust state.
53unsafe impl Send for Led {}
54
55impl Led {
56    /// Constructor, intended to be called by devicetree generated code.
57    #[allow(dead_code)]
58    pub(crate) unsafe fn new(
59        unique: &Unique,
60        _static: &NoStatic,
61        device: *const raw::device,
62        index: u32,
63    ) -> Option<Led> {
64        if !unique.once() {
65            return None;
66        }
67
68        Some(Led { device, index })
69    }
70
71    /// Verify that the underlying LED controller is ready for use.
72    pub fn is_ready(&self) -> bool {
73        unsafe { raw::device_is_ready(self.device) }
74    }
75
76    /// Set the LED brightness as a percentage in the range `0..=100`.
77    pub fn set_brightness(&mut self, value: u8) -> Result<()> {
78        to_result_void(unsafe { raw::led_set_brightness(self.device, self.index, value) })
79    }
80
81    /// Turn the LED fully on.
82    pub fn on(&mut self) -> Result<()> {
83        to_result_void(unsafe { raw::led_on(self.device, self.index) })
84    }
85
86    /// Turn the LED fully off.
87    pub fn off(&mut self) -> Result<()> {
88        to_result_void(unsafe { raw::led_off(self.device, self.index) })
89    }
90
91    /// Blink the LED using millisecond delays.
92    pub fn blink(&mut self, delay_on: u32, delay_off: u32) -> Result<()> {
93        to_result_void(unsafe { raw::led_blink(self.device, self.index, delay_on, delay_off) })
94    }
95}