1use core::marker::PhantomData;
2
3use heapless::Vec;
4
5use crate::{LedPixel, LedStripError, LedStripResult, SingleWireProtocol};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum RefreshError<CodecError, BackendError> {
15 Codec(CodecError),
17 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
47pub trait TransportBackend {
59 type Word: Copy;
62 type Error;
64
65 fn transmit(&mut self, words: &[Self::Word]) -> Result<(), Self::Error>;
67}
68
69pub trait WireCodec<P, Proto, Word>
86where
87 P: LedPixel,
88 Proto: SingleWireProtocol<P>,
89 Word: Copy,
90{
91 type EncodeError;
97
98 fn encoded_len(&self, pixel_count: usize) -> usize;
101
102 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
114pub 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 #[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 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 #[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 #[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 #[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 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 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 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 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}