From 5ac47b94622b5d41d730dea2c44f3210913be109 Mon Sep 17 00:00:00 2001 From: bullshit Date: Mon, 1 Sep 2025 01:22:28 +0200 Subject: [PATCH] feat(ups-status-led): ups led controller component Signed-off-by: bullshit --- README.md | 97 +---- components/ups_status_led/README.md | 185 +++++++++ components/ups_status_led/__init__.py | 120 ++++++ components/ups_status_led/ups_status_led.cpp | 374 ++++++++++++++++++ components/ups_status_led/ups_status_led.h | 213 ++++++++++ configs/README.md | 110 +++++- configs/base_ups.yaml | 69 +--- configs/base_ups_with_led.yaml | 31 ++ configs/device_types/apc_backups_es.yaml | 1 + configs/entity_groups.yaml | 5 + configs/examples/apc-ups-monitor.yaml | 4 +- configs/examples/rack-ups-monitor.yaml | 4 +- configs/testing/led_status_test.yaml | 112 ++++++ configs/testing/minimal_data_provider.yaml | 12 +- .../testing/north_american_template_test.yaml | 81 ---- configs/ups_led_controls.yaml | 182 +++++++++ configs/ups_status_led.yaml | 56 +++ 17 files changed, 1413 insertions(+), 243 deletions(-) create mode 100644 components/ups_status_led/README.md create mode 100644 components/ups_status_led/__init__.py create mode 100644 components/ups_status_led/ups_status_led.cpp create mode 100644 components/ups_status_led/ups_status_led.h create mode 100644 configs/base_ups_with_led.yaml create mode 100644 configs/testing/led_status_test.yaml delete mode 100644 configs/testing/north_american_template_test.yaml create mode 100644 configs/ups_led_controls.yaml create mode 100644 configs/ups_status_led.yaml diff --git a/README.md b/README.md index b8e539a..0b17050 100644 --- a/README.md +++ b/README.md @@ -18,84 +18,18 @@ Monitor UPS devices via direct USB connection on ESP32-S3. Supports APC, CyberPo [πŸ“– Full Documentation](components/ups_hid/README.md) -## Installation +### πŸ’‘ UPS Status LED Component (`ups_status_led`) -### Using External Components (Recommended) +Smart LED status indicator for UPS monitoring with automatic pattern management and night mode. Provides visual status indication using solid colors with thread-safe runtime configuration. -Add to your ESPHome configuration: +**Key Features:** +- **7 solid color patterns**: Critical (red), Battery (orange), Charging (yellow), Normal (green), Offline (blue), No Data (purple), Error (white) +- **Night mode**: Time-based brightness dimming with color compensation for WS2812 LEDs +- **Home Assistant controls**: Enable/disable, brightness, night mode settings via web UI +- **Thread-safe operation**: Safe concurrent access from web UI and main loop +- **Minimum brightness logic**: 20% minimum ensures meaningful enable/disable distinction -```yaml -external_components: - - source: github://bullshit/esphome-components - components: [ ups_hid ] # Add more components as needed -``` - -### Manual Installation - -1. Clone this repository: - ```bash - git clone https://github.com/bullshit/esphome-components.git - ``` - -2. Copy component directories to your ESPHome project: - ```bash - cp -r esphome-components/components/* /config/esphome/components/ - ``` - -3. Use local components in your configuration: - ```yaml - external_components: - - source: - type: local - path: components - ``` - -## Quick Start - -### UPS HID Component Example - -```yaml -esphome: - name: ups-monitor - platform: ESP32 - board: esp32-s3-devkitc-1 - -external_components: - - source: - type: local - path: components - -# Configure UPS monitoring -ups_hid: - id: ups_monitor - update_interval: 30s - simulation_mode: false # Set to true for testing - -# Monitor battery level -sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: battery_level - name: "UPS Battery Level" - -# Monitor UPS status -binary_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: online - name: "UPS Online" - -# Control UPS beeper -button: - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: enable - name: "UPS Beeper Enable" - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: mute - name: "UPS Beeper Mute" -``` +[πŸ“– Full Documentation](components/ups_status_led/README.md) ## Development @@ -112,6 +46,11 @@ components/ β”‚ β”œβ”€β”€ binary_sensor.py # Binary sensor platform β”‚ β”œβ”€β”€ text_sensor.py # Text sensor platform β”‚ └── ... # Protocol implementations +β”œβ”€β”€ ups_status_led/ # Smart LED status indicator component +β”‚ β”œβ”€β”€ README.md # Component documentation +β”‚ β”œβ”€β”€ __init__.py # Component configuration +β”‚ β”œβ”€β”€ ups_status_led.h # Component header +β”‚ └── ups_status_led.cpp # Component implementation β”œβ”€β”€ [future_component]/ # Additional components β”‚ └── ... └── ... @@ -156,6 +95,7 @@ tools/ Component-specific requirements are documented in each component's README: - **UPS HID**: ESP32-S3-DevKitC-1 v1.1 with USB OTG support +- **UPS Status LED**: WS2812 LED strip (1 LED), requires time component for night mode - **Future components**: Requirements will be listed here ## License @@ -167,7 +107,6 @@ Copyright bullshit ### Planned Components - 🌐 **NUT Server** (`nut_server`): A NUT (Network UPS Tools) server implementation that uses the ups_hid component for network-accessible UPS monitoring and supports minimal NUT commands with authentication -- πŸ’‘ **UPS Status LED** (`ups_status_led`): Smart LED status indicator component for UPS monitoring ### Current Status @@ -178,6 +117,12 @@ Copyright bullshit - βœ… **Real-world tested** - APC Back-UPS ES 700G with USB power cycling - βœ… **Advanced protocols** - 15+ sensors per device with comprehensive monitoring - βœ… **UPS control** - Beeper control and battery testing via HID write operations +- βœ… **UPS Status LED Component**: Thread-safe LED indicator with night mode + - βœ… **SOLID architecture** - Clean separation of concerns within ESPHome constraints + - βœ… **Thread-safe operation** - Safe concurrent web UI and main loop access + - βœ… **Smart brightness** - 20% minimum hardware brightness for meaningful controls + - βœ… **Night mode** - Time-based dimming with WS2812 color compensation + - βœ… **Home Assistant integration** - Full web UI controls and status reporting - βœ… **ESP-IDF Framework**: Fully migrated to v5.4.2 with enhanced stability - βœ… **Documentation**: Comprehensive component and API documentation - βœ… **Development Tools**: VSCode integration, USB scanning, vendor management diff --git a/components/ups_status_led/README.md b/components/ups_status_led/README.md new file mode 100644 index 0000000..db79ff2 --- /dev/null +++ b/components/ups_status_led/README.md @@ -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 +``` diff --git a/components/ups_status_led/__init__.py b/components/ups_status_led/__init__.py new file mode 100644 index 0000000..187d5d2 --- /dev/null +++ b/components/ups_status_led/__init__.py @@ -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. \ No newline at end of file diff --git a/components/ups_status_led/ups_status_led.cpp b/components/ups_status_led/ups_status_led.cpp new file mode 100644 index 0000000..53ca801 --- /dev/null +++ b/components/ups_status_led/ups_status_led.cpp @@ -0,0 +1,374 @@ +#include "ups_status_led.h" +#include "esphome/core/log.h" +#include + +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 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 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 \ No newline at end of file diff --git a/components/ups_status_led/ups_status_led.h b/components/ups_status_led/ups_status_led.h new file mode 100644 index 0000000..0db3849 --- /dev/null +++ b/components/ups_status_led/ups_status_led.h @@ -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 + +#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 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 lock(state_mutex_); + brightness_ = brightness; + force_update_ = true; // Flag for next loop update + } + void set_night_mode_enabled_api(bool enabled) { + std::lock_guard 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 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 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 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 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 \ No newline at end of file diff --git a/configs/README.md b/configs/README.md index 434f312..a81007f 100644 --- a/configs/README.md +++ b/configs/README.md @@ -11,10 +11,18 @@ Essential foundation for all UPS devices: - ESP32-S3 hardware configuration - Network setup (WiFi, OTA, Web server) - UPS HID component initialization with Protocol Factory -- **Data Provider Pattern**: LED automation accesses UPS data directly (no sensor entities required!) -- Status LED with smart patterns using `id(ups_monitor).is_online()`, etc. +- **Data Provider Pattern**: Components can access UPS data directly (no sensor entities required!) - **Optional sensors**: Only `status` and `protocol` text sensors (for Home Assistant integration) +#### `base_ups_with_led.yaml` +Complete UPS monitoring with automatic LED status indication: +- Includes all `base_ups.yaml` functionality +- **Automatic LED Package**: Integrates `ups_status_led.yaml` +- **Smart Status Display**: 7 priority-based LED patterns +- **Night Mode**: Time-based dimming with Home Assistant control +- **Zero Configuration**: Works immediately with substitution customization +- **Hardware Flexible**: Compatible with any ESPHome light component + #### `essential_sensors.yaml` / `essential_sensors_grouped.yaml` Core monitoring sensors (5 sensors) available on all protocols: - **Sensors**: `battery_level`, `input_voltage`, `output_voltage`, `load_percent`, `runtime` @@ -26,6 +34,35 @@ Core monitoring sensors (5 sensors) available on all protocols: ### **Optional Enhancement Packages** +#### `ups_status_led.yaml` +Automatic LED status indication using smart patterns: + +**Hardware Integration**: +- Works with any ESPHome light component (WS2812, FastLED, etc.) +- Hardware abstraction layer for maximum compatibility + +**Smart Pattern System** (priority-based, automatic selection with solid colors): +- **πŸ”΄ Critical Alert** (solid red) - Low battery/fault/overload +- **🟠 Battery Power** (solid orange) - Running on battery +- **🟑 Charging** (solid yellow) - Battery charging +- **🟒 Normal** (solid green) - Normal operation +- **πŸ”΅ UPS Offline** (solid blue) - UPS disconnected +- **🟣 No Data** (solid purple) - Component connected but no data +- **βšͺ Error** (solid white) - Component error + +**Advanced Features**: +- **Battery-aware Colors**: Discrete thresholds or smooth gradients +- **Night Mode**: Time-based dimming with Home Assistant control +- **Home Assistant Integration**: Auto-created entities for complete control + +**Automatic Entity Creation**: +- `switch.ups_status_led` (master enable/disable) +- `switch.ups_led_night_mode` (night mode toggle) +- `number.ups_led_brightness` (brightness 10-100%) +- `text_sensor.ups_led_pattern` (current pattern name) + +**Uses Data Provider Pattern**: No sensor entities required - accesses UPS data directly via `id(ups_monitor).is_online()`, etc. + #### `extended_sensors.yaml` / `extended_sensors_grouped.yaml` Advanced monitoring (17 additional sensors) for feature-rich devices: @@ -186,22 +223,57 @@ packages: - Comprehensive validation of data provider pattern - **Use for**: Testing component as pure data provider, custom automation development +### `testing/led_status_test.yaml` +UPS Status LED component comprehensive testing: +```yaml +substitutions: + simulation_mode: "true" # Test without hardware + led_color_mode: "gradient" # Test gradient colors +packages: + base_with_led: !include ../base_ups_with_led.yaml +``` +**Features**: +- Tests all 7 LED patterns with simulated UPS states +- Battery-aware gradient color calculation verification +- Night mode with time-based scheduling testing +- Home Assistant integration validation (4 auto-created entities) +- Performance optimization verification (10Hz updates) +- **Use for**: LED component development, pattern testing, HA integration validation + +### `testing/ups_with_smart_led.yaml` +Complete smart LED integration testing: +```yaml +substitutions: + led_brightness: "90%" + led_color_mode: "gradient" + timezone: "America/New_York" +packages: + base_with_led: !include ../base_ups_with_led.yaml + essential: !include ../essential_sensors.yaml +``` +**Features**: +- Full LED + sensor integration testing +- Customizable substitutions validation +- Advanced features testing (battery gradients, timezone support) +- Complete Home Assistant entity creation +- **Use for**: Integration testing, configuration validation + ## Production Examples ### `examples/apc-ups-monitor.yaml` -Complete APC UPS production configuration: -- Modular package composition -- Device-specific optimizations -- Custom automation examples -- Network and notification setup +Complete APC UPS production configuration with LED status indication: +- **Smart LED Integration**: Uses `base_ups_with_led.yaml` for automatic status display +- Modular package composition with device-specific optimizations +- Custom automation examples and notification setup - Choice of standard or grouped entity layout +- APC-specific timer monitoring and power outage handling ### `examples/rack-ups-monitor.yaml` -Complete CyberPower UPS production configuration: -- Advanced sensor utilization -- Smart threshold monitoring -- Rich data analysis -- Enhanced automation +Complete CyberPower UPS production configuration with LED status indication: +- **Smart LED Integration**: Uses `base_ups_with_led.yaml` for automatic status display +- Advanced sensor utilization with rich CyberPower data +- Smart threshold monitoring and power analysis +- Enhanced automation with battery threshold alerts - Choice of standard or grouped entity layout ### `examples/grouped-ups-monitor.yaml` @@ -221,7 +293,15 @@ packages: ``` **Result**: ~150 lines β†’ Essential monitoring only -### 2. Full-Featured UPS +### 2. UPS with Smart LED Status +```yaml +packages: + base_with_led: !include configs/base_ups_with_led.yaml + essential: !include configs/essential_sensors.yaml +``` +**Result**: ~200 lines β†’ Essential monitoring + automatic LED status indication + +### 3. Full-Featured UPS ```yaml packages: base_ups: !include configs/base_ups.yaml @@ -234,7 +314,7 @@ packages: ``` **Result**: ~380 lines β†’ Complete functionality with UPS configuration -### 3. Organized Interface UPS +### 4. Organized Interface UPS ```yaml packages: # Enable organized web interface @@ -251,7 +331,7 @@ packages: ``` **Result**: Same functionality with organized web interface layout -### 4. Custom Configuration +### 5. Custom Configuration ```yaml substitutions: name: "my-custom-ups" diff --git a/configs/base_ups.yaml b/configs/base_ups.yaml index fa6a8db..687171f 100644 --- a/configs/base_ups.yaml +++ b/configs/base_ups.yaml @@ -71,67 +71,14 @@ ups_hid: fallback_nominal_voltage: 230V # European standard (IEC 60038) for better international compatibility simulation_mode: ${simulation_mode} -# Status LED configuration -light: - - platform: esp32_rmt_led_strip - chipset: WS2812 - pin: ${led_pin} - num_leds: 1 - rgb_order: GRB - name: "UPS Status LED" - id: ups_status_led - restore_mode: ALWAYS_OFF - effects: - - strobe: - name: "Critical Alert" - colors: - - state: true - brightness: 100% - red: 100% - green: 0% - blue: 0% - duration: 200ms - - state: false - duration: 200ms - - pulse: - name: "Battery Warning" - transition_length: 1.5s - min_brightness: 10% - max_brightness: 90% - - pulse: - name: "Normal Status" - transition_length: 3s - min_brightness: 20% - max_brightness: 60% - -# LED control automation (no sensor entities required!) -interval: - - interval: 2s - then: - - lambda: |- - // Direct access to UPS data - no sensor entities needed - if (id(ups_monitor).is_low_battery() || id(ups_monitor).has_fault()) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 0.0, 0.0); - call.set_effect("Critical Alert"); - call.perform(); - } else if (id(ups_monitor).is_on_battery()) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 0.5, 0.0); - call.set_effect("Battery Warning"); - call.perform(); - } else if (id(ups_monitor).is_online()) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(0.0, 1.0, 0.0); - call.set_effect("Normal Status"); - call.perform(); - } else { - id(ups_status_led).turn_off().perform(); - } - -# Note: Binary sensors are now completely OPTIONAL! -# Only define them if you need Home Assistant entities -# The LED automation above works without any sensor entities +# Note: Status LED has been moved to a separate package for better modularity +# To enable automatic LED status indication, include the ups_status_led package: +# +# packages: +# status_led: !include ups_status_led.yaml +# +# This provides automatic LED control with night mode, Home Assistant integration, +# and smart pattern management - no manual automation needed! # Essential text sensors text_sensor: diff --git a/configs/base_ups_with_led.yaml b/configs/base_ups_with_led.yaml new file mode 100644 index 0000000..19bd442 --- /dev/null +++ b/configs/base_ups_with_led.yaml @@ -0,0 +1,31 @@ +# Base UPS Configuration with Status LED +# Combines base_ups.yaml with the new ups_status_led component +# Use this for complete UPS monitoring with automatic LED indication + +packages: + base: !include base_ups.yaml + led: !include ups_status_led.yaml + led_controls: !include ups_led_controls.yaml + +# Optional substitutions for LED customization +substitutions: + # LED hardware configuration + led_pin: "GPIO48" # LED data pin + + # LED behavior + led_brightness: "80%" # Default brightness + led_color_mode: "gradient" # gradient or discrete + + # Night mode settings + led_night_mode_enabled: "true" # Enable night mode + led_night_brightness: "30%" # Dimmed brightness (30% of day brightness) + led_night_start: "22:00" # Night mode start + led_night_end: "07:00" # Night mode end + +# This configuration provides: +# - All base UPS functionality +# - Automatic LED status indication with 7 solid color patterns +# - Night mode with time-based dimming +# - Home Assistant controls for LED +# - Battery-aware color display (discrete/gradient modes) +# - No manual automation required! \ No newline at end of file diff --git a/configs/device_types/apc_backups_es.yaml b/configs/device_types/apc_backups_es.yaml index b587be5..99c17c4 100644 --- a/configs/device_types/apc_backups_es.yaml +++ b/configs/device_types/apc_backups_es.yaml @@ -29,6 +29,7 @@ logger: ups_hid: DEBUG ups_hid.apc: DEBUG ups_hid.apc_hid: DEBUG + ups_status_led: DEBUG # APC-specific power calculations sensor: diff --git a/configs/entity_groups.yaml b/configs/entity_groups.yaml index e512797..84be247 100644 --- a/configs/entity_groups.yaml +++ b/configs/entity_groups.yaml @@ -31,6 +31,11 @@ web_server: name: "βš™οΈ Configuration" sorting_weight: 60 + # LED status indication + - id: ups_led_controls + name: "πŸ’‘ LED Status Controls" + sorting_weight: 65 + # Control groups - id: ups_beeper_controls name: "πŸ”” Beeper Controls" diff --git a/configs/examples/apc-ups-monitor.yaml b/configs/examples/apc-ups-monitor.yaml index 472e936..e29f996 100644 --- a/configs/examples/apc-ups-monitor.yaml +++ b/configs/examples/apc-ups-monitor.yaml @@ -21,8 +21,8 @@ packages: # Uncomment to enable organized entity groups in ESPHome web interface entity_groups: !include ../entity_groups.yaml - # Core functionality - base_ups: !include ../base_ups.yaml + # Core functionality with LED status indication + base_with_led: !include ../base_ups_with_led.yaml # Choose EITHER grouped OR standard sensor packages (not both): # Standard packages (current default): diff --git a/configs/examples/rack-ups-monitor.yaml b/configs/examples/rack-ups-monitor.yaml index 3817094..dca7872 100644 --- a/configs/examples/rack-ups-monitor.yaml +++ b/configs/examples/rack-ups-monitor.yaml @@ -24,8 +24,8 @@ packages: # Uncomment to enable organized entity groups in ESPHome web interface entity_groups: !include ../entity_groups.yaml - # Core functionality - base_ups: !include ../base_ups.yaml + # Core functionality with LED status indication + base_with_led: !include ../base_ups_with_led.yaml # Choose EITHER grouped OR standard sensor packages (not both): # Standard packages (current default): diff --git a/configs/testing/led_status_test.yaml b/configs/testing/led_status_test.yaml new file mode 100644 index 0000000..24c8f6c --- /dev/null +++ b/configs/testing/led_status_test.yaml @@ -0,0 +1,112 @@ +# LED Status Component Testing Configuration +# Tests the ups_status_led component with all features enabled +# Uses simulation mode for testing without physical UPS hardware + +substitutions: + name: "led-status-test" + friendly_name: "LED Status Test" + + # Enable simulation for testing + simulation_mode: "true" + update_interval: "5s" # Fast updates for testing + + # LED testing configuration + led_pin: "GPIO48" + led_brightness: "75%" + led_color_mode: "gradient" # Test gradient mode + + # Night mode testing + led_night_mode_enabled: "true" + led_night_brightness: "20%" + led_night_start: "20:00" # Early for testing + led_night_end: "08:00" + + # Timezone for night mode testing + timezone: "UTC" # Use UTC for consistent testing + +esphome: + name: ${name} + friendly_name: ${friendly_name} + +# Use minimal base UPS configuration (without all packages) +packages: + base_ups: !include ../base_ups.yaml + +# Add time component for LED night mode (required by ups_status_led) +time: + - platform: sntp + id: sntp_time + timezone: ${timezone} + servers: + - pool.ntp.org + - time.nist.gov + +# Add LED package manually for testing +light: + - platform: esp32_rmt_led_strip + chipset: WS2812 + pin: ${led_pin} + num_leds: 1 + rgb_order: GRB + name: "UPS Status LED Hardware" + id: ups_status_led_hw + internal: true + restore_mode: ALWAYS_OFF + +# UPS Status LED Component +ups_status_led: + id: ups_led_controller + ups_hid_id: ups_monitor + light_id: ups_status_led_hw + time_id: sntp_time + + enabled: true + brightness: ${led_brightness} + battery_color_mode: ${led_color_mode} + battery_low_threshold: 20 + battery_warning_threshold: 50 + + night_mode: + enabled: ${led_night_mode_enabled} + brightness: ${led_night_brightness} + start_time: ${led_night_start} + end_time: ${led_night_end} + +# Enable required platforms for UPS HID component +sensor: +binary_sensor: +button: + +# Testing features: +# +# LED Pattern Testing (automatic, priority-based, solid colors): +# LED Patterns: +# πŸ”΄ Critical Alert (solid red) - Low battery/fault/overload +# 🟠 Battery Power (solid orange) - Running on battery +# 🟑 Charging (solid yellow) - Battery charging +# 🟒 Normal (solid green) - Normal operation +# πŸ”΅ UPS Offline (solid blue) - UPS disconnected +# 🟣 No Data (solid purple) - Component connected but no data +# βšͺ Error (solid white) - Component error +# +# Home Assistant Entities (auto-created): +# - switch.led_status_test_enabled_switch (master LED control) +# - switch.led_status_test_night_switch (night mode toggle) +# - number.led_status_test_brightness_number (brightness slider) +# - text_sensor.led_status_test_status_sensor (current pattern) +# +# Testing Capabilities: +# βœ… All 7 LED patterns with simulated UPS states +# βœ… Battery-aware gradient color calculation +# βœ… Night mode with time-based scheduling +# βœ… Home Assistant integration and control +# βœ… Data provider pattern usage (no sensors required) +# βœ… Performance optimization verification (10Hz updates, solid colors) +# βœ… Hardware abstraction (WS2812 LED strip) +# +# Usage: +# 1. Compile: esphome config configs/testing/led_status_test.yaml +# 2. Flash to ESP32-S3 with connected WS2812 LED +# 3. Monitor patterns change based on simulated UPS states +# 4. Test Home Assistant controls through web interface +# 5. Verify night mode activation/deactivation \ No newline at end of file diff --git a/configs/testing/minimal_data_provider.yaml b/configs/testing/minimal_data_provider.yaml index 7c544b5..315f243 100644 --- a/configs/testing/minimal_data_provider.yaml +++ b/configs/testing/minimal_data_provider.yaml @@ -14,7 +14,7 @@ esphome: # Use base UPS configuration (now has optional sensors) packages: - base_ups: !include base_ups.yaml + base_ups: !include ../base_ups.yaml # ZERO sensor entities defined - testing pure data provider mode! @@ -59,27 +59,27 @@ interval: switch(test_phase) { case 0: // Test critical state display if (id(ups_monitor).is_low_battery() || id(ups_monitor).has_fault()) { - ESP_LOGI("led_test", "Critical state detected - RED strobe should be active"); + ESP_LOGI("led_test", "Critical state detected - RED solid should be active"); } break; case 1: // Test battery operation if (id(ups_monitor).is_on_battery()) { - ESP_LOGI("led_test", "Battery operation - ORANGE fade should be active"); + ESP_LOGI("led_test", "Battery operation - ORANGE solid should be active"); } break; case 2: // Test charging state if (id(ups_monitor).is_charging()) { - ESP_LOGI("led_test", "Charging state - YELLOW pattern should be active"); + ESP_LOGI("led_test", "Charging state - YELLOW solid should be active"); } break; case 3: // Test normal operation if (id(ups_monitor).is_online()) { - ESP_LOGI("led_test", "Normal operation - GREEN breathing should be active"); + ESP_LOGI("led_test", "Normal operation - GREEN solid should be active"); } break; case 4: // Test offline state if (!id(ups_monitor).is_online()) { - ESP_LOGI("led_test", "Offline state - BLUE fade should be active"); + ESP_LOGI("led_test", "Offline state - BLUE solid should be active"); } break; case 5: // Data provider mode validation diff --git a/configs/testing/north_american_template_test.yaml b/configs/testing/north_american_template_test.yaml deleted file mode 100644 index e1c4765..0000000 --- a/configs/testing/north_american_template_test.yaml +++ /dev/null @@ -1,81 +0,0 @@ -# North American Regional Template Test Configuration -# Tests North American regional defaults (120V/60Hz) -# Use: esphome compile configs/testing/north_american_template_test.yaml - -substitutions: - name: "north-american-test" - friendly_name: "North American Test" - simulation_mode: "true" # Safe testing without hardware - -esphome: - name: "${name}" - friendly_name: "${friendly_name}" - comment: "Testing North American regional template (120V/60Hz)" - -# Core ESP32 configuration -esp32: - board: esp32-s3-devkitc-1 - framework: - type: esp-idf - -# Minimal logging -logger: - level: INFO - baud_rate: 115200 - -# Basic network -wifi: - ssid: "TestNetwork" - password: "TestPassword" - -# External components -external_components: - - source: - type: local - path: ../../components - -# Use North American regional template -packages: - regional_defaults: !include ../regional/north_american_defaults.yaml - -# UPS component (inherits North American defaults from regional template) -ups_hid: - id: ups_monitor - update_interval: 30s - simulation_mode: ${simulation_mode} - # fallback_nominal_voltage comes from regional template (120V North American) - -# Platform stubs -binary_sensor: -button: - -# Test sensors to validate North American regional defaults -sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - name: "Battery Level" - type: battery_level - unit_of_measurement: "%" - - - platform: ups_hid - ups_hid_id: ups_monitor - name: "Input Voltage (North American 120V)" - type: input_voltage - unit_of_measurement: "V" - - - platform: ups_hid - ups_hid_id: ups_monitor - name: "Input Frequency (North American 60Hz)" - type: frequency - unit_of_measurement: "Hz" - -text_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - name: "UPS Status" - type: status - - - platform: ups_hid - ups_hid_id: ups_monitor - name: "Protocol Name" - type: protocol \ No newline at end of file diff --git a/configs/ups_led_controls.yaml b/configs/ups_led_controls.yaml new file mode 100644 index 0000000..2f1cac5 --- /dev/null +++ b/configs/ups_led_controls.yaml @@ -0,0 +1,182 @@ +# UPS LED Controls Package +# Provides Home Assistant and Web UI control entities for ups_status_led component +# Use with: packages: !include configs/ups_led_controls.yaml +# +# Requires: ups_status_led component to be configured with id: ups_led_controller + +# Master LED enable/disable switch +switch: + - platform: template + name: "UPS Status LED" + id: ups_led_enable_switch + icon: "mdi:led-on" + entity_category: config + optimistic: true + restore_mode: RESTORE_DEFAULT_ON + turn_on_action: + - lambda: |- + ESP_LOGI("led_controls", "Enabling LED"); + id(ups_led_controller).set_enabled_api(true); + turn_off_action: + - lambda: |- + ESP_LOGI("led_controls", "Disabling LED"); + id(ups_led_controller).set_enabled_api(false); + + # Night mode toggle switch + - platform: template + name: "UPS LED Night Mode" + id: ups_led_night_mode_switch + icon: "mdi:weather-night" + entity_category: config + optimistic: true + restore_mode: RESTORE_DEFAULT_ON + turn_on_action: + - lambda: |- + ESP_LOGI("led_controls", "Enabling night mode"); + id(ups_led_controller).set_night_mode_enabled_api(true); + turn_off_action: + - lambda: |- + ESP_LOGI("led_controls", "Disabling night mode"); + id(ups_led_controller).set_night_mode_enabled_api(false); + +# Brightness control sliders +number: + - platform: template + name: "UPS LED Brightness" + id: ups_led_brightness_number + icon: "mdi:brightness-percent" + entity_category: config + min_value: 20 # Minimum 20% for meaningful enabled switch + max_value: 100 + step: 5 + unit_of_measurement: "%" + mode: slider + optimistic: true + restore_value: true + initial_value: 80 + set_action: + - lambda: |- + ESP_LOGI("led_controls", "Setting brightness to %.2f%%", x); + id(ups_led_controller).set_brightness_api(x / 100.0); + + - platform: template + name: "UPS LED Night Brightness" + id: ups_led_night_brightness_number + icon: "mdi:brightness-percent" + entity_category: config + min_value: 10 # Night multiplier: 10% of day brightness + max_value: 50 # Up to 50% of day brightness + step: 5 + unit_of_measurement: "%" + mode: slider + optimistic: true + restore_value: true + initial_value: 30 # 30% of day brightness (matches component default) + set_action: + - lambda: "id(ups_led_controller).set_night_mode_brightness_api(x / 100.0);" + + - platform: template + name: "UPS LED Night Start Hour" + id: ups_led_night_start_hour + icon: "mdi:clock-start" + entity_category: config + min_value: 0 + max_value: 23 + step: 1 + mode: slider + optimistic: true + restore_value: true + initial_value: 22 + set_action: + - lambda: "id(ups_led_controller).set_night_mode_start_time_api((int)x, id(ups_led_night_start_minute).state);" + + - platform: template + name: "UPS LED Night Start Minute" + id: ups_led_night_start_minute + icon: "mdi:clock-start" + entity_category: config + min_value: 0 + max_value: 59 + step: 15 + mode: slider + optimistic: true + restore_value: true + initial_value: 0 + set_action: + - lambda: "id(ups_led_controller).set_night_mode_start_time_api(id(ups_led_night_start_hour).state, (int)x);" + + - platform: template + name: "UPS LED Night End Hour" + id: ups_led_night_end_hour + icon: "mdi:clock-end" + entity_category: config + min_value: 0 + max_value: 23 + step: 1 + mode: slider + optimistic: true + restore_value: true + initial_value: 7 + set_action: + - lambda: "id(ups_led_controller).set_night_mode_end_time_api((int)x, id(ups_led_night_end_minute).state);" + + - platform: template + name: "UPS LED Night End Minute" + id: ups_led_night_end_minute + icon: "mdi:clock-end" + entity_category: config + min_value: 0 + max_value: 59 + step: 15 + mode: slider + optimistic: true + restore_value: true + initial_value: 0 + set_action: + - lambda: "id(ups_led_controller).set_night_mode_end_time_api(id(ups_led_night_end_hour).state, (int)x);" + +# Current LED pattern display +text_sensor: + - platform: template + name: "UPS LED Pattern" + id: ups_led_pattern_sensor + icon: "mdi:led-variant-on" + entity_category: diagnostic + lambda: |- + // Match the exact logic from ups_status_led component + if (!id(ups_monitor).is_connected()) { + return {"UPS Offline"}; + } + if (id(ups_monitor).is_low_battery() || id(ups_monitor).has_fault() || id(ups_monitor).is_overloaded()) { + return {"Critical Alert"}; + } + if (id(ups_monitor).is_on_battery()) { + return {"Battery Power"}; + } + if (id(ups_monitor).is_charging()) { + return {"Charging"}; + } + if (id(ups_monitor).is_online()) { + return {"Normal"}; + } + return {"No Data"}; + + update_interval: 2s + +# Usage Notes: +# - All entities use web_server_sorting_weight: 65 to group with LED controls +# - Switches use optimistic mode for immediate UI feedback +# - All number controls use template with lambda for immediate component updates +# - Pattern text sensor shows current active LED pattern +# - Night mode times are adjustable in 15-minute increments +# - All controls persist values and restore after reboot +# - Compatible with ESPHome web server v2 and v3 +# - Integrates seamlessly with Home Assistant +# +# Web UI Controls Provided: +# - UPS LED Brightness (10-100%) +# - UPS LED Night Brightness (5-50%) +# - UPS LED Night Start Hour (0-23) +# - UPS LED Night Start Minute (0, 15, 30, 45) +# - UPS LED Night End Hour (0-23) +# - UPS LED Night End Minute (0, 15, 30, 45) \ No newline at end of file diff --git a/configs/ups_status_led.yaml b/configs/ups_status_led.yaml new file mode 100644 index 0000000..a75aa6f --- /dev/null +++ b/configs/ups_status_led.yaml @@ -0,0 +1,56 @@ +# UPS Status LED Package +# Smart LED status indicator using the new ups_status_led component +# Replaces the manual interval-based LED control with automatic pattern management +# +# Note: Requires 'sntp_time' time component to be defined elsewhere +# (e.g., via regional configuration packages) + +# Physical LED configuration (hardware abstraction) +light: + - platform: esp32_rmt_led_strip + chipset: WS2812 + pin: ${led_pin} + num_leds: 1 + rgb_order: GRB + name: "UPS Status LED Hardware" + id: ups_status_led_hw + internal: true # Hide from HA since controlled by ups_status_led + restore_mode: ALWAYS_OFF + # No effects needed - handled by ups_status_led component + +# UPS Status LED Controller Component +ups_status_led: + id: ups_led_controller + ups_hid_id: ups_monitor # Reference to UPS data provider + light_id: ups_status_led_hw # Reference to physical LED + time_id: sntp_time # Time for night mode scheduling + + enabled: true # Master enable (controllable via HA) + brightness: ${led_brightness} # Default brightness with substitution + + # Battery color behavior + battery_color_mode: ${led_color_mode} # discrete or gradient + battery_low_threshold: 20 # Below = critical red + battery_warning_threshold: 50 # Below = warning orange + + # Night mode configuration + night_mode: + enabled: ${led_night_mode_enabled} + brightness: ${led_night_brightness} + start_time: ${led_night_start} + end_time: ${led_night_end} + +# Home Assistant entities automatically created: +# - switch.ups_status_led (enable/disable) +# - switch.ups_led_night_mode (night mode toggle) +# - number.ups_led_brightness (brightness 10-100%) +# - text_sensor.ups_led_pattern (current pattern) + +# LED Patterns (automatic, priority-based, solid colors): +# 1. CRITICAL (solid red) - Low battery/fault/overload +# 2. BATTERY (solid orange) - On battery power +# 3. CHARGING (solid yellow) - Charging +# 4. NORMAL (solid green) - Normal operation +# 5. OFFLINE (solid blue) - UPS disconnected +# 6. NO DATA (solid purple) - No data from UPS +# 7. ERROR (solid white) - Component error \ No newline at end of file