added modified spi_led_strip with support for WS2801 LED strips

This commit is contained in:
2026-10-30 09:10:13 +01:00
commit b4d00f8ff8
5 changed files with 264 additions and 0 deletions
@@ -0,0 +1,89 @@
#include "spi_led_strip.h"
#include "esphome/core/helpers.h"
namespace esphome::spi_led_strip {
SpiLedStrip::SpiLedStrip(uint16_t num_leds, SpiLedChipset chipset) : num_leds_(num_leds), chipset_(chipset) {
RAMAllocator<uint8_t> allocator;
#ifdef USE_SPI_LED_STRIP_WS2801
if (chipset == SpiLedChipset::SPI_LED_CHIPSET_WS2801) {
this->buffer_size_ = num_leds * 3;
} else
#endif
{
this->buffer_size_ = num_leds * 4 + 8;
}
this->buf_ = allocator.allocate(this->buffer_size_);
if (this->buf_ == nullptr) {
ESP_LOGE(TAG, "Failed to allocate buffer of size %u", this->buffer_size_);
return;
}
this->effect_data_ = allocator.allocate(num_leds);
if (this->effect_data_ == nullptr) {
ESP_LOGE(TAG, "Failed to allocate effect data of size %u", num_leds);
return;
}
#ifdef USE_SPI_LED_STRIP_WS2801
if (chipset == SpiLedChipset::SPI_LED_CHIPSET_WS2801) {
memset(this->buf_, 0, this->buffer_size_);
return;
}
#endif
memset(this->buf_, 0xFF, this->buffer_size_);
memset(this->buf_, 0, 4);
}
void SpiLedStrip::setup() {
if (this->effect_data_ == nullptr || this->buf_ == nullptr) {
this->mark_failed();
return;
}
this->spi_setup();
}
light::LightTraits SpiLedStrip::get_traits() {
auto traits = light::LightTraits();
traits.set_supported_color_modes({light::ColorMode::RGB});
return traits;
}
void SpiLedStrip::dump_config() {
esph_log_config(
TAG,
"SPI LED Strip:\n"
" Chipset: %s\n"
" LEDs: %d",
this->chipset_ == SpiLedChipset::SPI_LED_CHIPSET_WS2801 ? LOG_STR_LITERAL("WS2801") : LOG_STR_LITERAL("APA102"),
this->num_leds_);
if (this->data_rate_ >= spi::DATA_RATE_1MHZ) {
esph_log_config(TAG, " Data rate: %uMHz", (unsigned) (this->data_rate_ / 1000000));
} else {
esph_log_config(TAG, " Data rate: %ukHz", (unsigned) (this->data_rate_ / 1000));
}
}
void SpiLedStrip::write_state(light::LightState *state) {
if (this->is_failed())
return;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
{
char strbuf[49]; // format_hex_pretty_size(16) = 48, fits 16 bytes
size_t len = std::min(this->buffer_size_, (size_t) 16);
format_hex_pretty_to(strbuf, sizeof(strbuf), this->buf_, len, ' ');
esph_log_v(TAG, "write_state: buf = %s", strbuf);
}
#endif
this->enable();
this->write_array(this->buf_, this->buffer_size_);
this->disable();
}
light::ESPColorView SpiLedStrip::get_view_internal(int32_t index) const {
#ifdef USE_SPI_LED_STRIP_WS2801
if (this->chipset_ == SpiLedChipset::SPI_LED_CHIPSET_WS2801) {
size_t pos = index * 3;
return {this->buf_ + pos + 0, this->buf_ + pos + 1, this->buf_ + pos + 2, nullptr,
this->effect_data_ + index, &this->correction_};
}
#endif
size_t pos = index * 4 + 5;
return {this->buf_ + pos + 2, this->buf_ + pos + 1, this->buf_ + pos + 0, nullptr,
this->effect_data_ + index, &this->correction_};
}
} // namespace esphome::spi_led_strip