refactor(led): drive the strip through the smart-leds traits

Replaces the hand-rolled Rgb type, HSV conversion and brightness scaling
with RGB8, hsv2rgb, gamma and brightness from smart-leds, and exposes the
driver as SmartLedsWriteAsync. The RMT symbol encoding stays in-tree: no
upstream RMT driver currently targets esp-hal 1.1.
This commit is contained in:
Matt Spencer committed 2026-10-17 15:42:13 +01:00
1 parent bb81182daa
commit e021ab751a
6 files changed
+97 -85

No files matched your search

Generated
+26
View File
@@ -1540,6 +1540,12 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rgb"
version = "0.8.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
[[package]]
name = "riscv"
version = "0.15.0"
@@ -1702,6 +1708,24 @@ version = "1.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
[[package]]
name = "smart-leds"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66df34e571fa9993fa6f99131a374d58ca3d694b75f9baac93458fe0d6057bf0"
dependencies = [
"smart-leds-trait",
]
[[package]]
name = "smart-leds-trait"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7f4441a131924d58da6b83a7ad765c460e64630cce504376c3a87a2558c487f"
dependencies = [
"rgb",
]
[[package]]
name = "smart-light"
version = "0.1.0"
@@ -1720,6 +1744,8 @@ dependencies = [
"esp-rtos",
"esp-storage",
"log",
"smart-leds",
"smart-leds-trait",
"static_cell",
"zigbee",
"zigbee-cluster-library",
+7
View File
@@ -35,6 +35,13 @@ embassy-embedded-hal = "0.5.0"
static_cell = "2.1"
log = "0.4"
# LED colour types, the async write trait, and the gamma/brightness helpers.
# The driver below encodes RMT symbols itself because no upstream RMT driver
# currently targets esp-hal 1.1: ws2812-esp32-rmt-driver is esp-idf only, and
# esp-hal-smartled pins ~1.0 (0.17) or ~1.2 (0.18).
smart-leds = "0.4"
smart-leds-trait = "0.3"
# vendored upstream: the lighting cluster is not implemented there yet, so the
# path dependency lets us add it in-tree and upstream it later
zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"] }
+1 -1
View File
@@ -57,7 +57,7 @@ pub async fn encoder_task(mut a: Input<'static>, mut b: Input<'static>) {
continue;
}
let delta = TRANSITIONS[usize::from((previous << 2) | current)];
let delta = TRANSITIONS[(previous << 2) | current];
previous = current;
if delta == 0 {
continue;
+27 -41
View File
@@ -6,15 +6,19 @@
use core::sync::atomic::AtomicBool;
use core::sync::atomic::AtomicU8;
use core::sync::atomic::AtomicU16;
use core::sync::atomic::Ordering;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use smart_leds::RGB8;
use smart_leds::SmartLedsWriteAsync;
use smart_leds::brightness as scale_brightness;
use smart_leds::gamma;
use smart_leds::hsv::Hsv;
use smart_leds::hsv::hsv2rgb;
use crate::config::LED_COUNT;
use crate::config::MAX_DUTY;
use crate::ws2812::Rgb;
use crate::ws2812::Ws2812;
/// What a turn of the encoder adjusts.
@@ -26,7 +30,7 @@ pub enum Mode {
static ON: AtomicBool = AtomicBool::new(false);
static BRIGHTNESS: AtomicU8 = AtomicU8::new(128);
static HUE: AtomicU16 = AtomicU16::new(0);
static HUE: AtomicU8 = AtomicU8::new(0);
static HUE_MODE: AtomicBool = AtomicBool::new(false);
static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
@@ -57,13 +61,13 @@ pub fn adjust_brightness(delta: i16) {
DIRTY.signal(());
}
pub fn hue() -> u16 {
pub fn hue() -> u8 {
HUE.load(Ordering::Relaxed)
}
/// Hue is a circle, so this one wraps.
/// Hue is a circle, so this one wraps. `smart-leds` spans it over a full u8.
pub fn adjust_hue(delta: i16) {
let hue = (i32::from(hue()) + i32::from(delta)).rem_euclid(360) as u16;
let hue = hue().wrapping_add_signed(delta as i8);
HUE.store(hue, Ordering::Relaxed);
DIRTY.signal(());
}
@@ -83,47 +87,29 @@ pub fn toggle_mode() -> Mode {
#[embassy_executor::task]
pub async fn render_task(mut strip: Ws2812<'static>) {
let mut frame = [Rgb::BLACK; LED_COUNT];
let mut frame = [RGB8::default(); LED_COUNT];
loop {
let colour = if is_on() {
let level = (u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8;
hsv_to_rgb(hue(), 255, 255).scaled(level)
} else {
Rgb::BLACK
};
frame.fill(colour);
frame.fill(hsv2rgb(Hsv {
hue: hue(),
sat: 255,
val: 255,
}));
if let Err(e) = strip.write(&frame).await {
// off is just zero brightness, so the colour survives a power cycle of
// the strip output and comes back as it was
let level = if is_on() {
(u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8
} else {
0
};
// gamma before brightness, as smart-leds requires
let pixels = scale_brightness(gamma(frame.iter().copied()), level);
if let Err(e) = strip.write(pixels).await {
log::warn!("strip write failed: {e:?}");
}
DIRTY.wait().await;
}
}
/// `hue` in degrees, `saturation` and `value` as 0..=255.
fn hsv_to_rgb(hue: u16, saturation: u8, value: u8) -> Rgb {
if saturation == 0 {
return Rgb::new(value, value, value);
}
let sector = u32::from(hue % 360) / 60;
let offset = u32::from(hue % 360) % 60;
let v = u32::from(value);
let s = u32::from(saturation);
let p = (v * (255 - s) / 255) as u8;
let q = (v * (255 - s * offset / 60) / 255) as u8;
let t = (v * (255 - s * (60 - offset) / 60) / 255) as u8;
let v = value;
match sector {
0 => Rgb::new(v, t, p),
1 => Rgb::new(q, v, p),
2 => Rgb::new(p, v, t),
3 => Rgb::new(p, q, v),
4 => Rgb::new(t, p, v),
_ => Rgb::new(v, p, q),
}
}
+2 -2
View File
@@ -38,8 +38,8 @@ static STACK: StaticCell<Stack> = StaticCell::new();
/// Brightness units per detent.
const BRIGHTNESS_STEP: i16 = 8;
/// Degrees of hue per detent.
const HUE_STEP: i16 = 6;
/// Hue per detent, in 1/256ths of the colour circle (~5.6 degrees).
const HUE_STEP: i16 = 4;
#[esp_rtos::main]
async fn main(spawner: embassy_executor::Spawner) -> ! {
+34 -41
View File
@@ -2,12 +2,18 @@
//!
//! The RMT clock is divided to 12.5 ns per tick, so each of the 24 colour bits
//! becomes one `PulseCode` whose high and low durations encode a 0 or a 1.
//!
//! Only the symbol encoding lives here; colour types, gamma and brightness
//! come from `smart-leds`, and the strip is driven through its async write
//! trait so an upstream driver can replace this one without touching callers.
use esp_hal::Async;
use esp_hal::gpio::Level;
use esp_hal::rmt::Channel;
use esp_hal::rmt::PulseCode;
use esp_hal::rmt::Tx;
use smart_leds_trait::RGB8;
use smart_leds_trait::SmartLedsWriteAsync;
use crate::config::LED_COUNT;
@@ -20,37 +26,6 @@ const T1L: u16 = 36; // 0.45 us
/// Pulse codes for a whole frame, plus the terminating end marker.
const PULSE_COUNT: usize = LED_COUNT * 24 + 1;
/// A colour in the order the application thinks about it; the wire order
/// (green first) is applied when encoding.
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
/// Scales every channel by `level / 255`, rounding so that a non-zero
/// channel at a non-zero level never collapses to off.
#[must_use]
pub const fn scaled(self, level: u8) -> Self {
const fn scale(channel: u8, level: u8) -> u8 {
((channel as u16 * level as u16 + 127) / 255) as u8
}
Self {
r: scale(self.r, level),
g: scale(self.g, level),
b: scale(self.b, level),
}
}
}
pub struct Ws2812<'d> {
channel: Channel<'d, Async, Tx>,
pulses: [PulseCode; PULSE_COUNT],
@@ -62,13 +37,35 @@ impl<'d> Ws2812<'d> {
pulses[PULSE_COUNT - 1] = PulseCode::end_marker();
Self { channel, pulses }
}
}
/// Encodes `pixels` and clocks the frame out.
///
/// A frame shorter than the strip leaves the remaining pixels dark.
pub async fn write(&mut self, pixels: &[Rgb]) -> Result<(), esp_hal::rmt::Error> {
for (led, slot) in self.pulses[..LED_COUNT * 24].chunks_exact_mut(24).enumerate() {
let colour = pixels.get(led).copied().unwrap_or(Rgb::BLACK);
impl SmartLedsWriteAsync for Ws2812<'_> {
type Error = esp_hal::rmt::Error;
type Color = RGB8;
/// An iterator shorter than the strip leaves the remaining pixels dark; a
/// longer one is truncated.
async fn write<T, I>(&mut self, iterator: T) -> Result<(), Self::Error>
where
T: IntoIterator<Item = I>,
I: Into<Self::Color>,
{
let (slots, _) = self.pulses[..LED_COUNT * 24].as_chunks_mut::<24>();
let mut slots = slots.iter_mut();
for colour in iterator {
let Some(slot) = slots.next() else { break };
encode(colour.into(), slot);
}
for slot in slots {
encode(RGB8::default(), slot);
}
self.channel.transmit(&self.pulses).await
}
}
fn encode(colour: RGB8, slot: &mut [PulseCode; 24]) {
// WS2812B latches GRB, most significant bit first
let word = u32::from(colour.g) << 16 | u32::from(colour.r) << 8 | u32::from(colour.b);
for (bit, code) in slot.iter_mut().enumerate() {
@@ -79,7 +76,3 @@ impl<'d> Ws2812<'d> {
};
}
}
self.channel.transmit(&self.pulses).await
}
}