ws2812_esp32_rmt_driver/
lib_smart_leds.rs

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
//! smart-leds driver wrapper API.

use crate::driver::color::{LedPixelColor, LedPixelColorGrb24, LedPixelColorImpl};
use crate::driver::{Ws2812Esp32RmtDriver, Ws2812Esp32RmtDriverError};
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::vec::Vec;
use core::marker::PhantomData;
#[cfg(feature = "alloc")]
use smart_leds_trait::SmartLedsWrite;
use smart_leds_trait::{RGB8, RGBW};

#[cfg(not(target_vendor = "espressif"))]
use crate::mock::esp_idf_hal;
use esp_idf_hal::{gpio::OutputPin, peripheral::Peripheral, rmt::RmtChannel};

/// 8-bit RGBW (RGB + white)
pub type RGBW8 = RGBW<u8, u8>;

impl<
        const N: usize,
        const R_ORDER: usize,
        const G_ORDER: usize,
        const B_ORDER: usize,
        const W_ORDER: usize,
    > From<RGB8> for LedPixelColorImpl<N, R_ORDER, G_ORDER, B_ORDER, W_ORDER>
{
    fn from(x: RGB8) -> Self {
        Self::new_with_rgb(x.r, x.g, x.b)
    }
}

impl<
        const N: usize,
        const R_ORDER: usize,
        const G_ORDER: usize,
        const B_ORDER: usize,
        const W_ORDER: usize,
    > From<RGBW8> for LedPixelColorImpl<N, R_ORDER, G_ORDER, B_ORDER, W_ORDER>
{
    fn from(x: RGBW8) -> Self {
        Self::new_with_rgbw(x.r, x.g, x.b, x.a.0)
    }
}

/// ws2812-like smart led driver wrapper providing smart-leds API
///
/// This is a generalization to handle variants such as SK6812-RGBW 4-color LED.
/// Use [`Ws2812Esp32Rmt`] for typical RGB LED (WS2812B/SK6812) consisting of 8-bit GRB (total 24-bit pixel).
///
/// # Examples
///
/// ```
/// #[cfg(not(target_vendor = "espressif"))]
/// use ws2812_esp32_rmt_driver::mock::esp_idf_hal;
///
/// use esp_idf_hal::peripherals::Peripherals;
/// use smart_leds::{SmartLedsWrite, White};
/// use ws2812_esp32_rmt_driver::{LedPixelEsp32Rmt, RGBW8};
/// use ws2812_esp32_rmt_driver::driver::color::LedPixelColorGrbw32;
///
/// let peripherals = Peripherals::take().unwrap();
/// let led_pin = peripherals.pins.gpio26;
/// let channel = peripherals.rmt.channel0;
/// let mut ws2812 = LedPixelEsp32Rmt::<RGBW8, LedPixelColorGrbw32>::new(channel, led_pin).unwrap();
///
/// let pixels = std::iter::repeat(RGBW8 {r: 0, g: 0, b: 0, a: White(30)}).take(25);
/// ws2812.write(pixels).unwrap();
/// ```
pub struct LedPixelEsp32Rmt<'d, CSmart, CDev>
where
    CDev: LedPixelColor + From<CSmart>,
{
    driver: Ws2812Esp32RmtDriver<'d>,
    phantom: PhantomData<(CSmart, CDev)>,
}

impl<'d, CSmart, CDev> LedPixelEsp32Rmt<'d, CSmart, CDev>
where
    CDev: LedPixelColor + From<CSmart>,
{
    /// Create a new driver wrapper.
    ///
    /// `channel` shall be different between different `pin`.
    pub fn new<C: RmtChannel>(
        channel: impl Peripheral<P = C> + 'd,
        pin: impl Peripheral<P = impl OutputPin> + 'd,
    ) -> Result<Self, Ws2812Esp32RmtDriverError> {
        let driver = Ws2812Esp32RmtDriver::<'d>::new(channel, pin)?;
        Ok(Self {
            driver,
            phantom: Default::default(),
        })
    }
}

impl<
        'd,
        CSmart,
        const N: usize,
        const R_ORDER: usize,
        const G_ORDER: usize,
        const B_ORDER: usize,
        const W_ORDER: usize,
    > LedPixelEsp32Rmt<'d, CSmart, LedPixelColorImpl<N, R_ORDER, G_ORDER, B_ORDER, W_ORDER>>
where
    LedPixelColorImpl<N, R_ORDER, G_ORDER, B_ORDER, W_ORDER>: From<CSmart>,
{
    /// Writes pixel data from a color sequence to the driver without data copy
    ///
    /// # Errors
    ///
    /// Returns an error if an RMT driver error occurred.
    pub fn write_nocopy<T, I>(&mut self, iterator: T) -> Result<(), Ws2812Esp32RmtDriverError>
    where
        T: IntoIterator<Item = I>,
        I: Into<CSmart>,
        <T as IntoIterator>::IntoIter: Send,
    {
        self.driver
            .write_blocking(iterator.into_iter().flat_map(|color| {
                let c =
                    LedPixelColorImpl::<N, R_ORDER, G_ORDER, B_ORDER, W_ORDER>::from(color.into());
                c.0
            }))?;
        Ok(())
    }
}

#[cfg(feature = "alloc")]
impl<'d, CSmart, CDev> SmartLedsWrite for LedPixelEsp32Rmt<'d, CSmart, CDev>
where
    CDev: LedPixelColor + From<CSmart>,
{
    type Error = Ws2812Esp32RmtDriverError;
    type Color = CSmart;

    /// Writes pixel data from a color sequence to the driver
    ///
    /// # Errors
    ///
    /// Returns an error if an RMT driver error occurred.
    fn write<T, I>(&mut self, iterator: T) -> Result<(), Self::Error>
    where
        T: IntoIterator<Item = I>,
        I: Into<Self::Color>,
    {
        let pixel_data = iterator.into_iter().fold(Vec::new(), |mut vec, color| {
            vec.extend_from_slice(CDev::from(color.into()).as_ref());
            vec
        });
        self.driver.write_blocking(pixel_data.into_iter())?;
        Ok(())
    }
}

/// 8-bit GRB (total 24-bit pixel) LED driver wrapper providing smart-leds API,
/// Typical RGB LED (WS2812B/SK6812) driver wrapper providing smart-leds API
///
/// # Examples
///
/// ```
/// #[cfg(not(target_vendor = "espressif"))]
/// use ws2812_esp32_rmt_driver::mock::esp_idf_hal;
///
/// use esp_idf_hal::peripherals::Peripherals;
/// use smart_leds::{RGB8, SmartLedsWrite};
/// use ws2812_esp32_rmt_driver::Ws2812Esp32Rmt;
///
/// let peripherals = Peripherals::take().unwrap();
/// let led_pin = peripherals.pins.gpio27;
/// let channel = peripherals.rmt.channel0;
/// let mut ws2812 = Ws2812Esp32Rmt::new(channel, led_pin).unwrap();
///
/// let pixels = std::iter::repeat(RGB8::new(30, 0, 0)).take(25);
/// ws2812.write(pixels).unwrap();
/// ```
pub type Ws2812Esp32Rmt<'d> = LedPixelEsp32Rmt<'d, RGB8, LedPixelColorGrb24>;

#[cfg(test)]
mod test {
    use super::*;
    use crate::mock::esp_idf_hal::peripherals::Peripherals;

    #[test]
    fn test_ws2812_esp32_rmt_smart_leds() {
        let sample_data = [RGB8::new(0x00, 0x01, 0x02), RGB8::new(0x03, 0x04, 0x05)];
        let expected_values: [u8; 6] = [0x01, 0x00, 0x02, 0x04, 0x03, 0x05];

        let peripherals = Peripherals::take().unwrap();
        let led_pin = peripherals.pins.gpio0;
        let channel = peripherals.rmt.channel0;

        let mut ws2812 = Ws2812Esp32Rmt::new(channel, led_pin).unwrap();
        ws2812.write(sample_data.iter().cloned()).unwrap();
        assert_eq!(ws2812.driver.pixel_data.unwrap(), &expected_values);
    }
}