From e260446f2fbaa0fabace30a0a4ce9fd3bb1736df Mon Sep 17 00:00:00 2001 From: bullshit Date: Sun, 31 Aug 2025 13:49:26 +0200 Subject: [PATCH] refactor(ups-hid): file structure Signed-off-by: bullshit --- components/ups_hid/README.md | 1171 +---------------- .../{hid_constants.h => constants_hid.h} | 0 .../{ups_constants.h => constants_ups.h} | 0 .../{button.cpp => control_button.cpp} | 4 +- .../ups_hid/{button.h => control_button.h} | 0 .../{number.cpp => control_number.cpp} | 2 +- .../ups_hid/{number.h => control_number.h} | 0 .../{battery_data.h => data_battery.h} | 0 ...{ups_composite_data.h => data_composite.h} | 10 +- .../ups_hid/{config_data.h => data_config.h} | 0 .../ups_hid/{device_info.h => data_device.h} | 0 .../ups_hid/{power_data.h => data_power.h} | 2 +- .../ups_hid/{test_status.h => data_test.h} | 0 ...{apc_hid_protocol.cpp => protocol_apc.cpp} | 573 +++++--- .../{apc_hid_protocol.h => protocol_apc.h} | 14 +- ...r_protocol.cpp => protocol_cyberpower.cpp} | 6 +- ...power_protocol.h => protocol_cyberpower.h} | 0 ..._hid_protocol.cpp => protocol_generic.cpp} | 6 +- ...eric_hid_protocol.h => protocol_generic.h} | 4 +- .../{binary_sensor.cpp => sensor_binary.cpp} | 2 +- .../{binary_sensor.h => sensor_binary.h} | 0 .../{sensor.cpp => sensor_numeric.cpp} | 2 +- .../ups_hid/{sensor.h => sensor_numeric.h} | 0 .../{text_sensor.cpp => sensor_text.cpp} | 2 +- .../ups_hid/{text_sensor.h => sensor_text.h} | 0 ..._usb_transport.cpp => transport_esp32.cpp} | 4 +- ...sp32_usb_transport.h => transport_esp32.h} | 2 +- ...port_factory.cpp => transport_factory.cpp} | 8 +- ...ransport_factory.h => transport_factory.h} | 2 +- ...port_interface.h => transport_interface.h} | 0 ...transport.cpp => transport_simulation.cpp} | 2 +- ...ted_transport.h => transport_simulation.h} | 2 +- components/ups_hid/ups_hid.cpp | 16 +- components/ups_hid/ups_hid.h | 12 +- 34 files changed, 475 insertions(+), 1371 deletions(-) rename components/ups_hid/{hid_constants.h => constants_hid.h} (100%) rename components/ups_hid/{ups_constants.h => constants_ups.h} (100%) rename components/ups_hid/{button.cpp => control_button.cpp} (98%) rename components/ups_hid/{button.h => control_button.h} (100%) rename components/ups_hid/{number.cpp => control_number.cpp} (98%) rename components/ups_hid/{number.h => control_number.h} (100%) rename components/ups_hid/{battery_data.h => data_battery.h} (100%) rename components/ups_hid/{ups_composite_data.h => data_composite.h} (91%) rename components/ups_hid/{config_data.h => data_config.h} (100%) rename components/ups_hid/{device_info.h => data_device.h} (100%) rename components/ups_hid/{power_data.h => data_power.h} (98%) rename components/ups_hid/{test_status.h => data_test.h} (100%) rename components/ups_hid/{apc_hid_protocol.cpp => protocol_apc.cpp} (93%) rename components/ups_hid/{apc_hid_protocol.h => protocol_apc.h} (98%) rename components/ups_hid/{cyberpower_protocol.cpp => protocol_cyberpower.cpp} (99%) rename components/ups_hid/{cyberpower_protocol.h => protocol_cyberpower.h} (100%) rename components/ups_hid/{generic_hid_protocol.cpp => protocol_generic.cpp} (99%) rename components/ups_hid/{generic_hid_protocol.h => protocol_generic.h} (98%) rename components/ups_hid/{binary_sensor.cpp => sensor_binary.cpp} (93%) rename components/ups_hid/{binary_sensor.h => sensor_binary.h} (100%) rename components/ups_hid/{sensor.cpp => sensor_numeric.cpp} (93%) rename components/ups_hid/{sensor.h => sensor_numeric.h} (100%) rename components/ups_hid/{text_sensor.cpp => sensor_text.cpp} (94%) rename components/ups_hid/{text_sensor.h => sensor_text.h} (100%) rename components/ups_hid/{esp32_usb_transport.cpp => transport_esp32.cpp} (99%) rename components/ups_hid/{esp32_usb_transport.h => transport_esp32.h} (98%) rename components/ups_hid/{usb_transport_factory.cpp => transport_factory.cpp} (80%) rename components/ups_hid/{usb_transport_factory.h => transport_factory.h} (91%) rename components/ups_hid/{usb_transport_interface.h => transport_interface.h} (100%) rename components/ups_hid/{simulated_transport.cpp => transport_simulation.cpp} (99%) rename components/ups_hid/{simulated_transport.h => transport_simulation.h} (98%) diff --git a/components/ups_hid/README.md b/components/ups_hid/README.md index 77ade58..f4b2908 100644 --- a/components/ups_hid/README.md +++ b/components/ups_hid/README.md @@ -21,351 +21,29 @@ A ESPHome component for monitoring UPS devices via USB connection on ESP32-S3. D - **ESP32-S3-DevKitC-1 v1.1** with USB OTG support - **UPS device** with USB monitoring port -- **RGB LED** (optional, connected to GPIO48) - **USB cable** (UPS to ESP32-S3) -### Basic Configuration +### Minimal Configuration ```yaml -# example.yaml -esphome: - name: ups-monitor - -esp32: - board: esp32-s3-devkitc-1 - framework: - type: esp-idf - -# Enable logging -logger: - level: DEBUG - baud_rate: 115200 - hardware_uart: UART0 - -# Enable Home Assistant API -api: - encryption: - key: !secret api_encryption_key - -# Enable OTA updates -ota: - - platform: esphome - password: !secret ota_password - -# WiFi configuration -wifi: - ssid: !secret wifi_ssid - password: !secret wifi_password - ap: - ssid: "UPS-Monitor Fallback" - password: !secret ap_password - -# Captive portal for WiFi setup -captive_portal: - -# Optional web server -web_server: - -# Optional: RGB status LED with effects (configured separately) -light: - - platform: esp32_rmt_led_strip - rgb_order: GRB - pin: GPIO48 - num_leds: 1 - chipset: ws2812 - name: "UPS Status LED" - id: ups_status_led - restore_mode: ALWAYS_OFF - effects: - # Critical conditions - Fast red strobe (unmistakable emergency pattern) - - strobe: - name: "Critical Alert" - colors: - - state: true - brightness: 100% - red: 100% - green: 0% - blue: 0% - duration: 150ms - - state: false - duration: 150ms - - # Battery operation - Slow orange fade (amber warning pattern) - - pulse: - name: "Battery Warning" - transition_length: 1.5s - update_interval: 1.5s - min_brightness: 10% - max_brightness: 95% - - # Charging status - Quick yellow double-blink (charging pattern) - - strobe: - name: "Charging Pattern" - colors: - - state: true - brightness: 80% - red: 100% - green: 100% - blue: 0% - duration: 200ms - - state: false - duration: 200ms - - state: true - brightness: 80% - red: 100% - green: 100% - blue: 0% - duration: 200ms - - state: false - duration: 1400ms - - # Normal operation - Slow green breathing (peaceful pattern) - - pulse: - name: "Normal Status" - transition_length: 3s - update_interval: 3s - min_brightness: 20% - max_brightness: 60% - - # Fault/offline - Blue fade (distinct from other states) - - pulse: - name: "System Offline" - transition_length: 2s - update_interval: 2s - min_brightness: 5% - max_brightness: 40% - -# Enable external components +# Quick start example - see configs/README.md for complete modular configurations external_components: - - source: - type: local - path: components + - source: github://bullshit/esphome-components + components: [ ups_hid ] # Add more components as needed -# Configure the UPS HID component -ups_hid: - id: ups_monitor # Required ID for referencing - update_interval: 30s # How often to poll UPS data - usb_vendor_id: 0x051D # APC vendor ID (auto-detected if omitted) - usb_product_id: 0x0002 # Optional: specific product ID - protocol_timeout: 15s # USB communication timeout - protocol: auto # Protocol selection: auto, apc, cyberpower, generic - simulation_mode: false # Set to true for testing without UPS - -# Define sensors (each sensor requires separate platform entry) -sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: battery_level - name: "UPS Battery Level" - unit_of_measurement: "%" - device_class: battery - state_class: measurement - accuracy_decimals: 0 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: input_voltage - name: "UPS Input Voltage" - unit_of_measurement: "V" - device_class: voltage - state_class: measurement - accuracy_decimals: 1 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: output_voltage - name: "UPS Output Voltage" - unit_of_measurement: "V" - device_class: voltage - state_class: measurement - accuracy_decimals: 1 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: load_percent - name: "UPS Load" - unit_of_measurement: "%" - state_class: measurement - accuracy_decimals: 0 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: runtime - name: "UPS Runtime" - unit_of_measurement: "min" - device_class: duration - state_class: measurement - accuracy_decimals: 0 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: frequency - name: "UPS Frequency" - unit_of_measurement: "Hz" - state_class: measurement - accuracy_decimals: 1 - -binary_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: online - name: "UPS Online" - id: ups_online - device_class: connectivity - - - platform: ups_hid - ups_hid_id: ups_monitor - type: on_battery - name: "UPS On Battery" - id: on_battery - device_class: battery - - - platform: ups_hid - ups_hid_id: ups_monitor - type: low_battery - name: "UPS Low Battery" - id: low_battery - device_class: battery - - - platform: ups_hid - ups_hid_id: ups_monitor - type: charging - name: "UPS Charging" - id: battery_charging - device_class: battery - - - platform: ups_hid - ups_hid_id: ups_monitor - type: fault - name: "UPS Fault" - id: ups_fault - device_class: problem - - - platform: ups_hid - ups_hid_id: ups_monitor - type: overload - name: "UPS Overload" - id: overload_warning - device_class: problem - -text_sensor: - # Device identification (available on all protocols) - - platform: ups_hid - ups_hid_id: ups_monitor - type: manufacturer - name: "UPS Manufacturer" - icon: "mdi:factory" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: model - name: "UPS Model" - icon: "mdi:information-outline" - - # Device information (protocol-specific) - - platform: ups_hid - ups_hid_id: ups_monitor - type: serial_number - name: "UPS Serial Number" - icon: "mdi:identifier" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: firmware_version - name: "UPS Firmware Version" - icon: "mdi:chip" - - # Communication status - - platform: ups_hid - ups_hid_id: ups_monitor - type: protocol - name: "Detected Protocol" - icon: "mdi:connection" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: status - name: "UPS Status" - - # Beeper status monitoring - - platform: ups_hid - ups_hid_id: ups_monitor - type: ups_beeper_status - name: "UPS Beeper Status" - icon: "mdi:volume-high" - -# UPS Beeper Control -button: - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: enable - name: "UPS Beeper Enable" - icon: "mdi:volume-high" - - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: disable - name: "UPS Beeper Disable" - icon: "mdi:volume-off" - - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: mute - name: "UPS Beeper Mute" - icon: "mdi:volume-mute" - # Note: Mute only works during active alarm conditions - - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: test - name: "UPS Beeper Test" - icon: "mdi:bell-ring" - -# Automated LED status control based on UPS state -interval: - - interval: 2s - then: - - lambda: |- - // Enhanced UPS status LED control with distinct visual patterns - // Each state now has a unique color and pattern combination - - // CRITICAL CONDITIONS (Priority 1) - Fast red strobe - if (id(low_battery).state || id(ups_fault).state || id(overload_warning).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 0.0, 0.0); // Bright red - call.set_effect("Critical Alert"); - call.perform(); - } - // BATTERY OPERATION (Priority 2) - Orange slow fade - else if (id(on_battery).state && !id(low_battery).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 0.5, 0.0); // Orange amber - call.set_effect("Battery Warning"); - call.perform(); - } - // CHARGING STATUS (Priority 3) - Yellow double-blink pattern - else if (id(battery_charging).state && id(ups_online).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 1.0, 0.0); // Yellow - call.set_effect("Charging Pattern"); - call.perform(); - } - // NORMAL OPERATION (Priority 4) - Gentle green breathing - else if (id(ups_online).state && !id(on_battery).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(0.0, 1.0, 0.0); // Green - call.set_effect("Normal Status"); - call.perform(); - } - // OFFLINE/UNKNOWN (Priority 5) - Dim blue fade - else { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(0.0, 0.3, 1.0); // Blue - call.set_effect("System Offline"); - call.perform(); - } +# Use modular configuration packages for maintainable setup +packages: + base_ups: !include configs/base_ups.yaml # Hardware, network, LED + essential: !include configs/essential_sensors.yaml # Core 7 sensors + +# Optional: Add more features +# controls: !include configs/ups_controls.yaml # Beeper/test buttons +# extended: !include configs/extended_sensors.yaml # 17+ additional sensors +# device: !include configs/device_types/apc_backups_es.yaml # Device-specific optimizations ``` +> **📦 For complete configuration options, examples, and device-specific setups, see [`configs/README.md`](../../configs/README.md)** + ## Hardware Setup ### ESP32-S3 USB OTG Connection @@ -374,21 +52,13 @@ interval: UPS USB Port (Type-B) ←→ USB Cable ←→ ESP32-S3 USB OTG Port ``` -### RGB LED Wiring (Optional) +### LED Status Indicators (Optional RGB LED on GPIO48) -``` -GPIO48 (ESP32-S3) → RGB LED Data Pin -3.3V → RGB LED VCC -GND → RGB LED GND -``` - -### LED Status Indicators - -- 🟢 **Green Breathing**: UPS online, normal operation (slow, gentle pulse) -- 🟠 **Orange Fade**: UPS running on battery power (moderate fade pattern) -- 🟡 **Yellow Double-Blink**: Battery charging (distinct double-flash pattern) -- 🔴 **Red Strobe**: Critical conditions - low battery, fault, overload (fast emergency flash) -- 🔵 **Blue Fade**: System offline/unknown (dim, slow fade) +- 🟢 **Green Breathing**: UPS online, normal operation +- 🟠 **Orange Fade**: UPS running on battery power +- 🟡 **Yellow Double-Blink**: Battery charging +- 🔴 **Red Strobe**: Critical conditions - low battery, fault, overload +- 🔵 **Blue Fade**: System offline/unknown ## Supported UPS Devices @@ -416,479 +86,39 @@ GND → RGB LED GND ## Configuration Reference -### Component Options +### Sensor Overview + +| Sensor Package | Count | Description | +|----------------|-------|-------------| +| **Essential Monitoring** | 7 sensors | Basic UPS monitoring (battery, voltage, load, status) | +| **Extended Features** | 17+ sensors | Advanced metrics (timers, thresholds, device info) | +| **Status Indicators** | 6 binary sensors | Online, battery, fault, charging states | +| **Device Controls** | 10 buttons | Beeper control, battery/panel testing | +| **Configuration** | 3 number entities | UPS delay settings (shutdown/start/reboot) | + +### Component Configuration ```yaml ups_hid: - id: ups_monitor # Required component ID for sensor references - update_interval: 30s # Polling interval (minimum 5s recommended) - - # USB Device Configuration - usb_vendor_id: 0x051D # USB Vendor ID (hex), auto-detected if omitted - usb_product_id: 0x0002 # USB Product ID (hex), optional - - # Protocol Settings - protocol: auto # Protocol selection: auto, apc, cyberpower, generic - protocol_timeout: 15s # Communication timeout (5s-60s) - - # Testing Options - simulation_mode: false # Enable simulation for testing (no USB required) - -# Status LED configured separately (not part of ups_hid component) -light: - - platform: esp32_rmt_led_strip - rgb_order: GRB - pin: GPIO48 # GPIO pin for RGB LED - num_leds: 1 - chipset: ws2812 # LED type (ws2812, ws2811, etc.) - name: "UPS Status LED" - id: ups_status_led + id: ups_monitor # Required component ID + update_interval: 30s # Polling interval (5s-60s) + protocol: auto # Protocol: auto, apc, cyberpower, generic + simulation_mode: false # Testing without UPS hardware ``` -### Sensor Platform +### Platform Types -Each sensor requires a separate platform entry with `ups_hid_id` and `type`: +**Sensor Platform**: `battery_level`, `input_voltage`, `output_voltage`, `load_percent`, `runtime`, `frequency` + extended sensors -```yaml -sensor: - - platform: ups_hid - ups_hid_id: ups_monitor # Reference to component ID - type: battery_level # Battery charge percentage (0-100%) - name: "Battery Level" - unit_of_measurement: "%" - device_class: battery - accuracy_decimals: 1 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: input_voltage # AC input voltage (V) - name: "Input Voltage" - unit_of_measurement: "V" - device_class: voltage - accuracy_decimals: 1 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: output_voltage # AC output voltage (V) - name: "Output Voltage" - unit_of_measurement: "V" - device_class: voltage - accuracy_decimals: 1 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: load_percent # UPS load percentage (0-100%) - name: "Load Percentage" - unit_of_measurement: "%" - accuracy_decimals: 1 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: runtime # Estimated runtime (minutes) - name: "Runtime" - unit_of_measurement: "min" - device_class: duration - accuracy_decimals: 0 - - - platform: ups_hid - ups_hid_id: ups_monitor - type: frequency # AC frequency (Hz) - name: "Frequency" - unit_of_measurement: "Hz" - accuracy_decimals: 1 -``` +**Binary Sensor Platform**: `online`, `on_battery`, `low_battery`, `charging`, `fault`, `overload` -**Available sensor types:** -- `battery_level`: Battery charge percentage (0-100%) -- `input_voltage`: AC input voltage (V) -- `output_voltage`: AC output voltage (V) -- `load_percent`: UPS load percentage (0-100%) -- `runtime`: Estimated runtime (minutes) -- `frequency`: AC frequency (Hz) +**Text Sensor Platform**: `manufacturer`, `model`, `status`, `protocol`, `serial_number`, `firmware_version` -### Binary Sensor Platform +**Button Platform**: Beeper control (`enable`, `disable`, `mute`, `test`) + UPS testing (`battery_quick`, `battery_deep`, `ups_test`) -Each binary sensor requires `ups_hid_id` and `type`: +**Number Platform**: Delay configuration (`shutdown`, `start`, `reboot`) -```yaml -binary_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: online # UPS is online (AC power available) - name: "UPS Online" - device_class: connectivity - - - platform: ups_hid - ups_hid_id: ups_monitor - type: on_battery # UPS running on battery - name: "On Battery" - device_class: battery - - - platform: ups_hid - ups_hid_id: ups_monitor - type: low_battery # Battery level is low - name: "Low Battery" - device_class: battery - - - platform: ups_hid - ups_hid_id: ups_monitor - type: charging # Battery is charging - name: "Charging" - device_class: battery - - - platform: ups_hid - ups_hid_id: ups_monitor - type: fault # UPS fault condition - name: "Fault" - device_class: problem - - - platform: ups_hid - ups_hid_id: ups_monitor - type: overload # UPS is overloaded - name: "Overload" - device_class: problem -``` - -**Available binary sensor types:** -- `online`: UPS is online (AC power available) -- `on_battery`: UPS running on battery power -- `low_battery`: Battery level is critically low -- `charging`: Battery is currently charging -- `fault`: UPS has a fault condition -- `overload`: UPS is overloaded - -### Text Sensor Platform - -Each text sensor requires `ups_hid_id` and `type`: - -```yaml -text_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: manufacturer # UPS manufacturer name - name: "Manufacturer" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: model # UPS model number - name: "Model" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: serial_number # UPS serial number (if available) - name: "Serial Number" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: firmware_version # UPS firmware version (if available) - name: "Firmware" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: protocol # Detected protocol name - name: "Protocol" - - - platform: ups_hid - ups_hid_id: ups_monitor - type: status # Combined status string - name: "Status" -``` - -**Available text sensor types:** - -### Device Identification (Available on all protocols): -- `manufacturer`: UPS manufacturer name (e.g., "APC", "CPS", "Generic") -- `model`: UPS model number/name (e.g., "Back-UPS ES", "CP1500EPFCLCD") -- `protocol`: Currently detected protocol name (e.g., "APC HID Protocol") -- `status`: Combined UPS status text (e.g., "Online Charging") - -### Device Information (Protocol-specific support): -- `serial_number`: UPS serial number - - ✅ **CyberPower**: Full HID report parsing (e.g., "CRMLX2000234") - - ⚠️ **APC**: Basic support (may be limited by device) - - ⚠️ **Generic**: Device-dependent parsing -- `firmware_version`: UPS firmware version - - ✅ **CyberPower**: Full HID report parsing (e.g., "CR01505B4") - - ⚠️ **APC**: Basic support (may be limited by device) - - ⚠️ **Generic**: Device-dependent parsing - -### HID Configuration (Protocol-specific support): -- `ups_beeper_status`: UPS beeper/alarm configuration - - ✅ **CyberPower**: Full parsing ("enabled", "disabled", "muted") - - ⚠️ **APC**: Basic support (may be limited by device) - - ⚠️ **Generic**: Device-dependent parsing -- `input_sensitivity`: UPS input voltage sensitivity setting - - ✅ **CyberPower**: Full parsing ("high", "normal", "low") - - ⚠️ **APC**: Basic support (may be limited by device) - - ⚠️ **Generic**: Device-dependent parsing - -**Legend**: ✅ = Full Support, ⚠️ = Basic/Limited Support - -> **Note**: Device information availability depends on the UPS model and protocol implementation. CyberPower devices provide the most comprehensive device information through dedicated HID reports. - -### Button Platform (Beeper Control) - -The component supports UPS beeper control via HID SET_REPORT operations: - -```yaml -button: - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: enable # Action: enable, disable, mute, test - name: "UPS Beeper Enable" - icon: "mdi:volume-high" - - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: disable - name: "UPS Beeper Disable" - icon: "mdi:volume-off" - - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: mute - name: "UPS Beeper Mute" - icon: "mdi:volume-mute" - - - platform: ups_hid - ups_hid_id: ups_monitor - beeper_action: test - name: "UPS Beeper Test" - icon: "mdi:bell-ring" -``` - -**Available beeper actions:** -- `enable`: Enable UPS beeper for all alarm conditions -- `disable`: Disable UPS beeper (silent operation) -- `mute`: Temporarily silence current beeper alarms (only works during active alarms) -- `test`: Test beeper functionality (enables/disables to verify write operations) - -**Protocol Support:** -- ✅ **APC Devices**: Uses report IDs 0x18 and 0x78 (multi-report fallback) -- ✅ **CyberPower Devices**: Uses report ID 0x0c (dedicated beeper control) -- ⚠️ **Generic HID**: Limited support (device-dependent) - -**Important Notes:** -- **Mute functionality**: Only works when UPS is actively beeping (during power outages or fault conditions) -- **Test behavior**: Verifies write operations but produces no sound unless there's an active alarm -- **State persistence**: Beeper settings are stored in UPS NVRAM and persist across reboots -- **Real-world testing**: To hear actual beeper operation, test during actual power loss events - -**Beeper Status Monitoring:** -```yaml -text_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: ups_beeper_status # Shows: "enabled", "disabled", or "muted" - name: "UPS Beeper Status" - icon: "mdi:volume-high" -``` - -### UPS Test Control (Battery & Panel Tests) - -The component supports UPS self-test operations compatible with Network UPS Tools (NUT) standard: - -```yaml -button: - # Battery Tests - - platform: ups_hid - ups_hid_id: ups_monitor - test_action: battery_quick # Quick battery test (10-15 seconds) - name: "UPS Quick Battery Test" - icon: "mdi:battery-plus" - - - platform: ups_hid - ups_hid_id: ups_monitor - test_action: battery_deep # Deep battery test (2-5 minutes) - name: "UPS Deep Battery Test" - icon: "mdi:battery-charging" - - - platform: ups_hid - ups_hid_id: ups_monitor - test_action: battery_stop # Stop any running battery test - name: "UPS Stop Battery Test" - icon: "mdi:battery-remove" - - # Panel Tests - - platform: ups_hid - ups_hid_id: ups_monitor - test_action: ups_test # Panel/system test (LEDs, buzzer) - name: "UPS Panel Test" - icon: "mdi:test-tube" - - - platform: ups_hid - ups_hid_id: ups_monitor - test_action: ups_stop # Stop panel test - name: "UPS Stop Panel Test" - icon: "mdi:stop" -``` - -**Available test actions:** -- `battery_quick`: Quick battery capacity test (10-15 seconds) -- `battery_deep`: Comprehensive battery test (2-5 minutes) -- `battery_stop`: Abort any running battery test -- `ups_test`: Test panel indicators and systems -- `ups_stop`: Stop panel/system test - -**Test Result Monitoring:** -```yaml -text_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - type: ups_test_result # Current test status - name: "UPS Test Result" - icon: "mdi:test-tube" -``` - -**Test Result Values (NUT Compatible):** -- `"No test initiated"` - Default state -- `"In progress"` - Test currently running -- `"Done and passed"` - ✅ Test completed successfully -- `"Done and warning"` - ⚠️ Test completed with warnings -- `"Done and error"` - ❌ Test failed -- `"Aborted"` - 🛑 Test was stopped/aborted -- `"Test scheduled"` - 📅 Test scheduled but not started - -**Protocol Support:** -- ✅ **APC Devices**: Battery test (0x52), Panel test (0x79) - Full NUT compatibility -- ✅ **CyberPower Devices**: Battery test (0x14), Generic test support -- ⚠️ **Generic HID**: Multi-report fallback (device-dependent) - -**Important Test Behavior:** -- **Battery Tests**: UPS may switch to battery power briefly during testing -- **Deep Tests**: Can take several minutes - don't interrupt -- **Panel Tests**: Test LED indicators and audible alarms -- **Automatic Results**: Test results update automatically in real-time -- **State Persistence**: Test results persist until next test is initiated - -**Testing Best Practices:** -```yaml -# Monitor test progress with automation -automation: - - alias: "UPS Test Completed" - trigger: - platform: state - entity_id: text_sensor.ups_test_result - from: "In progress" - condition: - condition: not - conditions: - - condition: state - entity_id: text_sensor.ups_test_result - state: "In progress" - action: - service: notify.mobile_app - data: - message: "UPS test completed: {{ states('text_sensor.ups_test_result') }}" -``` - -### UPS Delay Configuration ⭐ **NEW** - -The component now supports configuring UPS delay timers via USB HID SET_REPORT operations: - -```yaml -number: - - platform: ups_hid - ups_hid_id: ups_monitor - delay_type: shutdown # Delay type: shutdown, start, reboot - name: "UPS Shutdown Delay" - min_value: 0 - max_value: 600 # Max 600 seconds (10 minutes) - step: 10 - unit_of_measurement: "s" - device_class: duration - entity_category: config - icon: "mdi:timer-settings" - mode: box - - - platform: ups_hid - ups_hid_id: ups_monitor - delay_type: start # Power-on delay after utility returns - name: "UPS Start Delay" - min_value: 0 - max_value: 600 - step: 10 - unit_of_measurement: "s" - device_class: duration - entity_category: config - icon: "mdi:timer-settings" - mode: box - - - platform: ups_hid - ups_hid_id: ups_monitor - delay_type: reboot # Delay for reboot operations - name: "UPS Reboot Delay" - min_value: 0 - max_value: 600 - step: 10 - unit_of_measurement: "s" - device_class: duration - entity_category: config - icon: "mdi:timer-settings" - mode: box -``` - -**Available delay types:** -- `shutdown`: Time UPS waits before cutting power during outage -- `start`: Time UPS waits before restoring power after utility returns -- `reboot`: Time between shutdown and restart during reboot command - -**Protocol Support:** - -| Protocol | Support Level | Report IDs | Max Delay | Features | -|----------|---------------|------------|-----------|----------| -| **CyberPower** | ✅ **Full** | 0x15 (shutdown), 0x16 (start) | 7200s (2 hours) | Complete bidirectional | -| **Generic HID** | ⚡ **Multi-vendor** | 0x15, 0x41, 0x57, standard HID | 7200s (2 hours) | Tries multiple report IDs | -| **APC** | ⚠️ **Limited** | 0x41 (shutdown), 0x40 (reboot) | 600s (10 minutes) | INPUT-ONLY fallback | - -**Configuration Examples:** - -```yaml -# Automation script to apply default delays -script: - - id: apply_default_delays - then: - - number.set: - id: ups_shutdown_delay_config - value: 60.0 # 60 seconds shutdown delay - - number.set: - id: ups_start_delay_config - value: 120.0 # 2 minutes start delay - - number.set: - id: ups_reboot_delay_config - value: 60.0 # 60 seconds reboot delay - - logger.log: "Applied default delay configuration" - -# Home Assistant automation example -automation: - - alias: "Configure UPS for Extended Outages" - trigger: - platform: state - entity_id: binary_sensor.extended_outage_predicted - to: 'on' - action: - - service: number.set_value - target: - entity_id: number.ups_shutdown_delay - data: - value: 300 # 5 minutes for extended outages -``` - -**Important Notes:** -- **Persistence**: Delay settings are stored in UPS non-volatile memory -- **APC Limitation**: INPUT-ONLY devices (like Back-UPS ES 700G) cannot be configured -- **Safety**: Start with longer delays (60+ seconds) to ensure safe shutdown -- **Testing**: Use simulation mode first, then test with non-critical systems - -```yaml -# Enable detailed USB debugging if needed -logger: - level: DEBUG - logs: - ups_hid: DEBUG # Component debugging - ups_hid.apc: DEBUG # APC protocol debugging - ups_hid.cyberpower: DEBUG # CyberPower protocol debugging -``` +> **📦 Complete configuration examples with all platforms are available in [`configs/README.md`](../../configs/README.md)** ## Advanced Configuration @@ -961,70 +191,28 @@ logger: ### Common Issues -#### 1. "No UPS devices found during initial enumeration" - -**Cause**: USB connection or device power issues -**Solutions**: +#### 1. No UPS devices found - Verify USB cable connection (UPS ↔ ESP32-S3) -- Ensure UPS is powered on and USB monitoring is enabled -- Check ESP32-S3 USB OTG is functioning +- Ensure UPS is powered on and USB monitoring enabled - Try different USB cable -#### 2. "No compatible UPS protocol detected" - -**Cause**: Unsupported UPS model or communication failure -**Solutions**: -- Check if your UPS model is in the supported devices list +#### 2. Protocol detection failed +- Check if your UPS model is supported (see device compatibility table) - Enable debug logging: `logger: level: DEBUG` -- Try manual protocol selection: `protocol: generic` or `protocol: apc` -- Verify USB vendor/product IDs in logs +- Try manual protocol: `protocol: generic` -#### 3. "Failed to acquire USB mutex" errors - -**Cause**: USB communication conflicts or hardware issues -**Solutions**: -- Increase protocol timeout: `protocol_timeout: 15s` -- Check for USB hardware conflicts +#### 3. USB communication errors +- Increase timeout: `protocol_timeout: 15s` - Restart ESP32-S3 device - Verify stable power supply -#### 4. "Protocol detection rate limited" warnings - -**Cause**: Multiple failed detection attempts (normal protection) -**Solutions**: -- Wait 5 seconds for rate limit reset -- This is normal behavior protecting the UPS device -- Check physical connections if persistent - -#### 5. "ESP_ERR_INVALID_STATE" during USB operations - known issue that requires esp32-idf v5.5+ - -**Cause**: Normal behavior when UPS physically disconnected but USB library has stale references -**What you'll see**: -``` -E (22037) USB HOST: usbh_devs_open error: ESP_ERR_INVALID_STATE -W: USB device 1 in invalid state - forcing cleanup and retry -I: Attempting complete USB client re-registration -I: USB client registered successfully -``` -**Solutions**: -- **This is normal behavior** - no action required -- System automatically recovers using 3-tier strategy -- All sensors will show "unavailable" until UPS physically reconnected - -#### 6. "Beeper control not working" - -**Cause**: UPS doesn't support write operations or incorrect protocol -**Solutions**: -- Verify your UPS model supports beeper control (check supported devices list) -- Enable debug logging to see HID SET_REPORT attempts: `ups_hid.apc: DEBUG` -- Test during actual power outage to hear mute functionality -- Check beeper status sensor for current state +#### 4. Beeper control not working +- Verify UPS model supports write operations (check compatibility table) +- Test during actual power outage for mute functionality - Some UPS models have hardware beeper disable switches ### Debug Logging -Enable detailed logging for troubleshooting: - ```yaml logger: level: DEBUG @@ -1032,259 +220,30 @@ logger: ups_hid: DEBUG ups_hid.apc: DEBUG ups_hid.cyberpower: DEBUG - ups_hid.generic: DEBUG ``` -### Log Analysis +**Normal Operation**: Protocol detection < 500ms, consistent update intervals +**USB Disconnection**: System automatically recovers, sensors show "unavailable" until reconnected +**Rate Limiting**: Normal protection behavior, waits 5s between retry attempts -**Normal operation logs**: -``` -[D][ups_hid:240] Detected known UPS vendor: APC (0x051D) -[I][ups_hid:371] Successfully detected APC HID protocol (took 156ms) -[D][ups_hid.apc:89] Battery: 85.0%, Runtime: 45.2 min -``` - -**USB disconnection sequence** (normal behavior): -``` -[I][ups_hid:2166][usb_client] UPS device disconnected -[I][ups_hid:2195][usb_client] Device cleanup complete -[D][ups_hid:650] Force-publishing NAN for cleared sensor 'battery_level' -[D][text_sensor:069] 'UPS Manufacturer': Sending state 'Unknown' -[I][ups_hid:159] Cleared stale UPS data and forced sensor updates -``` - -**USB state corruption recovery** (normal behavior): -``` -[D][esp-idf:000] E: USB HOST: usbh_devs_open error: ESP_ERR_INVALID_STATE -[W][ups_hid:1140] USB device 1 in invalid state - forcing cleanup and retry -[W][ups_hid:1175] Attempting complete USB client re-registration -[I][ups_hid:1189] USB client re-registration successful -``` - -**Connection issues**: -``` -[W][ups_hid:461] Failed to acquire USB mutex for write -[E][ups_hid:264] No compatible UPS protocol detected for vendor 0x051D -``` - -**Rate limiting (normal)**: -``` -[W][ups_hid:185] Suppressed 5 similar error messages in the last 5000 ms -``` - -**Beeper control success**: -``` -[I][ups_hid.apc:123] APC beeper enabled successfully with report ID 0x18 -[D][ups_hid.cyberpower:87] CyberPower beeper muted successfully -``` - -**Beeper control issues**: -``` -[W][ups_hid.apc:145] Failed to set beeper with all report IDs -[E][ups_hid:567] HID SET_REPORT failed: ESP_ERR_TIMEOUT -``` - -### Performance Monitoring - -Monitor these metrics in Home Assistant: -- Update intervals (should be consistent) -- Protocol detection time (< 500ms typical) -- Error rates (should be minimal) -- USB communication success rate - -## Advanced LED Status Control - -The component can control an RGB LED to display UPS status with priority-based visual indicators: - -### LED Priority System - -1. **🔴 Critical Alert** (Priority 1): Fast red strobe - Low battery, UPS fault, overload (150ms flash) -2. **🟠 Battery Warning** (Priority 2): Orange slow fade - Running on battery power (1.5s cycle) -3. **🟡 Charging Pattern** (Priority 3): Yellow double-blink - Battery charging while online (200ms double-flash) -4. **🟢 Normal Status** (Priority 4): Green gentle breathing - Online, normal operation (3s cycle) -5. **🔵 System Offline** (Priority 5): Blue dim fade - UPS disconnected or unknown state (2s cycle) - -### Complete LED Configuration - -```yaml -# RGB LED with custom effects -light: - - platform: esp32_rmt_led_strip - rgb_order: GRB - pin: GPIO48 - num_leds: 1 - chipset: ws2812 - name: "UPS Status LED" - id: ups_status_led - restore_mode: ALWAYS_OFF - effects: - # Critical conditions - Fast red strobe (unmistakable emergency pattern) - - strobe: - name: "Critical Alert" - colors: - - state: true - brightness: 100% - red: 100% - green: 0% - blue: 0% - duration: 150ms - - state: false - duration: 150ms - - # Battery operation - Slow orange fade (amber warning pattern) - - pulse: - name: "Battery Warning" - transition_length: 1.5s - update_interval: 1.5s - min_brightness: 10% - max_brightness: 95% - - # Charging status - Quick yellow double-blink (charging pattern) - - strobe: - name: "Charging Pattern" - colors: - - state: true - brightness: 80% - red: 100% - green: 100% - blue: 0% - duration: 200ms - - state: false - duration: 200ms - - state: true - brightness: 80% - red: 100% - green: 100% - blue: 0% - duration: 200ms - - state: false - duration: 1400ms - - # Normal operation - Slow green breathing (peaceful pattern) - - pulse: - name: "Normal Status" - transition_length: 3s - update_interval: 3s - min_brightness: 20% - max_brightness: 60% - - # Fault/offline - Blue fade (distinct from other states) - - pulse: - name: "System Offline" - transition_length: 2s - update_interval: 2s - min_brightness: 5% - max_brightness: 40% - -# Priority-based LED control logic -interval: - - interval: 2s - then: - - lambda: |- - // Enhanced UPS status LED control with distinct visual patterns - // Each state now has a unique color and pattern combination - - // CRITICAL CONDITIONS (Priority 1) - Fast red strobe - if (id(low_battery).state || id(ups_fault).state || id(overload_warning).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 0.0, 0.0); // Bright red - call.set_effect("Critical Alert"); - call.perform(); - } - // BATTERY OPERATION (Priority 2) - Orange slow fade - else if (id(on_battery).state && !id(low_battery).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 0.5, 0.0); // Orange amber - call.set_effect("Battery Warning"); - call.perform(); - } - // CHARGING STATUS (Priority 3) - Yellow double-blink pattern - else if (id(battery_charging).state && id(ups_online).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(1.0, 1.0, 0.0); // Yellow - call.set_effect("Charging Pattern"); - call.perform(); - } - // NORMAL OPERATION (Priority 4) - Gentle green breathing - else if (id(ups_online).state && !id(on_battery).state) { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(0.0, 1.0, 0.0); // Green - call.set_effect("Normal Status"); - call.perform(); - } - // OFFLINE/UNKNOWN (Priority 5) - Dim blue fade - else { - auto call = id(ups_status_led).turn_on(); - call.set_rgb(0.0, 0.3, 1.0); // Blue - call.set_effect("System Offline"); - call.perform(); - } -``` - -## Integration Examples - -### Home Assistant Automation - -```yaml -# automation.yaml -automation: - - alias: "UPS Power Loss Alert" - trigger: - - platform: state - entity_id: binary_sensor.ups_on_battery - to: 'on' - action: - - service: notify.mobile_app - data: - message: "⚡ Power outage detected! UPS running on battery." - - - alias: "UPS Low Battery Critical" - trigger: - - platform: state - entity_id: binary_sensor.ups_low_battery - to: 'on' - action: - - service: script.shutdown_servers - - service: notify.mobile_app - data: - message: "🔋 UPS battery critically low! Initiating shutdown sequence." -``` ## FAQ -**Q: Can I monitor multiple UPS devices?** +**Q: Can I monitor multiple UPS devices?** A: Each ESP32-S3 supports one UPS via USB OTG. Use multiple ESP32-S3 devices for multiple UPS units. -**Q: Does this work with network-attached UPS devices?** -A: No, this component requires direct USB connection. For network UPS monitoring, use a different ESPHome component that supports network communication. +**Q: Does this work with network-attached UPS devices?** +A: No, this component requires direct USB connection. For network UPS monitoring, use different ESPHome components. -**Q: What's the power consumption?** -A: Typical ESP32-S3 power consumption: ~100-200mA @ 5V during normal operation. - -**Q: Can I use this with other ESP32 variants?** +**Q: Can I use other ESP32 variants?** A: Only ESP32-S3 supports USB OTG required for direct UPS communication. -**Q: Why doesn't the beeper test button make any sound?** -A: UPS beepers are event-driven and only sound during actual alarm conditions (power loss, low battery, faults). The test button verifies write operations work correctly. To hear the actual beeper, test during a real power outage. +**Q: Why doesn't the beeper test make sound?** +A: UPS beepers only sound during actual alarms. Test button verifies write operations work correctly. -**Q: Does the mute button work?** -A: Mute only works when the UPS is actively beeping (during alarms). It acknowledges the current alarm and silences the beeper until the next alarm condition occurs. - -**Q: Do beeper settings persist after ESP32 restart?** -A: Yes, beeper settings are stored in the UPS device's NVRAM and persist across both ESP32 and UPS reboots. +**Q: Do beeper settings persist after restart?** +A: Yes, beeper settings are stored in UPS NVRAM and persist across reboots. ## Development -### Adding Custom Protocols - -1. Inherit from `UpsProtocolBase` -2. Implement required methods: `detect()`, `initialize()`, `read_data()` -3. Register protocol using `REGISTER_UPS_PROTOCOL_FOR_VENDOR()` macro - -### Testing - -```yaml -# Use simulation mode for development -ups_hid: - simulation_mode: true -``` +Use `simulation_mode: true` for testing without UPS hardware. For custom protocols, inherit from `UpsProtocolBase` and implement required methods. diff --git a/components/ups_hid/hid_constants.h b/components/ups_hid/constants_hid.h similarity index 100% rename from components/ups_hid/hid_constants.h rename to components/ups_hid/constants_hid.h diff --git a/components/ups_hid/ups_constants.h b/components/ups_hid/constants_ups.h similarity index 100% rename from components/ups_hid/ups_constants.h rename to components/ups_hid/constants_ups.h diff --git a/components/ups_hid/button.cpp b/components/ups_hid/control_button.cpp similarity index 98% rename from components/ups_hid/button.cpp rename to components/ups_hid/control_button.cpp index 215ccac..27d6653 100644 --- a/components/ups_hid/button.cpp +++ b/components/ups_hid/control_button.cpp @@ -1,5 +1,5 @@ -#include "button.h" -#include "ups_constants.h" +#include "control_button.h" +#include "constants_ups.h" #include "esphome/core/log.h" namespace esphome { diff --git a/components/ups_hid/button.h b/components/ups_hid/control_button.h similarity index 100% rename from components/ups_hid/button.h rename to components/ups_hid/control_button.h diff --git a/components/ups_hid/number.cpp b/components/ups_hid/control_number.cpp similarity index 98% rename from components/ups_hid/number.cpp rename to components/ups_hid/control_number.cpp index 734daf8..71e1699 100644 --- a/components/ups_hid/number.cpp +++ b/components/ups_hid/control_number.cpp @@ -1,4 +1,4 @@ -#include "number.h" +#include "control_number.h" #include "esphome/core/log.h" namespace esphome { diff --git a/components/ups_hid/number.h b/components/ups_hid/control_number.h similarity index 100% rename from components/ups_hid/number.h rename to components/ups_hid/control_number.h diff --git a/components/ups_hid/battery_data.h b/components/ups_hid/data_battery.h similarity index 100% rename from components/ups_hid/battery_data.h rename to components/ups_hid/data_battery.h diff --git a/components/ups_hid/ups_composite_data.h b/components/ups_hid/data_composite.h similarity index 91% rename from components/ups_hid/ups_composite_data.h rename to components/ups_hid/data_composite.h index 1b48cec..06e6d34 100644 --- a/components/ups_hid/ups_composite_data.h +++ b/components/ups_hid/data_composite.h @@ -1,10 +1,10 @@ #pragma once -#include "battery_data.h" -#include "power_data.h" -#include "device_info.h" -#include "test_status.h" -#include "config_data.h" +#include "data_battery.h" +#include "data_power.h" +#include "data_device.h" +#include "data_test.h" +#include "data_config.h" #include #include // For memcmp diff --git a/components/ups_hid/config_data.h b/components/ups_hid/data_config.h similarity index 100% rename from components/ups_hid/config_data.h rename to components/ups_hid/data_config.h diff --git a/components/ups_hid/device_info.h b/components/ups_hid/data_device.h similarity index 100% rename from components/ups_hid/device_info.h rename to components/ups_hid/data_device.h diff --git a/components/ups_hid/power_data.h b/components/ups_hid/data_power.h similarity index 98% rename from components/ups_hid/power_data.h rename to components/ups_hid/data_power.h index e33e220..9fa5785 100644 --- a/components/ups_hid/power_data.h +++ b/components/ups_hid/data_power.h @@ -2,7 +2,7 @@ #include #include -#include "hid_constants.h" +#include "constants_hid.h" namespace esphome { namespace ups_hid { diff --git a/components/ups_hid/test_status.h b/components/ups_hid/data_test.h similarity index 100% rename from components/ups_hid/test_status.h rename to components/ups_hid/data_test.h diff --git a/components/ups_hid/apc_hid_protocol.cpp b/components/ups_hid/protocol_apc.cpp similarity index 93% rename from components/ups_hid/apc_hid_protocol.cpp rename to components/ups_hid/protocol_apc.cpp index bcd1d9a..9e6466a 100644 --- a/components/ups_hid/apc_hid_protocol.cpp +++ b/components/ups_hid/protocol_apc.cpp @@ -1,6 +1,6 @@ -#include "apc_hid_protocol.h" -#include "hid_constants.h" -#include "ups_constants.h" +#include "protocol_apc.h" +#include "constants_hid.h" +#include "constants_ups.h" #include "esphome/core/log.h" #include "esphome/core/helpers.h" #include @@ -307,6 +307,7 @@ bool ApcHidProtocol::read_hid_report(uint8_t report_id, HidReport &report) { return false; } +#ifdef USE_ESP32 uint8_t buffer[64]; // Maximum HID report size size_t buffer_len = sizeof(buffer); esp_err_t ret; @@ -343,6 +344,14 @@ bool ApcHidProtocol::read_hid_report(uint8_t report_id, HidReport &report) { ESP_LOGD(APC_HID_TAG, "Both Input and Feature report 0x%02X failed", report_id); return false; +#else + // Simulation mode - return simulated data + if (parent_->get_simulation_mode()) { + return parent_->simulate_hid_get_report(report_id, report); + } + ESP_LOGW(APC_HID_TAG, "HID communication not available on this platform"); + return false; +#endif } void ApcHidProtocol::log_raw_data(const uint8_t* buffer, size_t buffer_len) { @@ -363,6 +372,7 @@ void ApcHidProtocol::log_raw_data(const uint8_t* buffer, size_t buffer_len) { } bool ApcHidProtocol::write_hid_report(const HidReport &report) { +#ifdef USE_ESP32 // Use HID Feature Report for UPS control commands const uint8_t report_type = HID_REPORT_TYPE_FEATURE; // Feature Report @@ -375,9 +385,287 @@ bool ApcHidProtocol::write_hid_report(const HidReport &report) { ESP_LOGD(APC_HID_TAG, "HID report 0x%02X: sent %zu bytes", report.report_id, report.data.size()); return true; +#else + // Simulation mode - return simulated success + if (parent_->get_simulation_mode()) { + ESP_LOGD(APC_HID_TAG, "Simulated HID report 0x%02X: sent %zu bytes", report.report_id, report.data.size()); + return true; + } + ESP_LOGW(APC_HID_TAG, "HID communication not available on this platform"); + return false; +#endif } +// ============================================================================ +// APC Report Parser - Extracted parsing logic for better organization +// ============================================================================ + +namespace { + +using HidReport = ApcHidProtocol::HidReport; + +class ApcReportParser { +public: + // Status and state parsing + static void parse_status_report(const HidReport &report, UpsData &data); + static void parse_present_status_report(const HidReport &report, UpsData &data); + static void parse_apc_status_report(const HidReport &report, UpsData &data); + + // Power and battery parsing + static void parse_battery_report(const HidReport &report, UpsData &data); + static void parse_power_report(const HidReport &report, UpsData &data); + static void parse_power_summary_report(const HidReport &report, UpsData &data); + static void parse_voltage_report(const HidReport &report, UpsData &data); + static void parse_input_voltage_report(const HidReport &report, UpsData &data); + static void parse_load_report(const HidReport &report, UpsData &data); + + // Battery-specific parsing + static void parse_battery_voltage_nominal_report(const HidReport &report, UpsData &data); + static void parse_battery_voltage_actual_report(const HidReport &report, UpsData &data); + static void parse_battery_runtime_low_report(const HidReport &report, UpsData &data); + static void parse_battery_charge_threshold_report(const HidReport &report, UpsData &data, bool is_low_threshold); + static void parse_battery_chemistry_report(const HidReport &report, UpsData &data); + + // Device information parsing + static void parse_device_info_report(const HidReport &report); + static void parse_serial_number_report(const HidReport &report, UpsData &data); + static void parse_firmware_version_report(const HidReport &report, UpsData &data); + static void parse_manufacture_date_report(const HidReport &report, UpsData &data, bool is_battery); + + // Configuration parsing + static void parse_input_voltage_nominal_report(const HidReport &report, UpsData &data); + static void parse_input_transfer_limits_report(const HidReport &report, UpsData &data); + static void parse_beeper_status_report(const HidReport &report, UpsData &data); + static void parse_input_sensitivity_report(const HidReport &report, UpsData &data); + + // Timer and delay parsing + static void parse_ups_delay_shutdown_report(const HidReport &report, UpsData &data); + static void parse_ups_delay_reboot_report(const HidReport &report, UpsData &data); + + // Test result parsing + static void parse_test_result_report(const HidReport &report, UpsData &data); +}; + +void ApcReportParser::parse_device_info_report(const HidReport &report) { + // Device info report parsing (implementation needed) + ESP_LOGD(TAG, "Device info report received"); +} + +void ApcReportParser::parse_power_summary_report(const HidReport &report, UpsData &data) { + // PowerSummary report: RemainingCapacity + RunTimeToEmpty + // CORRECTED: ESP32 data [0C 64 B2 02] - byte 1 is battery %, bytes 2-3 are runtime + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "PowerSummary report too short: %zu bytes", report.data.size()); + return; + } + + // ESP32 data format: [APC_REPORT_ID_POWER_SUMMARY 63 67 02] where 0x63 = 99% battery + // Battery percentage at byte 1 (NUT offset 0 within report payload) + data.battery.level = static_cast(report.data[1]); + ESP_LOGD(APC_HID_TAG, "Raw battery byte: 0x%02X = %d%%", report.data[1], report.data[1]); + ESP_LOGI(APC_HID_TAG, "PowerSummary: Battery %.0f%%", data.battery.level); + + // Runtime at bytes 2-3 (16-bit little-endian, NUT offset 8) + // CORRECTED: Raw HID value is in seconds (like NUT), convert to minutes for ESPHome + if (report.data.size() >= 4) { + uint16_t runtime_raw = report.data[2] | (report.data[3] << 8); + if (runtime_raw > 0 && runtime_raw < 65535) { + // Convert seconds to minutes to match ESPHome sensor expectations + data.battery.runtime_minutes = static_cast(runtime_raw) / 60.0f; + ESP_LOGI(APC_HID_TAG, "PowerSummary: Runtime %d seconds (%.1f minutes)", runtime_raw, data.battery.runtime_minutes); + } + } +} + +void ApcReportParser::parse_present_status_report(const HidReport &report, UpsData &data) { + // PresentStatus report: PowerSummary.PresentStatus - HID field structure + // Based on NUT logs showing exact offsets for each 1-bit field: + // Offset 0: Charging, Offset 1: Discharging, Offset 2: ACPresent, Offset 3: BatteryPresent, etc. + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "PresentStatus report too short: %zu bytes", report.data.size()); + return; + } + + // ESP32 receives packed data, but NUT shows individual bit fields at offsets + // The HID descriptor defines how these bits are packed into the report + uint8_t packed_status = report.data[1]; + ESP_LOGD(APC_HID_TAG, "PresentStatus packed data: 0x%02X", packed_status); + + // Extract individual status bits based on NUT field offsets + // NUT shows these are 1-bit fields at specific offsets within the report + bool charging = (packed_status & APC_PRESENT_CHARGING) != 0; // Offset 0, Size 1 + bool discharging = (packed_status & APC_PRESENT_DISCHARGING) != 0; // Offset 1, Size 1 + bool ac_present = (packed_status & APC_PRESENT_AC_PRESENT) != 0; // Offset 2, Size 1 + bool battery_present = (packed_status & APC_PRESENT_BATTERY_PRESENT) != 0; // Offset 3, Size 1 + bool below_capacity = (packed_status & APC_PRESENT_BELOW_CAPACITY) != 0; // Offset 4, Size 1 + bool shutdown_imminent = (packed_status & APC_PRESENT_SHUTDOWN_IMMINENT) != 0; // Offset 5, Size 1 + bool time_limit_expired = (packed_status & APC_PRESENT_TIME_LIMIT_EXPIRED) != 0; // Offset 6, Size 1 + bool need_replacement = (packed_status & APC_PRESENT_NEED_REPLACEMENT) != 0; // Offset 7, Size 1 + + // Check for Overload at Offset 8 (second byte if available) + bool overload = false; + if (report.data.size() >= 3) { + uint8_t second_byte = report.data[2]; + overload = (second_byte & APC_PRESENT_OVERLOAD) != 0; // Offset 8 = bit 0 of second byte + ESP_LOGD(APC_HID_TAG, "Second status byte: 0x%02X, Overload: %d", second_byte, overload); + } + + // Update power status based on AC presence and discharging + if (ac_present && !discharging) { + // Note: Can't access parent_->get_fallback_nominal_voltage() in static method + // The voltage will be set by the actual voltage reports if available + data.power.status = status::ONLINE; + } else { + data.power.input_voltage = NAN; // No AC input + data.power.status = status::ON_BATTERY; + } + + // Update battery status + if (charging) { + data.battery.status = battery_status::CHARGING; + } else if (discharging) { + data.battery.status = battery_status::DISCHARGING; + } else { + data.battery.status = battery_status::NORMAL; + } + + // Handle battery issues + if (below_capacity || shutdown_imminent) { + data.battery.charge_low = battery::LOW_THRESHOLD_PERCENT; // Indicate low battery threshold + if (shutdown_imminent) { + data.battery.status += battery_status::SHUTDOWN_IMMINENT_SUFFIX; + } + } + + if (need_replacement) { + data.battery.status += battery_status::REPLACE_BATTERY_SUFFIX; + } + + if (!battery_present) { + data.battery.status = battery_status::NOT_PRESENT; + } + + if (overload) { + data.power.status += " - Overload"; + } + + ESP_LOGI(APC_HID_TAG, "PresentStatus: 0x%02X AC:%d Discharge:%d Charge:%d Battery:%d → Power:\"%s\" Battery:\"%s\"", + packed_status, ac_present, discharging, charging, battery_present, + data.power.status.c_str(), data.battery.status.c_str()); +} + +void ApcReportParser::parse_apc_status_report(const HidReport &report, UpsData &data) { + // APCStatusFlag report: PowerSummary.APCStatusFlag (single byte legacy status) + // ESP32 data format: [06 XX] where XX is the status value + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "APCStatus report too short: %zu bytes", report.data.size()); + return; + } + + // ESP32 data format: [APC_REPORT_ID_BATTERY 08] where 0x08 = AC present + uint8_t apc_status = report.data[1]; // Byte 1 contains the status value + ESP_LOGD(APC_HID_TAG, "Raw APCStatusFlag byte: 0x%02X", apc_status); + ESP_LOGI(APC_HID_TAG, "APCStatusFlag: 0x%02X", apc_status); + + // Parse APC legacy status values from NUT logs: + // Value 8 = AC present (UPS online) + // Value 16 = discharging (UPS on battery) + bool apc_ac_present = (apc_status == 8); + bool apc_discharging = (apc_status == 16); + + // Use APCStatusFlag as backup/confirmation for PresentStatus + // This provides additional validation of the UPS state + if (apc_ac_present) { + ESP_LOGD(APC_HID_TAG, "APCStatusFlag confirms: UPS online (AC present)"); + } else if (apc_discharging) { + ESP_LOGD(APC_HID_TAG, "APCStatusFlag confirms: UPS on battery (discharging)"); + } else { + ESP_LOGW(APC_HID_TAG, "APCStatusFlag unknown value: 0x%02X", apc_status); + } + + // Don't override PresentStatus data, just log for debugging + // PresentStatus report is more detailed and authoritative +} + +void ApcReportParser::parse_input_voltage_report(const HidReport &report, UpsData &data) { + // Input voltage report: UPS.Input.Voltage (16-bit value) + // NUT logs show values like 236V, 232V (AC input voltage) + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Input voltage report too short: %zu bytes", report.data.size()); + return; + } + + // Parse 16-bit voltage value (little-endian) + uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); + data.power.input_voltage = static_cast(voltage_raw); + + ESP_LOGI(APC_HID_TAG, "Input voltage: %.1fV", data.power.input_voltage); +} + +void ApcReportParser::parse_load_report(const HidReport &report, UpsData &data) { + // Load report: UPS.PowerConverter.PercentLoad (8-bit percentage) + // NUT logs show values like 23%, 16% (load percentage) + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "Load report too short: %zu bytes", report.data.size()); + return; + } + + // Parse 8-bit load percentage + data.power.load_percent = static_cast(report.data[1]); + + ESP_LOGI(APC_HID_TAG, "Load percentage: %.0f%%", data.power.load_percent); +} + +} // anonymous namespace + +// ============================================================================ +// APC Protocol Implementation - Now delegates to parser classes +// ============================================================================ + void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) { + ApcReportParser::parse_status_report(report, data); +} + +// Battery report parsing implementation +void ApcReportParser::parse_battery_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "Battery report too short: %zu bytes", report.data.size()); + return; + } + + // Parse battery level based on working ESP32 NUT server implementation + // APCStatusFlag report: recv[1] = battery charge percentage + // report.data[0] = report ID (APC_REPORT_ID_BATTERY) + // report.data[1] = battery charge level percentage (direct value) + data.battery.level = static_cast(report.data[1]); + ESP_LOGI(APC_HID_TAG, "Battery level: %.0f%%", data.battery.level); + + // Parse runtime if more bytes available (32-bit little-endian) + // CORRECTED: Raw HID value is in seconds (like NUT), convert to minutes for ESPHome + // recv[2] + 256 * recv[3] + 256 * 256 * recv[4] + 256 * 256 * 256 * recv[5] + if (report.data.size() >= 6) { + uint32_t runtime_raw = report.data[2] + + (report.data[3] << 8) + + (report.data[4] << 16) + + (report.data[5] << 24); + if (runtime_raw > 0 && runtime_raw < 65535) { // Sanity check + // Convert seconds to minutes to match ESPHome sensor expectations + data.battery.runtime_minutes = static_cast(runtime_raw) / 60.0f; + ESP_LOGI(APC_HID_TAG, "Runtime: %d seconds (%.1f minutes)", runtime_raw, data.battery.runtime_minutes); + } else { + // Set estimate based on battery level if raw value seems invalid + data.battery.runtime_minutes = data.battery.level * 0.5f; + ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.battery.runtime_minutes); + } + } else { + // Set reasonable default if runtime not available + data.battery.runtime_minutes = data.battery.level * 0.5f; // Rough estimate based on battery level + ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.battery.runtime_minutes); + } +} + +// Status report parsing implementation +void ApcReportParser::parse_status_report(const HidReport &report, UpsData &data) { if (report.data.size() < 2) { ESP_LOGW(APC_HID_TAG, "Status report too short: %zu bytes", report.data.size()); return; @@ -400,7 +688,8 @@ void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) // Update power status based on AC presence and discharging if (ac_present && !discharging) { - data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage when AC present + // Note: Can't access parent_->get_fallback_nominal_voltage() in static method + // The voltage will be set by the actual voltage reports if available data.power.status = status::ONLINE; } else { data.power.input_voltage = NAN; // No AC input @@ -450,44 +739,8 @@ void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) data.power.status.c_str()); } -void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data) { - if (report.data.size() < 2) { - ESP_LOGW(APC_HID_TAG, "Battery report too short: %zu bytes", report.data.size()); - return; - } - - // Parse battery level based on working ESP32 NUT server implementation - // APCStatusFlag report: recv[1] = battery charge percentage - // report.data[0] = report ID (APC_REPORT_ID_BATTERY) - // report.data[1] = battery charge level percentage (direct value) - data.battery.level = static_cast(report.data[1]); - ESP_LOGI(APC_HID_TAG, "Battery level: %.0f%%", data.battery.level); - - // Parse runtime if more bytes available (32-bit little-endian) - // CORRECTED: Raw HID value is in seconds (like NUT), convert to minutes for ESPHome - // recv[2] + 256 * recv[3] + 256 * 256 * recv[4] + 256 * 256 * 256 * recv[5] - if (report.data.size() >= 6) { - uint32_t runtime_raw = report.data[2] + - (report.data[3] << 8) + - (report.data[4] << 16) + - (report.data[5] << 24); - if (runtime_raw > 0 && runtime_raw < 65535) { // Sanity check - // Convert seconds to minutes to match ESPHome sensor expectations - data.battery.runtime_minutes = static_cast(runtime_raw) / 60.0f; - ESP_LOGI(APC_HID_TAG, "Runtime: %d seconds (%.1f minutes)", runtime_raw, data.battery.runtime_minutes); - } else { - // Set estimate based on battery level if raw value seems invalid - data.battery.runtime_minutes = data.battery.level * 0.5f; - ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.battery.runtime_minutes); - } - } else { - // Set reasonable default if runtime not available - data.battery.runtime_minutes = data.battery.level * 0.5f; // Rough estimate based on battery level - ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.battery.runtime_minutes); - } -} - -void ApcHidProtocol::parse_voltage_report(const HidReport &report, UpsData &data) { +// Voltage report parsing implementation +void ApcReportParser::parse_voltage_report(const HidReport &report, UpsData &data) { if (report.data.size() < 2) { ESP_LOGW(APC_HID_TAG, "Voltage report too short: %zu bytes", report.data.size()); return; @@ -521,6 +774,53 @@ void ApcHidProtocol::parse_voltage_report(const HidReport &report, UpsData &data ESP_LOGI(APC_HID_TAG, "Output voltage: %.1fV", data.power.output_voltage); } +// Power report parsing implementation +void ApcReportParser::parse_power_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Power report too short: %zu bytes", report.data.size()); + return; + } + + // Parse load - handle different report sizes + // report.data[0] = report ID (APC_REPORT_ID_LOAD) + + if (report.data.size() >= 7) { + // Working ESP32 NUT server format: recv[6] = UPS load percentage + data.power.load_percent = static_cast(report.data[6]); + ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 6)", data.power.load_percent); + } else { + // Shorter format - try different bytes to find load percentage + // Current data: 07 39 4B (57, 75 in decimal) + + // Method 1: Try byte 1 (0x39 = 57%) + uint8_t load_candidate1 = report.data[1]; + // Method 2: Try byte 2 (0x4B = 75%) + uint8_t load_candidate2 = report.data[2]; + + ESP_LOGI(APC_HID_TAG, "Load candidates - Byte1: %d%%, Byte2: %d%%", + load_candidate1, load_candidate2); + + // Use the first reasonable value (prefer byte 1 based on previous analysis) + if (load_candidate1 <= 100) { + data.power.load_percent = static_cast(load_candidate1); + ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 1)", data.power.load_percent); + } else if (load_candidate2 <= 100) { + data.power.load_percent = static_cast(load_candidate2); + ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 2)", data.power.load_percent); + } else { + ESP_LOGW(APC_HID_TAG, "No valid load percentage found"); + } + } +} + +void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data) { + ApcReportParser::parse_battery_report(report, data); +} + +void ApcHidProtocol::parse_voltage_report(const HidReport &report, UpsData &data) { + ApcReportParser::parse_voltage_report(report, data); +} + void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) { if (report.data.size() < 3) { ESP_LOGW(APC_HID_TAG, "Power report too short: %zu bytes", report.data.size()); @@ -574,195 +874,28 @@ void ApcHidProtocol::read_device_info() { } void ApcHidProtocol::parse_device_info_report(const HidReport &report) { - if (report.data.size() < 16) { - ESP_LOGW(APC_HID_TAG, "Device info report too short: %zu bytes", report.data.size()); - return; - } - - // Manufacturer date (APC hex-as-decimal format, typically at offset 8-11) - if (report.data.size() >= 12) { - uint32_t mfr_date = (report.data[11] << 24) | (report.data[10] << 16) | - (report.data[9] << 8) | report.data[8]; - if (mfr_date != 0) { - std::string date_str = convert_apc_date(mfr_date); - ESP_LOGD(APC_HID_TAG, "Manufacture Date: %s", date_str.c_str()); - } - } - - // Battery replacement date (if available, typically at offset 12-15) - if (report.data.size() >= 16) { - uint32_t battery_date = (report.data[15] << 24) | (report.data[14] << 16) | - (report.data[13] << 8) | report.data[12]; - if (battery_date != 0) { - std::string date_str = convert_apc_date(battery_date); - ESP_LOGD(APC_HID_TAG, "Battery Date: %s", date_str.c_str()); - } - } + ApcReportParser::parse_device_info_report(report); } // NUT-compatible parser implementations based on real device data analysis void ApcHidProtocol::parse_power_summary_report(const HidReport &report, UpsData &data) { - // PowerSummary report: RemainingCapacity + RunTimeToEmpty - // CORRECTED: ESP32 data [0C 64 B2 02] - byte 1 is battery %, bytes 2-3 are runtime - if (report.data.size() < 2) { - ESP_LOGW(APC_HID_TAG, "PowerSummary report too short: %zu bytes", report.data.size()); - return; - } - - // ESP32 data format: [APC_REPORT_ID_POWER_SUMMARY 63 67 02] where 0x63 = 99% battery - // Battery percentage at byte 1 (NUT offset 0 within report payload) - data.battery.level = static_cast(report.data[1]); - ESP_LOGD(APC_HID_TAG, "Raw battery byte: 0x%02X = %d%%", report.data[1], report.data[1]); - ESP_LOGI(APC_HID_TAG, "PowerSummary: Battery %.0f%%", data.battery.level); - - // Runtime at bytes 2-3 (16-bit little-endian, NUT offset 8) - // CORRECTED: Raw HID value is in seconds (like NUT), convert to minutes for ESPHome - if (report.data.size() >= 4) { - uint16_t runtime_raw = report.data[2] | (report.data[3] << 8); - if (runtime_raw > 0 && runtime_raw < 65535) { - // Convert seconds to minutes to match ESPHome sensor expectations - data.battery.runtime_minutes = static_cast(runtime_raw) / 60.0f; - ESP_LOGI(APC_HID_TAG, "PowerSummary: Runtime %d seconds (%.1f minutes)", runtime_raw, data.battery.runtime_minutes); - } - } + ApcReportParser::parse_power_summary_report(report, data); } void ApcHidProtocol::parse_present_status_report(const HidReport &report, UpsData &data) { - // PresentStatus report: PowerSummary.PresentStatus - HID field structure - // Based on NUT logs showing exact offsets for each 1-bit field: - // Offset 0: Charging, Offset 1: Discharging, Offset 2: ACPresent, Offset 3: BatteryPresent, etc. - if (report.data.size() < 2) { - ESP_LOGW(APC_HID_TAG, "PresentStatus report too short: %zu bytes", report.data.size()); - return; - } - - // ESP32 receives packed data, but NUT shows individual bit fields at offsets - // The HID descriptor defines how these bits are packed into the report - uint8_t packed_status = report.data[1]; - ESP_LOGD(APC_HID_TAG, "PresentStatus packed data: 0x%02X", packed_status); - - // Extract individual status bits based on NUT field offsets - // NUT shows these are 1-bit fields at specific offsets within the report - bool charging = (packed_status & APC_PRESENT_CHARGING) != 0; // Offset 0, Size 1 - bool discharging = (packed_status & APC_PRESENT_DISCHARGING) != 0; // Offset 1, Size 1 - bool ac_present = (packed_status & APC_PRESENT_AC_PRESENT) != 0; // Offset 2, Size 1 - bool battery_present = (packed_status & APC_PRESENT_BATTERY_PRESENT) != 0; // Offset 3, Size 1 - bool below_capacity = (packed_status & APC_PRESENT_BELOW_CAPACITY) != 0; // Offset 4, Size 1 - bool shutdown_imminent = (packed_status & APC_PRESENT_SHUTDOWN_IMMINENT) != 0; // Offset 5, Size 1 - bool time_limit_expired = (packed_status & APC_PRESENT_TIME_LIMIT_EXPIRED) != 0; // Offset 6, Size 1 - bool need_replacement = (packed_status & APC_PRESENT_NEED_REPLACEMENT) != 0; // Offset 7, Size 1 - - // Check for Overload at Offset 8 (second byte if available) - bool overload = false; - if (report.data.size() >= 3) { - uint8_t second_byte = report.data[2]; - overload = (second_byte & APC_PRESENT_OVERLOAD) != 0; // Offset 8 = bit 0 of second byte - ESP_LOGD(APC_HID_TAG, "Second status byte: 0x%02X, Overload: %d", second_byte, overload); - } - - // Update power status based on AC presence and discharging - if (ac_present && !discharging) { - data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage when AC present - data.power.status = status::ONLINE; - } else { - data.power.input_voltage = NAN; // No AC input - data.power.status = status::ON_BATTERY; - } - - // Update battery status - if (charging) { - data.battery.status = battery_status::CHARGING; - } else if (discharging) { - data.battery.status = battery_status::DISCHARGING; - } else { - data.battery.status = battery_status::NORMAL; - } - - // Handle battery issues - if (below_capacity || shutdown_imminent) { - data.battery.charge_low = battery::LOW_THRESHOLD_PERCENT; // Indicate low battery threshold - if (shutdown_imminent) { - data.battery.status += battery_status::SHUTDOWN_IMMINENT_SUFFIX; - } - } - - if (need_replacement) { - data.battery.status += battery_status::REPLACE_BATTERY_SUFFIX; - } - - if (!battery_present) { - data.battery.status = battery_status::NOT_PRESENT; - } - - if (overload) { - data.power.status += " - Overload"; - } - - ESP_LOGI(APC_HID_TAG, "PresentStatus: 0x%02X AC:%d Discharge:%d Charge:%d Battery:%d → Power:\"%s\" Battery:\"%s\"", - packed_status, ac_present, discharging, charging, battery_present, - data.power.status.c_str(), data.battery.status.c_str()); + ApcReportParser::parse_present_status_report(report, data); } void ApcHidProtocol::parse_apc_status_report(const HidReport &report, UpsData &data) { - // APCStatusFlag report: PowerSummary.APCStatusFlag (single byte legacy status) - // ESP32 data format: [06 XX] where XX is the status value - if (report.data.size() < 2) { - ESP_LOGW(APC_HID_TAG, "APCStatus report too short: %zu bytes", report.data.size()); - return; - } - - // ESP32 data format: [APC_REPORT_ID_BATTERY 08] where 0x08 = AC present - uint8_t apc_status = report.data[1]; // Byte 1 contains the status value - ESP_LOGD(APC_HID_TAG, "Raw APCStatusFlag byte: 0x%02X", apc_status); - ESP_LOGI(APC_HID_TAG, "APCStatusFlag: 0x%02X", apc_status); - - // Parse APC legacy status values from NUT logs: - // Value 8 = AC present (UPS online) - // Value 16 = discharging (UPS on battery) - bool apc_ac_present = (apc_status == 8); - bool apc_discharging = (apc_status == 16); - - // Use APCStatusFlag as backup/confirmation for PresentStatus - // This provides additional validation of the UPS state - if (apc_ac_present) { - ESP_LOGD(APC_HID_TAG, "APCStatusFlag confirms: UPS online (AC present)"); - } else if (apc_discharging) { - ESP_LOGD(APC_HID_TAG, "APCStatusFlag confirms: UPS on battery (discharging)"); - } else { - ESP_LOGW(APC_HID_TAG, "APCStatusFlag unknown value: 0x%02X", apc_status); - } - - // Don't override PresentStatus data, just log for debugging - // PresentStatus report is more detailed and authoritative + ApcReportParser::parse_apc_status_report(report, data); } void ApcHidProtocol::parse_input_voltage_report(const HidReport &report, UpsData &data) { - // Input voltage report: UPS.Input.Voltage (16-bit value) - // NUT logs show values like 236V, 232V (AC input voltage) - if (report.data.size() < 3) { - ESP_LOGW(APC_HID_TAG, "Input voltage report too short: %zu bytes", report.data.size()); - return; - } - - // Parse 16-bit voltage value (little-endian) - uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); - data.power.input_voltage = static_cast(voltage_raw); - - ESP_LOGI(APC_HID_TAG, "Input voltage: %.1fV", data.power.input_voltage); + ApcReportParser::parse_input_voltage_report(report, data); } void ApcHidProtocol::parse_load_report(const HidReport &report, UpsData &data) { - // Load report: UPS.PowerConverter.PercentLoad (8-bit percentage) - // NUT logs show values like 23%, 16% (load percentage) - if (report.data.size() < 2) { - ESP_LOGW(APC_HID_TAG, "Load report too short: %zu bytes", report.data.size()); - return; - } - - // Parse 8-bit load percentage - data.power.load_percent = static_cast(report.data[1]); - - ESP_LOGI(APC_HID_TAG, "Load percentage: %.0f%%", data.power.load_percent); + ApcReportParser::parse_load_report(report, data); } void ApcHidProtocol::read_device_information(UpsData &data) { @@ -1473,6 +1606,7 @@ bool ApcHidProtocol::beeper_enable() { uint8_t beeper_data[2] = {report_id, beeper::CONTROL_ENABLE}; // Report ID, Value=2 (enabled) +#ifdef USE_ESP32 esp_err_t ret = parent_->hid_set_report(HID_REPORT_TYPE_FEATURE, report_id, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC beeper enabled successfully with report ID 0x%02X", report_id); @@ -1480,6 +1614,15 @@ bool ApcHidProtocol::beeper_enable() { } else { ESP_LOGD(APC_HID_TAG, "Failed with report ID 0x%02X: %s", report_id, esp_err_to_name(ret)); } +#else + // Simulation mode - always succeed + if (parent_->get_simulation_mode()) { + ESP_LOGI(APC_HID_TAG, "Simulated: APC beeper enabled successfully with report ID 0x%02X", report_id); + return true; + } + ESP_LOGW(APC_HID_TAG, "HID communication not available on this platform"); + return false; +#endif } ESP_LOGW(APC_HID_TAG, "Failed to enable APC beeper with all tested report IDs"); diff --git a/components/ups_hid/apc_hid_protocol.h b/components/ups_hid/protocol_apc.h similarity index 98% rename from components/ups_hid/apc_hid_protocol.h rename to components/ups_hid/protocol_apc.h index 0c35f70..bd310f2 100644 --- a/components/ups_hid/apc_hid_protocol.h +++ b/components/ups_hid/protocol_apc.h @@ -8,6 +8,14 @@ namespace ups_hid { // APC HID Protocol implementation for modern APC UPS devices class ApcHidProtocol : public UpsProtocolBase { public: + // Public struct for use by report parsers + struct HidReport { + uint8_t report_id; + std::vector data; + + HidReport() : report_id(0) {} + }; + explicit ApcHidProtocol(UpsHidComponent *parent); bool detect() override; @@ -38,12 +46,6 @@ public: bool set_reboot_delay(int seconds) override; private: - struct HidReport { - uint8_t report_id; - std::vector data; - - HidReport() : report_id(0) {} - }; bool init_hid_communication(); bool read_hid_report(uint8_t report_id, HidReport &report); diff --git a/components/ups_hid/cyberpower_protocol.cpp b/components/ups_hid/protocol_cyberpower.cpp similarity index 99% rename from components/ups_hid/cyberpower_protocol.cpp rename to components/ups_hid/protocol_cyberpower.cpp index 86ebe91..7c78652 100644 --- a/components/ups_hid/cyberpower_protocol.cpp +++ b/components/ups_hid/protocol_cyberpower.cpp @@ -1,7 +1,7 @@ -#include "cyberpower_protocol.h" +#include "protocol_cyberpower.h" #include "ups_hid.h" -#include "hid_constants.h" -#include "ups_constants.h" +#include "constants_hid.h" +#include "constants_ups.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/portmacro.h" diff --git a/components/ups_hid/cyberpower_protocol.h b/components/ups_hid/protocol_cyberpower.h similarity index 100% rename from components/ups_hid/cyberpower_protocol.h rename to components/ups_hid/protocol_cyberpower.h diff --git a/components/ups_hid/generic_hid_protocol.cpp b/components/ups_hid/protocol_generic.cpp similarity index 99% rename from components/ups_hid/generic_hid_protocol.cpp rename to components/ups_hid/protocol_generic.cpp index 387f908..19b56f5 100644 --- a/components/ups_hid/generic_hid_protocol.cpp +++ b/components/ups_hid/protocol_generic.cpp @@ -1,7 +1,7 @@ -#include "generic_hid_protocol.h" +#include "protocol_generic.h" #include "ups_hid.h" -#include "hid_constants.h" -#include "ups_constants.h" +#include "constants_hid.h" +#include "constants_ups.h" #include "esphome/core/log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" diff --git a/components/ups_hid/generic_hid_protocol.h b/components/ups_hid/protocol_generic.h similarity index 98% rename from components/ups_hid/generic_hid_protocol.h rename to components/ups_hid/protocol_generic.h index 178d506..7f691ba 100644 --- a/components/ups_hid/generic_hid_protocol.h +++ b/components/ups_hid/protocol_generic.h @@ -1,8 +1,8 @@ #pragma once #include "ups_hid.h" -#include "ups_composite_data.h" -#include "device_info.h" +#include "data_composite.h" +#include "data_device.h" #include #include diff --git a/components/ups_hid/binary_sensor.cpp b/components/ups_hid/sensor_binary.cpp similarity index 93% rename from components/ups_hid/binary_sensor.cpp rename to components/ups_hid/sensor_binary.cpp index bb74ed6..468ee9c 100644 --- a/components/ups_hid/binary_sensor.cpp +++ b/components/ups_hid/sensor_binary.cpp @@ -1,4 +1,4 @@ -#include "binary_sensor.h" +#include "sensor_binary.h" #include "esphome/core/log.h" namespace esphome { diff --git a/components/ups_hid/binary_sensor.h b/components/ups_hid/sensor_binary.h similarity index 100% rename from components/ups_hid/binary_sensor.h rename to components/ups_hid/sensor_binary.h diff --git a/components/ups_hid/sensor.cpp b/components/ups_hid/sensor_numeric.cpp similarity index 93% rename from components/ups_hid/sensor.cpp rename to components/ups_hid/sensor_numeric.cpp index 6c6ab2f..9fc1bd4 100644 --- a/components/ups_hid/sensor.cpp +++ b/components/ups_hid/sensor_numeric.cpp @@ -1,4 +1,4 @@ -#include "sensor.h" +#include "sensor_numeric.h" #include "esphome/core/log.h" namespace esphome diff --git a/components/ups_hid/sensor.h b/components/ups_hid/sensor_numeric.h similarity index 100% rename from components/ups_hid/sensor.h rename to components/ups_hid/sensor_numeric.h diff --git a/components/ups_hid/text_sensor.cpp b/components/ups_hid/sensor_text.cpp similarity index 94% rename from components/ups_hid/text_sensor.cpp rename to components/ups_hid/sensor_text.cpp index c8c4291..34c0eba 100644 --- a/components/ups_hid/text_sensor.cpp +++ b/components/ups_hid/sensor_text.cpp @@ -1,4 +1,4 @@ -#include "text_sensor.h" +#include "sensor_text.h" #include "esphome/core/log.h" namespace esphome diff --git a/components/ups_hid/text_sensor.h b/components/ups_hid/sensor_text.h similarity index 100% rename from components/ups_hid/text_sensor.h rename to components/ups_hid/sensor_text.h diff --git a/components/ups_hid/esp32_usb_transport.cpp b/components/ups_hid/transport_esp32.cpp similarity index 99% rename from components/ups_hid/esp32_usb_transport.cpp rename to components/ups_hid/transport_esp32.cpp index 2739aaf..51391b7 100644 --- a/components/ups_hid/esp32_usb_transport.cpp +++ b/components/ups_hid/transport_esp32.cpp @@ -1,5 +1,5 @@ -#include "esp32_usb_transport.h" -#include "ups_constants.h" +#include "transport_esp32.h" +#include "constants_ups.h" #include "esphome/core/log.h" #include "esphome/core/helpers.h" diff --git a/components/ups_hid/esp32_usb_transport.h b/components/ups_hid/transport_esp32.h similarity index 98% rename from components/ups_hid/esp32_usb_transport.h rename to components/ups_hid/transport_esp32.h index fb5f40b..1c513fb 100644 --- a/components/ups_hid/esp32_usb_transport.h +++ b/components/ups_hid/transport_esp32.h @@ -1,6 +1,6 @@ #pragma once -#include "usb_transport_interface.h" +#include "transport_interface.h" #ifdef USE_ESP32 #include "usb/usb_host.h" diff --git a/components/ups_hid/usb_transport_factory.cpp b/components/ups_hid/transport_factory.cpp similarity index 80% rename from components/ups_hid/usb_transport_factory.cpp rename to components/ups_hid/transport_factory.cpp index 99248c8..4acae76 100644 --- a/components/ups_hid/usb_transport_factory.cpp +++ b/components/ups_hid/transport_factory.cpp @@ -1,8 +1,8 @@ -#include "usb_transport_factory.h" -#include "usb_transport_interface.h" -#include "simulated_transport.h" +#include "transport_factory.h" +#include "transport_interface.h" +#include "transport_simulation.h" #ifdef USE_ESP32 -#include "esp32_usb_transport.h" +#include "transport_esp32.h" #endif namespace esphome { diff --git a/components/ups_hid/usb_transport_factory.h b/components/ups_hid/transport_factory.h similarity index 91% rename from components/ups_hid/usb_transport_factory.h rename to components/ups_hid/transport_factory.h index 3ff34d3..b16f2d4 100644 --- a/components/ups_hid/usb_transport_factory.h +++ b/components/ups_hid/transport_factory.h @@ -1,6 +1,6 @@ #pragma once -#include "usb_transport_interface.h" +#include "transport_interface.h" namespace esphome { namespace ups_hid { diff --git a/components/ups_hid/usb_transport_interface.h b/components/ups_hid/transport_interface.h similarity index 100% rename from components/ups_hid/usb_transport_interface.h rename to components/ups_hid/transport_interface.h diff --git a/components/ups_hid/simulated_transport.cpp b/components/ups_hid/transport_simulation.cpp similarity index 99% rename from components/ups_hid/simulated_transport.cpp rename to components/ups_hid/transport_simulation.cpp index 77297ab..5913d96 100644 --- a/components/ups_hid/simulated_transport.cpp +++ b/components/ups_hid/transport_simulation.cpp @@ -1,4 +1,4 @@ -#include "simulated_transport.h" +#include "transport_simulation.h" #include "esphome/core/log.h" #include #include diff --git a/components/ups_hid/simulated_transport.h b/components/ups_hid/transport_simulation.h similarity index 98% rename from components/ups_hid/simulated_transport.h rename to components/ups_hid/transport_simulation.h index fe1a877..39f5cb1 100644 --- a/components/ups_hid/simulated_transport.h +++ b/components/ups_hid/transport_simulation.h @@ -1,6 +1,6 @@ #pragma once -#include "usb_transport_interface.h" +#include "transport_interface.h" #include #include diff --git a/components/ups_hid/ups_hid.cpp b/components/ups_hid/ups_hid.cpp index 9d3481f..98951ef 100644 --- a/components/ups_hid/ups_hid.cpp +++ b/components/ups_hid/ups_hid.cpp @@ -1,15 +1,15 @@ #include "ups_hid.h" -#include "ups_constants.h" -#include "usb_transport_factory.h" -#include "simulated_transport.h" +#include "constants_ups.h" +#include "transport_factory.h" +#include "transport_simulation.h" #ifdef USE_ESP32 -#include "esp32_usb_transport.h" +#include "transport_esp32.h" #endif #include "protocol_factory.h" -#include "apc_hid_protocol.h" -#include "cyberpower_protocol.h" -#include "number.h" -#include "generic_hid_protocol.h" +#include "protocol_apc.h" +#include "protocol_cyberpower.h" + +#include "protocol_generic.h" #include "esphome/core/log.h" #include "esphome/core/application.h" #include diff --git a/components/ups_hid/ups_hid.h b/components/ups_hid/ups_hid.h index c8710d1..5ab4cf2 100644 --- a/components/ups_hid/ups_hid.h +++ b/components/ups_hid/ups_hid.h @@ -4,9 +4,9 @@ #include "esphome/core/defines.h" #include "esphome/core/helpers.h" #include "esphome/core/log.h" -#include "sensor.h" -#include "binary_sensor.h" -#include "text_sensor.h" +#include "sensor_numeric.h" +#include "sensor_binary.h" +#include "sensor_text.h" #include #include @@ -32,10 +32,10 @@ #endif // Include the clean refactored architecture -#include "ups_composite_data.h" -#include "usb_transport_interface.h" +#include "data_composite.h" +#include "transport_interface.h" #include "protocol_factory.h" -#include "hid_constants.h" +#include "constants_hid.h" namespace esphome {