Skip to main content

led_strip/
api.rs

1use core::marker::PhantomData;
2
3use heapless::Vec;
4
5use crate::{LedPixel, LedStripError, LedStripResult, SingleWireProtocol};
6
7/// Unified error type returned by [`LedStrip::write`].
8///
9/// Wraps either a codec-level error (encoding failure) or a backend-level
10/// error (transmission failure), so callers see a single error shape
11/// regardless of which layer failed.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum RefreshError<CodecError, BackendError> {
15    /// The codec failed to encode the pixel data into transport words.
16    Codec(CodecError),
17    /// The transport backend failed to transmit the encoded words.
18    Backend(BackendError),
19}
20
21impl<CodecError, BackendError> core::fmt::Display for RefreshError<CodecError, BackendError>
22where
23    CodecError: core::fmt::Display,
24    BackendError: core::fmt::Display,
25{
26    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
27        match self {
28            Self::Codec(inner) => write!(f, "codec error: {inner}"),
29            Self::Backend(inner) => write!(f, "backend error: {inner}"),
30        }
31    }
32}
33
34impl<CodecError, BackendError> core::error::Error for RefreshError<CodecError, BackendError>
35where
36    CodecError: core::error::Error + 'static,
37    BackendError: core::error::Error + 'static,
38{
39    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
40        match self {
41            Self::Codec(inner) => Some(inner),
42            Self::Backend(inner) => Some(inner),
43        }
44    }
45}
46
47/// Low-level transport for encoded LED data.
48///
49/// A backend owns a hardware peripheral (SPI bus, or a future peripheral such
50/// as an RMT channel or PIO state machine) and knows how to push pre-encoded
51/// words onto the wire. It does **not** understand LED protocol timings —/// that is the codec's job.
52///
53/// # Implementing
54///
55/// Backends are stateless beyond the peripheral handle. [`transmit`](Self::transmit)
56/// should block until the entire buffer has been sent, then return.
57/// Reset/latch timing is handled by the codec (appended as trailing fill bytes).
58pub trait TransportBackend {
59    /// The unit of transmission. SPI uses `u8`; future backends (RMT, PIO)
60    /// may use `u32`.
61    type Word: Copy;
62    /// Backend-specific error (e.g. `SPI::Error`).
63    type Error;
64
65    /// Sends `words` over the wire. Blocks until transmission completes.
66    fn transmit(&mut self, words: &[Self::Word]) -> Result<(), Self::Error>;
67}
68
69/// Encodes LED pixel data into transport words for a specific protocol.
70///
71/// A codec understands a particular encoding scheme (SPI bit-banging, or
72/// future schemes like RMT pulse codes or PIO FIFO words) and translates raw
73/// pixel bytes into the word stream that a [`TransportBackend`] can transmit.
74///
75/// The generic parameters lock a `<pixel, protocol, codec>` triple at compile
76/// time —you cannot accidentally drive SK6812 pixels with a WS2812B encoding plan.
77///
78/// # Implementing
79///
80/// - [`encoded_len`](Self::encoded_len) must return the exact number of
81///   `Word`s that [`encode`](Self::encode) will produce for the given pixel
82///   count (including reset/trailer). This is used for capacity checks before encoding.
83/// - [`encode`](Self::encode) writes into a caller-supplied `Vec` to avoid
84///   heap allocation.
85pub trait WireCodec<P, Proto, Word>
86where
87    P: LedPixel,
88    Proto: SingleWireProtocol<P>,
89    Word: Copy,
90{
91    /// Error type produced by [`encode`](Self::encode).
92    ///
93    /// For `SpiCodec` this is `SpiEncodeError`,
94    /// which reports only internal-consistency failures (a codec logic bug)
95    /// rather than user-input errors such as buffer overflows.
96    type EncodeError;
97
98    /// Returns the exact number of `Word`s that [`encode`](Self::encode) will
99    /// produce for `pixel_count` pixels. Includes payload + reset/trailer overhead.
100    fn encoded_len(&self, pixel_count: usize) -> usize;
101
102    /// Encodes `pixels` into transport words, appending to `out`.
103    ///
104    /// The buffer is cleared before encoding begins, so callers may safely
105    /// reuse a buffer across multiple `encode` calls without manual `out.clear()`.
106    fn encode<const TX_CAPACITY: usize>(
107        &self,
108        color_order: P::Order,
109        pixels: &[P],
110        out: &mut Vec<Word, TX_CAPACITY>,
111    ) -> LedStripResult<(), Self::EncodeError>;
112}
113
114/// Stateless driver for a single-wire addressable LED strip.
115///
116/// Owns a codec, a transport backend, and a reusable transmission buffer.
117/// This driver does **not** cache a frame buffer —each [`write`](Self::write) call accepts a dynamic-length pixel slice,
118/// encodes it, and transmits it to the strip in a single operation.
119///
120/// # Type parameters
121///
122/// | Parameter | Role |
123/// |-----------|------|
124/// | `P` | Pixel type ([`crate::Rgb`], [`crate::Rgbw`], [`crate::Rgb16`]) |
125/// | `Proto` | Protocol marker ([`crate::Ws2812B`], [`crate::Sk6812`], [`crate::Ws2811`], [`crate::Ws2816`]) |
126/// | `Codec` | Encoding scheme (currently `SpiCodec`; future backends may provide their own) |
127/// | `Backend` | Transport layer (currently `SpiBackend`; future backends may provide their own) |
128/// | `TX_CAPACITY` | Compile-time upper bound on transport buffer size (in `Word`s) |
129pub struct LedStrip<P, Proto, Codec, Backend, const TX_CAPACITY: usize>
130where
131    P: LedPixel,
132    Proto: SingleWireProtocol<P>,
133    Codec: WireCodec<P, Proto, Backend::Word>,
134    Backend: TransportBackend,
135{
136    color_order: P::Order,
137    codec: Codec,
138    backend: Backend,
139    tx_buf: Vec<Backend::Word, TX_CAPACITY>,
140    _proto: PhantomData<Proto>,
141}
142
143impl<P, Proto, Codec, Backend, const TX_CAPACITY: usize>
144    LedStrip<P, Proto, Codec, Backend, TX_CAPACITY>
145where
146    P: LedPixel,
147    Proto: SingleWireProtocol<P>,
148    Codec: WireCodec<P, Proto, Backend::Word>,
149    Backend: TransportBackend,
150{
151    /// Constructs the driver.
152    ///
153    /// `color_order` determines the on-wire byte order (e.g. `RgbOrder::Grb`
154    /// for WS2812B). Use the protocol's `DEFAULT_COLOR_ORDER` associated
155    /// constant for the typical wiring.
156    ///
157    /// No capacity validation is performed here —[`write`](Self::write)
158    /// checks `TX_CAPACITY` on each call and returns
159    /// [`BufferTooSmall`](LedStripError::BufferTooSmall) if the encoded
160    /// frame exceeds the buffer.
161    #[must_use]
162    pub fn new(color_order: P::Order, codec: Codec, backend: Backend) -> Self {
163        Self {
164            color_order,
165            codec,
166            backend,
167            tx_buf: Vec::new(),
168            _proto: PhantomData,
169        }
170    }
171
172    /// Encodes `pixels` and transmits them to the LED strip in one call.
173    ///
174    /// Returns [`LedStripError::BufferTooSmall`] if the encoded payload
175    /// (including reset/trailer) exceeds `TX_CAPACITY`. All other errors
176    /// are wrapped in [`RefreshError`].
177    ///
178    /// The pixel count is dynamic —pass any slice length supported by your
179    /// `TX_CAPACITY`.
180    pub fn write(
181        &mut self,
182        pixels: &[P],
183    ) -> LedStripResult<(), RefreshError<Codec::EncodeError, Backend::Error>> {
184        self.codec
185            .encode(self.color_order, pixels, &mut self.tx_buf)
186            .map_err(|e| e.map_operation(RefreshError::Codec))?;
187
188        self.backend
189            .transmit(self.tx_buf.as_slice())
190            .map_err(|error| LedStripError::Operation(RefreshError::Backend(error)))
191    }
192
193    /// Destructures the driver, returning ownership of the codec and backend.
194    /// Useful for reusing the backend (e.g. SPI bus) or the codec
195    /// after the LED strip is no longer needed.
196    #[must_use]
197    pub fn into_parts(self) -> (Codec, Backend) {
198        (self.codec, self.backend)
199    }
200}
201
202impl<P, Proto, Codec, Backend, const TX_CAPACITY: usize> core::fmt::Debug
203    for LedStrip<P, Proto, Codec, Backend, TX_CAPACITY>
204where
205    P: LedPixel,
206    P::Order: core::fmt::Debug,
207    Proto: SingleWireProtocol<P>,
208    Codec: WireCodec<P, Proto, Backend::Word> + core::fmt::Debug,
209    Backend: TransportBackend + core::fmt::Debug,
210    Backend::Word: core::fmt::Debug,
211{
212    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
213        f.debug_struct("LedStrip")
214            .field("color_order", &self.color_order)
215            .field("codec", &self.codec)
216            .field("backend", &self.backend)
217            .field("tx_buf", &self.tx_buf)
218            .finish()
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[derive(Debug)]
227    struct CodecErr;
228    impl core::fmt::Display for CodecErr {
229        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
230            f.write_str("encode failed")
231        }
232    }
233    impl core::error::Error for CodecErr {}
234
235    #[derive(Debug)]
236    struct BackendErr;
237    impl core::fmt::Display for BackendErr {
238        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
239            f.write_str("bus busy")
240        }
241    }
242    impl core::error::Error for BackendErr {}
243
244    #[test]
245    fn display_codec_variant_wraps_inner() {
246        let e: RefreshError<CodecErr, BackendErr> = RefreshError::Codec(CodecErr);
247        let s = e.to_string();
248        assert!(s.starts_with("codec error:"), "{s}");
249        assert!(s.contains("encode failed"), "{s}");
250    }
251
252    #[test]
253    fn display_backend_variant_wraps_inner() {
254        let e: RefreshError<CodecErr, BackendErr> = RefreshError::Backend(BackendErr);
255        let s = e.to_string();
256        assert!(s.starts_with("backend error:"), "{s}");
257        assert!(s.contains("bus busy"), "{s}");
258    }
259
260    #[test]
261    fn source_returns_inner_for_both_variants() {
262        let c: RefreshError<CodecErr, BackendErr> = RefreshError::Codec(CodecErr);
263        assert_eq!(
264            core::error::Error::source(&c).unwrap().to_string(),
265            "encode failed"
266        );
267
268        let b: RefreshError<CodecErr, BackendErr> = RefreshError::Backend(BackendErr);
269        assert_eq!(
270            core::error::Error::source(&b).unwrap().to_string(),
271            "bus busy"
272        );
273    }
274
275    // ── LedStrip integration tests ──────────────────────────────────
276
277    #[cfg(feature = "spi")]
278    mod spi_tests {
279        use super::*;
280        use crate::{Rgb, RgbOrder, SpiCodec, SpiEncodingPlan, Ws2812B};
281        use core::cell::Cell;
282
283        /// Mock backend that records the byte count of the last transmit call.
284        #[derive(Debug)]
285        struct MockBackend(Cell<usize>);
286
287        impl MockBackend {
288            fn new() -> Self {
289                Self(Cell::new(0))
290            }
291            fn last_tx_len(&self) -> usize {
292                self.0.get()
293            }
294        }
295
296        impl TransportBackend for MockBackend {
297            type Word = u8;
298            type Error = core::convert::Infallible;
299
300            fn transmit(&mut self, words: &[Self::Word]) -> Result<(), Self::Error> {
301                self.0.set(words.len());
302                Ok(())
303            }
304        }
305
306        type TestStrip = LedStrip<Rgb, Ws2812B, SpiCodec<Rgb, Ws2812B>, MockBackend, 256>;
307
308        fn make_codec() -> SpiCodec<Rgb, Ws2812B> {
309            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap()
310        }
311
312        fn make_strip() -> TestStrip {
313            TestStrip::new(RgbOrder::Grb, make_codec(), MockBackend::new())
314        }
315
316        #[test]
317        fn new_constructs_without_error() {
318            let strip = make_strip();
319            // Verify default state
320            let _ = format!("{strip:?}");
321        }
322
323        #[test]
324        fn write_transmits_encoded_data() {
325            let mut strip = make_strip();
326            strip
327                .write(&[
328                    Rgb::new(255, 0, 0),
329                    Rgb::new(0, 255, 0),
330                    Rgb::new(0, 0, 255),
331                ])
332                .unwrap();
333            assert!(
334                strip.backend.last_tx_len() > 0,
335                "expected non-zero transmit length"
336            );
337        }
338
339        #[test]
340        fn write_with_zero_pixels_sends_reset_only() {
341            let mut strip = make_strip();
342            strip.write(&[]).unwrap();
343            // Zero pixels still produce reset/latch bytes
344            assert!(strip.backend.last_tx_len() > 0);
345        }
346
347        #[test]
348        fn write_rejects_buffer_too_small() {
349            type TinyStrip = LedStrip<Rgb, Ws2812B, SpiCodec<Rgb, Ws2812B>, MockBackend, 5>;
350            let mut strip = TinyStrip::new(RgbOrder::Grb, make_codec(), MockBackend::new());
351            // 2 pixels × 9 payload bytes + reset ≫ 5
352            let err = strip
353                .write(&[Rgb::new(0, 0, 0), Rgb::new(0, 0, 0)])
354                .unwrap_err();
355            assert!(matches!(err, LedStripError::BufferTooSmall { .. }));
356        }
357
358        #[test]
359        fn into_parts_returns_owned_codec_and_backend() {
360            let strip = make_strip();
361            let (codec, _backend) = strip.into_parts();
362            // Verify the codec still works
363            assert_eq!(codec.plan().spi_hz(), 2_400_000);
364        }
365
366        #[test]
367        fn debug_output_contains_fields() {
368            let strip = make_strip();
369            let s = format!("{strip:?}");
370            assert!(s.contains("LedStrip"), "{s}");
371            assert!(s.contains("color_order"), "{s}");
372            assert!(s.contains("codec"), "{s}");
373            assert!(s.contains("backend"), "{s}");
374            assert!(s.contains("tx_buf"), "{s}");
375        }
376    }
377}