Public Access
feat(ups-status-led): ups led controller component
Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
17 files changed
+1413
-243
No files matched your search
@@ -0,0 +1,185 @@
|
||||
# UPS Status LED Component
|
||||
|
||||
A smart LED status indicator for UPS monitoring that uses the UPS HID component's data provider.
|
||||
|
||||
## Features
|
||||
|
||||
- **🎨 Automatic Status Display**: Priority-based patterns for different UPS states
|
||||
- **🌙 Night Mode**: Automatic brightness dimming during specified hours
|
||||
- **🏠 Home Assistant Integration**: Control LED, night mode, and brightness from HA
|
||||
- **🔌 Hardware Agnostic**: Works with any ESPHome light component
|
||||
|
||||
## LED Patterns
|
||||
|
||||
The component automatically displays these solid color patterns based on UPS status (priority order):
|
||||
|
||||
1. **🔴 Critical Alert** (Solid red) - Low battery, fault, or overload
|
||||
2. **🟠 Battery Power** (Solid orange) - Running on battery
|
||||
3. **🟡 Charging** (Solid yellow) - Battery charging while online
|
||||
4. **🟢 Normal** (Solid green) - Normal operation
|
||||
5. **🔵 UPS Offline** (Solid blue) - UPS disconnected
|
||||
6. **🟣 No Data** (Solid purple) - Component connected but no data
|
||||
7. **⚪ Error** (Solid white) - Component error
|
||||
|
||||
## Configuration
|
||||
|
||||
### Basic Example
|
||||
|
||||
```yaml
|
||||
# Time component (required for night mode)
|
||||
time:
|
||||
- platform: sntp
|
||||
id: sntp_time
|
||||
|
||||
# Physical LED (any light component)
|
||||
light:
|
||||
- platform: esp32_rmt_led_strip
|
||||
pin: GPIO48
|
||||
num_leds: 1
|
||||
id: my_led
|
||||
internal: true # Hide from HA
|
||||
|
||||
# UPS Status LED Controller
|
||||
ups_status_led:
|
||||
ups_hid_id: ups_monitor # UPS data provider
|
||||
light_id: my_led # Physical LED
|
||||
time_id: sntp_time # Time source
|
||||
```
|
||||
|
||||
### Full Configuration
|
||||
|
||||
```yaml
|
||||
ups_status_led:
|
||||
id: ups_led_controller
|
||||
ups_hid_id: ups_monitor # Required: UPS HID component ID
|
||||
light_id: status_led # Required: Light component ID
|
||||
time_id: sntp_time # Optional: Time component for night mode
|
||||
|
||||
enabled: true # Enable/disable LED (default: true)
|
||||
brightness: 80% # Base brightness 10-100% (default: 80%)
|
||||
|
||||
# Battery color behavior
|
||||
battery_color_mode: gradient # discrete or gradient (default: discrete)
|
||||
battery_low_threshold: 20 # Critical threshold % (default: 20)
|
||||
battery_warning_threshold: 50 # Warning threshold % (default: 50)
|
||||
|
||||
# Night mode settings
|
||||
night_mode:
|
||||
enabled: true # Enable night mode (default: true)
|
||||
brightness: 15% # Night brightness (default: 15%)
|
||||
start_time: "22:00" # Start time HH:MM (default: 22:00)
|
||||
end_time: "07:00" # End time HH:MM (default: 07:00)
|
||||
```
|
||||
|
||||
## Home Assistant Entities
|
||||
|
||||
The component automatically creates these entities (via `ups_led_controls.yaml`):
|
||||
|
||||
| Entity | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `switch.ups_status_led` | Switch | Enable/disable the LED |
|
||||
| `switch.ups_led_night_mode` | Switch | Enable/disable night mode |
|
||||
| `number.ups_led_brightness` | Number | Adjust brightness (10-100%) |
|
||||
| `number.ups_led_night_brightness` | Number | Adjust night mode brightness (5-50%) |
|
||||
| `number.ups_led_night_start_hour` | Number | Night mode start hour (0-23) |
|
||||
| `number.ups_led_night_start_minute` | Number | Night mode start minute (0,15,30,45) |
|
||||
| `number.ups_led_night_end_hour` | Number | Night mode end hour (0-23) |
|
||||
| `number.ups_led_night_end_minute` | Number | Night mode end minute (0,15,30,45) |
|
||||
| `text_sensor.ups_led_pattern` | Text | Current pattern being displayed |
|
||||
|
||||
## Performance
|
||||
|
||||
- **Update Rate**: 20Hz (50ms intervals)
|
||||
|
||||
## Data Provider Pattern
|
||||
|
||||
This component demonstrates the UPS HID data provider pattern:
|
||||
|
||||
```cpp
|
||||
// Direct access to UPS data - no sensor entities needed!
|
||||
if (ups_hid_->is_low_battery()) {
|
||||
// Show critical pattern
|
||||
}
|
||||
|
||||
float battery = ups_hid_->get_battery_level();
|
||||
// Adjust color based on battery level
|
||||
```
|
||||
|
||||
## Supported Light Types
|
||||
|
||||
Works with any ESPHome light component:
|
||||
- WS2812/NeoPixel strips
|
||||
- RGB LEDs
|
||||
- Single color LEDs (patterns only, no color)
|
||||
- PWM LEDs
|
||||
- FastLED compatible strips
|
||||
|
||||
## Example Automations
|
||||
|
||||
### Disable LED During Sleep Hours
|
||||
```yaml
|
||||
automation:
|
||||
- alias: "UPS LED Sleep Mode"
|
||||
trigger:
|
||||
platform: time
|
||||
at: "23:00:00"
|
||||
action:
|
||||
service: switch.turn_off
|
||||
target:
|
||||
entity_id: switch.ups_status_led
|
||||
```
|
||||
|
||||
### Increase Brightness During Emergencies
|
||||
```yaml
|
||||
automation:
|
||||
- alias: "UPS Emergency Brightness"
|
||||
trigger:
|
||||
platform: state
|
||||
entity_id: text_sensor.ups_led_pattern
|
||||
to: "Critical"
|
||||
action:
|
||||
service: number.set_value
|
||||
target:
|
||||
entity_id: number.ups_led_brightness
|
||||
data:
|
||||
value: 100
|
||||
```
|
||||
|
||||
### Toggle Night Mode Based on Presence
|
||||
```yaml
|
||||
automation:
|
||||
- alias: "UPS LED Night Mode Control"
|
||||
trigger:
|
||||
platform: state
|
||||
entity_id: binary_sensor.someone_home
|
||||
action:
|
||||
service: >
|
||||
switch.turn_{{ 'on' if trigger.to_state.state == 'off' else 'off' }}
|
||||
target:
|
||||
entity_id: switch.ups_led_night_mode
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### LED Not Working
|
||||
- Verify UPS HID component is working: Check logs for UPS data
|
||||
- Verify light component works: Try controlling it directly
|
||||
- Check component logs: Enable `DEBUG` logging
|
||||
|
||||
### Night Mode Not Working
|
||||
- Ensure time component is configured and has valid time
|
||||
- Verify timezone is set correctly
|
||||
- Check start/end times don't conflict
|
||||
|
||||
### Colors Look Wrong
|
||||
- For RGB strips: Check `rgb_order` in light configuration
|
||||
- For single-color LEDs: Only patterns work, not colors
|
||||
- Try switching between discrete/gradient modes
|
||||
|
||||
## Debug Logging
|
||||
|
||||
```yaml
|
||||
logger:
|
||||
logs:
|
||||
ups_status_led: DEBUG
|
||||
```
|
||||
@@ -0,0 +1,120 @@
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.components import light, time, switch, number, text_sensor
|
||||
from esphome.const import (
|
||||
CONF_ID,
|
||||
CONF_BRIGHTNESS,
|
||||
CONF_TIME_ID,
|
||||
)
|
||||
|
||||
CONF_ENABLED = "enabled"
|
||||
|
||||
DEPENDENCIES = ["ups_hid", "light"]
|
||||
AUTO_LOAD = ["switch", "number", "text_sensor"]
|
||||
|
||||
ups_status_led_ns = cg.esphome_ns.namespace("ups_status_led")
|
||||
UpsStatusLedComponent = ups_status_led_ns.class_("UpsStatusLedComponent", cg.Component)
|
||||
|
||||
BatteryColorMode = ups_status_led_ns.enum("BatteryColorMode", is_class=True)
|
||||
BATTERY_COLOR_MODES = {
|
||||
"discrete": BatteryColorMode.DISCRETE,
|
||||
"gradient": BatteryColorMode.GRADIENT,
|
||||
}
|
||||
|
||||
CONF_UPS_HID_ID = "ups_hid_id"
|
||||
CONF_LIGHT_ID = "light_id"
|
||||
CONF_NIGHT_MODE = "night_mode"
|
||||
CONF_START_TIME = "start_time"
|
||||
CONF_END_TIME = "end_time"
|
||||
CONF_BATTERY_COLOR_MODE = "battery_color_mode"
|
||||
CONF_BATTERY_LOW_THRESHOLD = "battery_low_threshold"
|
||||
CONF_BATTERY_WARNING_THRESHOLD = "battery_warning_threshold"
|
||||
|
||||
def validate_time(value):
|
||||
"""Validate time format HH:MM"""
|
||||
if isinstance(value, str):
|
||||
parts = value.split(":")
|
||||
if len(parts) != 2:
|
||||
raise cv.Invalid("Time must be in format HH:MM")
|
||||
try:
|
||||
hour = int(parts[0])
|
||||
minute = int(parts[1])
|
||||
if not (0 <= hour <= 23):
|
||||
raise cv.Invalid("Hour must be between 0 and 23")
|
||||
if not (0 <= minute <= 59):
|
||||
raise cv.Invalid("Minute must be between 0 and 59")
|
||||
return {"hour": hour, "minute": minute}
|
||||
except ValueError:
|
||||
raise cv.Invalid("Invalid time format")
|
||||
return value
|
||||
|
||||
NIGHT_MODE_SCHEMA = cv.Schema({
|
||||
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
|
||||
cv.Optional(CONF_BRIGHTNESS, default="30%"): cv.percentage, # Changed from 15% to 30%
|
||||
cv.Optional(CONF_START_TIME, default="22:00"): validate_time,
|
||||
cv.Optional(CONF_END_TIME, default="07:00"): validate_time,
|
||||
})
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema({
|
||||
cv.GenerateID(): cv.declare_id(UpsStatusLedComponent),
|
||||
cv.Required(CONF_UPS_HID_ID): cv.use_id("ups_hid.UpsHidComponent"),
|
||||
cv.Required(CONF_LIGHT_ID): cv.use_id(light.LightState),
|
||||
cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
|
||||
|
||||
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
|
||||
cv.Optional(CONF_BRIGHTNESS, default="80%"): cv.percentage,
|
||||
cv.Optional(CONF_BATTERY_COLOR_MODE, default="discrete"): cv.enum(
|
||||
BATTERY_COLOR_MODES, lower=True
|
||||
),
|
||||
|
||||
cv.Optional(CONF_NIGHT_MODE): NIGHT_MODE_SCHEMA,
|
||||
|
||||
cv.Optional(CONF_BATTERY_LOW_THRESHOLD, default=20.0): cv.float_range(
|
||||
min=0, max=100
|
||||
),
|
||||
cv.Optional(CONF_BATTERY_WARNING_THRESHOLD, default=50.0): cv.float_range(
|
||||
min=0, max=100
|
||||
),
|
||||
}).extend(cv.COMPONENT_SCHEMA)
|
||||
|
||||
async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
|
||||
# Link UPS HID component
|
||||
ups = await cg.get_variable(config[CONF_UPS_HID_ID])
|
||||
cg.add(var.set_ups_hid(ups))
|
||||
|
||||
# Link Light component
|
||||
light_var = await cg.get_variable(config[CONF_LIGHT_ID])
|
||||
cg.add(var.set_light(light_var))
|
||||
|
||||
# Optional time component for night mode
|
||||
if CONF_TIME_ID in config:
|
||||
time_var = await cg.get_variable(config[CONF_TIME_ID])
|
||||
cg.add(var.set_time(time_var))
|
||||
|
||||
# Basic configuration
|
||||
cg.add(var.set_enabled(config[CONF_ENABLED]))
|
||||
cg.add(var.set_brightness(config[CONF_BRIGHTNESS]))
|
||||
cg.add(var.set_battery_color_mode(config[CONF_BATTERY_COLOR_MODE]))
|
||||
|
||||
# Battery thresholds
|
||||
cg.add(var.set_battery_low_threshold(config[CONF_BATTERY_LOW_THRESHOLD]))
|
||||
cg.add(var.set_battery_warning_threshold(config[CONF_BATTERY_WARNING_THRESHOLD]))
|
||||
|
||||
# Night mode configuration
|
||||
if CONF_NIGHT_MODE in config:
|
||||
night_config = config[CONF_NIGHT_MODE]
|
||||
cg.add(var.set_night_mode_enabled(night_config[CONF_ENABLED]))
|
||||
cg.add(var.set_night_mode_brightness(night_config[CONF_BRIGHTNESS]))
|
||||
|
||||
start_time = night_config[CONF_START_TIME]
|
||||
cg.add(var.set_night_mode_start_time(start_time["hour"], start_time["minute"]))
|
||||
|
||||
end_time = night_config[CONF_END_TIME]
|
||||
cg.add(var.set_night_mode_end_time(end_time["hour"], end_time["minute"]))
|
||||
|
||||
# Note: For Home Assistant control entities, users should manually add
|
||||
# switch, number, and text_sensor entities in their configuration.
|
||||
# This provides better flexibility and follows ESPHome best practices.
|
||||
@@ -0,0 +1,374 @@
|
||||
#include "ups_status_led.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <algorithm>
|
||||
|
||||
namespace esphome {
|
||||
namespace ups_status_led {
|
||||
|
||||
static const char *const TAG = "ups_status_led";
|
||||
|
||||
void UpsStatusLedComponent::setup() {
|
||||
ESP_LOGI(TAG, "*** UPS STATUS LED SETUP STARTING ***");
|
||||
ESP_LOGCONFIG(TAG, "Setting up UPS Status LED...");
|
||||
|
||||
// Validate required components
|
||||
if (!ups_hid_) {
|
||||
ESP_LOGE(TAG, "UPS HID component is required!");
|
||||
mark_failed();
|
||||
return;
|
||||
}
|
||||
ESP_LOGI(TAG, "UPS HID component found and linked");
|
||||
|
||||
if (!light_) {
|
||||
ESP_LOGE(TAG, "Light component is required!");
|
||||
mark_failed();
|
||||
return;
|
||||
}
|
||||
ESP_LOGI(TAG, "Light component found and linked");
|
||||
|
||||
// Initialize light to known OFF state during setup
|
||||
// This ensures the light component is working and ready
|
||||
initialize_light_component();
|
||||
|
||||
// Initialize Home Assistant entities with SAFE callbacks
|
||||
#ifdef USE_SWITCH
|
||||
if (enabled_switch_) {
|
||||
enabled_switch_->add_on_state_callback([this](bool state) {
|
||||
// SAFE: Use flag-based approach, never direct calls during setup
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
enabled_ = state;
|
||||
force_update_ = true; // Let loop handle the update
|
||||
ESP_LOGD(TAG, "Enabled switch changed to: %s", state ? "ON" : "OFF");
|
||||
});
|
||||
}
|
||||
if (night_mode_switch_) {
|
||||
night_mode_switch_->add_on_state_callback([this](bool state) {
|
||||
set_night_mode_enabled_api(state);
|
||||
});
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
if (brightness_number_) {
|
||||
brightness_number_->add_on_state_callback([this](float value) {
|
||||
set_brightness_api(value / 100.0f); // Convert percentage to 0-1
|
||||
});
|
||||
}
|
||||
#endif
|
||||
|
||||
ESP_LOGI(TAG, "*** UPS STATUS LED SETUP COMPLETE ***");
|
||||
ESP_LOGCONFIG(TAG, "UPS Status LED setup complete");
|
||||
}
|
||||
|
||||
void UpsStatusLedComponent::loop() {
|
||||
static bool first_evaluation = true;
|
||||
static uint32_t startup_delay = 0;
|
||||
|
||||
if (first_evaluation) {
|
||||
ESP_LOGI(TAG, "*** UPS STATUS LED FIRST LOOP - COMPONENT IS RUNNING ***");
|
||||
startup_delay = millis() + 2000; // 2 second startup delay for UPS initialization
|
||||
first_evaluation = false;
|
||||
}
|
||||
|
||||
uint32_t now = millis();
|
||||
|
||||
// Thread-safe state access
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
|
||||
// Handle disabled state properly (don't interfere with startup delay)
|
||||
if (!enabled_) {
|
||||
// Only turn off LED if we're past startup or if we've already started
|
||||
if (startup_delay == 0 || now >= startup_delay) {
|
||||
ESP_LOGD(TAG, "LED disabled - turning off");
|
||||
set_led_color(0, 0, 0, 0);
|
||||
startup_delay = 0; // Clear startup delay
|
||||
force_update_ = false; // Clear flag
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for startup delay to complete
|
||||
if (startup_delay > 0 && now < startup_delay) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear startup delay after waiting
|
||||
bool startup_complete = false;
|
||||
if (startup_delay > 0) {
|
||||
startup_complete = true;
|
||||
startup_delay = 0;
|
||||
force_update_ = true; // Force first update after startup delay
|
||||
ESP_LOGI(TAG, "LED startup delay complete - forcing initial pattern evaluation");
|
||||
}
|
||||
|
||||
bool should_update = (now - last_update_ >= UPDATE_INTERVAL_MS) || force_update_;
|
||||
|
||||
if (should_update) {
|
||||
// Evaluate and apply pattern
|
||||
LedPattern new_pattern = evaluate_pattern();
|
||||
|
||||
// Update on startup completion, pattern changes, or forced updates
|
||||
if (startup_complete || new_pattern != current_pattern_ || force_update_) {
|
||||
ESP_LOGD(TAG, "Pattern update: reason=%s, pattern=%d, forced=%s",
|
||||
startup_complete ? "STARTUP_COMPLETE" : (new_pattern != current_pattern_ ? "PATTERN_CHANGE" : "FORCED"),
|
||||
(int)new_pattern,
|
||||
force_update_ ? "true" : "false");
|
||||
|
||||
current_pattern_ = new_pattern;
|
||||
pattern_start_time_ = now;
|
||||
apply_pattern(current_pattern_);
|
||||
force_update_ = false; // Clear flag after update
|
||||
}
|
||||
last_update_ = now;
|
||||
}
|
||||
|
||||
// Update Home Assistant entities periodically
|
||||
static uint32_t last_ha_update = 0;
|
||||
if (now - last_ha_update > 1000) { // Update every second
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
if (status_text_sensor_) {
|
||||
std::string pattern_name;
|
||||
switch (current_pattern_) {
|
||||
case LedPattern::NORMAL_SOLID: pattern_name = "Normal"; break;
|
||||
case LedPattern::CHARGING_SOLID: pattern_name = "Charging"; break;
|
||||
case LedPattern::BATTERY_WARNING: pattern_name = "Battery Warning"; break;
|
||||
case LedPattern::CRITICAL_SOLID: pattern_name = "Critical"; break;
|
||||
case LedPattern::OFFLINE_SOLID: pattern_name = "Offline"; break;
|
||||
case LedPattern::NO_DATA_SOLID: pattern_name = "No Data"; break;
|
||||
case LedPattern::COMPONENT_ERROR: pattern_name = "Component Error"; break;
|
||||
default: pattern_name = "Off"; break;
|
||||
}
|
||||
if (status_text_sensor_->state != pattern_name) {
|
||||
status_text_sensor_->publish_state(pattern_name);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
last_ha_update = now;
|
||||
}
|
||||
}
|
||||
|
||||
void UpsStatusLedComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "UPS Status LED:");
|
||||
ESP_LOGCONFIG(TAG, " Enabled: %s", enabled_ ? "YES" : "NO");
|
||||
ESP_LOGCONFIG(TAG, " Brightness: %.1f%%", brightness_ * 100);
|
||||
ESP_LOGCONFIG(TAG, " Battery Color Mode: %s",
|
||||
battery_color_mode_ == BatteryColorMode::DISCRETE ? "Discrete" : "Gradient");
|
||||
ESP_LOGCONFIG(TAG, " Night Mode: %s", night_mode_enabled_ ? "YES" : "NO");
|
||||
if (night_mode_enabled_) {
|
||||
ESP_LOGCONFIG(TAG, " Time: %02d:%02d - %02d:%02d",
|
||||
night_mode_start_hour_, night_mode_start_minute_,
|
||||
night_mode_end_hour_, night_mode_end_minute_);
|
||||
ESP_LOGCONFIG(TAG, " Brightness: %.1f%%", night_mode_brightness_ * 100);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Battery Thresholds:");
|
||||
ESP_LOGCONFIG(TAG, " Low: %.1f%%", battery_low_threshold_);
|
||||
ESP_LOGCONFIG(TAG, " Warning: %.1f%%", battery_warning_threshold_);
|
||||
}
|
||||
|
||||
// SOLID principle: Single Responsibility - focused pattern evaluation
|
||||
LedPattern UpsStatusLedComponent::evaluate_pattern() {
|
||||
if (!ups_hid_) {
|
||||
return LedPattern::COMPONENT_ERROR;
|
||||
}
|
||||
|
||||
// Priority-based evaluation (highest priority first)
|
||||
if (!ups_hid_->is_connected()) {
|
||||
return LedPattern::OFFLINE_SOLID;
|
||||
}
|
||||
|
||||
if (ups_hid_->is_low_battery() || ups_hid_->has_fault() || ups_hid_->is_overloaded()) {
|
||||
return LedPattern::CRITICAL_SOLID;
|
||||
}
|
||||
|
||||
if (ups_hid_->is_on_battery()) {
|
||||
return LedPattern::BATTERY_WARNING;
|
||||
}
|
||||
|
||||
if (ups_hid_->is_charging()) {
|
||||
return LedPattern::CHARGING_SOLID;
|
||||
}
|
||||
|
||||
if (ups_hid_->is_online()) {
|
||||
return LedPattern::NORMAL_SOLID;
|
||||
}
|
||||
|
||||
return LedPattern::NO_DATA_SOLID;
|
||||
}
|
||||
|
||||
void UpsStatusLedComponent::apply_pattern(LedPattern pattern) {
|
||||
float brightness = calculate_brightness(); // Calculate once
|
||||
float r, g, b;
|
||||
calculate_color(r, g, b, pattern, brightness); // Pass brightness as parameter
|
||||
|
||||
// Simple solid color display - no animations
|
||||
switch (pattern) {
|
||||
case LedPattern::CRITICAL_SOLID:
|
||||
// Critical: Solid red
|
||||
set_led_color(r, g, b, brightness);
|
||||
break;
|
||||
case LedPattern::BATTERY_WARNING:
|
||||
// Battery warning: Solid orange
|
||||
set_led_color(r, g, b, brightness);
|
||||
break;
|
||||
case LedPattern::CHARGING_SOLID:
|
||||
// Charging: Solid yellow
|
||||
set_led_color(r, g, b, brightness);
|
||||
break;
|
||||
case LedPattern::NORMAL_SOLID:
|
||||
// Normal: Solid green
|
||||
set_led_color(r, g, b, brightness);
|
||||
break;
|
||||
case LedPattern::OFFLINE_SOLID:
|
||||
// Offline: Solid blue
|
||||
set_led_color(r, g, b, brightness);
|
||||
break;
|
||||
case LedPattern::NO_DATA_SOLID:
|
||||
// No data: Solid purple
|
||||
set_led_color(r, g, b, brightness);
|
||||
break;
|
||||
case LedPattern::COMPONENT_ERROR:
|
||||
// Error: Solid white
|
||||
set_led_color(r, g, b, brightness);
|
||||
break;
|
||||
default:
|
||||
// Off
|
||||
set_led_color(0, 0, 0, 0);
|
||||
break;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, "Applying solid pattern: R=%.2f G=%.2f B=%.2f calculated_brightness=%.2f", r, g, b, brightness);
|
||||
}
|
||||
|
||||
// SOLID principle: Single Responsibility - focused color calculation
|
||||
void UpsStatusLedComponent::calculate_color(float &r, float &g, float &b, LedPattern pattern, float brightness) {
|
||||
// Check if night mode is active for color compensation
|
||||
bool night_active = night_mode_enabled_ && is_night_time();
|
||||
|
||||
// Default colors for patterns with night mode color compensation
|
||||
switch (pattern) {
|
||||
case LedPattern::CRITICAL_SOLID:
|
||||
r = 1.0f; g = 0.0f; b = 0.0f; // Red
|
||||
break;
|
||||
case LedPattern::BATTERY_WARNING:
|
||||
// Orange: Boost green channel in night mode to maintain orange appearance
|
||||
r = 1.0f;
|
||||
if (night_active) {
|
||||
// Scale green boost based on how dim it is
|
||||
float boost_factor = 1.4f - brightness; // More boost when dimmer
|
||||
g = std::min(0.8f, 0.5f + boost_factor);
|
||||
} else {
|
||||
g = 0.5f; // Normal orange
|
||||
}
|
||||
b = 0.0f;
|
||||
break;
|
||||
case LedPattern::CHARGING_SOLID:
|
||||
// Yellow: Boost green channel in night mode to prevent red appearance
|
||||
r = 1.0f;
|
||||
if (night_active) {
|
||||
// Scale green boost based on how dim it is
|
||||
float boost_factor = 1.5f - brightness; // More boost when dimmer
|
||||
g = std::min(1.3f, 1.0f + boost_factor);
|
||||
} else {
|
||||
g = 1.0f; // Normal yellow
|
||||
}
|
||||
b = 0.0f;
|
||||
break;
|
||||
case LedPattern::NORMAL_SOLID:
|
||||
// Normal operation should always be solid green
|
||||
r = 0.0f; g = 1.0f; b = 0.0f; // Green
|
||||
break;
|
||||
case LedPattern::OFFLINE_SOLID:
|
||||
r = 0.0f; g = 0.0f; b = 1.0f; // Blue
|
||||
break;
|
||||
case LedPattern::NO_DATA_SOLID:
|
||||
r = 0.8f; g = 0.0f; b = 1.0f; // Purple
|
||||
break;
|
||||
case LedPattern::COMPONENT_ERROR:
|
||||
r = 1.0f; g = 1.0f; b = 1.0f; // White
|
||||
break;
|
||||
default:
|
||||
r = 0.0f; g = 0.0f; b = 0.0f; // Off
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
float UpsStatusLedComponent::calculate_brightness() {
|
||||
float base_brightness = brightness_;
|
||||
bool night_active = night_mode_enabled_ && is_night_time();
|
||||
|
||||
ESP_LOGD(TAG, "Brightness calc: base=%.2f, night_mode=%s, is_night=%s",
|
||||
base_brightness, night_mode_enabled_ ? "ON" : "OFF", night_active ? "YES" : "NO");
|
||||
|
||||
// Apply night mode
|
||||
if (night_active) {
|
||||
base_brightness *= night_mode_brightness_;
|
||||
ESP_LOGD(TAG, "Night mode applied: %.2f * %.2f = %.2f",
|
||||
brightness_, night_mode_brightness_, base_brightness);
|
||||
}
|
||||
|
||||
// Enforce minimum hardware brightness to make enabled switch meaningful
|
||||
float final_brightness = std::max(base_brightness, MIN_HARDWARE_BRIGHTNESS);
|
||||
|
||||
if (final_brightness != base_brightness) {
|
||||
ESP_LOGD(TAG, "Applied minimum brightness: %.2f → %.2f", base_brightness, final_brightness);
|
||||
}
|
||||
|
||||
return final_brightness;
|
||||
}
|
||||
|
||||
bool UpsStatusLedComponent::is_night_time() const {
|
||||
if (!time_ || !time_->now().is_valid()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int current_hour = time_->now().hour;
|
||||
int current_minute = time_->now().minute;
|
||||
int current_time_minutes = current_hour * 60 + current_minute;
|
||||
int start_time_minutes = night_mode_start_hour_ * 60 + night_mode_start_minute_;
|
||||
int end_time_minutes = night_mode_end_hour_ * 60 + night_mode_end_minute_;
|
||||
|
||||
if (start_time_minutes <= end_time_minutes) {
|
||||
return (current_time_minutes >= start_time_minutes && current_time_minutes < end_time_minutes);
|
||||
} else {
|
||||
return (current_time_minutes >= start_time_minutes || current_time_minutes < end_time_minutes);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Hardware abstraction
|
||||
void UpsStatusLedComponent::set_led_color(float r, float g, float b, float brightness) {
|
||||
if (!light_) {
|
||||
ESP_LOGW(TAG, "Light component not available - cannot set LED color");
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, "Setting LED: R=%.2f G=%.2f B=%.2f Brightness=%.2f", r, g, b, brightness);
|
||||
|
||||
// Don't pre-multiply RGB by brightness - let light component handle it
|
||||
ESP_LOGD(TAG, "Sending to light: RGB=(%.2f,%.2f,%.2f) Brightness=%.2f", r, g, b, brightness);
|
||||
|
||||
// Use light component API properly
|
||||
auto call = light_->make_call();
|
||||
call.set_state(true);
|
||||
call.set_rgb(r, g, b); // Set color
|
||||
call.set_brightness(brightness); // Set brightness separately
|
||||
call.perform();
|
||||
}
|
||||
|
||||
void UpsStatusLedComponent::initialize_light_component() {
|
||||
if (!light_) {
|
||||
ESP_LOGE(TAG, "Cannot initialize light component - not available");
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Initializing light component to known OFF state");
|
||||
|
||||
// Set light to known OFF state and test that it works
|
||||
auto call = light_->make_call();
|
||||
call.set_state(false); // Ensure light is OFF during setup
|
||||
call.perform();
|
||||
|
||||
ESP_LOGI(TAG, "Light component initialized successfully");
|
||||
}
|
||||
|
||||
} // namespace ups_status_led
|
||||
} // namespace esphome
|
||||
@@ -0,0 +1,213 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/components/time/real_time_clock.h"
|
||||
#include "../ups_hid/ups_hid.h"
|
||||
|
||||
// Light component include
|
||||
#include "esphome/components/light/light_state.h"
|
||||
|
||||
// Thread safety
|
||||
#include <mutex>
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
#include "esphome/components/switch/switch.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
#include "esphome/components/number/number.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
#include "esphome/components/text_sensor/text_sensor.h"
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
namespace ups_status_led {
|
||||
|
||||
// LED patterns (solid colors for simple indication)
|
||||
enum class LedPattern : uint8_t {
|
||||
OFF = 0,
|
||||
CRITICAL_SOLID, // Solid red - emergencies
|
||||
BATTERY_WARNING, // Solid orange - on battery
|
||||
CHARGING_SOLID, // Solid yellow - charging
|
||||
NORMAL_SOLID, // Solid green - normal (or gradient)
|
||||
OFFLINE_SOLID, // Solid blue - UPS disconnected
|
||||
NO_DATA_SOLID, // Solid purple - no data from UPS component
|
||||
COMPONENT_ERROR // Solid white - component error
|
||||
};
|
||||
|
||||
// Battery color mode configuration
|
||||
enum class BatteryColorMode : uint8_t {
|
||||
DISCRETE, // Green > 50%, Orange 20-50%, Red < 20%
|
||||
GRADIENT // Smooth green→yellow→red transition
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief SOLID-inspired UPS Status LED Component
|
||||
*
|
||||
* Simplified version that maintains separation of concerns while being ESPHome compatible.
|
||||
* Follows Single Responsibility and Open/Closed principles where possible.
|
||||
*/
|
||||
class UpsStatusLedComponent : public Component {
|
||||
public:
|
||||
float get_setup_priority() const override { return setup_priority::HARDWARE - 1.0f; }
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
|
||||
// Configuration setters
|
||||
void set_ups_hid(ups_hid::UpsHidComponent *ups) { ups_hid_ = ups; }
|
||||
void set_light(light::LightState *light) { light_ = light; }
|
||||
void set_time(time::RealTimeClock *time) { time_ = time; }
|
||||
|
||||
// Basic settings
|
||||
void set_enabled(bool enabled) { enabled_ = enabled; }
|
||||
void set_brightness(float brightness) { brightness_ = brightness; }
|
||||
void set_battery_color_mode(BatteryColorMode mode) { battery_color_mode_ = mode; }
|
||||
|
||||
// Night mode configuration (for YAML config)
|
||||
void set_night_mode_enabled(bool enabled) { night_mode_enabled_ = enabled; }
|
||||
void set_night_mode_brightness(float brightness) { night_mode_brightness_ = brightness; }
|
||||
void set_night_mode_start_time(uint8_t hour, uint8_t minute) {
|
||||
night_mode_start_hour_ = hour;
|
||||
night_mode_start_minute_ = minute;
|
||||
}
|
||||
void set_night_mode_end_time(uint8_t hour, uint8_t minute) {
|
||||
night_mode_end_hour_ = hour;
|
||||
night_mode_end_minute_ = minute;
|
||||
}
|
||||
|
||||
// Battery thresholds
|
||||
void set_battery_low_threshold(float threshold) { battery_low_threshold_ = threshold; }
|
||||
void set_battery_warning_threshold(float threshold) { battery_warning_threshold_ = threshold; }
|
||||
|
||||
// Home Assistant API methods (for web controls)
|
||||
void set_enabled_api(bool enabled) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
enabled_ = enabled;
|
||||
if (!enabled_) {
|
||||
set_led_color(0, 0, 0, 0); // Turn off immediately when disabled
|
||||
} else {
|
||||
force_update_ = true; // Flag for next loop update
|
||||
}
|
||||
}
|
||||
void set_brightness_api(float brightness) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
brightness_ = brightness;
|
||||
force_update_ = true; // Flag for next loop update
|
||||
}
|
||||
void set_night_mode_enabled_api(bool enabled) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
night_mode_enabled_ = enabled;
|
||||
force_update_ = true; // Flag for next loop update
|
||||
}
|
||||
void set_battery_color_mode_api(BatteryColorMode mode) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
battery_color_mode_ = mode;
|
||||
force_update_ = true; // Flag for next loop update
|
||||
}
|
||||
|
||||
// Night mode API methods (for web UI runtime control)
|
||||
void set_night_mode_brightness_api(float brightness) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
night_mode_brightness_ = brightness;
|
||||
force_update_ = true; // Flag for next loop update
|
||||
}
|
||||
void set_night_mode_start_time_api(uint8_t hour, uint8_t minute) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
night_mode_start_hour_ = hour;
|
||||
night_mode_start_minute_ = minute;
|
||||
force_update_ = true; // Flag for next loop update
|
||||
}
|
||||
void set_night_mode_end_time_api(uint8_t hour, uint8_t minute) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
night_mode_end_hour_ = hour;
|
||||
night_mode_end_minute_ = minute;
|
||||
force_update_ = true; // Flag for next loop update
|
||||
}
|
||||
|
||||
// Status getters
|
||||
bool is_enabled() const { return enabled_; }
|
||||
float get_brightness() const { return brightness_; }
|
||||
bool is_night_mode_active() const { return is_night_time(); }
|
||||
LedPattern get_current_pattern() const { return current_pattern_; }
|
||||
|
||||
// Home Assistant entity setters
|
||||
#ifdef USE_SWITCH
|
||||
void set_enabled_switch(switch_::Switch *sw) { enabled_switch_ = sw; }
|
||||
void set_night_mode_switch(switch_::Switch *sw) { night_mode_switch_ = sw; }
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
void set_brightness_number(number::Number *num) { brightness_number_ = num; }
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
void set_status_text_sensor(text_sensor::TextSensor *sensor) { status_text_sensor_ = sensor; }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
// SOLID principle: Single Responsibility - each method has one focused task
|
||||
LedPattern evaluate_pattern();
|
||||
void apply_pattern(LedPattern pattern);
|
||||
void calculate_color(float &r, float &g, float &b, LedPattern pattern, float brightness);
|
||||
float calculate_brightness();
|
||||
bool is_night_time() const;
|
||||
|
||||
// Pattern implementation - simplified solid colors only
|
||||
|
||||
// Hardware abstraction
|
||||
void set_led_color(float r, float g, float b, float brightness);
|
||||
void initialize_light_component();
|
||||
|
||||
private:
|
||||
// Dependencies (Dependency Inversion principle)
|
||||
ups_hid::UpsHidComponent *ups_hid_{nullptr};
|
||||
light::LightState *light_{nullptr};
|
||||
time::RealTimeClock *time_{nullptr};
|
||||
|
||||
// Configuration
|
||||
bool enabled_{true};
|
||||
float brightness_{0.8f};
|
||||
BatteryColorMode battery_color_mode_{BatteryColorMode::DISCRETE};
|
||||
|
||||
// Night mode settings
|
||||
bool night_mode_enabled_{true};
|
||||
float night_mode_brightness_{0.3f}; // 30% of day brightness, ensures min 20% when base is 80%
|
||||
uint8_t night_mode_start_hour_{22};
|
||||
uint8_t night_mode_start_minute_{0};
|
||||
uint8_t night_mode_end_hour_{7};
|
||||
uint8_t night_mode_end_minute_{0};
|
||||
|
||||
// Battery thresholds
|
||||
float battery_low_threshold_{20.0f};
|
||||
float battery_warning_threshold_{50.0f};
|
||||
|
||||
// Pattern state tracking
|
||||
LedPattern current_pattern_{LedPattern::OFF};
|
||||
uint32_t pattern_start_time_{0};
|
||||
uint32_t last_update_{0};
|
||||
bool force_update_{false}; // Flag for immediate updates from API calls
|
||||
static constexpr uint32_t UPDATE_INTERVAL_MS = 50; // 20Hz update rate for faster response
|
||||
|
||||
// Hardware brightness constraints
|
||||
static constexpr float MIN_HARDWARE_BRIGHTNESS = 0.2f; // 20% minimum for switch meaning
|
||||
|
||||
// Home Assistant entities
|
||||
#ifdef USE_SWITCH
|
||||
switch_::Switch *enabled_switch_{nullptr};
|
||||
switch_::Switch *night_mode_switch_{nullptr};
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
number::Number *brightness_number_{nullptr};
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
text_sensor::TextSensor *status_text_sensor_{nullptr};
|
||||
#endif
|
||||
|
||||
// Thread safety mutex
|
||||
mutable std::mutex state_mutex_;
|
||||
};
|
||||
|
||||
} // namespace ups_status_led
|
||||
} // namespace esphome
|
||||
Reference in new issue
Block a user