DualLedController/components/LedController/LedController.cpp

106 lines
3.1 KiB
C++

#include "LedController.h"
#include <cstring>
#include <iostream>
LedController::LedController() {
memset(m_channels, 0, sizeof(m_channels));
}
bool LedController::initialize() {
ledc_timer_config_t ledc_timer;
memset(&ledc_timer, 0, sizeof(ledc_timer));
ledc_timer.speed_mode = LEDC_HIGH_SPEED_MODE;
ledc_timer.duty_resolution = TimerBit;
ledc_timer.timer_num = LEDC_TIMER_0;
ledc_timer.freq_hz = 4000;
ledc_timer.clk_cfg = LEDC_AUTO_CLK;
auto status = ledc_timer_config(&ledc_timer);
if (status != ESP_OK) {
std::cout << "ledc_timer_config() failed." << std::endl;
}
m_channels[0].gpio_num = 18; // gpio18
m_channels[0].speed_mode = LEDC_HIGH_SPEED_MODE;
m_channels[0].channel = LEDC_CHANNEL_0;
m_channels[0].timer_sel = LEDC_TIMER_0;
m_channels[0].duty = 0;
m_channels[0].hpoint = 0;
m_channels[0].flags.output_invert = 0;
m_channels[1].gpio_num = 19; // gpio19
m_channels[1].speed_mode = LEDC_HIGH_SPEED_MODE;
m_channels[1].channel = LEDC_CHANNEL_1;
m_channels[1].timer_sel = LEDC_TIMER_0;
m_channels[1].duty = 0;
m_channels[1].hpoint = 0;
m_channels[1].flags.output_invert = 0;
for (int i = 0; i < sizeof(m_channels) / sizeof(m_channels[0]); i++) {
status = ledc_channel_config(&m_channels[i]);
if (status != ESP_OK) {
std::cout << "ledc_timer_config() failed." << std::endl;
}
ledc_set_duty(m_channels[i].speed_mode, m_channels[i].channel, 0);
ledc_update_duty(m_channels[i].speed_mode, m_channels[i].channel);
}
return true;
}
int32_t LedController::brightness() const {
return m_brightness;
}
void LedController::setBrightness(int32_t brightness) {
if (m_brightness != brightness) {
m_brightness = brightness;
update();
}
}
int32_t LedController::colorTemperature() const {
return m_colorTemp;
}
void LedController::setColorTemperature(int32_t temp) {
if (m_colorTemp != temp) {
m_colorTemp = temp;
update();
}
}
bool LedController::enabled() const {
return m_enabled;
}
void LedController::setEnabled(bool enabled) {
if (m_enabled != enabled) {
m_enabled = enabled;
update();
}
}
void LedController::update() {
if (!m_enabled) {
setDuty(Warm, 0);
setDuty(Cold, 0);
return;
}
auto warm = static_cast<float>(m_colorTemp - MinimumColorTemp) / (MaximumColorTemp - MinimumColorTemp);
auto wamDuty = m_brightness * warm;
setDuty(Warm, wamDuty);
setDuty(Cold, m_brightness - wamDuty);
}
void LedController::setDuty(Channel channel, int32_t duty) {
if ((channel < 0) || (channel >= sizeof(m_channels) / sizeof(m_channels[0]))) return;
std::cout << "set channle " << channel << " duty: " << duty << std::endl;
ledc_set_duty(m_channels[channel].speed_mode, m_channels[channel].channel, duty);
ledc_update_duty(m_channels[channel].speed_mode, m_channels[channel].channel);
}
LedController *LedController::instance() {
static LedController self;
return &self;
}