use core::marker::PhantomData;
use heapless::Vec;
use crate::{LedPixel, LedStripError, LedStripResult, SingleWireProtocol};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RefreshError<CodecError, BackendError> {
Codec(CodecError),
Backend(BackendError),
}
impl<CodecError, BackendError> core::fmt::Display for RefreshError<CodecError, BackendError>
where
CodecError: core::fmt::Display,
BackendError: core::fmt::Display,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Codec(inner) => write!(f, "codec error: {inner}"),
Self::Backend(inner) => write!(f, "backend error: {inner}"),
}
}
}
impl<CodecError, BackendError> core::error::Error for RefreshError<CodecError, BackendError>
where
CodecError: core::error::Error + 'static,
BackendError: core::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Codec(inner) => Some(inner),
Self::Backend(inner) => Some(inner),
}
}
}
pub trait TransportBackend {
type Word: Copy;
type Error;
fn transmit(&mut self, words: &[Self::Word]) -> Result<(), Self::Error>;
}
pub trait WireCodec<P, Proto, Word>
where
P: LedPixel,
Proto: SingleWireProtocol<P>,
Word: Copy,
{
type EncodeError;
fn encoded_len(&self, pixel_count: usize) -> usize;
fn encode<const TX_CAPACITY: usize>(
&self,
color_order: P::Order,
pixels: &[P],
out: &mut Vec<Word, TX_CAPACITY>,
) -> LedStripResult<(), Self::EncodeError>;
}
pub struct LedStrip<P, Proto, Codec, Backend, const TX_CAPACITY: usize>
where
P: LedPixel,
Proto: SingleWireProtocol<P>,
Codec: WireCodec<P, Proto, Backend::Word>,
Backend: TransportBackend,
{
color_order: P::Order,
codec: Codec,
backend: Backend,
tx_buf: Vec<Backend::Word, TX_CAPACITY>,
_proto: PhantomData<Proto>,
}
impl<P, Proto, Codec, Backend, const TX_CAPACITY: usize>
LedStrip<P, Proto, Codec, Backend, TX_CAPACITY>
where
P: LedPixel,
Proto: SingleWireProtocol<P>,
Codec: WireCodec<P, Proto, Backend::Word>,
Backend: TransportBackend,
{
#[must_use]
pub fn new(color_order: P::Order, codec: Codec, backend: Backend) -> Self {
Self {
color_order,
codec,
backend,
tx_buf: Vec::new(),
_proto: PhantomData,
}
}
pub fn write(
&mut self,
pixels: &[P],
) -> LedStripResult<(), RefreshError<Codec::EncodeError, Backend::Error>> {
self.codec
.encode(self.color_order, pixels, &mut self.tx_buf)
.map_err(|e| e.map_operation(RefreshError::Codec))?;
self.backend
.transmit(self.tx_buf.as_slice())
.map_err(|error| LedStripError::Operation(RefreshError::Backend(error)))
}
#[must_use]
pub fn into_parts(self) -> (Codec, Backend) {
(self.codec, self.backend)
}
}
impl<P, Proto, Codec, Backend, const TX_CAPACITY: usize> core::fmt::Debug
for LedStrip<P, Proto, Codec, Backend, TX_CAPACITY>
where
P: LedPixel,
P::Order: core::fmt::Debug,
Proto: SingleWireProtocol<P>,
Codec: WireCodec<P, Proto, Backend::Word> + core::fmt::Debug,
Backend: TransportBackend + core::fmt::Debug,
Backend::Word: core::fmt::Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("LedStrip")
.field("color_order", &self.color_order)
.field("codec", &self.codec)
.field("backend", &self.backend)
.field("tx_buf", &self.tx_buf)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
struct CodecErr;
impl core::fmt::Display for CodecErr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("encode failed")
}
}
impl core::error::Error for CodecErr {}
#[derive(Debug)]
struct BackendErr;
impl core::fmt::Display for BackendErr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("bus busy")
}
}
impl core::error::Error for BackendErr {}
#[test]
fn display_codec_variant_wraps_inner() {
let e: RefreshError<CodecErr, BackendErr> = RefreshError::Codec(CodecErr);
let s = e.to_string();
assert!(s.starts_with("codec error:"), "{s}");
assert!(s.contains("encode failed"), "{s}");
}
#[test]
fn display_backend_variant_wraps_inner() {
let e: RefreshError<CodecErr, BackendErr> = RefreshError::Backend(BackendErr);
let s = e.to_string();
assert!(s.starts_with("backend error:"), "{s}");
assert!(s.contains("bus busy"), "{s}");
}
#[test]
fn source_returns_inner_for_both_variants() {
let c: RefreshError<CodecErr, BackendErr> = RefreshError::Codec(CodecErr);
assert_eq!(
core::error::Error::source(&c).unwrap().to_string(),
"encode failed"
);
let b: RefreshError<CodecErr, BackendErr> = RefreshError::Backend(BackendErr);
assert_eq!(
core::error::Error::source(&b).unwrap().to_string(),
"bus busy"
);
}
#[cfg(feature = "spi")]
mod spi_tests {
use super::*;
use crate::{Rgb, RgbOrder, SpiCodec, SpiEncodingPlan, Ws2812B};
use core::cell::Cell;
#[derive(Debug)]
struct MockBackend(Cell<usize>);
impl MockBackend {
fn new() -> Self {
Self(Cell::new(0))
}
fn last_tx_len(&self) -> usize {
self.0.get()
}
}
impl TransportBackend for MockBackend {
type Word = u8;
type Error = core::convert::Infallible;
fn transmit(&mut self, words: &[Self::Word]) -> Result<(), Self::Error> {
self.0.set(words.len());
Ok(())
}
}
type TestStrip = LedStrip<Rgb, Ws2812B, SpiCodec<Rgb, Ws2812B>, MockBackend, 256>;
fn make_codec() -> SpiCodec<Rgb, Ws2812B> {
SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap()
}
fn make_strip() -> TestStrip {
TestStrip::new(RgbOrder::Grb, make_codec(), MockBackend::new())
}
#[test]
fn new_constructs_without_error() {
let strip = make_strip();
let _ = format!("{strip:?}");
}
#[test]
fn write_transmits_encoded_data() {
let mut strip = make_strip();
strip
.write(&[
Rgb::new(255, 0, 0),
Rgb::new(0, 255, 0),
Rgb::new(0, 0, 255),
])
.unwrap();
assert!(
strip.backend.last_tx_len() > 0,
"expected non-zero transmit length"
);
}
#[test]
fn write_with_zero_pixels_sends_reset_only() {
let mut strip = make_strip();
strip.write(&[]).unwrap();
assert!(strip.backend.last_tx_len() > 0);
}
#[test]
fn write_rejects_buffer_too_small() {
type TinyStrip = LedStrip<Rgb, Ws2812B, SpiCodec<Rgb, Ws2812B>, MockBackend, 5>;
let mut strip = TinyStrip::new(RgbOrder::Grb, make_codec(), MockBackend::new());
let err = strip
.write(&[Rgb::new(0, 0, 0), Rgb::new(0, 0, 0)])
.unwrap_err();
assert!(matches!(err, LedStripError::BufferTooSmall { .. }));
}
#[test]
fn into_parts_returns_owned_codec_and_backend() {
let strip = make_strip();
let (codec, _backend) = strip.into_parts();
assert_eq!(codec.plan().spi_hz(), 2_400_000);
}
#[test]
fn debug_output_contains_fields() {
let strip = make_strip();
let s = format!("{strip:?}");
assert!(s.contains("LedStrip"), "{s}");
assert!(s.contains("color_order"), "{s}");
assert!(s.contains("codec"), "{s}");
assert!(s.contains("backend"), "{s}");
assert!(s.contains("tx_buf"), "{s}");
}
}
}