diff --git a/components/ups_hid/README.md b/components/ups_hid/README.md index 6cec87b..fff099f 100644 --- a/components/ups_hid/README.md +++ b/components/ups_hid/README.md @@ -147,7 +147,7 @@ ups_hid: 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 - auto_detect_protocol: true # Enable automatic protocol detection + 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) @@ -427,7 +427,7 @@ ups_hid: usb_product_id: 0x0002 # USB Product ID (hex), optional # Protocol Settings - auto_detect_protocol: true # Enable automatic protocol detection + protocol: auto # Protocol selection: auto, apc, cyberpower, generic protocol_timeout: 15s # Communication timeout (5s-60s) # Testing Options @@ -794,14 +794,46 @@ logger: ## Advanced Configuration -### Custom Protocol Priority +### Protocol Selection + +You can now manually select which UPS protocol to use instead of relying on auto-detection: ```yaml ups_hid: - auto_detect_protocol: false # Disable auto-detection - # Component will use APC HID Protocol by default + protocol: auto # Default: automatic selection based on USB vendor ID + # protocol: apc # Force APC HID protocol + # protocol: cyberpower # Force CyberPower HID protocol + # protocol: generic # Force Generic HID protocol ``` +**Protocol Options:** + +- **`auto`** (default): Automatically select protocol based on USB vendor ID + - APC devices (0x051D): Uses APC HID Protocol + - CyberPower (0x0764): Uses CyberPower HID Protocol + - Unknown devices: Falls back to Generic HID Protocol + +- **`apc`**: Force APC HID Protocol + - Use for APC devices: Back-UPS ES, Smart-UPS series + - Comprehensive sensor support with 20+ HID reports + - Battery and beeper testing (device-dependent) + +- **`cyberpower`**: Force CyberPower HID Protocol + - Use for CyberPower CP series devices + - Enhanced sensor support with 12+ additional sensors + - Runtime scaling and advanced thresholds + +- **`generic`**: Force Generic HID Protocol + - Universal fallback for unknown UPS brands + - Basic 5-sensor support with intelligent detection + - Limited beeper/testing functionality + +**When to use manual selection:** +- Testing different protocols on the same device +- Troubleshooting protocol detection issues +- Using non-standard USB vendor/product IDs +- Forcing generic protocol for maximum compatibility + ### Performance Tuning ```yaml @@ -846,7 +878,7 @@ logger: **Solutions**: - Check if your UPS model is in the supported devices list - Enable debug logging: `logger: level: DEBUG` -- Try manual protocol selection: `auto_detect_protocol: false` +- Try manual protocol selection: `protocol: generic` or `protocol: apc` - Verify USB vendor/product IDs in logs #### 3. "Failed to acquire USB mutex" errors diff --git a/components/ups_hid/__init__.py b/components/ups_hid/__init__.py index d929e59..3884735 100644 --- a/components/ups_hid/__init__.py +++ b/components/ups_hid/__init__.py @@ -14,7 +14,8 @@ CONF_SIMULATION_MODE = "simulation_mode" CONF_USB_VENDOR_ID = "usb_vendor_id" CONF_USB_PRODUCT_ID = "usb_product_id" CONF_PROTOCOL_TIMEOUT = "protocol_timeout" -CONF_AUTO_DETECT_PROTOCOL = "auto_detect_protocol" +CONF_PROTOCOL = "protocol" +CONF_FALLBACK_NOMINAL_VOLTAGE = "fallback_nominal_voltage" CONF_UPS_HID_ID = "ups_hid_id" # Known UPS vendor IDs for validation @@ -96,6 +97,18 @@ def validate_update_interval(value): return value +def validate_fallback_nominal_voltage(value): + """Validate fallback nominal voltage for international compatibility.""" + value = cv.voltage(value) + + if value < 80.0: + raise cv.Invalid("Fallback nominal voltage must be at least 80V") + if value > 300.0: + raise cv.Invalid("Fallback nominal voltage must be at most 300V") + + return value + + CONFIG_SCHEMA = cv.All( cv.Schema( { @@ -107,8 +120,12 @@ CONFIG_SCHEMA = cv.All( cv.Optional( CONF_PROTOCOL_TIMEOUT, default="15s" ): validate_protocol_timeout, - # Auto-detection is now always attempted first, this controls fallback behavior - cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean, + # Protocol selection: auto (default), apc, cyberpower, generic + cv.Optional(CONF_PROTOCOL, default="auto"): cv.one_of( + "auto", "apc", "cyberpower", "generic", lower=True + ), + # Fallback nominal voltage (European 230V default for international compatibility) + cv.Optional(CONF_FALLBACK_NOMINAL_VOLTAGE, default="230V"): validate_fallback_nominal_voltage, } ).extend(cv.polling_component_schema("30s")) .extend(cv.COMPONENT_SCHEMA), @@ -129,4 +146,5 @@ async def to_code(config): cg.add(var.set_usb_product_id(config[CONF_USB_PRODUCT_ID])) cg.add(var.set_protocol_timeout(config[CONF_PROTOCOL_TIMEOUT])) - cg.add(var.set_auto_detect_protocol(config[CONF_AUTO_DETECT_PROTOCOL])) + cg.add(var.set_protocol_selection(config[CONF_PROTOCOL])) + cg.add(var.set_fallback_nominal_voltage(config[CONF_FALLBACK_NOMINAL_VOLTAGE])) diff --git a/components/ups_hid/apc_hid_protocol.cpp b/components/ups_hid/apc_hid_protocol.cpp index ac7230a..da85db9 100644 --- a/components/ups_hid/apc_hid_protocol.cpp +++ b/components/ups_hid/apc_hid_protocol.cpp @@ -1,7 +1,10 @@ #include "apc_hid_protocol.h" +#include "hid_constants.h" #include "esphome/core/log.h" #include "esphome/core/helpers.h" #include +#include +#include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/portmacro.h" @@ -175,7 +178,8 @@ bool ApcHidProtocol::read_data(UpsData &data) { } // Set frequency to NaN - not available in debug logs for this APC model - data.frequency = NAN; + // Try to read frequency from HID reports + read_frequency_data(data); ESP_LOGV(APC_HID_TAG, "Frequency: Not available on this UPS model"); // TIMING FIX: Only read USB string descriptors after successful HID communication @@ -189,10 +193,10 @@ bool ApcHidProtocol::read_data(UpsData &data) { esp_err_t mfr_ret = parent_->usb_get_string_descriptor(3, manufacturer_string); if (mfr_ret == ESP_OK && !manufacturer_string.empty()) { - data.manufacturer = manufacturer_string; - ESP_LOGI(APC_HID_TAG, "Successfully read manufacturer from USB descriptor: \"%s\"", data.manufacturer.c_str()); + data.device.manufacturer = manufacturer_string; + ESP_LOGI(APC_HID_TAG, "Successfully read manufacturer from USB descriptor: \"%s\"", data.device.manufacturer.c_str()); } else { - data.manufacturer.clear(); // Set to unset state instead of hardcoded fallback + data.device.manufacturer.clear(); // Set to unset state instead of hardcoded fallback ESP_LOGW(APC_HID_TAG, "Failed to read USB Manufacturer descriptor: %s, leaving unset", esp_err_to_name(mfr_ret)); } @@ -208,10 +212,13 @@ bool ApcHidProtocol::read_data(UpsData &data) { if (fw_pos != std::string::npos) { model_name = model_name.substr(0, fw_pos); } - data.model = model_name; - ESP_LOGI(APC_HID_TAG, "Successfully read APC model from USB Product descriptor: \"%s\"", data.model.c_str()); + data.device.model = model_name; + ESP_LOGI(APC_HID_TAG, "Successfully read APC model from USB Product descriptor: \"%s\"", data.device.model.c_str()); + + // Detect and set nominal power rating based on model name + detect_nominal_power_rating(data.device.model, data); } else { - data.model.clear(); // Set to unset state instead of hardcoded fallback + data.device.model.clear(); // Set to unset state instead of hardcoded fallback ESP_LOGW(APC_HID_TAG, "Failed to read USB Product descriptor: %s, leaving model unset", esp_err_to_name(prod_ret)); } @@ -225,13 +232,13 @@ bool ApcHidProtocol::read_data(UpsData &data) { } else { ESP_LOGW(APC_HID_TAG, "Failed to read any APC HID reports"); // Leave manufacturer and model unset when HID communication fails - data.manufacturer.clear(); - data.model.clear(); + data.device.manufacturer.clear(); + data.device.model.clear(); } // Set default test result - if (data.ups_test_result.empty()) { - data.ups_test_result = "No test initiated"; + if (data.test.ups_test_result.empty()) { + data.test.ups_test_result = "No test initiated"; } return success; @@ -257,7 +264,7 @@ bool ApcHidProtocol::read_hid_report(uint8_t report_id, HidReport &report) { // CRITICAL FIX: Try Input Report first (0x01) - this is what NUT uses for real-time data // Based on NUT logs showing PowerSummary fields work with Input Reports ESP_LOGV(APC_HID_TAG, "Trying Input report 0x%02X...", report_id); - ret = parent_->hid_get_report(0x01, report_id, buffer, &buffer_len); + ret = parent_->hid_get_report(0x01, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { report.report_id = report_id; report.data.assign(buffer, buffer + buffer_len); @@ -275,7 +282,7 @@ bool ApcHidProtocol::read_hid_report(uint8_t report_id, HidReport &report) { // Fall back to Feature Report (0x03) for static/config data buffer_len = sizeof(buffer); // Reset buffer length ESP_LOGV(APC_HID_TAG, "Trying Feature report 0x%02X...", report_id); - ret = parent_->hid_get_report(0x03, report_id, buffer, &buffer_len); + ret = parent_->hid_get_report(0x03, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { report.report_id = report_id; report.data.assign(buffer, buffer + buffer_len); @@ -310,7 +317,7 @@ bool ApcHidProtocol::write_hid_report(const HidReport &report) { const uint8_t report_type = 0x03; // Feature Report esp_err_t ret = parent_->hid_set_report(report_type, report.report_id, - report.data.data(), report.data.size()); + report.data.data(), report.data.size(), parent_->get_protocol_timeout()); if (ret != ESP_OK) { ESP_LOGD(APC_HID_TAG, "HID SET_REPORT failed: %s", esp_err_to_name(ret)); return false; @@ -326,8 +333,6 @@ void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) return; } - uint32_t status_flags = 0; - // Parse APC HID status based on working NUT implementation // report.data[0] = report ID (0x01) // report.data[1] = status flags byte @@ -343,47 +348,56 @@ void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) bool internal_failure = status_byte & 0x40; // Bit 6: Internal failure bool need_replacement = status_byte & 0x80; // Bit 7: Need replacement - // Set primary status flags - prioritize discharging status for accurate battery detection - if (discharging || !ac_present) { - status_flags |= UPS_STATUS_ON_BATTERY; - } else if (ac_present && !discharging) { - status_flags |= UPS_STATUS_ONLINE; + // 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 = "Online"; } else { - // Default to online if status is ambiguous - status_flags |= UPS_STATUS_ONLINE; + data.power.input_voltage = NAN; // No AC input + data.power.status = "On Battery"; } + // Update battery status if (charging) { - status_flags |= UPS_STATUS_CHARGING; + data.battery.status = "Charging"; + } else if (discharging) { + data.battery.status = "Discharging"; + } else { + data.battery.status = "Not Charging"; } + // Check battery health if (!good || internal_failure || need_replacement) { - status_flags |= UPS_STATUS_FAULT; + if (need_replacement) { + data.battery.status += " - Replace Battery"; + } else if (internal_failure) { + data.battery.status += " - Internal Failure"; + } else { + data.battery.status += " - Check Battery"; + } } // Check for additional status bytes if available (flexible parsing) if (report.data.size() >= 3) { uint8_t overload_byte = report.data[2]; if (overload_byte > 0) { - status_flags |= UPS_STATUS_OVERLOAD; + data.power.status += " - Overload"; } } if (report.data.size() >= 4) { uint8_t shutdown_byte = report.data[3]; if (shutdown_byte > 0) { - status_flags |= UPS_STATUS_LOW_BATTERY; + data.battery.charge_low = 10.0f; // Indicate low battery threshold } } - data.status_flags = status_flags; - - ESP_LOGI(APC_HID_TAG, "UPS Status - AC:%s, Charging:%s, Discharging:%s, Good:%s, Flags:0x%02X", + ESP_LOGI(APC_HID_TAG, "UPS Status - AC:%s, Charging:%s, Discharging:%s, Good:%s, Status:\"%s\"", ac_present ? "Yes" : "No", charging ? "Yes" : "No", discharging ? "Yes" : "No", good ? "Yes" : "No", - status_byte); + data.power.status.c_str()); } void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data) { @@ -396,8 +410,8 @@ void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data // Report 0x06: recv[1] = battery charge percentage // report.data[0] = report ID (0x06) // 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); + 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) // recv[2] + 256 * recv[3] + 256 * 256 * recv[4] + 256 * 256 * 256 * recv[5] @@ -407,17 +421,17 @@ void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data (report.data[4] << 16) + (report.data[5] << 24); if (runtime_raw > 0 && runtime_raw < 65535) { // Sanity check - data.runtime_minutes = static_cast(runtime_raw); - ESP_LOGI(APC_HID_TAG, "Runtime: %.0f minutes", data.runtime_minutes); + data.battery.runtime_minutes = static_cast(runtime_raw); + ESP_LOGI(APC_HID_TAG, "Runtime: %.0f minutes", data.battery.runtime_minutes); } else { // Set estimate based on battery level if raw value seems invalid - data.runtime_minutes = data.battery_level * 0.5f; - ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.runtime_minutes); + 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.runtime_minutes = data.battery_level * 0.5f; // Rough estimate based on battery level - ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.runtime_minutes); + 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); } } @@ -450,9 +464,9 @@ void ApcHidProtocol::parse_voltage_report(const HidReport &report, UpsData &data voltage_scaled = static_cast(voltage_raw); } - data.output_voltage = voltage_scaled; + data.power.output_voltage = voltage_scaled; - ESP_LOGI(APC_HID_TAG, "Output voltage: %.1fV", data.output_voltage); + ESP_LOGI(APC_HID_TAG, "Output voltage: %.1fV", data.power.output_voltage); } void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) { @@ -466,8 +480,8 @@ void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) if (report.data.size() >= 7) { // Working ESP32 NUT server format: recv[6] = UPS load percentage - data.load_percent = static_cast(report.data[6]); - ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 6)", data.load_percent); + 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) @@ -482,11 +496,11 @@ void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) // Use the first reasonable value (prefer byte 1 based on previous analysis) if (load_candidate1 <= 100) { - data.load_percent = static_cast(load_candidate1); - ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 1)", data.load_percent); + 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.load_percent = static_cast(load_candidate2); - ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 2)", data.load_percent); + 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"); } @@ -494,9 +508,9 @@ void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) } void ApcHidProtocol::read_device_info() { - // Skip reading device info for input-only devices - if (parent_->is_input_only_device()) { - ESP_LOGD(APC_HID_TAG, "Skipping device info read for input-only device"); + // Skip reading device info if not connected + if (!parent_->is_connected()) { + ESP_LOGD(APC_HID_TAG, "Skipping device info read - device not connected"); return; } @@ -545,15 +559,15 @@ void ApcHidProtocol::parse_power_summary_report(const HidReport &report, UpsData // ESP32 data format: [0C 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]); + 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); + ESP_LOGI(APC_HID_TAG, "PowerSummary: Battery %.0f%%", data.battery.level); // Runtime at bytes 2-3 (16-bit little-endian, NUT offset 8) if (report.data.size() >= 4) { uint16_t runtime_raw = report.data[2] | (report.data[3] << 8); if (runtime_raw > 0 && runtime_raw < 65535) { - data.runtime_minutes = static_cast(runtime_raw); + data.battery.runtime_minutes = static_cast(runtime_raw); ESP_LOGI(APC_HID_TAG, "PowerSummary: Runtime %d minutes", runtime_raw); } } @@ -592,24 +606,47 @@ void ApcHidProtocol::parse_present_status_report(const HidReport &report, UpsDat ESP_LOGD(APC_HID_TAG, "Second status byte: 0x%02X, Overload: %d", second_byte, overload); } - uint32_t status_flags = 0; - - // Set UPS status flags based on NUT behavior patterns + // Update power status based on AC presence and discharging if (ac_present && !discharging) { - status_flags |= UPS_STATUS_ONLINE; - } else if (discharging || !ac_present) { - status_flags |= UPS_STATUS_ON_BATTERY; + data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage when AC present + data.power.status = "Online"; + } else { + data.power.input_voltage = NAN; // No AC input + data.power.status = "On Battery"; } - if (charging) status_flags |= UPS_STATUS_CHARGING; - if (below_capacity || shutdown_imminent) status_flags |= UPS_STATUS_LOW_BATTERY; - if (need_replacement || !battery_present) status_flags |= UPS_STATUS_FAULT; - if (overload) status_flags |= UPS_STATUS_OVERLOAD; + // Update battery status + if (charging) { + data.battery.status = "Charging"; + } else if (discharging) { + data.battery.status = "Discharging"; + } else { + data.battery.status = "Normal"; + } - data.status_flags = status_flags; + // Handle battery issues + if (below_capacity || shutdown_imminent) { + data.battery.charge_low = 10.0f; // Indicate low battery threshold + if (shutdown_imminent) { + data.battery.status += " - Shutdown Imminent"; + } + } - ESP_LOGI(APC_HID_TAG, "PresentStatus: 0x%02X AC:%d Discharge:%d Charge:%d Battery:%d → Status:0x%02X", - packed_status, ac_present, discharging, charging, battery_present, status_flags); + if (need_replacement) { + data.battery.status += " - Replace Battery"; + } + + if (!battery_present) { + data.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 ApcHidProtocol::parse_apc_status_report(const HidReport &report, UpsData &data) { @@ -655,9 +692,9 @@ void ApcHidProtocol::parse_input_voltage_report(const HidReport &report, UpsData // Parse 16-bit voltage value (little-endian) uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); - data.input_voltage = static_cast(voltage_raw); + data.power.input_voltage = static_cast(voltage_raw); - ESP_LOGI(APC_HID_TAG, "Input voltage: %.1fV", data.input_voltage); + ESP_LOGI(APC_HID_TAG, "Input voltage: %.1fV", data.power.input_voltage); } void ApcHidProtocol::parse_load_report(const HidReport &report, UpsData &data) { @@ -669,9 +706,9 @@ void ApcHidProtocol::parse_load_report(const HidReport &report, UpsData &data) { } // Parse 8-bit load percentage - data.load_percent = static_cast(report.data[1]); + data.power.load_percent = static_cast(report.data[1]); - ESP_LOGI(APC_HID_TAG, "Load percentage: %.0f%%", data.load_percent); + ESP_LOGI(APC_HID_TAG, "Load percentage: %.0f%%", data.power.load_percent); } void ApcHidProtocol::read_device_information(UpsData &data) { @@ -726,16 +763,16 @@ void ApcHidProtocol::parse_serial_number_report(const HidReport &report, UpsData esp_err_t ret = parent_->usb_get_string_descriptor(string_index, actual_serial); if (ret == ESP_OK && !actual_serial.empty()) { - data.serial_number = actual_serial; + data.device.serial_number = actual_serial; ESP_LOGI(APC_HID_TAG, "Successfully read APC serial number from USB string descriptor %d: \"%s\"", - string_index, data.serial_number.c_str()); + string_index, data.device.serial_number.c_str()); } else { // Fallback if USB string descriptor reading fails ESP_LOGW(APC_HID_TAG, "Failed to read USB string descriptor %d: %s", string_index, esp_err_to_name(ret)); // Set to unset state instead of generating fallback ID - data.serial_number.clear(); + data.device.serial_number.clear(); ESP_LOGW(APC_HID_TAG, "Leaving serial number unset due to USB string descriptor failure"); } } @@ -759,9 +796,9 @@ void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsD esp_err_t ret = parent_->usb_get_string_descriptor(first_byte, firmware_from_usb); if (ret == ESP_OK && !firmware_from_usb.empty() && - firmware_from_usb != "APC" && firmware_from_usb != data.manufacturer) { + firmware_from_usb != "APC" && firmware_from_usb != data.device.manufacturer) { // Successfully read firmware from USB string descriptor (not manufacturer) - data.firmware_version = firmware_from_usb; + data.device.firmware_version = firmware_from_usb; // Extract auxiliary firmware info (NUT shows ups.firmware.aux: "O4 ") // Format: "871.O4 .I" → main="871.O4" aux="O4" @@ -770,13 +807,13 @@ void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsD std::string after_dot = firmware_from_usb.substr(dot_pos + 1); size_t space_pos = after_dot.find(' '); if (space_pos != std::string::npos) { - data.ups_firmware_aux = after_dot.substr(0, space_pos); - ESP_LOGI(APC_HID_TAG, "Extracted APC firmware aux: \"%s\"", data.ups_firmware_aux.c_str()); + data.device.firmware_aux = after_dot.substr(0, space_pos); + ESP_LOGI(APC_HID_TAG, "Extracted APC firmware aux: \"%s\"", data.device.firmware_aux.c_str()); } } ESP_LOGI(APC_HID_TAG, "Successfully read APC firmware from USB string descriptor %d: \"%s\"", - first_byte, data.firmware_version.c_str()); + first_byte, data.device.firmware_version.c_str()); return; } else { ESP_LOGD(APC_HID_TAG, "USB string descriptor %d read failed or contains manufacturer info: %s, trying other methods", @@ -803,7 +840,7 @@ void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsD if (fw_end != std::string::npos) { extracted_fw = extracted_fw.substr(0, fw_end); } - data.firmware_version = extracted_fw; + data.device.firmware_version = extracted_fw; // Extract auxiliary firmware info from product string // Format: "FW:871.O4" → aux="O4" @@ -812,13 +849,13 @@ void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsD std::string after_fw_dot = extracted_fw.substr(fw_dot_pos + 1); // Remove "FW:" prefix if present if (after_fw_dot.length() >= 2) { - data.ups_firmware_aux = after_fw_dot; - ESP_LOGI(APC_HID_TAG, "Extracted APC firmware aux from product: \"%s\"", data.ups_firmware_aux.c_str()); + data.device.firmware_aux = after_fw_dot; + ESP_LOGI(APC_HID_TAG, "Extracted APC firmware aux from product: \"%s\"", data.device.firmware_aux.c_str()); } } ESP_LOGI(APC_HID_TAG, "Successfully extracted firmware from USB Product descriptor: \"%s\"", - data.firmware_version.c_str()); + data.device.firmware_version.c_str()); return; } } else { @@ -827,16 +864,16 @@ void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsD } // FALLBACK 1B: Parse firmware from the model string if already available - if (!data.model.empty() && data.model.find("FW:") != std::string::npos) { - size_t fw_start = data.model.find("FW:"); + if (!data.device.model.empty() && data.device.model.find("FW:") != std::string::npos) { + size_t fw_start = data.device.model.find("FW:"); if (fw_start != std::string::npos) { - std::string model_fw = data.model.substr(fw_start); + std::string model_fw = data.device.model.substr(fw_start); size_t fw_end = model_fw.find(' ', 3); if (fw_end != std::string::npos) { model_fw = model_fw.substr(0, fw_end); } - data.firmware_version = model_fw; - ESP_LOGI(APC_HID_TAG, "Firmware version extracted from model field: %s", data.firmware_version.c_str()); + data.device.firmware_version = model_fw; + ESP_LOGI(APC_HID_TAG, "Firmware version extracted from model field: %s", data.device.firmware_version.c_str()); return; } } @@ -849,9 +886,9 @@ void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsD } } - if (!firmware_str.empty() && firmware_str != "APC" && firmware_str != data.manufacturer) { - data.firmware_version = firmware_str; - ESP_LOGI(APC_HID_TAG, "Firmware version from HID data: %s", data.firmware_version.c_str()); + if (!firmware_str.empty() && firmware_str != "APC" && firmware_str != data.device.manufacturer) { + data.device.firmware_version = firmware_str; + ESP_LOGI(APC_HID_TAG, "Firmware version from HID data: %s", data.device.firmware_version.c_str()); return; } @@ -860,11 +897,11 @@ void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsD char firmware_fallback[32]; snprintf(firmware_fallback, sizeof(firmware_fallback), "FW:%d.%d", report.data[1], report.data[2]); - data.firmware_version = firmware_fallback; - ESP_LOGD(APC_HID_TAG, "Using binary firmware version fallback: %s", data.firmware_version.c_str()); + data.device.firmware_version = firmware_fallback; + ESP_LOGD(APC_HID_TAG, "Using binary firmware version fallback: %s", data.device.firmware_version.c_str()); } else { // No firmware version could be determined - data.firmware_version.clear(); + data.device.firmware_version.clear(); ESP_LOGW(APC_HID_TAG, "Unable to determine firmware version from any source"); } } @@ -884,19 +921,19 @@ void ApcHidProtocol::parse_beeper_status_report(const HidReport &report, UpsData // DYNAMIC BEEPER STATUS MAPPING: Handle known APC values with intelligent fallbacks switch (beeper_value) { case 1: - data.ups_beeper_status = "disabled"; + data.config.beeper_status = "disabled"; ESP_LOGI(APC_HID_TAG, "APC beeper status: disabled (raw: %d)", beeper_value); break; case 2: - data.ups_beeper_status = "enabled"; + data.config.beeper_status = "enabled"; ESP_LOGI(APC_HID_TAG, "APC beeper status: enabled (raw: %d)", beeper_value); break; case 3: - data.ups_beeper_status = "muted"; + data.config.beeper_status = "muted"; ESP_LOGI(APC_HID_TAG, "APC beeper status: muted (raw: %d)", beeper_value); break; case 0: - data.ups_beeper_status = "disabled"; + data.config.beeper_status = "disabled"; ESP_LOGI(APC_HID_TAG, "APC beeper status: disabled (zero value) (raw: %d)", beeper_value); break; default: @@ -914,30 +951,30 @@ void ApcHidProtocol::parse_beeper_status_report(const HidReport &report, UpsData if (alt_value <= 3) { switch (alt_value) { case 0: - case 1: data.ups_beeper_status = "disabled"; break; - case 2: data.ups_beeper_status = "enabled"; break; - case 3: data.ups_beeper_status = "muted"; break; + case 1: data.config.beeper_status = "disabled"; break; + case 2: data.config.beeper_status = "enabled"; break; + case 3: data.config.beeper_status = "muted"; break; } ESP_LOGI(APC_HID_TAG, "APC beeper status (alt parsing): %s (raw: %d)", - data.ups_beeper_status.c_str(), alt_value); + data.config.beeper_status.c_str(), alt_value); return; } } // Fallback for large values - use boolean logic - data.ups_beeper_status = "enabled"; // Assume enabled for non-zero large values + data.config.beeper_status = "enabled"; // Assume enabled for non-zero large values ESP_LOGW(APC_HID_TAG, "Using default 'enabled' beeper due to unexpected value: %d", beeper_value); } else { // Values 4-99 - extend mapping for future APC models if (beeper_value >= 4 && beeper_value <= 10) { // Map higher values to muted/custom modes - data.ups_beeper_status = "muted"; + data.config.beeper_status = "muted"; ESP_LOGI(APC_HID_TAG, "APC beeper status: muted (extended value) (raw: %d)", beeper_value); } else { // General fallback - use boolean interpretation - data.ups_beeper_status = (beeper_value == 0) ? "disabled" : "enabled"; + data.config.beeper_status = (beeper_value == 0) ? "disabled" : "enabled"; ESP_LOGW(APC_HID_TAG, "Unknown APC beeper value %d, using boolean interpretation: %s", - beeper_value, data.ups_beeper_status.c_str()); + beeper_value, data.config.beeper_status.c_str()); } } break; @@ -959,15 +996,15 @@ void ApcHidProtocol::parse_input_sensitivity_report(const HidReport &report, Ups // DYNAMIC SENSITIVITY MAPPING: Handle known APC values and provide intelligent fallbacks switch (sensitivity_value) { case 0: - data.input_sensitivity = "high"; + data.config.input_sensitivity = "high"; ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: high (raw: %d)", sensitivity_value); break; case 1: - data.input_sensitivity = "normal"; + data.config.input_sensitivity = "normal"; ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: normal (raw: %d)", sensitivity_value); break; case 2: - data.input_sensitivity = "low"; + data.config.input_sensitivity = "low"; ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: low (raw: %d)", sensitivity_value); break; default: @@ -985,26 +1022,26 @@ void ApcHidProtocol::parse_input_sensitivity_report(const HidReport &report, Ups if (alt_value <= 2) { sensitivity_value = alt_value; switch (sensitivity_value) { - case 0: data.input_sensitivity = "high"; break; - case 1: data.input_sensitivity = "normal"; break; - case 2: data.input_sensitivity = "low"; break; + case 0: data.config.input_sensitivity = "high"; break; + case 1: data.config.input_sensitivity = "normal"; break; + case 2: data.config.input_sensitivity = "low"; break; } ESP_LOGI(APC_HID_TAG, "APC Input sensitivity (alt parsing): %s (raw: %d)", - data.input_sensitivity.c_str(), sensitivity_value); + data.config.input_sensitivity.c_str(), sensitivity_value); return; } } - data.input_sensitivity = "unknown"; + data.config.input_sensitivity = "unknown"; ESP_LOGW(APC_HID_TAG, "Unknown APC sensitivity value: %d - please report this for future support", sensitivity_value); } else { // Values 3-99 - extend mapping dynamically if (sensitivity_value == 3) { - data.input_sensitivity = "auto"; + data.config.input_sensitivity = "auto"; ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: auto (raw: %d)", sensitivity_value); } else { - data.input_sensitivity = "unknown"; + data.config.input_sensitivity = "unknown"; ESP_LOGW(APC_HID_TAG, "Unknown APC sensitivity value: %d - please report this for future support", sensitivity_value); } @@ -1067,6 +1104,12 @@ void ApcHidProtocol::read_missing_dynamic_values(UpsData &data) { if (read_hid_report(0x41, ups_delay_shutdown_report)) { parse_ups_delay_shutdown_report(ups_delay_shutdown_report, data); } + + // 7. UPS delay reboot (Report 0x40) + HidReport ups_delay_reboot_report; + if (read_hid_report(0x40, ups_delay_reboot_report)) { + parse_ups_delay_reboot_report(ups_delay_reboot_report, data); + } // 7. Battery charge thresholds (Reports 0x0f, 0x11) HidReport battery_charge_warning_report; @@ -1085,27 +1128,27 @@ void ApcHidProtocol::read_missing_dynamic_values(UpsData &data) { parse_battery_chemistry_report(battery_chemistry_report, data); } - // Note: ups.timer.reboot and ups.timer.shutdown are not in HID reports - // They appear to be calculated/derived values by NUT, set defaults - data.ups_timer_reboot = 0; // Default from NUT - data.ups_timer_shutdown = -1; // Default from NUT - data.ups_timer_start = -1; // Not found in APC debug logs + // Set timer values based on delay settings (negative indicates no active countdown) + // NUT shows these as derived from delay values when no countdown is active + data.test.timer_shutdown = -static_cast(data.config.delay_shutdown); + data.test.timer_start = -static_cast(data.config.delay_start); + // timer_reboot is set in parse_ups_delay_reboot_report() if available // ups.firmware.aux needs to be extracted from firmware string // This will be handled in the existing firmware parsing logic // Set battery status based on current battery level and charging state - if (!std::isnan(data.battery_level)) { - if (data.battery_level >= 90) { - data.battery_status = "Full"; - } else if (data.battery_level >= 20) { - data.battery_status = "Good"; - } else if (data.battery_level >= 10) { - data.battery_status = "Low"; + if (!std::isnan(data.battery.level)) { + if (data.battery.level >= 90) { + data.battery.status = "Full"; + } else if (data.battery.level >= 20) { + data.battery.status = "Good"; + } else if (data.battery.level >= 10) { + data.battery.status = "Low"; } else { - data.battery_status = "Critical"; + data.battery.status = "Critical"; } - ESP_LOGI(APC_HID_TAG, "APC Battery status: %s (%.0f%%)", data.battery_status.c_str(), data.battery_level); + ESP_LOGI(APC_HID_TAG, "APC Battery status: %s (%.0f%%)", data.battery.status.c_str(), data.battery.level); } // 8. Test result reading (Report 0x52 - same as test command) @@ -1128,10 +1171,10 @@ void ApcHidProtocol::parse_battery_voltage_nominal_report(const HidReport &repor // Data format: [ID, volt_low, volt_high] - 16-bit little endian // CRITICAL FIX: Raw value 1200 needs to be scaled to 12.0V (divide by 100) uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); - data.battery_voltage_nominal = static_cast(voltage_raw) / 100.0f; + data.battery.voltage_nominal = static_cast(voltage_raw) / 100.0f; ESP_LOGI(APC_HID_TAG, "APC Battery voltage nominal: %.1fV (raw: 0x%02X%02X = %d, scaled from %d)", - data.battery_voltage_nominal, report.data[2], report.data[1], voltage_raw, voltage_raw); + data.battery.voltage_nominal, report.data[2], report.data[1], voltage_raw, voltage_raw); } void ApcHidProtocol::parse_battery_voltage_actual_report(const HidReport &report, UpsData &data) { @@ -1152,21 +1195,21 @@ void ApcHidProtocol::parse_battery_voltage_actual_report(const HidReport &report // Choose the one closest to expected battery voltage range (10-15V) if (voltage_candidate1 >= 10.0f && voltage_candidate1 <= 20.0f) { - data.battery_voltage = voltage_candidate1; + data.battery.voltage = voltage_candidate1; ESP_LOGI(APC_HID_TAG, "APC Battery voltage: %.2fV (raw: 0x%02X%02X = %d, scaled /100)", - data.battery_voltage, report.data[2], report.data[1], voltage_raw); + data.battery.voltage, report.data[2], report.data[1], voltage_raw); } else if (voltage_candidate2 >= 10.0f && voltage_candidate2 <= 20.0f) { - data.battery_voltage = voltage_candidate2; + data.battery.voltage = voltage_candidate2; ESP_LOGI(APC_HID_TAG, "APC Battery voltage: %.2fV (raw: 0x%02X%02X = %d, scaled /10)", - data.battery_voltage, report.data[2], report.data[1], voltage_raw); + data.battery.voltage, report.data[2], report.data[1], voltage_raw); } else if (voltage_candidate3 >= 10.0f && voltage_candidate3 <= 20.0f) { - data.battery_voltage = voltage_candidate3; + data.battery.voltage = voltage_candidate3; ESP_LOGI(APC_HID_TAG, "APC Battery voltage: %.2fV (raw: 0x%02X%02X = %d, no scaling)", - data.battery_voltage, report.data[2], report.data[1], voltage_raw); + data.battery.voltage, report.data[2], report.data[1], voltage_raw); } else { ESP_LOGW(APC_HID_TAG, "APC Battery voltage out of expected range: raw=%d, candidates: %.2f, %.2f, %.2f", voltage_raw, voltage_candidate1, voltage_candidate2, voltage_candidate3); - data.battery_voltage = voltage_candidate1; // Default to /100 scaling + data.battery.voltage = voltage_candidate1; // Default to /100 scaling } } @@ -1179,10 +1222,10 @@ void ApcHidProtocol::parse_input_voltage_nominal_report(const HidReport &report, // NUT debug: ReportID: 0x30, Value: 230 (UPS.Input.ConfigVoltage) // Data format: [ID, volt_low, volt_high] - 16-bit little endian uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); - data.input_voltage_nominal = static_cast(voltage_raw); + data.power.input_voltage_nominal = static_cast(voltage_raw); ESP_LOGI(APC_HID_TAG, "APC Input voltage nominal: %.0fV (raw: 0x%02X%02X = %d)", - data.input_voltage_nominal, report.data[2], report.data[1], voltage_raw); + data.power.input_voltage_nominal, report.data[2], report.data[1], voltage_raw); } void ApcHidProtocol::parse_input_transfer_limits_report(const HidReport &report, UpsData &data) { @@ -1196,14 +1239,14 @@ void ApcHidProtocol::parse_input_transfer_limits_report(const HidReport &report, if (report.report_id == 0x32) { // NUT debug: ReportID: 0x32, Value: 180 (UPS.Input.LowVoltageTransfer) - data.input_transfer_low = static_cast(limit_raw); + data.power.input_transfer_low = static_cast(limit_raw); ESP_LOGI(APC_HID_TAG, "APC Input transfer low: %.0fV (raw: 0x%02X%02X = %d)", - data.input_transfer_low, report.data[2], report.data[1], limit_raw); + data.power.input_transfer_low, report.data[2], report.data[1], limit_raw); } else if (report.report_id == 0x33) { // NUT debug: ReportID: 0x33, Value: 266 (UPS.Input.HighVoltageTransfer) - data.input_transfer_high = static_cast(limit_raw); + data.power.input_transfer_high = static_cast(limit_raw); ESP_LOGI(APC_HID_TAG, "APC Input transfer high: %.0fV (raw: 0x%02X%02X = %d)", - data.input_transfer_high, report.data[2], report.data[1], limit_raw); + data.power.input_transfer_high, report.data[2], report.data[1], limit_raw); } } @@ -1216,10 +1259,10 @@ void ApcHidProtocol::parse_battery_runtime_low_report(const HidReport &report, U // NUT debug: ReportID: 0x24, Value: 120 (UPS.Battery.RemainingTimeLimit) // Data format: [ID, time_low, time_high] - 16-bit little endian uint16_t time_raw = report.data[1] | (report.data[2] << 8); - data.battery_runtime_low = static_cast(time_raw); + data.battery.runtime_low = static_cast(time_raw); ESP_LOGI(APC_HID_TAG, "APC Battery runtime low threshold: %.0f minutes (raw: 0x%02X%02X = %d)", - data.battery_runtime_low, report.data[2], report.data[1], time_raw); + data.battery.runtime_low, report.data[2], report.data[1], time_raw); } void ApcHidProtocol::parse_manufacture_date_report(const HidReport &report, UpsData &data, bool is_battery) { @@ -1237,13 +1280,13 @@ void ApcHidProtocol::parse_manufacture_date_report(const HidReport &report, UpsD std::string date_str = convert_apc_date(date_raw); if (is_battery) { - data.battery_mfr_date = date_str; + data.battery.mfr_date = date_str; ESP_LOGI(APC_HID_TAG, "APC Battery manufacture date: %s (raw: %d)", - data.battery_mfr_date.c_str(), date_raw); + data.battery.mfr_date.c_str(), date_raw); } else { - data.ups_mfr_date = date_str; + data.device.mfr_date = date_str; ESP_LOGI(APC_HID_TAG, "APC UPS manufacture date: %s (raw: %d)", - data.ups_mfr_date.c_str(), date_raw); + data.device.mfr_date.c_str(), date_raw); } } @@ -1261,16 +1304,33 @@ void ApcHidProtocol::parse_ups_delay_shutdown_report(const HidReport &report, Up if (delay_raw == -1) { // NUT shows 20 seconds for this APC model when HID shows -1 // This is likely a model-specific default value - data.ups_delay_shutdown = 20; // Use NUT's processed value + data.config.delay_shutdown = 20; // Use NUT's processed value ESP_LOGI(APC_HID_TAG, "APC UPS delay shutdown: %d seconds (processed from HID value %d)", - data.ups_delay_shutdown, delay_raw); + data.config.delay_shutdown, delay_raw); } else { - data.ups_delay_shutdown = delay_raw; + data.config.delay_shutdown = delay_raw; ESP_LOGI(APC_HID_TAG, "APC UPS delay shutdown: %d seconds (raw: %d)", - data.ups_delay_shutdown, delay_raw); + data.config.delay_shutdown, delay_raw); } } +void ApcHidProtocol::parse_ups_delay_reboot_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "UPS delay reboot report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug: ReportID: 0x40, Value: 0 + // APC uses 8-bit value for reboot delay + uint8_t delay_raw = report.data[1]; + + // Set both delay and timer values + data.config.delay_reboot = static_cast(delay_raw); + data.test.timer_reboot = -static_cast(delay_raw); // Negative indicates no active countdown + + ESP_LOGI(APC_HID_TAG, "APC UPS delay reboot: %d seconds", data.config.delay_reboot); +} + std::string ApcHidProtocol::convert_apc_date(uint16_t date_value) { ESP_LOGD(APC_HID_TAG, "Converting USB PDC date value: %u (0x%04X)", date_value, date_value); @@ -1314,14 +1374,14 @@ void ApcHidProtocol::parse_battery_charge_threshold_report(const HidReport &repo if (is_low_threshold) { // NUT debug: ReportID: 0x11, Value: 10 (RemainingCapacityLimit) - data.battery_charge_low = static_cast(threshold_raw); + data.battery.charge_low = static_cast(threshold_raw); ESP_LOGI(APC_HID_TAG, "APC Battery charge low threshold: %.0f%% (raw: %d)", - data.battery_charge_low, threshold_raw); + data.battery.charge_low, threshold_raw); } else { // NUT debug: ReportID: 0x0f, Value: 50 (WarningCapacityLimit) - data.battery_charge_warning = static_cast(threshold_raw); + data.battery.charge_warning = static_cast(threshold_raw); ESP_LOGI(APC_HID_TAG, "APC Battery charge warning threshold: %.0f%% (raw: %d)", - data.battery_charge_warning, threshold_raw); + data.battery.charge_warning, threshold_raw); } } @@ -1337,31 +1397,31 @@ void ApcHidProtocol::parse_battery_chemistry_report(const HidReport &report, Ups // Map chemistry values based on NUT libhid implementation switch (chemistry_raw) { case 1: - data.battery_type = "Alkaline"; + data.battery.type = "Alkaline"; break; case 2: - data.battery_type = "NiCd"; + data.battery.type = "NiCd"; break; case 3: - data.battery_type = "NiMH"; + data.battery.type = "NiMH"; break; case 4: - data.battery_type = "PbAc"; // Lead Acid (matches NUT output) + data.battery.type = "PbAc"; // Lead Acid (matches NUT output) break; case 5: - data.battery_type = "LiIon"; + data.battery.type = "LiIon"; break; case 6: - data.battery_type = "LiPoly"; + data.battery.type = "LiPoly"; break; default: - data.battery_type = "Unknown"; + data.battery.type = "Unknown"; ESP_LOGW(APC_HID_TAG, "Unknown APC battery chemistry value: %d", chemistry_raw); break; } ESP_LOGI(APC_HID_TAG, "APC Battery chemistry: %s (raw: %d)", - data.battery_type.c_str(), chemistry_raw); + data.battery.type.c_str(), chemistry_raw); } bool ApcHidProtocol::beeper_enable() { @@ -1378,7 +1438,7 @@ bool ApcHidProtocol::beeper_enable() { uint8_t beeper_data[2] = {report_id, 0x02}; // Report ID, Value=2 (enabled) - esp_err_t ret = parent_->hid_set_report(0x03, report_id, beeper_data, sizeof(beeper_data)); + esp_err_t ret = parent_->hid_set_report(0x03, 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); return true; @@ -1405,7 +1465,7 @@ bool ApcHidProtocol::beeper_disable() { uint8_t beeper_data[2] = {report_id, 0x01}; // Report ID, Value=1 (disabled) - esp_err_t ret = parent_->hid_set_report(0x03, report_id, beeper_data, sizeof(beeper_data)); + esp_err_t ret = parent_->hid_set_report(0x03, report_id, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC beeper disabled successfully with report ID 0x%02X", report_id); return true; @@ -1435,7 +1495,7 @@ bool ApcHidProtocol::beeper_mute() { uint8_t beeper_data[2] = {report_id, 0x03}; // Report ID, Value=3 (muted/acknowledged) - esp_err_t ret = parent_->hid_set_report(0x03, report_id, beeper_data, sizeof(beeper_data)); + esp_err_t ret = parent_->hid_set_report(0x03, report_id, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC beeper muted (current alarms acknowledged) with report ID 0x%02X", report_id); return true; @@ -1490,7 +1550,7 @@ bool ApcHidProtocol::beeper_test() { // Step 4: Restore original beeper state ESP_LOGI(APC_HID_TAG, "Step 4: Restoring original beeper state: %d", original_state); uint8_t restore_data[2] = {0x18, original_state}; - esp_err_t ret = parent_->hid_set_report(0x03, APC_REPORT_ID_AUDIBLE_ALARM, restore_data, sizeof(restore_data)); + esp_err_t ret = parent_->hid_set_report(0x03, APC_REPORT_ID_AUDIBLE_ALARM, restore_data, sizeof(restore_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC beeper test sequence completed successfully"); @@ -1505,16 +1565,31 @@ bool ApcHidProtocol::beeper_test() { bool ApcHidProtocol::start_battery_test_quick() { ESP_LOGI(APC_HID_TAG, "Starting APC quick battery test"); - // Based on NUT debug logs, APC uses report ID 0x52 for battery test + // Check if device supports SET_REPORT operations + if (!parent_->get_vendor_id()) { + ESP_LOGW(APC_HID_TAG, "Device not available for test commands"); + return false; + } + + // APC Back-UPS ES 700G (PID=0x0002) is INPUT-ONLY and doesn't support HID SET_REPORT + uint16_t product_id = parent_->get_product_id(); + if (product_id == 0x0002) { + ESP_LOGW(APC_HID_TAG, "APC Back-UPS ES 700G (PID=0x0002) is INPUT-ONLY device - battery tests not supported via HID"); + ESP_LOGI(APC_HID_TAG, "Tip: Use the physical TEST button on the UPS instead"); + return false; + } + + // For supported models: Based on NUT debug logs, APC uses report ID 0x52 for battery test // Command value 1 = Quick test (based on NUT test_write_info struct) uint8_t test_data[2] = {0x52, 1}; - esp_err_t ret = parent_->hid_set_report(0x03, 0x52, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, 0x52, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC quick battery test command sent successfully"); return true; } else { ESP_LOGW(APC_HID_TAG, "Failed to send APC quick battery test: %s", esp_err_to_name(ret)); + ESP_LOGI(APC_HID_TAG, "This may be an INPUT-ONLY device - use physical TEST button on UPS"); return false; } } @@ -1522,16 +1597,25 @@ bool ApcHidProtocol::start_battery_test_quick() { bool ApcHidProtocol::start_battery_test_deep() { ESP_LOGI(APC_HID_TAG, "Starting APC deep battery test"); - // Based on NUT debug logs, APC uses report ID 0x52 for battery test + // APC Back-UPS ES 700G (PID=0x0002) is INPUT-ONLY and doesn't support HID SET_REPORT + uint16_t product_id = parent_->get_product_id(); + if (product_id == 0x0002) { + ESP_LOGW(APC_HID_TAG, "APC Back-UPS ES 700G (PID=0x0002) is INPUT-ONLY device - battery tests not supported via HID"); + ESP_LOGI(APC_HID_TAG, "Tip: Use the physical TEST button on the UPS instead"); + return false; + } + + // For supported models: Based on NUT debug logs, APC uses report ID 0x52 for battery test // Command value 2 = Deep test (based on NUT test_write_info struct) uint8_t test_data[2] = {0x52, 2}; - esp_err_t ret = parent_->hid_set_report(0x03, 0x52, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, 0x52, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC deep battery test command sent successfully"); return true; } else { ESP_LOGW(APC_HID_TAG, "Failed to send APC deep battery test: %s", esp_err_to_name(ret)); + ESP_LOGI(APC_HID_TAG, "This may be an INPUT-ONLY device - use physical TEST button on UPS"); return false; } } @@ -1539,16 +1623,25 @@ bool ApcHidProtocol::start_battery_test_deep() { bool ApcHidProtocol::stop_battery_test() { ESP_LOGI(APC_HID_TAG, "Stopping APC battery test"); - // Based on NUT debug logs, APC uses report ID 0x52 for battery test + // APC Back-UPS ES 700G (PID=0x0002) is INPUT-ONLY and doesn't support HID SET_REPORT + uint16_t product_id = parent_->get_product_id(); + if (product_id == 0x0002) { + ESP_LOGW(APC_HID_TAG, "APC Back-UPS ES 700G (PID=0x0002) is INPUT-ONLY device - battery tests not supported via HID"); + ESP_LOGI(APC_HID_TAG, "Physical test will stop automatically after completion"); + return false; + } + + // For supported models: Based on NUT debug logs, APC uses report ID 0x52 for battery test // Command value 3 = Abort test (based on NUT test_write_info struct) uint8_t test_data[2] = {0x52, 3}; - esp_err_t ret = parent_->hid_set_report(0x03, 0x52, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, 0x52, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC battery test stop command sent successfully"); return true; } else { ESP_LOGW(APC_HID_TAG, "Failed to send APC battery test stop: %s", esp_err_to_name(ret)); + ESP_LOGI(APC_HID_TAG, "This may be an INPUT-ONLY device - test will stop automatically"); return false; } } @@ -1560,7 +1653,7 @@ bool ApcHidProtocol::start_ups_test() { // Command value 1 = Start panel test (based on NUT analysis) uint8_t test_data[2] = {0x79, 1}; - esp_err_t ret = parent_->hid_set_report(0x03, 0x79, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, 0x79, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC UPS panel test command sent successfully"); return true; @@ -1577,7 +1670,7 @@ bool ApcHidProtocol::stop_ups_test() { // Command value 0 = Stop/abort panel test (based on NUT analysis) uint8_t test_data[2] = {0x79, 0}; - esp_err_t ret = parent_->hid_set_report(0x03, 0x79, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, 0x79, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(APC_HID_TAG, "APC UPS panel test stop command sent successfully"); return true; @@ -1590,7 +1683,7 @@ bool ApcHidProtocol::stop_ups_test() { void ApcHidProtocol::parse_test_result_report(const HidReport &report, UpsData &data) { if (report.data.size() < 2) { ESP_LOGW(APC_HID_TAG, "Test result report too short: %zu bytes", report.data.size()); - data.ups_test_result = "Error reading test result"; + data.test.ups_test_result = "Error reading test result"; return; } @@ -1603,34 +1696,204 @@ void ApcHidProtocol::parse_test_result_report(const HidReport &report, UpsData & switch (test_result_value) { case 1: - data.ups_test_result = "Done and passed"; + data.test.ups_test_result = "Done and passed"; break; case 2: - data.ups_test_result = "Done and warning"; + data.test.ups_test_result = "Done and warning"; break; case 3: - data.ups_test_result = "Done and error"; + data.test.ups_test_result = "Done and error"; break; case 4: - data.ups_test_result = "Aborted"; + data.test.ups_test_result = "Aborted"; break; case 5: - data.ups_test_result = "In progress"; + data.test.ups_test_result = "In progress"; break; case 6: - data.ups_test_result = "No test initiated"; + data.test.ups_test_result = "No test initiated"; break; case 7: - data.ups_test_result = "Test scheduled"; + data.test.ups_test_result = "Test scheduled"; break; default: - data.ups_test_result = "Unknown test result (" + std::to_string(test_result_value) + ")"; + data.test.ups_test_result = "Unknown test result (" + std::to_string(test_result_value) + ")"; ESP_LOGW(APC_HID_TAG, "Unknown APC test result value: %d", test_result_value); break; } - ESP_LOGI(APC_HID_TAG, "APC Test result: %s (raw: %d)", data.ups_test_result.c_str(), test_result_value); + ESP_LOGI(APC_HID_TAG, "APC Test result: %s (raw: %d)", data.test.ups_test_result.c_str(), test_result_value); +} + +void ApcHidProtocol::read_frequency_data(UpsData &data) { + // Initialize frequency to NaN + data.power.frequency = NAN; + + // Try to read frequency from various HID report IDs + // Based on NUT reference, frequency is typically in input/output measurement reports + + // Report IDs commonly used for frequency measurements: + const std::vector frequency_report_ids = { + HID_USAGE_POW_FREQUENCY, // 0x32 - Standard HID frequency usage + HID_USAGE_POW_VOLTAGE, // 0x30 - Input measurements (may include frequency) + HID_USAGE_POW_CURRENT, // 0x31 - Output measurements (may include frequency) + HID_USAGE_POW_OUTPUT, // 0x1C - Output collection (might contain frequency) + HID_USAGE_POW_INPUT, // 0x1A - Input collection (might contain frequency) + }; + + for (uint8_t report_id : frequency_report_ids) { + HidReport freq_report; + if (read_hid_report(report_id, freq_report)) { + float frequency_value = parse_frequency_from_report(freq_report); + if (!std::isnan(frequency_value)) { + data.power.frequency = frequency_value; + ESP_LOGD(APC_HID_TAG, "Found frequency %.1f Hz in report 0x%02X", frequency_value, report_id); + return; + } + } + } + + ESP_LOGV(APC_HID_TAG, "Frequency data not available from any HID report"); +} + +float ApcHidProtocol::parse_frequency_from_report(const HidReport &report) { + if (report.data.size() < 2) { + return NAN; + } + + // Try different byte positions and formats commonly used for frequency + // Most UPS devices report frequency as integer Hz (50 or 60) + + // Method 1: Single byte at position 1 (common for simple frequency reports) + if (report.data.size() >= 2) { + uint8_t freq_byte = report.data[1]; + if (freq_byte >= FREQUENCY_MIN_VALID && freq_byte <= FREQUENCY_MAX_VALID) { + return static_cast(freq_byte); + } + } + + // Method 2: 16-bit little-endian value at position 1-2 + if (report.data.size() >= 3) { + uint16_t freq_word = report.data[1] | (report.data[2] << 8); + if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) { + return static_cast(freq_word); + } + } + + // Method 3: 16-bit big-endian value at position 1-2 + if (report.data.size() >= 3) { + uint16_t freq_word = (report.data[1] << 8) | report.data[2]; + if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) { + return static_cast(freq_word); + } + } + + // Method 4: Scaled frequency (multiply by 0.1 for devices reporting in 0.1 Hz units) + if (report.data.size() >= 3) { + uint16_t freq_scaled = report.data[1] | (report.data[2] << 8); + float freq_value = static_cast(freq_scaled) / 10.0f; + if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) { + return freq_value; + } + } + + return NAN; +} + +void ApcHidProtocol::detect_nominal_power_rating(const std::string& model_name, UpsData &data) { + ESP_LOGD(APC_HID_TAG, "Detecting nominal power rating for model: \"%s\"", model_name.c_str()); + + // APC Back-UPS ES Series Power Ratings (based on model identification) + // Reference: APC product specifications and actual device testing + + // Convert model name to lowercase for case-insensitive matching + std::string model_lower = model_name; + std::transform(model_lower.begin(), model_lower.end(), model_lower.begin(), ::tolower); + + float nominal_power_watts = 0.0f; + + if (model_lower.find("back-ups es 350") != std::string::npos) { + nominal_power_watts = 200.0f; // 350VA ≈ 200W + } + else if (model_lower.find("back-ups es 425") != std::string::npos) { + nominal_power_watts = 255.0f; // 425VA ≈ 255W + } + else if (model_lower.find("back-ups es 500") != std::string::npos) { + nominal_power_watts = 300.0f; // 500VA ≈ 300W + } + else if (model_lower.find("back-ups es 550") != std::string::npos) { + nominal_power_watts = 330.0f; // 550VA ≈ 330W + } + else if (model_lower.find("back-ups es 650") != std::string::npos) { + nominal_power_watts = 390.0f; // 650VA ≈ 390W + } + else if (model_lower.find("back-ups es 700") != std::string::npos || + model_lower.find("back-ups es 700g") != std::string::npos) { + nominal_power_watts = 405.0f; // 700VA ≈ 405W (confirmed from config) + } + else if (model_lower.find("back-ups es 750") != std::string::npos) { + nominal_power_watts = 450.0f; // 750VA ≈ 450W + } + else if (model_lower.find("back-ups es 850") != std::string::npos) { + nominal_power_watts = 510.0f; // 850VA ≈ 510W + } + else if (model_lower.find("back-ups es 900") != std::string::npos) { + nominal_power_watts = 540.0f; // 900VA ≈ 540W + } + else if (model_lower.find("back-ups es 1000") != std::string::npos) { + nominal_power_watts = 600.0f; // 1000VA ≈ 600W + } + else if (model_lower.find("back-ups es 1200") != std::string::npos) { + nominal_power_watts = 720.0f; // 1200VA ≈ 720W + } + else if (model_lower.find("back-ups es 1400") != std::string::npos) { + nominal_power_watts = 840.0f; // 1400VA ≈ 840W + } + + // Generic fallback patterns for other APC Back-UPS models + else if (model_lower.find("back-ups") != std::string::npos) { + // Try to extract VA rating from model name (e.g., "Back-UPS 1500") + std::regex va_pattern(R"(\b(\d{3,4})\b)"); // Match 3-4 digit numbers + std::smatch match; + if (std::regex_search(model_lower, match, va_pattern)) { + int va_rating = std::stoi(match[1].str()); + // Typical APC power factor is ~0.6 for ES series, ~0.7 for higher-end + if (model_lower.find(" es ") != std::string::npos) { + nominal_power_watts = va_rating * 0.6f; // ES series: lower power factor + } else { + nominal_power_watts = va_rating * 0.7f; // Pro/Smart series: higher power factor + } + ESP_LOGD(APC_HID_TAG, "Extracted VA rating %d from model, calculated %0.1fW", va_rating, nominal_power_watts); + } + } + + // Set the nominal power if detected + if (nominal_power_watts > 0.0f) { + data.power.realpower_nominal = nominal_power_watts; + ESP_LOGI(APC_HID_TAG, "Detected APC nominal power rating: %.1fW for model \"%s\"", + nominal_power_watts, model_name.c_str()); + } else { + ESP_LOGW(APC_HID_TAG, "Could not determine nominal power rating for APC model: \"%s\"", model_name.c_str()); + // Don't set realpower_nominal - leave it as NaN so template sensors can handle gracefully + } } } // namespace ups_hid -} // namespace esphome \ No newline at end of file +} // namespace esphome + +// Protocol Factory Self-Registration +#include "protocol_factory.h" + +namespace esphome { +namespace ups_hid { + +// Creator function for APC protocol +std::unique_ptr create_apc_protocol(UpsHidComponent* parent) { + return std::make_unique(parent); +} + +} // namespace ups_hid +} // namespace esphome + +// Register APC protocol for vendor ID 0x051D +REGISTER_UPS_PROTOCOL_FOR_VENDOR(0x051D, apc_hid_protocol, esphome::ups_hid::create_apc_protocol, "APC HID Protocol", "APC Back-UPS and Smart-UPS HID protocol implementation with comprehensive sensor support", 100); \ No newline at end of file diff --git a/components/ups_hid/apc_hid_protocol.h b/components/ups_hid/apc_hid_protocol.h index e63e84c..de3516b 100644 --- a/components/ups_hid/apc_hid_protocol.h +++ b/components/ups_hid/apc_hid_protocol.h @@ -13,7 +13,7 @@ public: bool detect() override; bool initialize() override; bool read_data(UpsData &data) override; - UpsProtocol get_protocol_type() const override { return PROTOCOL_APC_HID; } + DeviceInfo::DetectedProtocol get_protocol_type() const override { return DeviceInfo::PROTOCOL_APC_HID; } std::string get_protocol_name() const override { return "APC HID Protocol"; } // Beeper control methods @@ -72,10 +72,18 @@ private: void parse_battery_runtime_low_report(const HidReport &report, UpsData &data); void parse_manufacture_date_report(const HidReport &report, UpsData &data, bool is_battery); void parse_ups_delay_shutdown_report(const HidReport &report, UpsData &data); + void parse_ups_delay_reboot_report(const HidReport &report, UpsData &data); void parse_battery_charge_threshold_report(const HidReport &report, UpsData &data, bool is_low_threshold); void parse_battery_chemistry_report(const HidReport &report, UpsData &data); void parse_test_result_report(const HidReport &report, UpsData &data); std::string convert_apc_date(uint16_t date_value); + + // Device model detection and configuration + void detect_nominal_power_rating(const std::string& model_name, UpsData &data); + + // Frequency reading methods + void read_frequency_data(UpsData &data); + float parse_frequency_from_report(const HidReport &report); }; } // namespace ups_hid diff --git a/components/ups_hid/battery_data.h b/components/ups_hid/battery_data.h new file mode 100644 index 0000000..ad1ffcd --- /dev/null +++ b/components/ups_hid/battery_data.h @@ -0,0 +1,56 @@ +#pragma once + +#include +#include + +namespace esphome { +namespace ups_hid { + +struct BatteryData { + // Core battery metrics + float level{NAN}; // Battery charge level (0-100%) + float voltage{NAN}; // Current battery voltage (V) + float voltage_nominal{NAN}; // Nominal battery voltage (V) + float runtime_minutes{NAN}; // Estimated runtime (minutes) + + // Battery thresholds + float charge_low{NAN}; // Low battery threshold (%) + float charge_warning{NAN}; // Warning battery threshold (%) + float runtime_low{NAN}; // Low runtime threshold (minutes) + + // Battery status information + std::string status{}; // Battery status text + std::string type{}; // Battery chemistry type + std::string mfr_date{}; // Battery manufacture date + + // Validation and utility methods + bool is_valid() const { + return !std::isnan(level) || !std::isnan(voltage) || !std::isnan(runtime_minutes); + } + + bool is_low() const { + return !std::isnan(level) && !std::isnan(charge_low) && level <= charge_low; + } + + bool is_warning() const { + return !std::isnan(level) && !std::isnan(charge_warning) && level <= charge_warning; + } + + bool has_runtime_estimate() const { + return !std::isnan(runtime_minutes) && runtime_minutes > 0; + } + + void reset() { + *this = BatteryData{}; + } + + // Copy constructor and assignment for safe copying + BatteryData() = default; + BatteryData(const BatteryData&) = default; + BatteryData& operator=(const BatteryData&) = default; + BatteryData(BatteryData&&) = default; + BatteryData& operator=(BatteryData&&) = default; +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/button.cpp b/components/ups_hid/button.cpp index c94e7cf..b1758a4 100644 --- a/components/ups_hid/button.cpp +++ b/components/ups_hid/button.cpp @@ -32,7 +32,7 @@ void UpsHidButton::press_action() { // Get the current protocol from the parent component UpsData ups_data = parent_->get_ups_data(); - if (ups_data.detected_protocol == PROTOCOL_UNKNOWN) { + if (ups_data.device.detected_protocol == DeviceInfo::PROTOCOL_UNKNOWN) { ESP_LOGW(BUTTON_TAG, "UPS protocol not detected, cannot execute button action"); return; } diff --git a/components/ups_hid/config_data.h b/components/ups_hid/config_data.h new file mode 100644 index 0000000..faff6c6 --- /dev/null +++ b/components/ups_hid/config_data.h @@ -0,0 +1,150 @@ +#pragma once + +#include +#include + +namespace esphome { +namespace ups_hid { + +struct ConfigData { + // Timing configuration + int16_t delay_shutdown{-1}; // Shutdown delay (seconds, -1 = not set) + int16_t delay_start{-1}; // Start delay (seconds, -1 = not set) + int16_t delay_reboot{-1}; // Reboot delay (seconds, -1 = not set) + + // Beeper configuration + std::string beeper_status{}; // Current beeper status + + enum BeeperState { + BEEPER_UNKNOWN = 0, + BEEPER_ENABLED, + BEEPER_DISABLED, + BEEPER_MUTED + }; + + BeeperState beeper_state{BEEPER_UNKNOWN}; + + // Input sensitivity configuration + std::string input_sensitivity{}; // Input sensitivity setting + + enum SensitivityLevel { + SENSITIVITY_UNKNOWN = 0, + SENSITIVITY_LOW, + SENSITIVITY_MEDIUM, + SENSITIVITY_HIGH, + SENSITIVITY_AUTO + }; + + SensitivityLevel sensitivity_level{SENSITIVITY_UNKNOWN}; + + // Power management thresholds (configurable on some UPS models) + float low_battery_threshold{NAN}; // Low battery warning threshold (%) + float critical_battery_threshold{NAN}; // Critical battery threshold (%) + float high_temperature_threshold{NAN}; // High temperature warning (°C) + + // Advanced configuration options + bool auto_restart_enabled{false}; // Auto restart after power restoration + bool cold_start_enabled{false}; // Cold start capability + bool audible_alarm_enabled{true}; // Audible alarm on events + + // Communication settings + uint16_t protocol_timeout_ms{15000}; // Protocol communication timeout + uint16_t retry_count{3}; // Number of communication retries + bool auto_detect_protocol{true}; // Automatic protocol detection + + // Validation and utility methods + bool has_timing_config() const { + return delay_shutdown != -1 || delay_start != -1 || delay_reboot != -1; + } + + bool has_beeper_config() const { + return !beeper_status.empty() || beeper_state != BEEPER_UNKNOWN; + } + + bool has_sensitivity_config() const { + return !input_sensitivity.empty() || sensitivity_level != SENSITIVITY_UNKNOWN; + } + + bool has_thresholds() const { + return !std::isnan(low_battery_threshold) || + !std::isnan(critical_battery_threshold) || + !std::isnan(high_temperature_threshold); + } + + std::string get_beeper_state_name() const { + switch (beeper_state) { + case BEEPER_ENABLED: return "Enabled"; + case BEEPER_DISABLED: return "Disabled"; + case BEEPER_MUTED: return "Muted"; + default: return "Unknown"; + } + } + + std::string get_sensitivity_name() const { + switch (sensitivity_level) { + case SENSITIVITY_LOW: return "Low"; + case SENSITIVITY_MEDIUM: return "Medium"; + case SENSITIVITY_HIGH: return "High"; + case SENSITIVITY_AUTO: return "Auto"; + default: return "Unknown"; + } + } + + void parse_beeper_status(const std::string& status) { + beeper_status = status; + + // Convert string to enum for easier handling + if (status == "enabled" || status == "on" || status == "1") { + beeper_state = BEEPER_ENABLED; + } else if (status == "disabled" || status == "off" || status == "0") { + beeper_state = BEEPER_DISABLED; + } else if (status == "muted") { + beeper_state = BEEPER_MUTED; + } else { + beeper_state = BEEPER_UNKNOWN; + } + } + + void parse_input_sensitivity(const std::string& sensitivity) { + input_sensitivity = sensitivity; + + // Convert string to enum for easier handling + if (sensitivity == "low" || sensitivity == "L") { + sensitivity_level = SENSITIVITY_LOW; + } else if (sensitivity == "medium" || sensitivity == "M" || sensitivity == "normal") { + sensitivity_level = SENSITIVITY_MEDIUM; + } else if (sensitivity == "high" || sensitivity == "H") { + sensitivity_level = SENSITIVITY_HIGH; + } else if (sensitivity == "auto" || sensitivity == "A") { + sensitivity_level = SENSITIVITY_AUTO; + } else { + sensitivity_level = SENSITIVITY_UNKNOWN; + } + } + + bool is_beeper_enabled() const { + return beeper_state == BEEPER_ENABLED; + } + + bool is_beeper_muted() const { + return beeper_state == BEEPER_MUTED; + } + + bool is_valid() const { + return has_timing_config() || has_beeper_config() || has_sensitivity_config() || has_thresholds(); + } + + void reset() { + *this = ConfigData{}; + } + + // Copy constructor and assignment for safe copying + ConfigData() = default; + ConfigData(const ConfigData&) = default; + ConfigData& operator=(const ConfigData&) = default; + ConfigData(ConfigData&&) = default; + ConfigData& operator=(ConfigData&&) = default; +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/cyberpower_protocol.cpp b/components/ups_hid/cyberpower_protocol.cpp index 17c2002..3b024be 100644 --- a/components/ups_hid/cyberpower_protocol.cpp +++ b/components/ups_hid/cyberpower_protocol.cpp @@ -1,5 +1,6 @@ #include "cyberpower_protocol.h" #include "ups_hid.h" +#include "hid_constants.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/portmacro.h" @@ -189,8 +190,15 @@ bool CyberPowerProtocol::read_data(UpsData &data) { parse_firmware_version_report(firmware_version_report, data); } + // Read test result (Report 0x14) - same report ID used for test commands + HidReport test_result_report; + if (read_hid_report(TEST_RESULT_REPORT_ID, test_result_report)) { + parse_test_result_report(test_result_report, data); + } + // Set frequency to NaN - not available for CyberPower CP1500 model - data.frequency = NAN; + // Try to read frequency from HID reports + read_frequency_data(data); // TIMING FIX: Only read USB string descriptors after successful HID communication // This ensures the device is ready and responsive before attempting descriptor access @@ -203,10 +211,10 @@ bool CyberPowerProtocol::read_data(UpsData &data) { esp_err_t mfr_ret = parent_->usb_get_string_descriptor(3, manufacturer_string); if (mfr_ret == ESP_OK && !manufacturer_string.empty()) { - data.manufacturer = manufacturer_string; - ESP_LOGI(CP_TAG, "Successfully read manufacturer from USB descriptor: \"%s\"", data.manufacturer.c_str()); + data.device.manufacturer = manufacturer_string; + ESP_LOGI(CP_TAG, "Successfully read manufacturer from USB descriptor: \"%s\"", data.device.manufacturer.c_str()); } else { - data.manufacturer.clear(); // Set to unset state instead of hardcoded fallback + data.device.manufacturer.clear(); // Set to unset state instead of hardcoded fallback ESP_LOGW(CP_TAG, "Failed to read USB Manufacturer descriptor: %s, leaving unset", esp_err_to_name(mfr_ret)); } @@ -216,10 +224,10 @@ bool CyberPowerProtocol::read_data(UpsData &data) { esp_err_t prod_ret = parent_->usb_get_string_descriptor(1, product_string); if (prod_ret == ESP_OK && !product_string.empty()) { - data.model = product_string; - ESP_LOGI(CP_TAG, "Successfully read CyberPower model from USB Product descriptor: \"%s\"", data.model.c_str()); + data.device.model = product_string; + ESP_LOGI(CP_TAG, "Successfully read CyberPower model from USB Product descriptor: \"%s\"", data.device.model.c_str()); } else { - data.model.clear(); // Set to unset state instead of hardcoded fallback + data.device.model.clear(); // Set to unset state instead of hardcoded fallback ESP_LOGW(CP_TAG, "Failed to read USB Product descriptor: %s, leaving model unset", esp_err_to_name(prod_ret)); } @@ -230,8 +238,8 @@ bool CyberPowerProtocol::read_data(UpsData &data) { } else { ESP_LOGW(CP_TAG, "Failed to read any CyberPower HID reports"); // Leave manufacturer and model unset when HID communication fails - data.manufacturer.clear(); - data.model.clear(); + data.device.manufacturer.clear(); + data.device.model.clear(); } return success; @@ -252,7 +260,7 @@ bool CyberPowerProtocol::read_hid_report(uint8_t report_id, HidReport &report) { ESP_LOGD(CP_TAG, "Attempting to read report 0x%02X from parent device", report_id); // CyberPower devices primarily use Feature Reports (0x03) - based on NUT debug logs - ret = parent_->hid_get_report(0x03, report_id, buffer, &buffer_len); + ret = parent_->hid_get_report(0x03, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { report.report_id = report_id; report.data.assign(buffer, buffer + buffer_len); @@ -271,7 +279,7 @@ bool CyberPowerProtocol::read_hid_report(uint8_t report_id, HidReport &report) { // Fallback: try Input Report (0x01) for real-time data buffer_len = sizeof(buffer); - ret = parent_->hid_get_report(0x01, report_id, buffer, &buffer_len); + ret = parent_->hid_get_report(0x01, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { report.report_id = report_id; report.data.assign(buffer, buffer + buffer_len); @@ -293,24 +301,27 @@ void CyberPowerProtocol::parse_battery_runtime_report(const HidReport &report, U // NUT mapping: // Offset 0 (byte 1): RemainingCapacity (battery %) - Size: 8 - // Offset 8 (bytes 2-3): RunTimeToEmpty - Size: 16, little-endian + // Offset 8 (bytes 2-3): RunTimeToEmpty - Size: 16, little-endian (IN SECONDS) // Offset 24 (bytes 4-5): RemainingTimeLimit - Size: 16, little-endian uint8_t battery_percentage = report.data[1]; - uint16_t runtime_minutes = report.data[2] | (report.data[3] << 8); + uint16_t runtime_seconds = report.data[2] | (report.data[3] << 8); // Clamp battery to 100% like NUT does - data.battery_level = static_cast(battery_percentage > 100 ? 100 : battery_percentage); - data.runtime_minutes = static_cast(runtime_minutes); + data.battery.level = static_cast(battery_percentage > 100 ? 100 : battery_percentage); + + // CRITICAL FIX: Convert runtime from seconds to minutes + // CyberPower reports runtime in seconds, but ESPHome expects minutes + data.battery.runtime_minutes = static_cast(runtime_seconds) / 60.0f; // Extract runtime low threshold if available (offset 24 = bytes 4-5) if (report.data.size() >= 6) { - uint16_t runtime_low_minutes = report.data[4] | (report.data[5] << 8); - data.battery_runtime_low = static_cast(runtime_low_minutes); - ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.0f min, Runtime Low: %.0f min", - data.battery_level, data.runtime_minutes, data.battery_runtime_low); + uint16_t runtime_low_seconds = report.data[4] | (report.data[5] << 8); + data.battery.runtime_low = static_cast(runtime_low_seconds) / 60.0f; // Convert to minutes + ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.1f min (%.0f sec), Runtime Low: %.1f min", + data.battery.level, data.battery.runtime_minutes, static_cast(runtime_seconds), data.battery.runtime_low); } else { - ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.0f min (raw: %02X %02X%02X)", - data.battery_level, data.runtime_minutes, battery_percentage, report.data[3], report.data[2]); + ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.1f min (%.0f sec raw: %02X %02X%02X)", + data.battery.level, data.battery.runtime_minutes, static_cast(runtime_seconds), battery_percentage, report.data[3], report.data[2]); } } @@ -324,10 +335,10 @@ void CyberPowerProtocol::parse_battery_voltage_report(const HidReport &report, U // Current raw value: 0xF0 (240) should become 24V // So scaling factor is 24/240 = 0.1 (divide by 10) uint8_t voltage_raw = report.data[1]; - data.battery_voltage = static_cast(voltage_raw) / 10.0f; // Scale by 0.1 + data.battery.voltage = static_cast(voltage_raw) / 10.0f; // Scale by 0.1 ESP_LOGD(CP_TAG, "Battery voltage: %.1fV (raw: 0x%02X = %d)", - data.battery_voltage, voltage_raw, voltage_raw); + data.battery.voltage, voltage_raw, voltage_raw); } void CyberPowerProtocol::parse_present_status_report(const HidReport &report, UpsData &data) { @@ -347,44 +358,40 @@ void CyberPowerProtocol::parse_present_status_report(const HidReport &report, Up bool fully_charged = (status_byte & 0x10) != 0; // Offset 4 bool time_limit_expired = (status_byte & 0x20) != 0; // Offset 5 - // Build status flags - uint32_t status_flags = 0; - - if (ac_present) { - status_flags |= UPS_STATUS_ONLINE; - } - - if (!ac_present || discharging) { - status_flags |= UPS_STATUS_ON_BATTERY; - } - - if (charging) { - status_flags |= UPS_STATUS_CHARGING; - } - - if (low_battery || time_limit_expired) { - status_flags |= UPS_STATUS_LOW_BATTERY; - } - - data.status_flags = status_flags; - - // Set battery status based on charging/discharging state (not FullChargeCapacity) - if (charging) { - data.battery_status = "charging"; - } else if (discharging || !ac_present) { - data.battery_status = "discharging"; - } else if (fully_charged) { - data.battery_status = "fully charged"; + // Update power status based on AC presence + if (ac_present && !discharging) { + data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage when AC present + data.power.status = "Online"; } else { - data.battery_status = "normal"; + data.power.input_voltage = NAN; // No AC input + data.power.status = "On Battery"; + } + + // Set battery status based on charging/discharging state + if (charging) { + data.battery.status = "Charging"; + } else if (discharging || !ac_present) { + data.battery.status = "Discharging"; + } else if (fully_charged) { + data.battery.status = "Fully Charged"; + } else { + data.battery.status = "Normal"; + } + + // Set low battery indicators + if (low_battery || time_limit_expired) { + data.battery.charge_low = 10.0f; // Indicate low battery threshold + if (time_limit_expired) { + data.battery.status += " - Time Limit Expired"; + } } ESP_LOGD(CP_TAG, "Status: AC:%s Charging:%s OnBatt:%s LowBatt:%s BattStatus:\"%s\"", ac_present ? "Yes" : "No", charging ? "Yes" : "No", - (status_flags & UPS_STATUS_ON_BATTERY) ? "Yes" : "No", - (status_flags & UPS_STATUS_LOW_BATTERY) ? "Yes" : "No", - data.battery_status.c_str()); + (!ac_present || discharging) ? "Yes" : "No", + (low_battery || time_limit_expired) ? "Yes" : "No", + data.battery.status.c_str()); } void CyberPowerProtocol::parse_input_voltage_report(const HidReport &report, UpsData &data) { @@ -396,10 +403,10 @@ void CyberPowerProtocol::parse_input_voltage_report(const HidReport &report, Ups // NUT debug: Report 0x0f, Value: 231 (matches our 0x00E6 = 230) // Data format: [ID, volt_low, volt_high] - 16-bit little endian uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); - data.input_voltage = static_cast(voltage_raw); + data.power.input_voltage = static_cast(voltage_raw); ESP_LOGD(CP_TAG, "Input voltage: %.1fV (raw: 0x%02X%02X = %d)", - data.input_voltage, report.data[2], report.data[1], voltage_raw); + data.power.input_voltage, report.data[2], report.data[1], voltage_raw); } void CyberPowerProtocol::parse_output_voltage_report(const HidReport &report, UpsData &data) { @@ -411,10 +418,10 @@ void CyberPowerProtocol::parse_output_voltage_report(const HidReport &report, Up // NUT debug: Report 0x12, Value: 231 (matches our 0x00E6 = 230) // Data format: [ID, volt_low, volt_high] - 16-bit little endian uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); - data.output_voltage = static_cast(voltage_raw); + data.power.output_voltage = static_cast(voltage_raw); ESP_LOGD(CP_TAG, "Output voltage: %.1fV (raw: 0x%02X%02X = %d)", - data.output_voltage, report.data[2], report.data[1], voltage_raw); + data.power.output_voltage, report.data[2], report.data[1], voltage_raw); } void CyberPowerProtocol::parse_load_percent_report(const HidReport &report, UpsData &data) { @@ -426,10 +433,10 @@ void CyberPowerProtocol::parse_load_percent_report(const HidReport &report, UpsD // NUT debug: Report 0x13, Value: 8 (our raw: 0x07 = 7%) // Data format: [ID, load%] - single byte uint8_t load_percent = report.data[1]; - data.load_percent = static_cast(load_percent); + data.power.load_percent = static_cast(load_percent); ESP_LOGD(CP_TAG, "Load: %.0f%% (raw: 0x%02X = %d)", - data.load_percent, load_percent, load_percent); + data.power.load_percent, load_percent, load_percent); } void CyberPowerProtocol::check_battery_voltage_scaling(float battery_voltage, float nominal_voltage) { @@ -462,10 +469,10 @@ void CyberPowerProtocol::parse_battery_voltage_nominal_report(const HidReport &r // NUT debug shows: Report 0x09, Value: 24 (ConfigVoltage) // Some CyberPower models report in decivolts (240 = 24.0V) uint8_t voltage_raw = report.data[1]; - data.battery_voltage_nominal = static_cast(voltage_raw) / 10.0f; + data.battery.voltage_nominal = static_cast(voltage_raw) / 10.0f; ESP_LOGD(CP_TAG, "Battery voltage nominal: %.0fV (raw: 0x%02X = %d)", - data.battery_voltage_nominal, voltage_raw, voltage_raw); + data.battery.voltage_nominal, voltage_raw, voltage_raw); } void CyberPowerProtocol::parse_beeper_status_report(const HidReport &report, UpsData &data) { @@ -480,21 +487,21 @@ void CyberPowerProtocol::parse_beeper_status_report(const HidReport &report, Ups // Map NUT values: 1=disabled, 2=enabled, 3=muted switch (beeper_raw) { case 1: - data.ups_beeper_status = "disabled"; + data.config.beeper_status = "disabled"; break; case 2: - data.ups_beeper_status = "enabled"; + data.config.beeper_status = "enabled"; break; case 3: - data.ups_beeper_status = "muted"; + data.config.beeper_status = "muted"; break; default: - data.ups_beeper_status = "unknown"; + data.config.beeper_status = "unknown"; break; } ESP_LOGD(CP_TAG, "Beeper status: %s (raw: 0x%02X = %d)", - data.ups_beeper_status.c_str(), beeper_raw, beeper_raw); + data.config.beeper_status.c_str(), beeper_raw, beeper_raw); } void CyberPowerProtocol::parse_input_voltage_nominal_report(const HidReport &report, UpsData &data) { @@ -505,10 +512,10 @@ void CyberPowerProtocol::parse_input_voltage_nominal_report(const HidReport &rep // NUT debug shows: Report 0x0e, Value: 230 (ConfigVoltage) uint8_t voltage_raw = report.data[1]; - data.input_voltage_nominal = static_cast(voltage_raw); + data.power.input_voltage_nominal = static_cast(voltage_raw); ESP_LOGD(CP_TAG, "Input voltage nominal: %.0fV (raw: 0x%02X = %d)", - data.input_voltage_nominal, voltage_raw, voltage_raw); + data.power.input_voltage_nominal, voltage_raw, voltage_raw); } void CyberPowerProtocol::parse_input_transfer_report(const HidReport &report, UpsData &data) { @@ -523,11 +530,11 @@ void CyberPowerProtocol::parse_input_transfer_report(const HidReport &report, Up uint16_t low_transfer = report.data[1] | (report.data[2] << 8); uint16_t high_transfer = report.data[3] | (report.data[4] << 8); - data.input_transfer_low = static_cast(low_transfer); - data.input_transfer_high = static_cast(high_transfer); + data.power.input_transfer_low = static_cast(low_transfer); + data.power.input_transfer_high = static_cast(high_transfer); ESP_LOGD(CP_TAG, "Input transfer limits: Low=%.0fV, High=%.0fV", - data.input_transfer_low, data.input_transfer_high); + data.power.input_transfer_low, data.power.input_transfer_high); } void CyberPowerProtocol::parse_delay_shutdown_report(const HidReport &report, UpsData &data) { @@ -541,12 +548,12 @@ void CyberPowerProtocol::parse_delay_shutdown_report(const HidReport &report, Up uint16_t delay_raw_unsigned = report.data[1] | (report.data[2] << 8); if (delay_raw_unsigned == 0xFFFF) { // When disabled, use NUT default for CyberPower (DEFAULT_OFFDELAY_CPS = 60) - data.ups_delay_shutdown = 60; + data.config.delay_shutdown = 60; ESP_LOGD(CP_TAG, "UPS delay shutdown: 60 seconds (default, raw: 0xFFFF)"); } else { int16_t delay_raw = static_cast(delay_raw_unsigned); - data.ups_delay_shutdown = delay_raw; - ESP_LOGD(CP_TAG, "UPS delay shutdown: %d seconds", data.ups_delay_shutdown); + data.config.delay_shutdown = delay_raw; + ESP_LOGD(CP_TAG, "UPS delay shutdown: %d seconds", data.config.delay_shutdown); } } @@ -561,12 +568,12 @@ void CyberPowerProtocol::parse_delay_start_report(const HidReport &report, UpsDa uint16_t delay_raw_unsigned = report.data[1] | (report.data[2] << 8); if (delay_raw_unsigned == 0xFFFF) { // When disabled, use NUT default for CyberPower (DEFAULT_ONDELAY_CPS = 120) - data.ups_delay_start = 120; + data.config.delay_start = 120; ESP_LOGD(CP_TAG, "UPS delay start: 120 seconds (default, raw: 0xFFFF)"); } else { int16_t delay_raw = static_cast(delay_raw_unsigned); - data.ups_delay_start = delay_raw; - ESP_LOGD(CP_TAG, "UPS delay start: %d seconds", data.ups_delay_start); + data.config.delay_start = delay_raw; + ESP_LOGD(CP_TAG, "UPS delay start: %d seconds", data.config.delay_start); } } @@ -578,9 +585,9 @@ void CyberPowerProtocol::parse_realpower_nominal_report(const HidReport &report, // NUT debug shows: Report 0x18, Value: 900 (ConfigActivePower) uint16_t power_raw = report.data[1] | (report.data[2] << 8); - data.ups_realpower_nominal = static_cast(power_raw); + data.power.realpower_nominal = static_cast(power_raw); - ESP_LOGD(CP_TAG, "UPS nominal real power: %.0fW", data.ups_realpower_nominal); + ESP_LOGD(CP_TAG, "UPS nominal real power: %.0fW", data.power.realpower_nominal); } void CyberPowerProtocol::parse_input_sensitivity_report(const HidReport &report, UpsData &data) { @@ -596,15 +603,15 @@ void CyberPowerProtocol::parse_input_sensitivity_report(const HidReport &report, // DYNAMIC SENSITIVITY MAPPING: Handle known CyberPower values with intelligent fallbacks switch (sensitivity_raw) { case 0: - data.input_sensitivity = "high"; + data.config.input_sensitivity = "high"; ESP_LOGI(CP_TAG, "CyberPower input sensitivity: high (raw: %d)", sensitivity_raw); break; case 1: - data.input_sensitivity = "normal"; + data.config.input_sensitivity = "normal"; ESP_LOGI(CP_TAG, "CyberPower input sensitivity: normal (raw: %d)", sensitivity_raw); break; case 2: - data.input_sensitivity = "low"; + data.config.input_sensitivity = "low"; ESP_LOGI(CP_TAG, "CyberPower input sensitivity: low (raw: %d)", sensitivity_raw); break; default: @@ -622,26 +629,26 @@ void CyberPowerProtocol::parse_input_sensitivity_report(const HidReport &report, if (alt_value <= 2) { sensitivity_raw = alt_value; switch (sensitivity_raw) { - case 0: data.input_sensitivity = "high"; break; - case 1: data.input_sensitivity = "normal"; break; - case 2: data.input_sensitivity = "low"; break; + case 0: data.config.input_sensitivity = "high"; break; + case 1: data.config.input_sensitivity = "normal"; break; + case 2: data.config.input_sensitivity = "low"; break; } ESP_LOGI(CP_TAG, "CyberPower input sensitivity (alt parsing): %s (raw: %d)", - data.input_sensitivity.c_str(), sensitivity_raw); + data.config.input_sensitivity.c_str(), sensitivity_raw); return; } } // Fallback for problematic values - data.input_sensitivity = "normal"; + data.config.input_sensitivity = "normal"; ESP_LOGW(CP_TAG, "Using default 'normal' sensitivity due to unexpected value: %d", sensitivity_raw); } else { // Values 3-99 - extend mapping for future CyberPower models if (sensitivity_raw == 3) { - data.input_sensitivity = "auto"; + data.config.input_sensitivity = "auto"; ESP_LOGI(CP_TAG, "CyberPower input sensitivity: auto (raw: %d)", sensitivity_raw); } else { - data.input_sensitivity = "unknown"; + data.config.input_sensitivity = "unknown"; ESP_LOGW(CP_TAG, "Unknown CyberPower sensitivity value: %d - please report this for future support", sensitivity_raw); } @@ -670,9 +677,9 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report, if (fw_ret == ESP_OK && !actual_firmware.empty()) { // Clean up firmware string - remove invalid characters and trim std::string cleaned_firmware = clean_firmware_string(actual_firmware); - data.firmware_version = cleaned_firmware; + data.device.firmware_version = cleaned_firmware; ESP_LOGI(CP_TAG, "Successfully read CyberPower firmware from USB string descriptor %d: \"%s\"", - string_index, data.firmware_version.c_str()); + string_index, data.device.firmware_version.c_str()); if (cleaned_firmware != actual_firmware) { ESP_LOGD(CP_TAG, "Cleaned firmware string from \"%s\" to \"%s\"", actual_firmware.c_str(), cleaned_firmware.c_str()); @@ -696,8 +703,8 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report, } if (!firmware_from_hid.empty() && firmware_from_hid.length() >= 3) { - data.firmware_version = firmware_from_hid; - ESP_LOGI(CP_TAG, "Firmware version from HID report data: %s", data.firmware_version.c_str()); + data.device.firmware_version = firmware_from_hid; + ESP_LOGI(CP_TAG, "Firmware version from HID report data: %s", data.device.firmware_version.c_str()); return; } @@ -716,9 +723,9 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report, if ((cleaned_fw.find("CR") == 0 || cleaned_fw.find("CP") == 0 || cleaned_fw.find("FW") != std::string::npos)) { // Looks like a valid CyberPower firmware string - data.firmware_version = cleaned_fw; + data.device.firmware_version = cleaned_fw; ESP_LOGI(CP_TAG, "Found CyberPower firmware at alternative string descriptor %d: \"%s\"", - idx, data.firmware_version.c_str()); + idx, data.device.firmware_version.c_str()); if (cleaned_fw != fw_attempt) { ESP_LOGD(CP_TAG, "Cleaned alternative firmware string from \"%s\" to \"%s\"", fw_attempt.c_str(), cleaned_fw.c_str()); @@ -734,16 +741,16 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report, snprintf(firmware_fallback, sizeof(firmware_fallback), "CP-%02X.%02X.%02X", report.data[1], report.data[2], (report.data.size() > 3) ? report.data[3] : 0); - data.firmware_version = firmware_fallback; - ESP_LOGD(CP_TAG, "Using binary firmware version fallback: %s", data.firmware_version.c_str()); + data.device.firmware_version = firmware_fallback; + ESP_LOGD(CP_TAG, "Using binary firmware version fallback: %s", data.device.firmware_version.c_str()); } else { // No firmware version could be determined - data.firmware_version.clear(); + data.device.firmware_version.clear(); ESP_LOGW(CP_TAG, "Unable to determine CyberPower firmware version from any source"); } ESP_LOGD(CP_TAG, "Final firmware version: %s (original string index: %d)", - data.firmware_version.c_str(), string_index); + data.device.firmware_version.c_str(), string_index); } void CyberPowerProtocol::parse_overload_report(const HidReport &report, UpsData &data) { @@ -758,10 +765,14 @@ void CyberPowerProtocol::parse_overload_report(const HidReport &report, UpsData bool overload = (overload_byte & 0x01) != 0; // Check bit 0 (Offset 1 in NUT = bit 0) if (overload) { - data.status_flags |= UPS_STATUS_OVERLOAD; + data.power.status += " - Overload"; ESP_LOGW(CP_TAG, "CyberPower UPS OVERLOAD detected (raw: 0x%02X)", overload_byte); } else { - data.status_flags &= ~UPS_STATUS_OVERLOAD; + // Remove overload from status if it was there + size_t pos = data.power.status.find(" - Overload"); + if (pos != std::string::npos) { + data.power.status.erase(pos, 11); // Length of " - Overload" + } ESP_LOGD(CP_TAG, "CyberPower UPS overload status: normal (raw: 0x%02X)", overload_byte); } } @@ -784,21 +795,21 @@ void CyberPowerProtocol::parse_serial_number_report(const HidReport &report, Ups esp_err_t ret = parent_->usb_get_string_descriptor(string_index, actual_serial); if (ret == ESP_OK && !actual_serial.empty()) { - data.serial_number = actual_serial; + data.device.serial_number = actual_serial; ESP_LOGI(CP_TAG, "Successfully read CyberPower serial number from USB string descriptor %d: \"%s\"", - string_index, data.serial_number.c_str()); + string_index, data.device.serial_number.c_str()); } else { // Fallback if USB string descriptor reading fails ESP_LOGW(CP_TAG, "Failed to read USB string descriptor %d: %s", string_index, esp_err_to_name(ret)); // Set to unset state instead of generating fallback ID - data.serial_number.clear(); + data.device.serial_number.clear(); ESP_LOGW(CP_TAG, "Leaving serial number unset due to USB string descriptor failure"); } ESP_LOGD(CP_TAG, "Serial number: %s (string index: %d)", - data.serial_number.c_str(), string_index); + data.device.serial_number.c_str(), string_index); } void CyberPowerProtocol::read_missing_dynamic_values(UpsData &data) { @@ -821,15 +832,15 @@ void CyberPowerProtocol::read_missing_dynamic_values(UpsData &data) { // Just need to extract it properly // 4. Set static/derived values based on NUT behavior - data.ups_test_result = "No test initiated"; // Default test result + data.test.ups_test_result = "No test initiated"; // Default test result // NOTE: battery_status is now properly set based on charging state in parse_present_status_report // 5. Timer values represent active countdown (negative when no countdown active) // NUT shows: ups.timer.shutdown: -60, ups.timer.start: -60 - data.ups_timer_shutdown = -data.ups_delay_shutdown; // Negative indicates no active countdown - data.ups_timer_start = -data.ups_delay_start; // Negative indicates no active countdown - data.ups_timer_reboot = -10; // CyberPower doesn't have separate reboot timer, use default + data.test.timer_shutdown = -data.config.delay_shutdown; // Negative indicates no active countdown + data.test.timer_start = -data.config.delay_start; // Negative indicates no active countdown + data.test.timer_reboot = -10; // CyberPower doesn't have separate reboot timer, use default ESP_LOGD(CP_TAG, "Completed reading CyberPower missing dynamic values"); } @@ -853,17 +864,17 @@ void CyberPowerProtocol::parse_battery_capacity_limits_report(const HidReport &r // Extract warning capacity limit (offset 24 = byte 4) if (report.data.size() > 4) { uint8_t warning_limit = report.data[4]; // Offset 24 bits = byte 3 + 1 - data.battery_charge_warning = static_cast(warning_limit); + data.battery.charge_warning = static_cast(warning_limit); ESP_LOGI(CP_TAG, "CyberPower Battery charge warning threshold: %.0f%% (raw: %d)", - data.battery_charge_warning, warning_limit); + data.battery.charge_warning, warning_limit); } // Extract remaining capacity limit (offset 32 = byte 5) if (report.data.size() > 5) { uint8_t remaining_limit = report.data[5]; // Offset 32 bits = byte 4 + 1 - data.battery_charge_low = static_cast(remaining_limit); + data.battery.charge_low = static_cast(remaining_limit); ESP_LOGI(CP_TAG, "CyberPower Battery charge low threshold: %.0f%% (raw: %d)", - data.battery_charge_low, remaining_limit); + data.battery.charge_low, remaining_limit); } // Extract full charge capacity (offset 40 = byte 6) - this is NOT used for battery.status @@ -887,31 +898,31 @@ void CyberPowerProtocol::parse_battery_chemistry_report(const HidReport &report, // Map chemistry values based on NUT libhid implementation (same as APC) switch (chemistry_raw) { case 1: - data.battery_type = "Alkaline"; + data.battery.type = "Alkaline"; break; case 2: - data.battery_type = "NiCd"; + data.battery.type = "NiCd"; break; case 3: - data.battery_type = "NiMH"; + data.battery.type = "NiMH"; break; case 4: - data.battery_type = "PbAcid"; // Lead Acid (matches NUT output) + data.battery.type = "PbAcid"; // Lead Acid (matches NUT output) break; case 5: - data.battery_type = "LiIon"; + data.battery.type = "LiIon"; break; case 6: - data.battery_type = "LiPoly"; + data.battery.type = "LiPoly"; break; default: - data.battery_type = "Unknown"; + data.battery.type = "Unknown"; ESP_LOGW(CP_TAG, "Unknown CyberPower battery chemistry value: %d", chemistry_raw); break; } ESP_LOGI(CP_TAG, "CyberPower Battery chemistry: %s (raw: %d)", - data.battery_type.c_str(), chemistry_raw); + data.battery.type.c_str(), chemistry_raw); } std::string CyberPowerProtocol::clean_firmware_string(const std::string &raw_firmware) { @@ -956,7 +967,7 @@ bool CyberPowerProtocol::beeper_enable() { uint8_t beeper_data[2] = {BEEPER_STATUS_REPORT_ID, 0x02}; // Report ID, Value=2 (enabled) - esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data)); + esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(CP_TAG, "CyberPower beeper enabled successfully with report ID 0x%02X", BEEPER_STATUS_REPORT_ID); return true; @@ -974,7 +985,7 @@ bool CyberPowerProtocol::beeper_disable() { uint8_t beeper_data[2] = {BEEPER_STATUS_REPORT_ID, 0x01}; // Report ID, Value=1 (disabled) - esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data)); + esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(CP_TAG, "CyberPower beeper disabled successfully with report ID 0x%02X", BEEPER_STATUS_REPORT_ID); return true; @@ -993,7 +1004,7 @@ bool CyberPowerProtocol::beeper_mute() { // - Different from DISABLE (1) which turns off beeper completely uint8_t beeper_data[2] = {0x0c, 0x03}; // Report ID, Value=3 (muted/acknowledged) - esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data)); + esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(CP_TAG, "CyberPower beeper muted (current alarms acknowledged) successfully"); return true; @@ -1045,7 +1056,7 @@ bool CyberPowerProtocol::beeper_test() { // Step 4: Restore original beeper state ESP_LOGI(CP_TAG, "Step 4: Restoring original beeper state: %d", original_state); uint8_t restore_data[2] = {0x0c, original_state}; - esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, restore_data, sizeof(restore_data)); + esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, restore_data, sizeof(restore_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(CP_TAG, "CyberPower beeper test sequence completed successfully"); @@ -1064,7 +1075,7 @@ bool CyberPowerProtocol::start_battery_test_quick() { // Quick test command value is 1 (from NUT test_write_info) uint8_t test_data[2] = {0x14, 1}; // Report ID 0x14, value 1 = Quick test - esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2); + esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2, parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(CP_TAG, "Quick battery test command sent successfully"); return true; @@ -1080,7 +1091,7 @@ bool CyberPowerProtocol::start_battery_test_deep() { // Deep test command value is 2 (from NUT test_write_info) uint8_t test_data[2] = {0x14, 2}; // Report ID 0x14, value 2 = Deep test - esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2); + esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2, parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(CP_TAG, "Deep battery test command sent successfully"); return true; @@ -1096,7 +1107,7 @@ bool CyberPowerProtocol::stop_battery_test() { // Abort test command value is 3 (from NUT test_write_info) uint8_t test_data[2] = {0x14, 3}; // Report ID 0x14, value 3 = Abort test - esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2); + esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2, parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(CP_TAG, "Battery test stop command sent successfully"); return true; @@ -1119,5 +1130,156 @@ bool CyberPowerProtocol::stop_ups_test() { return stop_battery_test(); } +void CyberPowerProtocol::parse_test_result_report(const HidReport &report, UpsData &data) { + // Parse test result from Report 0x14 (UPS.Output.Test) + // Based on NUT test_read_info lookup table + if (report.data.size() < 2) { + data.test.ups_test_result = "Error reading test result"; + return; + } + + // Based on NUT test_read_info lookup table for CyberPower: + // 1 = "Done and passed", 2 = "Done and warning", 3 = "Done and error" + // 4 = "Aborted", 5 = "In progress", 6 = "No test initiated", 7 = "Test scheduled" + uint8_t test_result_value = report.data[1]; + + ESP_LOGD(CP_TAG, "Raw test result from report 0x14: 0x%02X (%d)", test_result_value, test_result_value); + + switch (test_result_value) { + case 1: + data.test.ups_test_result = "Done and passed"; + break; + case 2: + data.test.ups_test_result = "Done and warning"; + break; + case 3: + data.test.ups_test_result = "Done and error"; + break; + case 4: + data.test.ups_test_result = "Aborted"; + break; + case 5: + data.test.ups_test_result = "In progress"; + break; + case 6: + data.test.ups_test_result = "No test initiated"; + break; + case 7: + data.test.ups_test_result = "Test scheduled"; + break; + default: + data.test.ups_test_result = "Unknown test result (" + std::to_string(test_result_value) + ")"; + ESP_LOGW(CP_TAG, "Unknown CyberPower test result value: %d", test_result_value); + break; + } + + ESP_LOGI(CP_TAG, "CyberPower Test result: %s (raw: %d)", data.test.ups_test_result.c_str(), test_result_value); +} + +void CyberPowerProtocol::read_frequency_data(UpsData &data) { + // Initialize frequency to NaN + data.power.frequency = NAN; + + // Try to read frequency from various HID report IDs + // CyberPower devices may have frequency in input/output measurement reports + + // Report IDs commonly used for frequency measurements: + const std::vector frequency_report_ids = { + HID_USAGE_POW_FREQUENCY, // 0x32 - Standard HID frequency usage + HID_USAGE_POW_VOLTAGE, // 0x30 - Input measurements (may include frequency) + HID_USAGE_POW_CURRENT, // 0x31 - Output measurements (may include frequency) + 0x11, // CyberPower-specific frequency report (based on NUT analysis) + INPUT_VOLTAGE_REPORT_ID, // 0x0F - might contain frequency data + OUTPUT_VOLTAGE_REPORT_ID, // 0x12 - might contain frequency data + }; + + for (uint8_t report_id : frequency_report_ids) { + HidReport freq_report; + if (read_hid_report(report_id, freq_report)) { + float frequency_value = parse_frequency_from_report(freq_report); + if (!std::isnan(frequency_value)) { + data.power.frequency = frequency_value; + ESP_LOGD(CP_TAG, "Found frequency %.1f Hz in report 0x%02X", frequency_value, report_id); + return; + } + } + } + + ESP_LOGV(CP_TAG, "Frequency data not available from any HID report"); +} + +float CyberPowerProtocol::parse_frequency_from_report(const HidReport &report) { + if (report.data.size() < 2) { + return NAN; + } + + // Try different byte positions and formats commonly used for frequency + // CyberPower devices may use 0.1 Hz scaling (report 501 becomes 50.1 Hz) + + // Method 1: Single byte at position 1 (common for simple frequency reports) + if (report.data.size() >= 2) { + uint8_t freq_byte = report.data[1]; + if (freq_byte >= FREQUENCY_MIN_VALID && freq_byte <= FREQUENCY_MAX_VALID) { + return static_cast(freq_byte); + } + } + + // Method 2: 16-bit little-endian value at position 1-2 + if (report.data.size() >= 3) { + uint16_t freq_word = report.data[1] | (report.data[2] << 8); + if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) { + return static_cast(freq_word); + } + } + + // Method 3: 16-bit big-endian value at position 1-2 + if (report.data.size() >= 3) { + uint16_t freq_word = (report.data[1] << 8) | report.data[2]; + if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) { + return static_cast(freq_word); + } + } + + // Method 4: CyberPower-specific scaled frequency (0.1 factor) + // Some CyberPower models report frequency * 10 (e.g., 500 for 50.0 Hz, 600 for 60.0 Hz) + if (report.data.size() >= 3) { + uint16_t freq_scaled = report.data[1] | (report.data[2] << 8); + float freq_value = static_cast(freq_scaled) / 10.0f; + if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) { + ESP_LOGD(CP_TAG, "Applied CyberPower 0.1x frequency scaling: %d -> %.1f Hz", freq_scaled, freq_value); + return freq_value; + } + } + + // Method 5: Check for hundreds scaling (e.g., 5000 for 50.0 Hz) + if (report.data.size() >= 3) { + uint16_t freq_scaled = report.data[1] | (report.data[2] << 8); + float freq_value = static_cast(freq_scaled) / 100.0f; + if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) { + ESP_LOGD(CP_TAG, "Applied CyberPower 0.01x frequency scaling: %d -> %.1f Hz", freq_scaled, freq_value); + return freq_value; + } + } + + return NAN; +} + } // namespace ups_hid -} // namespace esphome \ No newline at end of file +} // namespace esphome + +// Protocol Factory Self-Registration +#include "protocol_factory.h" + +namespace esphome { +namespace ups_hid { + +// Creator function for CyberPower protocol +std::unique_ptr create_cyberpower_protocol(UpsHidComponent* parent) { + return std::make_unique(parent); +} + +} // namespace ups_hid +} // namespace esphome + +// Register CyberPower protocol for vendor ID 0x0764 +REGISTER_UPS_PROTOCOL_FOR_VENDOR(0x0764, cyberpower_hid_protocol, esphome::ups_hid::create_cyberpower_protocol, "CyberPower HID Protocol", "CyberPower CP series HID protocol with comprehensive sensor support and test functionality", 100); \ No newline at end of file diff --git a/components/ups_hid/cyberpower_protocol.h b/components/ups_hid/cyberpower_protocol.h index 2e60207..97b5ece 100644 --- a/components/ups_hid/cyberpower_protocol.h +++ b/components/ups_hid/cyberpower_protocol.h @@ -24,7 +24,7 @@ class CyberPowerProtocol : public UpsProtocolBase { bool detect() override; bool initialize() override; bool read_data(UpsData &data) override; - UpsProtocol get_protocol_type() const override { return PROTOCOL_CYBERPOWER_HID; } + DeviceInfo::DetectedProtocol get_protocol_type() const override { return DeviceInfo::PROTOCOL_CYBERPOWER_HID; } std::string get_protocol_name() const override { return "CyberPower HID"; } // Beeper control methods @@ -60,6 +60,7 @@ class CyberPowerProtocol : public UpsProtocolBase { static const uint8_t INPUT_SENSITIVITY_REPORT_ID = 0x1a; // Input sensitivity static const uint8_t FIRMWARE_VERSION_REPORT_ID = 0x1b; // Firmware version static const uint8_t SERIAL_NUMBER_REPORT_ID = 0x02; // Serial number + static const uint8_t TEST_RESULT_REPORT_ID = 0x14; // UPS test result (same as test command) // HID Report structure struct HidReport { @@ -95,6 +96,7 @@ class CyberPowerProtocol : public UpsProtocolBase { void parse_input_sensitivity_report(const HidReport &report, UpsData &data); void parse_firmware_version_report(const HidReport &report, UpsData &data); void parse_serial_number_report(const HidReport &report, UpsData &data); + void parse_test_result_report(const HidReport &report, UpsData &data); // Missing dynamic values from NUT analysis void read_missing_dynamic_values(UpsData &data); @@ -106,6 +108,10 @@ class CyberPowerProtocol : public UpsProtocolBase { // CyberPower-specific scaling logic void check_battery_voltage_scaling(float battery_voltage, float nominal_voltage); + + // Frequency reading methods + void read_frequency_data(UpsData &data); + float parse_frequency_from_report(const HidReport &report); }; } // namespace ups_hid diff --git a/components/ups_hid/device_info.h b/components/ups_hid/device_info.h new file mode 100644 index 0000000..6099bc4 --- /dev/null +++ b/components/ups_hid/device_info.h @@ -0,0 +1,101 @@ +#pragma once + +#include + +namespace esphome { +namespace ups_hid { + +struct DeviceInfo { + // Basic device identification + std::string manufacturer{}; // Device manufacturer + std::string model{}; // Device model name + std::string serial_number{}; // Device serial number + std::string firmware_version{}; // Primary firmware version + std::string firmware_aux{}; // Auxiliary firmware info + std::string mfr_date{}; // Device manufacture date + + // USB device identification + uint16_t usb_vendor_id{0}; // USB Vendor ID + uint16_t usb_product_id{0}; // USB Product ID + + // Protocol information + enum DetectedProtocol { + PROTOCOL_UNKNOWN = 0, + PROTOCOL_APC_HID, + PROTOCOL_CYBERPOWER_HID, + PROTOCOL_GENERIC_HID + }; + + DetectedProtocol detected_protocol{PROTOCOL_UNKNOWN}; + + // Device capabilities flags + struct Capabilities { + bool supports_hid_get_report{false}; + bool supports_hid_set_report{false}; + bool supports_beeper_control{false}; + bool supports_battery_test{false}; + bool supports_ups_test{false}; + bool is_input_only_device{false}; + bool supports_runtime_estimation{false}; + bool supports_configuration_queries{false}; + }; + + Capabilities capabilities{}; + + // Validation and utility methods + bool is_valid() const { + return !manufacturer.empty() || !model.empty() || !serial_number.empty(); + } + + bool has_basic_info() const { + return !manufacturer.empty() && !model.empty(); + } + + bool has_usb_info() const { + return usb_vendor_id != 0; + } + + std::string get_protocol_name() const { + switch (detected_protocol) { + case PROTOCOL_APC_HID: return "APC HID"; + case PROTOCOL_CYBERPOWER_HID: return "CyberPower HID"; + case PROTOCOL_GENERIC_HID: return "Generic HID"; + default: return "Unknown"; + } + } + + std::string get_device_description() const { + if (has_basic_info()) { + return manufacturer + " " + model; + } else if (!model.empty()) { + return model; + } else if (!manufacturer.empty()) { + return manufacturer + " Device"; + } else { + return "Unknown UPS"; + } + } + + std::string get_usb_description() const { + if (has_usb_info()) { + char buffer[32]; + snprintf(buffer, sizeof(buffer), "0x%04X:0x%04X", usb_vendor_id, usb_product_id); + return std::string(buffer); + } + return "Unknown USB ID"; + } + + void reset() { + *this = DeviceInfo{}; + } + + // Copy constructor and assignment for safe copying + DeviceInfo() = default; + DeviceInfo(const DeviceInfo&) = default; + DeviceInfo& operator=(const DeviceInfo&) = default; + DeviceInfo(DeviceInfo&&) = default; + DeviceInfo& operator=(DeviceInfo&&) = default; +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/esp32_usb_transport.cpp b/components/ups_hid/esp32_usb_transport.cpp new file mode 100644 index 0000000..f1057e3 --- /dev/null +++ b/components/ups_hid/esp32_usb_transport.cpp @@ -0,0 +1,881 @@ +#include "esp32_usb_transport.h" +#include "esphome/core/log.h" +#include "esphome/core/helpers.h" + +#ifdef USE_ESP32 + +namespace esphome { +namespace ups_hid { + +static const char *const ESP32_USB_TAG = "ups_hid.esp32_usb"; + +// USB HID Class defines +#ifndef USB_CLASS_HID +#define USB_CLASS_HID 0x03 +#endif + +Esp32UsbTransport::Esp32UsbTransport() { + memset(&device_, 0, sizeof(device_)); +} + +Esp32UsbTransport::~Esp32UsbTransport() { + deinitialize(); +} + +esp_err_t Esp32UsbTransport::initialize() { + std::lock_guard lock(device_mutex_); + + if (initialized_.load()) { + return ESP_OK; + } + + ESP_LOGI(ESP32_USB_TAG, "Initializing ESP32 USB transport"); + + esp_err_t ret = setup_usb_host(); + if (ret != ESP_OK) { + set_last_error("Failed to setup USB host: " + std::string(esp_err_to_name(ret))); + return ret; + } + + // Register USB client for device events - connection will be asynchronous + ret = find_and_open_device(); + if (ret != ESP_OK) { + teardown_usb_host(); + return ret; + } + + initialized_ = true; + + ESP_LOGI(ESP32_USB_TAG, "ESP32 USB transport initialized - waiting for USB device connection events"); + + return ESP_OK; +} + +esp_err_t Esp32UsbTransport::deinitialize() { + std::lock_guard lock(device_mutex_); + + if (!initialized_.load()) { + return ESP_OK; + } + + ESP_LOGI(ESP32_USB_TAG, "Deinitializing ESP32 USB transport"); + + connected_ = false; + initialized_ = false; + + esp_err_t ret = teardown_usb_host(); + if (ret != ESP_OK) { + ESP_LOGW(ESP32_USB_TAG, "USB teardown had issues: %s", esp_err_to_name(ret)); + } + + return ret; +} + +bool Esp32UsbTransport::is_connected() const { + return connected_.load() && initialized_.load(); +} + +uint16_t Esp32UsbTransport::get_vendor_id() const { + std::lock_guard lock(device_mutex_); + return device_.vendor_id; +} + +uint16_t Esp32UsbTransport::get_product_id() const { + std::lock_guard lock(device_mutex_); + return device_.product_id; +} + +esp_err_t Esp32UsbTransport::hid_get_report(uint8_t report_type, uint8_t report_id, + uint8_t* data, size_t* data_len, + uint32_t timeout_ms) { + if (!device_.dev_hdl) { + ESP_LOGE(ESP32_USB_TAG, "HID GET_REPORT: No device handle"); + return ESP_ERR_INVALID_ARG; + } + if (!data || !data_len || *data_len == 0) { + ESP_LOGE(ESP32_USB_TAG, "HID GET_REPORT: Invalid parameters"); + return ESP_ERR_INVALID_ARG; + } + + ESP_LOGD(ESP32_USB_TAG, "HID GET_REPORT: type=0x%02X, id=0x%02X, max_len=%zu", + report_type, report_id, *data_len); + + // Use fixed buffer sizes like working implementation + uint8_t buffer[64] = {0}; // Fixed size buffer + size_t expected_len = std::min(*data_len, sizeof(buffer)); + + // Create USB control transfer for HID GET_REPORT + const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_IN | + USB_BM_REQUEST_TYPE_TYPE_CLASS | + USB_BM_REQUEST_TYPE_RECIP_INTERFACE; + const uint8_t bRequest = 0x01; // HID GET_REPORT + const uint16_t wValue = (report_type << 8) | report_id; + const uint16_t wIndex = device_.interface_num; + const uint16_t wLength = expected_len; + + usb_transfer_t *transfer = nullptr; + size_t transfer_size = sizeof(usb_setup_packet_t) + expected_len; + esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer); + if (ret != ESP_OK) { + ESP_LOGE(ESP32_USB_TAG, "Failed to allocate transfer: %s", esp_err_to_name(ret)); + return ret; + } + + // Setup control transfer + transfer->device_handle = device_.dev_hdl; + transfer->bEndpointAddress = 0; + transfer->num_bytes = transfer_size; + transfer->timeout_ms = timeout_ms; + + // Create setup packet + usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer; + setup->bmRequestType = bmRequestType; + setup->bRequest = bRequest; + setup->wValue = wValue; + setup->wIndex = wIndex; + setup->wLength = wLength; + + // Use semaphore for synchronous operation + SemaphoreHandle_t done_sem = xSemaphoreCreateBinary(); + if (!done_sem) { + usb_host_transfer_free(transfer); + return ESP_ERR_NO_MEM; + } + + // Simple context for completion + struct { + SemaphoreHandle_t sem; + esp_err_t result; + size_t actual_bytes; + } ctx = {done_sem, ESP_ERR_TIMEOUT, 0}; + + transfer->context = &ctx; + transfer->callback = [](usb_transfer_t *t) { + auto *c = static_cast(t->context); + c->result = (t->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL; + c->actual_bytes = t->actual_num_bytes; + xSemaphoreGive(c->sem); + }; + + ret = usb_host_transfer_submit_control(device_.client_hdl, transfer); + if (ret == ESP_OK) { + if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) { + ret = ctx.result; + if (ret == ESP_OK && ctx.actual_bytes > sizeof(usb_setup_packet_t)) { + size_t data_received = ctx.actual_bytes - sizeof(usb_setup_packet_t); + size_t copy_len = std::min(data_received, *data_len); + memcpy(data, transfer->data_buffer + sizeof(usb_setup_packet_t), copy_len); + *data_len = copy_len; + + ESP_LOGD(ESP32_USB_TAG, "HID GET_REPORT success: received %zu bytes", *data_len); + } else { + ESP_LOGW(ESP32_USB_TAG, "HID GET_REPORT: No data received"); + *data_len = 0; + ret = ESP_FAIL; + } + } else { + ESP_LOGW(ESP32_USB_TAG, "HID GET_REPORT timeout"); + ret = ESP_ERR_TIMEOUT; + } + } else { + ESP_LOGW(ESP32_USB_TAG, "Failed to submit HID GET_REPORT: %s", esp_err_to_name(ret)); + } + + vSemaphoreDelete(done_sem); + usb_host_transfer_free(transfer); + return ret; +} + +esp_err_t Esp32UsbTransport::hid_set_report(uint8_t report_type, uint8_t report_id, + const uint8_t* data, size_t data_len, + uint32_t timeout_ms) { + if (!device_.dev_hdl) { + ESP_LOGE(ESP32_USB_TAG, "HID SET_REPORT: No device handle"); + return ESP_ERR_INVALID_ARG; + } + if (!data || data_len == 0) { + ESP_LOGE(ESP32_USB_TAG, "HID SET_REPORT: Invalid parameters"); + return ESP_ERR_INVALID_ARG; + } + + ESP_LOGD(ESP32_USB_TAG, "HID SET_REPORT: type=0x%02X, id=0x%02X, len=%zu", + report_type, report_id, data_len); + + // Create USB control transfer for HID SET_REPORT + const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_OUT | + USB_BM_REQUEST_TYPE_TYPE_CLASS | + USB_BM_REQUEST_TYPE_RECIP_INTERFACE; + const uint8_t bRequest = 0x09; // HID SET_REPORT + const uint16_t wValue = (report_type << 8) | report_id; + const uint16_t wIndex = device_.interface_num; + const uint16_t wLength = data_len; + + usb_transfer_t *transfer = nullptr; + size_t transfer_size = sizeof(usb_setup_packet_t) + data_len; + esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer); + if (ret != ESP_OK) { + ESP_LOGE(ESP32_USB_TAG, "Failed to allocate transfer: %s", esp_err_to_name(ret)); + return ret; + } + + // Setup control transfer + transfer->device_handle = device_.dev_hdl; + transfer->bEndpointAddress = 0; + transfer->num_bytes = transfer_size; + transfer->timeout_ms = timeout_ms; + + // Create setup packet + usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer; + setup->bmRequestType = bmRequestType; + setup->bRequest = bRequest; + setup->wValue = wValue; + setup->wIndex = wIndex; + setup->wLength = wLength; + + // Copy data to transfer buffer + memcpy(transfer->data_buffer + sizeof(usb_setup_packet_t), data, data_len); + + // Use semaphore for synchronous operation + SemaphoreHandle_t done_sem = xSemaphoreCreateBinary(); + if (!done_sem) { + usb_host_transfer_free(transfer); + return ESP_ERR_NO_MEM; + } + + // Simple context for completion + struct { + SemaphoreHandle_t sem; + esp_err_t result; + } ctx = {done_sem, ESP_ERR_TIMEOUT}; + + transfer->context = &ctx; + transfer->callback = [](usb_transfer_t *t) { + auto *c = static_cast(t->context); + c->result = (t->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL; + xSemaphoreGive(c->sem); + }; + + ret = usb_host_transfer_submit_control(device_.client_hdl, transfer); + if (ret == ESP_OK) { + if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) { + ret = ctx.result; + if (ret == ESP_OK) { + ESP_LOGD(ESP32_USB_TAG, "HID SET_REPORT success"); + } else { + ESP_LOGW(ESP32_USB_TAG, "HID SET_REPORT failed"); + } + } else { + ESP_LOGW(ESP32_USB_TAG, "HID SET_REPORT timeout"); + ret = ESP_ERR_TIMEOUT; + } + } else { + ESP_LOGW(ESP32_USB_TAG, "Failed to submit HID SET_REPORT: %s", esp_err_to_name(ret)); + } + + vSemaphoreDelete(done_sem); + usb_host_transfer_free(transfer); + return ret; +} + +esp_err_t Esp32UsbTransport::get_string_descriptor(uint8_t string_index, + std::string& result) { + result.clear(); + + if (!device_.dev_hdl) { + set_last_error("USB device not ready"); + return ESP_ERR_INVALID_STATE; + } + + ESP_LOGD(ESP32_USB_TAG, "USB GET_STRING_DESCRIPTOR: index=%d, language_id=0x0409", string_index); + + // USB string descriptors can be up to 255 bytes, but typically much smaller + const size_t max_string_len = 255; + const uint16_t language_id = 0x0409; // English US + + // USB string descriptor request parameters + const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_IN | + USB_BM_REQUEST_TYPE_TYPE_STANDARD | + USB_BM_REQUEST_TYPE_RECIP_DEVICE; + const uint8_t bRequest = USB_B_REQUEST_GET_DESCRIPTOR; + const uint16_t wValue = (USB_B_DESCRIPTOR_TYPE_STRING << 8) | string_index; + const uint16_t wIndex = language_id; + const uint16_t wLength = max_string_len; + + usb_transfer_t *transfer = nullptr; + size_t transfer_size = sizeof(usb_setup_packet_t) + max_string_len; + esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer); + if (ret != ESP_OK) { + set_last_error("Failed to allocate string descriptor transfer: " + std::string(esp_err_to_name(ret))); + return ret; + } + + // Setup control transfer + transfer->device_handle = device_.dev_hdl; + transfer->bEndpointAddress = 0; // Control endpoint + transfer->num_bytes = transfer_size; + transfer->timeout_ms = 1000; + + // Create setup packet + usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer; + setup->bmRequestType = bmRequestType; + setup->bRequest = bRequest; + setup->wValue = wValue; + setup->wIndex = wIndex; + setup->wLength = wLength; + + // Use semaphore for synchronous operation + SemaphoreHandle_t done_sem = xSemaphoreCreateBinary(); + if (!done_sem) { + usb_host_transfer_free(transfer); + return ESP_ERR_NO_MEM; + } + + // Context for completion + struct { + SemaphoreHandle_t sem; + esp_err_t result; + size_t actual_bytes; + } ctx = {done_sem, ESP_ERR_TIMEOUT, 0}; + + transfer->context = &ctx; + transfer->callback = [](usb_transfer_t *t) { + auto *c = static_cast(t->context); + c->result = (t->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL; + c->actual_bytes = t->actual_num_bytes; + xSemaphoreGive(c->sem); + }; + + ret = usb_host_transfer_submit_control(device_.client_hdl, transfer); + if (ret == ESP_OK) { + if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(1000)) == pdTRUE) { + ret = ctx.result; + if (ret == ESP_OK && ctx.actual_bytes > sizeof(usb_setup_packet_t)) { + // Parse the USB string descriptor + uint8_t *desc_data = transfer->data_buffer + sizeof(usb_setup_packet_t); + size_t desc_len = ctx.actual_bytes - sizeof(usb_setup_packet_t); + + if (desc_len >= 2) { + uint8_t bLength = desc_data[0]; // Total length of descriptor + uint8_t bDescriptorType = desc_data[1]; // Should be USB_B_DESCRIPTOR_TYPE_STRING (0x03) + + if (bDescriptorType == USB_B_DESCRIPTOR_TYPE_STRING && bLength >= 2) { + // USB string descriptors are UTF-16LE encoded, skip the 2-byte header + size_t string_data_len = std::min(static_cast(bLength - 2), desc_len - 2); + uint8_t *string_data = desc_data + 2; + + // Convert UTF-16LE to ASCII (simplified, handles ASCII characters) + result.reserve(string_data_len / 2); + for (size_t i = 0; i < string_data_len; i += 2) { + if (i + 1 < string_data_len) { + uint16_t utf16_char = string_data[i] | (string_data[i + 1] << 8); + if (utf16_char < 128 && utf16_char > 0) { // ASCII range, non-null + result += static_cast(utf16_char); + } else if (utf16_char >= 128) { + result += '?'; // Non-ASCII character placeholder + } + } + } + + // Trim trailing whitespace + while (!result.empty() && std::isspace(result.back())) { + result.pop_back(); + } + + ESP_LOGI(ESP32_USB_TAG, "USB string descriptor %d: \"%s\"", string_index, result.c_str()); + } else { + ESP_LOGW(ESP32_USB_TAG, "Invalid string descriptor: type=0x%02X, length=%d", bDescriptorType, bLength); + ret = ESP_ERR_INVALID_RESPONSE; + } + } else { + ESP_LOGW(ESP32_USB_TAG, "String descriptor too short: %zu bytes", desc_len); + ret = ESP_ERR_INVALID_SIZE; + } + } else { + ESP_LOGW(ESP32_USB_TAG, "USB string descriptor request failed or no data received"); + ret = ESP_FAIL; + } + } else { + ESP_LOGW(ESP32_USB_TAG, "USB string descriptor request timeout"); + ret = ESP_ERR_TIMEOUT; + } + } else { + ESP_LOGW(ESP32_USB_TAG, "Failed to submit string descriptor request: %s", esp_err_to_name(ret)); + } + + vSemaphoreDelete(done_sem); + usb_host_transfer_free(transfer); + return ret; +} + +std::string Esp32UsbTransport::get_last_error() const { + std::lock_guard lock(error_mutex_); + return last_error_; +} + +// Private methods implementation + +void Esp32UsbTransport::set_last_error(const std::string& error) { + std::lock_guard lock(error_mutex_); + last_error_ = error; + ESP_LOGW(ESP32_USB_TAG, "%s", error.c_str()); +} + +esp_err_t Esp32UsbTransport::setup_usb_host() { + // Create USB library task - USB Host installation happens inside the task + if (!usb_tasks_running_.load()) { + usb_tasks_running_ = true; + + // Create USB Host Library task first + BaseType_t task_created = xTaskCreate(usb_lib_task, "usb_lib_task", 4096, this, 2, &usb_lib_task_handle_); + if (task_created != pdTRUE) { + ESP_LOGE(ESP32_USB_TAG, "Failed to create USB Host Library task"); + usb_tasks_running_ = false; + return ESP_FAIL; + } + + // Give USB Host Library task time to initialize + vTaskDelay(pdMS_TO_TICKS(100)); + + // Create USB client task + task_created = xTaskCreate(usb_client_task, "usb_client_task", 6144, this, 3, &usb_client_task_handle_); + if (task_created != pdTRUE) { + ESP_LOGE(ESP32_USB_TAG, "Failed to create USB client task"); + usb_tasks_running_ = false; + return ESP_FAIL; + } + + ESP_LOGI(ESP32_USB_TAG, "USB Host tasks created successfully"); + } + + return ESP_OK; +} + +esp_err_t Esp32UsbTransport::teardown_usb_host() { + // Signal tasks to stop (they will self-terminate and handle USB cleanup) + if (usb_tasks_running_.load()) { + ESP_LOGI(ESP32_USB_TAG, "Stopping USB Host tasks..."); + usb_tasks_running_ = false; + + // Wait for tasks to self-terminate + vTaskDelay(pdMS_TO_TICKS(500)); // Give tasks time to exit cleanly + + usb_client_task_handle_ = nullptr; + usb_lib_task_handle_ = nullptr; + + ESP_LOGI(ESP32_USB_TAG, "USB Host tasks stopped"); + } + + // Release interface and device + if (device_.dev_hdl) { + ESP_LOGI(ESP32_USB_TAG, "Cleaning up device resources"); + usb_host_interface_release(device_.client_hdl, device_.dev_hdl, device_.interface_num); + usb_host_device_close(device_.client_hdl, device_.dev_hdl); + device_.dev_hdl = nullptr; + } + + if (device_.client_hdl) { + ESP_LOGI(ESP32_USB_TAG, "Deregistering USB client"); + usb_host_client_deregister(device_.client_hdl); + device_.client_hdl = nullptr; + } + + // USB Host uninstallation happens inside usb_lib_task now + return ESP_OK; +} + +esp_err_t Esp32UsbTransport::find_and_open_device() { + // Register USB client in asynchronous mode for event-driven device detection + usb_host_client_config_t client_config = { + .is_synchronous = false, // Use asynchronous mode for USB_HOST_CLIENT_EVENT_NEW_DEV events + .max_num_event_msg = 5, + .async = { + .client_event_callback = usb_client_event_callback, + .callback_arg = this + } + }; + + esp_err_t ret = usb_host_client_register(&client_config, &device_.client_hdl); + if (ret != ESP_OK) { + set_last_error("Client register failed: " + std::string(esp_err_to_name(ret))); + return ret; + } + + ESP_LOGI(ESP32_USB_TAG, "USB client registered (handle=0x%p), waiting for device connection events...", + device_.client_hdl); + + // Force immediate device enumeration check in addition to event-driven detection + ESP_LOGI(ESP32_USB_TAG, "Performing immediate device enumeration check..."); + vTaskDelay(pdMS_TO_TICKS(100)); // Small delay for USB stack to stabilize + + int num_dev = 10; + uint8_t dev_addr_list[10]; + esp_err_t enum_ret = usb_host_device_addr_list_fill(num_dev, dev_addr_list, &num_dev); + if (enum_ret == ESP_OK && num_dev > 0) { + ESP_LOGI(ESP32_USB_TAG, "Found %d existing USB devices during initial enumeration:", num_dev); + for (int i = 0; i < num_dev; i++) { + ESP_LOGI(ESP32_USB_TAG, " Attempting to handle existing device at address %d", dev_addr_list[i]); + handle_new_device(dev_addr_list[i]); + } + } else { + ESP_LOGI(ESP32_USB_TAG, "No existing USB devices found - waiting for connection events"); + } + + return ESP_OK; +} + +esp_err_t Esp32UsbTransport::claim_interface() { + const usb_config_desc_t *config_desc; + esp_err_t ret = usb_host_get_active_config_descriptor(device_.dev_hdl, &config_desc); + if (ret != ESP_OK) { + set_last_error("Failed to get config descriptor"); + return ret; + } + + // Find HID interface + const usb_intf_desc_t *intf_desc = nullptr; + int offset = 0; + + for (int i = 0; i < config_desc->bNumInterfaces; i++) { + intf_desc = usb_parse_interface_descriptor(config_desc, i, 0, &offset); + if (intf_desc && intf_desc->bInterfaceClass == USB_CLASS_HID) { + device_.interface_num = intf_desc->bInterfaceNumber; + break; + } + } + + if (!intf_desc || intf_desc->bInterfaceClass != USB_CLASS_HID) { + set_last_error("No HID interface found"); + return ESP_ERR_NOT_FOUND; + } + + ret = usb_host_interface_claim(device_.client_hdl, device_.dev_hdl, + device_.interface_num, 0); + if (ret != ESP_OK) { + set_last_error("Failed to claim interface: " + std::string(esp_err_to_name(ret))); + return ret; + } + + return ESP_OK; +} + +esp_err_t Esp32UsbTransport::find_endpoints() { + const usb_config_desc_t *config_desc; + esp_err_t ret = usb_host_get_active_config_descriptor(device_.dev_hdl, &config_desc); + if (ret != ESP_OK) { + return ret; + } + + int offset = 0; + const usb_intf_desc_t *intf_desc = usb_parse_interface_descriptor( + config_desc, device_.interface_num, 0, &offset); + + if (!intf_desc) { + set_last_error("Interface descriptor not found"); + return ESP_ERR_NOT_FOUND; + } + + // Parse endpoints correctly using ESP-IDF approach + const usb_ep_desc_t *ep_desc = nullptr; + int ep_offset = offset; + + ESP_LOGD(ESP32_USB_TAG, "Interface has %d endpoints", intf_desc->bNumEndpoints); + + for (int i = 0; i < intf_desc->bNumEndpoints; i++) { + ep_desc = usb_parse_endpoint_descriptor_by_index(intf_desc, i, config_desc->wTotalLength, &ep_offset); + if (ep_desc) { + if (USB_EP_DESC_GET_EP_DIR(ep_desc)) { + // IN endpoint (device to host) + device_.ep_in = ep_desc->bEndpointAddress; + device_.max_packet_size_in = ep_desc->wMaxPacketSize; + ESP_LOGD(ESP32_USB_TAG, "Found IN endpoint: 0x%02X (max packet size: %d)", + device_.ep_in, device_.max_packet_size_in); + } else { + // OUT endpoint (host to device) + device_.ep_out = ep_desc->bEndpointAddress; + device_.max_packet_size_out = ep_desc->wMaxPacketSize; + ESP_LOGD(ESP32_USB_TAG, "Found OUT endpoint: 0x%02X (max packet size: %d)", + device_.ep_out, device_.max_packet_size_out); + } + } else { + ESP_LOGW(ESP32_USB_TAG, "Failed to parse endpoint %d", i); + } + } + + if (device_.ep_in == 0) { + set_last_error("No IN endpoint found"); + return ESP_ERR_NOT_FOUND; + } + + // Detect input-only devices (no OUT endpoint) + if (device_.ep_out == 0) { + ESP_LOGW(ESP32_USB_TAG, "INPUT-ONLY HID device detected - no OUT endpoint available"); + ESP_LOGI(ESP32_USB_TAG, "Device supports HID GET_REPORT only (no SET_REPORT)"); + } else { + ESP_LOGD(ESP32_USB_TAG, "Bidirectional device detected - has both IN and OUT endpoints"); + } + + return ESP_OK; +} + +esp_err_t Esp32UsbTransport::submit_control_transfer(uint8_t bmRequestType, uint8_t bRequest, + uint16_t wValue, uint16_t wIndex, + uint8_t* data, size_t data_len, + uint32_t timeout_ms) { + std::lock_guard lock(device_mutex_); + + if (!device_.dev_hdl) { + return ESP_ERR_INVALID_STATE; + } + + usb_transfer_t *transfer; + esp_err_t ret = usb_host_transfer_alloc(sizeof(usb_setup_packet_t) + data_len, 0, &transfer); + if (ret != ESP_OK) { + set_last_error("Transfer alloc failed: " + std::string(esp_err_to_name(ret))); + return ret; + } + + // Setup packet + usb_setup_packet_t *setup = (usb_setup_packet_t *)transfer->data_buffer; + setup->bmRequestType = bmRequestType; + setup->bRequest = bRequest; + setup->wValue = wValue; + setup->wIndex = wIndex; + setup->wLength = data_len; + + if (data_len > 0 && data) { + if (bmRequestType & USB_BM_REQUEST_TYPE_DIR_IN) { + // IN transfer - device to host + memset(transfer->data_buffer + sizeof(usb_setup_packet_t), 0, data_len); + } else { + // OUT transfer - host to device + memcpy(transfer->data_buffer + sizeof(usb_setup_packet_t), data, data_len); + } + } + + transfer->device_handle = device_.dev_hdl; + transfer->bEndpointAddress = 0; // Control endpoint + transfer->callback = nullptr; + transfer->context = nullptr; + transfer->num_bytes = sizeof(usb_setup_packet_t) + data_len; + transfer->timeout_ms = timeout_ms; + + ret = usb_host_transfer_submit_control(device_.client_hdl, transfer); + if (ret != ESP_OK) { + usb_host_transfer_free(transfer); + set_last_error("Control transfer submit failed: " + std::string(esp_err_to_name(ret))); + return ret; + } + + // Copy response data back + if (data_len > 0 && data && (bmRequestType & USB_BM_REQUEST_TYPE_DIR_IN)) { + memcpy(data, transfer->data_buffer + sizeof(usb_setup_packet_t), data_len); + } + + usb_host_transfer_free(transfer); + return ESP_OK; +} + +void Esp32UsbTransport::usb_client_event_callback(const usb_host_client_event_msg_t* event_msg, void* arg) { + Esp32UsbTransport* transport = static_cast(arg); + + switch (event_msg->event) { + case USB_HOST_CLIENT_EVENT_NEW_DEV: + ESP_LOGI(ESP32_USB_TAG, "New USB device detected: address=%d", event_msg->new_dev.address); + transport->handle_new_device(event_msg->new_dev.address); + break; + + case USB_HOST_CLIENT_EVENT_DEV_GONE: + ESP_LOGI(ESP32_USB_TAG, "USB device disconnected"); + transport->handle_device_gone(event_msg->dev_gone.dev_hdl); + break; + + default: + ESP_LOGW(ESP32_USB_TAG, "Unhandled USB client event: %d", event_msg->event); + break; + } +} + +void Esp32UsbTransport::handle_new_device(uint8_t dev_addr) { + ESP_LOGI(ESP32_USB_TAG, "Handling new USB device at address %d", dev_addr); + + std::lock_guard lock(device_mutex_); + + // Check if we already have a device connected + if (device_.dev_hdl != nullptr) { + ESP_LOGW(ESP32_USB_TAG, "Device already connected - skipping new device at address %d", dev_addr); + return; + } + + // Open the device + esp_err_t ret = usb_host_device_open(device_.client_hdl, dev_addr, &device_.dev_hdl); + if (ret != ESP_OK) { + ESP_LOGE(ESP32_USB_TAG, "Failed to open device at address %d: %s", dev_addr, esp_err_to_name(ret)); + return; + } + + ESP_LOGI(ESP32_USB_TAG, "Successfully opened USB device at address %d", dev_addr); + + // Get device information + usb_device_info_t dev_info; + ret = usb_host_device_info(device_.dev_hdl, &dev_info); + if (ret != ESP_OK) { + ESP_LOGE(ESP32_USB_TAG, "Failed to get device info: %s", esp_err_to_name(ret)); + usb_host_device_close(device_.client_hdl, device_.dev_hdl); + device_.dev_hdl = nullptr; + return; + } + + device_.address = dev_addr; + device_.speed = dev_info.speed; + + // Get device descriptor to extract VID/PID + const usb_device_desc_t* device_desc; + ret = usb_host_get_device_descriptor(device_.dev_hdl, &device_desc); + if (ret == ESP_OK) { + device_.vendor_id = device_desc->idVendor; + device_.product_id = device_desc->idProduct; + + ESP_LOGI(ESP32_USB_TAG, "USB device opened: VID=0x%04X, PID=0x%04X, Speed=%d", + device_.vendor_id, device_.product_id, dev_info.speed); + + // Check if this is a UPS device (HID class) + if (device_desc->bDeviceClass == USB_CLASS_HID || + device_desc->bDeviceClass == 0x00) { // Device class defined at interface level + + // Try to claim HID interface and find endpoints + ret = claim_interface(); + if (ret == ESP_OK) { + ret = find_endpoints(); + if (ret == ESP_OK) { + connected_ = true; + ESP_LOGI(ESP32_USB_TAG, "UPS device successfully configured and ready"); + return; + } + } + } else { + ESP_LOGW(ESP32_USB_TAG, "Connected device is not a HID device (class=0x%02X)", device_desc->bDeviceClass); + } + } + + // Clean up on failure + usb_host_device_close(device_.client_hdl, device_.dev_hdl); + device_.dev_hdl = nullptr; +} + +void Esp32UsbTransport::handle_device_gone(usb_device_handle_t dev_hdl) { + ESP_LOGI(ESP32_USB_TAG, "Handling USB device disconnection"); + + std::lock_guard lock(device_mutex_); + + if (device_.dev_hdl == dev_hdl) { + connected_ = false; + + // Clean up device resources + if (device_.dev_hdl) { + usb_host_interface_release(device_.client_hdl, device_.dev_hdl, device_.interface_num); + usb_host_device_close(device_.client_hdl, device_.dev_hdl); + device_.dev_hdl = nullptr; + } + + // Reset device info + device_.address = 0; + device_.vendor_id = 0; + device_.product_id = 0; + + ESP_LOGI(ESP32_USB_TAG, "USB device disconnected and cleaned up"); + } +} + +void Esp32UsbTransport::usb_lib_task(void* arg) { + Esp32UsbTransport* transport = static_cast(arg); + + ESP_LOGI(ESP32_USB_TAG, "USB Host Library task starting..."); + + // Initialize USB Host library inside task (following working prototype) + usb_host_config_t host_config = { + .skip_phy_setup = false, + .intr_flags = ESP_INTR_FLAG_LEVEL1 + }; + + esp_err_t ret = usb_host_install(&host_config); + if (ret != ESP_OK) { + ESP_LOGE(ESP32_USB_TAG, "USB Host install failed: %s", esp_err_to_name(ret)); + transport->usb_tasks_running_ = false; // Stop other tasks + vTaskDelete(nullptr); + return; + } + + ESP_LOGI(ESP32_USB_TAG, "USB Host library installed successfully"); + + // Main USB Host event loop - following working prototype pattern + bool has_clients = true; + bool has_devices = false; + + while (has_clients && transport->usb_tasks_running_.load()) { + uint32_t event_flags; + ret = usb_host_lib_handle_events(portMAX_DELAY, &event_flags); + + if (ret != ESP_OK) { + ESP_LOGE(ESP32_USB_TAG, "USB Host event handling failed: %s", esp_err_to_name(ret)); + continue; + } + + // Handle USB Host events (following ESP-IDF v5.4 patterns) + if (event_flags & USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) { + ESP_LOGI(ESP32_USB_TAG, "No more USB clients"); + if (usb_host_device_free_all() == ESP_OK) { + ESP_LOGI(ESP32_USB_TAG, "All devices freed"); + has_clients = false; + } else { + ESP_LOGI(ESP32_USB_TAG, "Waiting for devices to be freed"); + has_devices = true; + } + } + + if (has_devices && (event_flags & USB_HOST_LIB_EVENT_FLAGS_ALL_FREE)) { + ESP_LOGI(ESP32_USB_TAG, "All devices freed"); + has_clients = false; + } + } + + // Cleanup USB Host library + ESP_LOGI(ESP32_USB_TAG, "Uninstalling USB Host library"); + usb_host_uninstall(); + + ESP_LOGI(ESP32_USB_TAG, "USB Host Library task ending"); + vTaskDelete(nullptr); +} + +void Esp32UsbTransport::usb_client_task(void* arg) { + Esp32UsbTransport* transport = static_cast(arg); + + ESP_LOGI(ESP32_USB_TAG, "USB client task started"); + + while (transport->usb_tasks_running_.load()) { + if (transport->device_.client_hdl) { + // Use shorter timeout for more responsive event processing + esp_err_t ret = usb_host_client_handle_events(transport->device_.client_hdl, 100); + + if (ret == ESP_ERR_TIMEOUT) { + // Timeout is normal - continue processing + } else if (ret != ESP_OK) { + ESP_LOGW(ESP32_USB_TAG, "USB client event handling failed: %s", esp_err_to_name(ret)); + vTaskDelay(pdMS_TO_TICKS(100)); // Brief delay on error + } + } else { + ESP_LOGD(ESP32_USB_TAG, "No USB client handle available"); + vTaskDelay(pdMS_TO_TICKS(100)); + } + + // Small delay to prevent busy-waiting + vTaskDelay(pdMS_TO_TICKS(10)); + } + + ESP_LOGI(ESP32_USB_TAG, "USB client task stopping"); + vTaskDelete(nullptr); +} + +} // namespace ups_hid +} // namespace esphome + +#endif // USE_ESP32 \ No newline at end of file diff --git a/components/ups_hid/esp32_usb_transport.h b/components/ups_hid/esp32_usb_transport.h new file mode 100644 index 0000000..fb5f40b --- /dev/null +++ b/components/ups_hid/esp32_usb_transport.h @@ -0,0 +1,104 @@ +#pragma once + +#include "usb_transport_interface.h" + +#ifdef USE_ESP32 +#include "usb/usb_host.h" +#include "usb/usb_types_ch9.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include +#include +#include + +namespace esphome { +namespace ups_hid { + +/** + * ESP32 USB Transport Implementation + * + * Concrete implementation using ESP-IDF USB Host API + * Handles all ESP32-specific USB communication details + */ +class Esp32UsbTransport : public IUsbTransport { +public: + Esp32UsbTransport(); + ~Esp32UsbTransport() override; + + // IUsbTransport implementation + esp_err_t initialize() override; + esp_err_t deinitialize() override; + + bool is_connected() const override; + uint16_t get_vendor_id() const override; + uint16_t get_product_id() const override; + + esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id, + uint8_t* data, size_t* data_len, + uint32_t timeout_ms = 1000) override; + + esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, + const uint8_t* data, size_t data_len, + uint32_t timeout_ms = 1000) override; + + esp_err_t get_string_descriptor(uint8_t string_index, + std::string& result) override; + + std::string get_last_error() const override; + +private: + // USB device structure + struct UsbDevice { + usb_host_client_handle_t client_hdl{nullptr}; + usb_device_handle_t dev_hdl{nullptr}; + uint8_t address{0}; + uint8_t interface_num{0}; + uint8_t ep_in{0}; + uint8_t ep_out{0}; + uint16_t vendor_id{0}; + uint16_t product_id{0}; + uint16_t max_packet_size_in{0}; + uint16_t max_packet_size_out{0}; + usb_speed_t speed{USB_SPEED_LOW}; + }; + + UsbDevice device_; + mutable std::mutex device_mutex_; + std::atomic connected_{false}; + std::atomic initialized_{false}; + + // USB Host Library management + TaskHandle_t usb_lib_task_handle_{nullptr}; + TaskHandle_t usb_client_task_handle_{nullptr}; + std::atomic usb_tasks_running_{false}; + + // Error handling + mutable std::mutex error_mutex_; + std::string last_error_; + + // Private methods + static void usb_lib_task(void* arg); + static void usb_client_task(void* arg); + static void usb_client_event_callback(const usb_host_client_event_msg_t* event_msg, void* arg); + + void handle_new_device(uint8_t dev_addr); + void handle_device_gone(usb_device_handle_t dev_hdl); + + esp_err_t setup_usb_host(); + esp_err_t teardown_usb_host(); + esp_err_t find_and_open_device(); + esp_err_t claim_interface(); + esp_err_t find_endpoints(); + + void set_last_error(const std::string& error); + esp_err_t submit_control_transfer(uint8_t bmRequestType, uint8_t bRequest, + uint16_t wValue, uint16_t wIndex, + uint8_t* data, size_t data_len, + uint32_t timeout_ms); +}; + +} // namespace ups_hid +} // namespace esphome + +#endif // USE_ESP32 \ No newline at end of file diff --git a/components/ups_hid/generic_hid_protocol.cpp b/components/ups_hid/generic_hid_protocol.cpp index 584b077..0e72f96 100644 --- a/components/ups_hid/generic_hid_protocol.cpp +++ b/components/ups_hid/generic_hid_protocol.cpp @@ -1,4 +1,6 @@ +#include "generic_hid_protocol.h" #include "ups_hid.h" +#include "hid_constants.h" #include "esphome/core/log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" @@ -34,21 +36,19 @@ static const uint8_t EXTENDED_REPORT_IDS[] = { }; // Report type constants for HID -static const uint8_t HID_REPORT_TYPE_INPUT = 0x01; -static const uint8_t HID_REPORT_TYPE_OUTPUT = 0x02; -static const uint8_t HID_REPORT_TYPE_FEATURE = 0x03; +// HID report types are now defined in hid_constants.h bool GenericHidProtocol::detect() { ESP_LOGD(GEN_TAG, "Detecting Generic HID Protocol..."); // Check device connection status first - if (!parent_->is_device_connected()) { + if (!parent_->is_connected()) { ESP_LOGD(GEN_TAG, "Device not connected, skipping protocol detection"); return false; } // Check if this is a known vendor that should use a specific protocol - uint16_t vid = parent_->get_usb_vendor_id(); + uint16_t vid = parent_->get_vendor_id(); if (vid == 0x051D || vid == 0x0764) { // APC or CyberPower ESP_LOGD(GEN_TAG, "Known vendor 0x%04X should use specific protocol", vid); return false; @@ -60,14 +60,14 @@ bool GenericHidProtocol::detect() { for (uint8_t report_id : COMMON_REPORT_IDS) { // Check connection status before each attempt - if (!parent_->is_device_connected()) { + if (!parent_->is_connected()) { ESP_LOGD(GEN_TAG, "Device disconnected during protocol detection"); return false; } // Try Input Report first (real-time data) buffer_len = sizeof(buffer); - esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len); + esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { available_input_reports_.insert(report_id); ESP_LOGI(GEN_TAG, "Found Input report 0x%02X (%zu bytes)", report_id, buffer_len); @@ -76,14 +76,14 @@ bool GenericHidProtocol::detect() { } // Check connection again before trying Feature report - if (!parent_->is_device_connected()) { + if (!parent_->is_connected()) { ESP_LOGD(GEN_TAG, "Device disconnected during protocol detection"); return false; } // Try Feature Report (static/configuration data) buffer_len = sizeof(buffer); - ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len); + ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { available_feature_reports_.insert(report_id); ESP_LOGI(GEN_TAG, "Found Feature report 0x%02X (%zu bytes)", report_id, buffer_len); @@ -188,7 +188,10 @@ bool GenericHidProtocol::read_data(UpsData &data) { success = true; } - // 8. Try any other discovered reports with heuristic parsing + // 8. Try to read frequency data + read_frequency_data(data); + + // 9. Try any other discovered reports with heuristic parsing if (!success) { for (uint8_t id : available_input_reports_) { if (id == 0x01 || id == 0x06 || id == 0x0C || id == 0x16 || @@ -207,25 +210,26 @@ bool GenericHidProtocol::read_data(UpsData &data) { } // Set generic manufacturer/model if not already set - if (data.manufacturer.empty()) { - data.manufacturer = "Generic"; + if (data.device.manufacturer.empty()) { + data.device.manufacturer = "Generic"; } - if (data.model.empty()) { - uint16_t vid = parent_->get_usb_vendor_id(); - uint16_t pid = parent_->get_usb_product_id(); + if (data.device.model.empty()) { + uint16_t vid = parent_->get_vendor_id(); + uint16_t pid = parent_->get_product_id(); char model_str[32]; snprintf(model_str, sizeof(model_str), "HID UPS %04X:%04X", vid, pid); - data.model = model_str; + data.device.model = model_str; } - // Ensure we have at least basic status - if (success && data.status_flags == 0) { - // If we got data but no status flags, assume online - data.status_flags = UPS_STATUS_ONLINE; + // Ensure we have at least basic power status + if (success && data.power.status.empty()) { + // If we got data but no power status, assume online + data.power.status = "Online"; + data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage } // Set default test result - data.ups_test_result = "No test initiated"; + data.test.ups_test_result = "No test initiated"; return success; } @@ -240,14 +244,14 @@ void GenericHidProtocol::enumerate_reports() { // First try common report IDs for (uint8_t id : COMMON_REPORT_IDS) { // Check device connection before each report - if (!parent_->is_device_connected()) { + if (!parent_->is_connected()) { ESP_LOGD(GEN_TAG, "Device disconnected during report enumeration"); return; } // Check Input reports buffer_len = sizeof(buffer); - esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len); + esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { available_input_reports_.insert(id); report_sizes_[id] = buffer_len; @@ -256,14 +260,14 @@ void GenericHidProtocol::enumerate_reports() { } // Check connection again before Feature report - if (!parent_->is_device_connected()) { + if (!parent_->is_connected()) { ESP_LOGD(GEN_TAG, "Device disconnected during report enumeration"); return; } // Check Feature reports buffer_len = sizeof(buffer); - ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, id, buffer, &buffer_len); + ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { available_feature_reports_.insert(id); if (report_sizes_.find(id) == report_sizes_.end()) { @@ -286,7 +290,7 @@ void GenericHidProtocol::enumerate_reports() { ESP_LOGD(GEN_TAG, "Performing extended report search..."); for (uint8_t id : EXTENDED_REPORT_IDS) { // Check device connection before each extended report - if (!parent_->is_device_connected()) { + if (!parent_->is_connected()) { ESP_LOGD(GEN_TAG, "Device disconnected during extended report search"); return; } @@ -297,7 +301,7 @@ void GenericHidProtocol::enumerate_reports() { } buffer_len = sizeof(buffer); - esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len); + esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { available_input_reports_.insert(id); report_sizes_[id] = buffer_len; @@ -315,7 +319,7 @@ bool GenericHidProtocol::read_report(uint8_t report_id, uint8_t* buffer, size_t& // Try Input report first if available (real-time data) if (available_input_reports_.count(report_id)) { buffer_len = 64; - esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len); + esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { ESP_LOGV(GEN_TAG, "Read Input report 0x%02X: %zu bytes", report_id, buffer_len); return true; @@ -325,7 +329,7 @@ bool GenericHidProtocol::read_report(uint8_t report_id, uint8_t* buffer, size_t& // Try Feature report (static/configuration data) if (available_feature_reports_.count(report_id)) { buffer_len = 64; - esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len); + esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len, parent_->get_protocol_timeout()); if (ret == ESP_OK && buffer_len > 0) { ESP_LOGV(GEN_TAG, "Read Feature report 0x%02X: %zu bytes", report_id, buffer_len); return true; @@ -343,12 +347,12 @@ void GenericHidProtocol::parse_power_summary(uint8_t* data, size_t len, UpsData& // Battery percentage typically at byte 1 uint8_t battery = data[1]; if (battery <= 100) { - ups_data.battery_level = static_cast(battery); + ups_data.battery.level = static_cast(battery); ESP_LOGD(GEN_TAG, "Power summary: Battery %d%%", battery); } else if (battery <= 200 && battery > 100) { // Some devices use 0-200 scale - ups_data.battery_level = static_cast(battery) / 2.0f; - ESP_LOGD(GEN_TAG, "Power summary: Battery %.1f%% (scaled from %d)", ups_data.battery_level, battery); + ups_data.battery.level = static_cast(battery) / 2.0f; + ESP_LOGD(GEN_TAG, "Power summary: Battery %.1f%% (scaled from %d)", ups_data.battery.level, battery); } } @@ -356,7 +360,7 @@ void GenericHidProtocol::parse_power_summary(uint8_t* data, size_t len, UpsData& // Runtime in minutes (16-bit little-endian at bytes 2-3) uint16_t runtime = data[2] | (data[3] << 8); if (runtime > 0 && runtime < 10000) { - ups_data.runtime_minutes = static_cast(runtime); + ups_data.battery.runtime_minutes = static_cast(runtime); ESP_LOGD(GEN_TAG, "Power summary: Runtime %d minutes", runtime); } } @@ -369,20 +373,39 @@ void GenericHidProtocol::parse_battery_status(uint8_t* data, size_t len, UpsData // Common battery status bits (varies by vendor) if (status != 0xFF && status != 0x00) { // Valid status - if (status & 0x01) ups_data.status_flags |= UPS_STATUS_ONLINE; - if (status & 0x02) ups_data.status_flags |= UPS_STATUS_ON_BATTERY; - if (status & 0x04) ups_data.status_flags |= UPS_STATUS_LOW_BATTERY; - if (status & 0x08) ups_data.status_flags |= UPS_STATUS_CHARGING; - if (status & 0x10) ups_data.status_flags |= UPS_STATUS_REPLACE_BATTERY; - ESP_LOGD(GEN_TAG, "Battery status: 0x%02X -> flags 0x%08X", status, ups_data.status_flags); + // Update power status + if (status & 0x01) { + ups_data.power.status = "Online"; + ups_data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage + } + if (status & 0x02) { + ups_data.power.status = "On Battery"; + ups_data.power.input_voltage = NAN; + } + + // Update battery status + if (status & 0x08) { + ups_data.battery.status = "Charging"; + } + + if (status & 0x04) { + ups_data.battery.charge_low = 10.0f; // Low battery + } + + if (status & 0x10) { + ups_data.battery.status += " - Replace Battery"; + } + + ESP_LOGD(GEN_TAG, "Battery status: 0x%02X -> Power: \"%s\", Battery: \"%s\"", + status, ups_data.power.status.c_str(), ups_data.battery.status.c_str()); } } // Some devices include battery level here too - if (len >= 3 && std::isnan(ups_data.battery_level)) { + if (len >= 3 && std::isnan(ups_data.battery.level)) { uint8_t battery = data[2]; if (battery <= 100) { - ups_data.battery_level = static_cast(battery); + ups_data.battery.level = static_cast(battery); ESP_LOGD(GEN_TAG, "Battery status: Battery %d%%", battery); } } @@ -393,18 +416,40 @@ void GenericHidProtocol::parse_present_status(uint8_t* data, size_t len, UpsData // Based on HID Power Device spec, these are common bit positions if (len >= 2) { uint8_t status = data[1]; - ups_data.status_flags = 0; - // Standard HID Power Device status bits - if (status & 0x01) ups_data.status_flags |= UPS_STATUS_CHARGING; - if (status & 0x02) ups_data.status_flags |= UPS_STATUS_ON_BATTERY; - if (status & 0x04) ups_data.status_flags |= UPS_STATUS_ONLINE; - if (status & 0x08) ups_data.status_flags |= UPS_STATUS_LOW_BATTERY; - if (status & 0x10) ups_data.status_flags |= UPS_STATUS_REPLACE_BATTERY; - if (status & 0x20) ups_data.status_flags |= UPS_STATUS_OVERLOAD; - if (status & 0x40) ups_data.status_flags |= UPS_STATUS_FAULT; + // Standard HID Power Device status bits - map to data structures + if (status & 0x01) { + ups_data.battery.status = "Charging"; + } - ESP_LOGD(GEN_TAG, "Present status: 0x%02X -> flags 0x%08X", status, ups_data.status_flags); + if (status & 0x02) { + ups_data.power.status = "On Battery"; + ups_data.power.input_voltage = NAN; + } + + if (status & 0x04) { + ups_data.power.status = "Online"; + ups_data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage + } + + if (status & 0x08) { + ups_data.battery.charge_low = 10.0f; // Low battery + } + + if (status & 0x10) { + ups_data.battery.status += " - Replace Battery"; + } + + if (status & 0x20) { + ups_data.power.status += " - Overload"; + } + + if (status & 0x40) { + ups_data.battery.status += " - Fault"; + } + + ESP_LOGD(GEN_TAG, "Present status: 0x%02X -> Power: \"%s\", Battery: \"%s\"", + status, ups_data.power.status.c_str(), ups_data.battery.status.c_str()); } } @@ -416,13 +461,15 @@ void GenericHidProtocol::parse_general_status(uint8_t* data, size_t len, UpsData // Different vendors use different bit patterns, try common ones if (byte1 & 0x01) { - ups_data.status_flags |= UPS_STATUS_ONLINE; + ups_data.power.status = "Online"; + ups_data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage } if (byte1 & 0x10) { - ups_data.status_flags |= UPS_STATUS_ON_BATTERY; + ups_data.power.status = "On Battery"; + ups_data.power.input_voltage = NAN; } - ESP_LOGV(GEN_TAG, "General status byte: 0x%02X", byte1); + ESP_LOGV(GEN_TAG, "General status byte: 0x%02X -> Power: \"%s\"", byte1, ups_data.power.status.c_str()); } } @@ -440,10 +487,10 @@ void GenericHidProtocol::parse_voltage(uint8_t* data, size_t len, UpsData& ups_d // Sanity check if (voltage >= 80.0f && voltage <= 300.0f) { if (is_input) { - ups_data.input_voltage = voltage; + ups_data.power.input_voltage = voltage; ESP_LOGD(GEN_TAG, "Input voltage: %.1fV", voltage); } else { - ups_data.output_voltage = voltage; + ups_data.power.output_voltage = voltage; ESP_LOGD(GEN_TAG, "Output voltage: %.1fV", voltage); } } @@ -454,12 +501,12 @@ void GenericHidProtocol::parse_load(uint8_t* data, size_t len, UpsData& ups_data if (len >= 2) { uint8_t load = data[1]; if (load <= 100) { - ups_data.load_percent = static_cast(load); + ups_data.power.load_percent = static_cast(load); ESP_LOGD(GEN_TAG, "Load: %d%%", load); } else if (load <= 200) { // Some devices use 0-200 scale - ups_data.load_percent = static_cast(load) / 2.0f; - ESP_LOGD(GEN_TAG, "Load: %.1f%% (scaled from %d)", ups_data.load_percent, load); + ups_data.power.load_percent = static_cast(load) / 2.0f; + ESP_LOGD(GEN_TAG, "Load: %.1f%% (scaled from %d)", ups_data.power.load_percent, load); } } } @@ -471,12 +518,12 @@ bool GenericHidProtocol::parse_unknown_report(uint8_t* data, size_t len, UpsData // Look for percentage values (0-100) for (size_t i = 1; i < len && i < 4; i++) { if (data[i] <= 100 && data[i] > 0) { - if (std::isnan(ups_data.battery_level)) { - ups_data.battery_level = static_cast(data[i]); + if (std::isnan(ups_data.battery.level)) { + ups_data.battery.level = static_cast(data[i]); ESP_LOGV(GEN_TAG, "Heuristic: Found possible battery level %d%% at byte %zu", data[i], i); found_data = true; - } else if (std::isnan(ups_data.load_percent)) { - ups_data.load_percent = static_cast(data[i]); + } else if (std::isnan(ups_data.power.load_percent)) { + ups_data.power.load_percent = static_cast(data[i]); ESP_LOGV(GEN_TAG, "Heuristic: Found possible load %d%% at byte %zu", data[i], i); found_data = true; } @@ -492,8 +539,8 @@ bool GenericHidProtocol::parse_unknown_report(uint8_t* data, size_t len, UpsData if (voltage > 1000) voltage /= 10.0f; if (voltage >= 80.0f && voltage <= 300.0f) { - if (std::isnan(ups_data.input_voltage)) { - ups_data.input_voltage = voltage; + if (std::isnan(ups_data.power.input_voltage)) { + ups_data.power.input_voltage = voltage; ESP_LOGV(GEN_TAG, "Heuristic: Found possible voltage %.1fV at bytes %zu-%zu", voltage, i, i+1); found_data = true; @@ -517,19 +564,19 @@ void GenericHidProtocol::parse_input_sensitivity(uint8_t* data, size_t len, UpsD // Handle both APC-style (0x35) and CyberPower-style (0x1a) with intelligent fallbacks switch (sensitivity_raw) { case 0: - ups_data.input_sensitivity = "high"; + ups_data.config.input_sensitivity = "high"; ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): high (raw: %d)", style, sensitivity_raw); break; case 1: - ups_data.input_sensitivity = "normal"; + ups_data.config.input_sensitivity = "normal"; ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): normal (raw: %d)", style, sensitivity_raw); break; case 2: - ups_data.input_sensitivity = "low"; + ups_data.config.input_sensitivity = "low"; ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): low (raw: %d)", style, sensitivity_raw); break; case 3: - ups_data.input_sensitivity = "auto"; + ups_data.config.input_sensitivity = "auto"; ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): auto (raw: %d)", style, sensitivity_raw); break; default: @@ -544,19 +591,19 @@ void GenericHidProtocol::parse_input_sensitivity(uint8_t* data, size_t len, UpsD uint8_t alt_value = data[i]; if (alt_value <= 3) { switch (alt_value) { - case 0: ups_data.input_sensitivity = "high"; break; - case 1: ups_data.input_sensitivity = "normal"; break; - case 2: ups_data.input_sensitivity = "low"; break; - case 3: ups_data.input_sensitivity = "auto"; break; + case 0: ups_data.config.input_sensitivity = "high"; break; + case 1: ups_data.config.input_sensitivity = "normal"; break; + case 2: ups_data.config.input_sensitivity = "low"; break; + case 3: ups_data.config.input_sensitivity = "auto"; break; } ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s, alt byte[%zu]): %s (raw: %d)", - style, i, ups_data.input_sensitivity.c_str(), alt_value); + style, i, ups_data.config.input_sensitivity.c_str(), alt_value); return; } } // Fallback to reasonable default - ups_data.input_sensitivity = "normal"; + ups_data.config.input_sensitivity = "normal"; ESP_LOGW(GEN_TAG, "Using default 'normal' sensitivity (%s) due to unexpected value: %d", style, sensitivity_raw); } else { @@ -564,16 +611,16 @@ void GenericHidProtocol::parse_input_sensitivity(uint8_t* data, size_t len, UpsD if (sensitivity_raw <= 10) { // Map to nearest known value if (sensitivity_raw <= 3) { - ups_data.input_sensitivity = "high"; + ups_data.config.input_sensitivity = "high"; } else if (sensitivity_raw <= 6) { - ups_data.input_sensitivity = "normal"; + ups_data.config.input_sensitivity = "normal"; } else { - ups_data.input_sensitivity = "low"; + ups_data.config.input_sensitivity = "low"; } ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s, mapped): %s (raw: %d)", - style, ups_data.input_sensitivity.c_str(), sensitivity_raw); + style, ups_data.config.input_sensitivity.c_str(), sensitivity_raw); } else { - ups_data.input_sensitivity = "unknown"; + ups_data.config.input_sensitivity = "unknown"; ESP_LOGW(GEN_TAG, "Unknown generic sensitivity value (%s): %d", style, sensitivity_raw); } } @@ -594,7 +641,7 @@ bool GenericHidProtocol::start_battery_test_quick() { uint8_t test_data[2] = {report_id, 1}; // Command value 1 = Quick test ESP_LOGD(GEN_TAG, "Trying quick battery test with report ID 0x%02X", report_id); - esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(GEN_TAG, "Generic quick battery test command sent with report ID 0x%02X", report_id); @@ -619,7 +666,7 @@ bool GenericHidProtocol::start_battery_test_deep() { uint8_t test_data[2] = {report_id, 2}; // Command value 2 = Deep test ESP_LOGD(GEN_TAG, "Trying deep battery test with report ID 0x%02X", report_id); - esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(GEN_TAG, "Generic deep battery test command sent with report ID 0x%02X", report_id); @@ -644,7 +691,7 @@ bool GenericHidProtocol::stop_battery_test() { uint8_t test_data[2] = {report_id, 3}; // Command value 3 = Abort test ESP_LOGD(GEN_TAG, "Trying battery test stop with report ID 0x%02X", report_id); - esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(GEN_TAG, "Generic battery test stop command sent with report ID 0x%02X", report_id); @@ -669,7 +716,7 @@ bool GenericHidProtocol::start_ups_test() { uint8_t test_data[2] = {report_id, 1}; // Command value 1 = Start test ESP_LOGD(GEN_TAG, "Trying UPS test with report ID 0x%02X", report_id); - esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(GEN_TAG, "Generic UPS test command sent with report ID 0x%02X", report_id); @@ -694,7 +741,7 @@ bool GenericHidProtocol::stop_ups_test() { uint8_t test_data[2] = {report_id, 0}; // Command value 0 = Stop test ESP_LOGD(GEN_TAG, "Trying UPS test stop with report ID 0x%02X", report_id); - esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data)); + esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout()); if (ret == ESP_OK) { ESP_LOGI(GEN_TAG, "Generic UPS test stop command sent with report ID 0x%02X", report_id); @@ -708,5 +755,124 @@ bool GenericHidProtocol::stop_ups_test() { return false; } +void GenericHidProtocol::read_frequency_data(UpsData &data) { + // Initialize frequency to NaN + data.power.frequency = NAN; + + // Try to read frequency from common HID report IDs used across different vendors + // Generic protocol attempts broader range of report IDs + + const std::vector frequency_report_ids = { + HID_USAGE_POW_FREQUENCY, // 0x32 - Standard HID frequency usage + HID_USAGE_POW_VOLTAGE, // 0x30 - Input measurements (may include frequency) + HID_USAGE_POW_CURRENT, // 0x31 - Output measurements (may include frequency) + HID_USAGE_POW_OUTPUT, // 0x1C - Output collection + HID_USAGE_POW_INPUT, // 0x1A - Input collection + 0x11, // Common alternative frequency report + 0x0F, // Input voltage report (might contain frequency) + 0x12, // Output voltage report (might contain frequency) + }; + + uint8_t buffer[64]; + size_t buffer_len; + + for (uint8_t report_id : frequency_report_ids) { + if (read_report(report_id, buffer, buffer_len)) { + float frequency_value = parse_frequency_from_report(buffer, buffer_len); + if (!std::isnan(frequency_value)) { + data.power.frequency = frequency_value; + ESP_LOGD(GEN_TAG, "Found frequency %.1f Hz in report 0x%02X", frequency_value, report_id); + return; + } + } + } + + ESP_LOGV(GEN_TAG, "Frequency data not available from any HID report"); +} + +float GenericHidProtocol::parse_frequency_from_report(uint8_t* data, size_t len) { + if (len < 2) { + return NAN; + } + + // Try different byte positions and formats commonly used for frequency across vendors + // Generic protocol uses broader heuristics than vendor-specific protocols + + // Method 1: Single byte at position 1 (simple frequency reports) + if (len >= 2) { + uint8_t freq_byte = data[1]; + if (freq_byte >= FREQUENCY_MIN_VALID && freq_byte <= FREQUENCY_MAX_VALID) { + ESP_LOGD(GEN_TAG, "Found frequency %d Hz (single byte)", freq_byte); + return static_cast(freq_byte); + } + } + + // Method 2: Check all byte positions for valid frequency values + for (size_t i = 1; i < len; i++) { + uint8_t freq_byte = data[i]; + if ((freq_byte == 50 || freq_byte == 60) && freq_byte <= FREQUENCY_MAX_VALID) { + ESP_LOGD(GEN_TAG, "Found standard frequency %d Hz at byte %zu", freq_byte, i); + return static_cast(freq_byte); + } + } + + // Method 3: 16-bit little-endian values + for (size_t i = 1; i <= len - 2; i++) { + uint16_t freq_word = data[i] | (data[i + 1] << 8); + if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) { + ESP_LOGD(GEN_TAG, "Found frequency %d Hz (16-bit LE) at bytes %zu-%zu", freq_word, i, i + 1); + return static_cast(freq_word); + } + } + + // Method 4: 16-bit big-endian values + for (size_t i = 1; i <= len - 2; i++) { + uint16_t freq_word = (data[i] << 8) | data[i + 1]; + if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) { + ESP_LOGD(GEN_TAG, "Found frequency %d Hz (16-bit BE) at bytes %zu-%zu", freq_word, i, i + 1); + return static_cast(freq_word); + } + } + + // Method 5: Scaled frequencies (0.1x factor common in some devices) + for (size_t i = 1; i <= len - 2; i++) { + uint16_t freq_scaled = data[i] | (data[i + 1] << 8); + float freq_value = static_cast(freq_scaled) / 10.0f; + if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) { + ESP_LOGD(GEN_TAG, "Found scaled frequency %.1f Hz (0.1x) at bytes %zu-%zu", freq_value, i, i + 1); + return freq_value; + } + } + + // Method 6: Check for hundreds scaling (0.01x factor) + for (size_t i = 1; i <= len - 2; i++) { + uint16_t freq_scaled = data[i] | (data[i + 1] << 8); + float freq_value = static_cast(freq_scaled) / 100.0f; + if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) { + ESP_LOGD(GEN_TAG, "Found scaled frequency %.1f Hz (0.01x) at bytes %zu-%zu", freq_value, i, i + 1); + return freq_value; + } + } + + return NAN; +} + } // namespace ups_hid -} // namespace esphome \ No newline at end of file +} // namespace esphome + +// Protocol Factory Self-Registration +#include "protocol_factory.h" + +namespace esphome { +namespace ups_hid { + +// Creator function for Generic protocol +std::unique_ptr create_generic_protocol(UpsHidComponent* parent) { + return std::make_unique(parent); +} + +} // namespace ups_hid +} // namespace esphome + +// Register Generic protocol as fallback for all unknown vendors +REGISTER_UPS_FALLBACK_PROTOCOL(generic_hid_protocol, esphome::ups_hid::create_generic_protocol, "Generic HID Protocol", "Universal HID protocol fallback for unknown UPS vendors with basic monitoring capabilities", 10); \ No newline at end of file diff --git a/components/ups_hid/generic_hid_protocol.h b/components/ups_hid/generic_hid_protocol.h new file mode 100644 index 0000000..ec49517 --- /dev/null +++ b/components/ups_hid/generic_hid_protocol.h @@ -0,0 +1,79 @@ +#pragma once + +#include "ups_hid.h" +#include "ups_composite_data.h" +#include "device_info.h" +#include +#include + +namespace esphome { +namespace ups_hid { + +/** + * Generic HID Protocol Implementation + * + * Provides fallback support for unknown UPS vendors by attempting to + * discover and parse common HID Power Device report IDs. + * + * This protocol uses a discovery-based approach, testing standard report IDs + * that are commonly used across different UPS manufacturers based on NUT + * (Network UPS Tools) analysis. + */ +class GenericHidProtocol : public UpsProtocolBase { +public: + explicit GenericHidProtocol(UpsHidComponent* parent) : UpsProtocolBase(parent) {} + ~GenericHidProtocol() override = default; + + // Protocol identification + DeviceInfo::DetectedProtocol get_protocol_type() const override { + return DeviceInfo::PROTOCOL_GENERIC_HID; + } + std::string get_protocol_name() const override { + return "Generic HID"; + } + + // Core protocol interface + bool detect() override; + bool initialize() override; + bool read_data(UpsData &data) override; + + // Report discovery and enumeration + void enumerate_reports(); + bool read_report(uint8_t report_id, uint8_t* buffer, size_t& buffer_len); + + // Data parsing methods for different report types + void parse_power_summary(uint8_t* data, size_t len, UpsData& ups_data); + void parse_battery_status(uint8_t* data, size_t len, UpsData& ups_data); + void parse_present_status(uint8_t* data, size_t len, UpsData& ups_data); + void parse_general_status(uint8_t* data, size_t len, UpsData& ups_data); + void parse_voltage(uint8_t* data, size_t len, UpsData& ups_data, bool is_input); + void parse_load(uint8_t* data, size_t len, UpsData& ups_data); + void parse_input_sensitivity(uint8_t* data, size_t len, UpsData& ups_data, const char* style); + bool parse_unknown_report(uint8_t* data, size_t len, UpsData& ups_data); + + // Frequency reading methods + void read_frequency_data(UpsData &data); + float parse_frequency_from_report(uint8_t* data, size_t len); + + // Test control methods (generic implementations) + bool start_battery_test_quick() override; + bool start_battery_test_deep() override; + bool stop_battery_test() override; + bool start_ups_test() override; + bool stop_ups_test() override; + + // Beeper control - not implemented for generic protocol + bool beeper_enable() override { return false; } + bool beeper_disable() override { return false; } + bool beeper_mute() override { return false; } + bool beeper_test() override { return false; } + +private: + // Report discovery state + std::set available_input_reports_; + std::set available_feature_reports_; + std::map report_sizes_; +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/hid_constants.h b/components/ups_hid/hid_constants.h new file mode 100644 index 0000000..f57a32a --- /dev/null +++ b/components/ups_hid/hid_constants.h @@ -0,0 +1,173 @@ +#pragma once + +/** + * @file hid_constants.h + * @brief HID Constants for UPS Power Device Class + * + * Standard USB HID constants following USB HID Usage Tables v1.6 + * and USB Device Class Definition for HID Power Devices v1.1 + * + * References: + * - USB HID Usage Tables v1.6: https://usb.org/document-library/hid-usage-tables-16 + * - USB Power Device Class v1.1: https://usb.org/sites/default/files/pdcv11.pdf + * - NUT HID Implementation: drivers/hidtypes.h + */ + +// ============================================================================= +// USB HID Class and Report Types (USB HID Specification v1.11) +// ============================================================================= + +#define USB_CLASS_HID 0x03 + +#define HID_REPORT_TYPE_INPUT 0x01 +#define HID_REPORT_TYPE_OUTPUT 0x02 +#define HID_REPORT_TYPE_FEATURE 0x03 + +// ============================================================================= +// HID Usage Pages (USB HID Usage Tables v1.12) +// ============================================================================= + +#define HID_USAGE_PAGE_POWER_DEVICE 0x84 +#define HID_USAGE_PAGE_BATTERY_SYSTEM 0x85 + +// ============================================================================= +// Power Device Usage IDs (HID Power Device Class v1.1) +// ============================================================================= + +// Device Identification +#define HID_USAGE_POW_I_NAME 0x0001 +#define HID_USAGE_POW_PRESENT_STATUS 0x0002 +#define HID_USAGE_POW_UPS 0x0004 +#define HID_USAGE_POW_POWER_SUPPLY 0x0005 + +// Power Components +#define HID_USAGE_POW_BATTERY_SYSTEM 0x0010 +#define HID_USAGE_POW_BATTERY 0x0012 +#define HID_USAGE_POW_INPUT 0x001A +#define HID_USAGE_POW_OUTPUT 0x001C +#define HID_USAGE_POW_POWER_SUMMARY 0x0024 + +// Measurements +#define HID_USAGE_POW_VOLTAGE 0x0030 +#define HID_USAGE_POW_CURRENT 0x0031 +#define HID_USAGE_POW_FREQUENCY 0x0032 +#define HID_USAGE_POW_APPARENT_POWER 0x0033 +#define HID_USAGE_POW_ACTIVE_POWER 0x0034 +#define HID_USAGE_POW_PERCENT_LOAD 0x0035 +#define HID_USAGE_POW_TEMPERATURE 0x0036 + +// Configuration Values (Nominal/Reference) +#define HID_USAGE_POW_CONFIG_VOLTAGE 0x0040 +#define HID_USAGE_POW_CONFIG_CURRENT 0x0041 +#define HID_USAGE_POW_CONFIG_FREQUENCY 0x0042 +#define HID_USAGE_POW_CONFIG_APPARENT_POWER 0x0043 +#define HID_USAGE_POW_CONFIG_ACTIVE_POWER 0x0044 +#define HID_USAGE_POW_CONFIG_PERCENT_LOAD 0x0045 + +// Control Operations +#define HID_USAGE_POW_SWITCH_ON_CONTROL 0x0050 +#define HID_USAGE_POW_SWITCH_OFF_CONTROL 0x0051 +#define HID_USAGE_POW_LOW_VOLTAGE_TRANSFER 0x0053 +#define HID_USAGE_POW_HIGH_VOLTAGE_TRANSFER 0x0054 +#define HID_USAGE_POW_DELAY_BEFORE_REBOOT 0x0055 +#define HID_USAGE_POW_DELAY_BEFORE_STARTUP 0x0056 +#define HID_USAGE_POW_DELAY_BEFORE_SHUTDOWN 0x0057 +#define HID_USAGE_POW_TEST 0x0058 +#define HID_USAGE_POW_AUDIBLE_ALARM_CONTROL 0x005A + +// Status Indicators +#define HID_USAGE_POW_PRESENT 0x0060 +#define HID_USAGE_POW_GOOD 0x0061 +#define HID_USAGE_POW_INTERNAL_FAILURE 0x0062 +#define HID_USAGE_POW_VOLTAGE_OUT_OF_RANGE 0x0063 +#define HID_USAGE_POW_OVERLOAD 0x0065 +#define HID_USAGE_POW_OVER_CHARGED 0x0066 +#define HID_USAGE_POW_SHUTDOWN_REQUESTED 0x0068 +#define HID_USAGE_POW_SHUTDOWN_IMMINENT 0x0069 + +// Device Information +#define HID_USAGE_POW_I_MANUFACTURER 0x00FD +#define HID_USAGE_POW_I_PRODUCT 0x00FE +#define HID_USAGE_POW_I_SERIAL_NUMBER 0x00FF + +// ============================================================================= +// Battery System Usage IDs (HID Power Device Class v1.1) +// ============================================================================= + +// Battery Status +#define HID_USAGE_BAT_CHARGING 0x0044 +#define HID_USAGE_BAT_DISCHARGING 0x0045 +#define HID_USAGE_BAT_FULLY_CHARGED 0x0046 +#define HID_USAGE_BAT_NEED_REPLACEMENT 0x004B + +// Battery Measurements +#define HID_USAGE_BAT_REMAINING_CAPACITY 0x0066 +#define HID_USAGE_BAT_FULL_CHARGE_CAPACITY 0x0067 +#define HID_USAGE_BAT_RUN_TIME_TO_EMPTY 0x0068 +#define HID_USAGE_BAT_AVERAGE_TIME_TO_EMPTY 0x0069 +#define HID_USAGE_BAT_AVERAGE_TIME_TO_FULL 0x006A + +// Battery Configuration +#define HID_USAGE_BAT_DESIGN_CAPACITY 0x0083 +#define HID_USAGE_BAT_WARNING_CAPACITY_LIMIT 0x008C + +// Battery Information +#define HID_USAGE_BAT_I_MANUFACTURER_NAME 0x0087 +#define HID_USAGE_BAT_I_DEVICE_NAME 0x0088 +#define HID_USAGE_BAT_I_DEVICE_CHEMISTRY 0x0089 + +// ============================================================================= +// Regional Voltage Standards (IEC 60038) +// ============================================================================= + +// Single-phase nominal voltages (RMS) +#define VOLTAGE_NOMINAL_EU 230.0f // Europe (IEC 60038) +#define VOLTAGE_NOMINAL_US 120.0f // North America +#define VOLTAGE_NOMINAL_JP 100.0f // Japan +#define VOLTAGE_NOMINAL_UK 230.0f // United Kingdom +#define VOLTAGE_NOMINAL_AU 230.0f // Australia + +// Voltage tolerance ranges (±10% typical) +#define VOLTAGE_MIN_VALID 80.0f // Minimum valid voltage +#define VOLTAGE_MAX_VALID 300.0f // Maximum valid voltage + +// Three-phase nominal voltages (for industrial UPS) +#define VOLTAGE_NOMINAL_3P_EU 400.0f // Europe 3-phase +#define VOLTAGE_NOMINAL_3P_US 208.0f // North America 3-phase + +// ============================================================================= +// Regional Frequency Standards (IEC 60038) +// ============================================================================= + +// Standard AC frequencies (Hz) +#define FREQUENCY_NOMINAL_EU 50.0f // Europe (IEC 60038) +#define FREQUENCY_NOMINAL_US 60.0f // North America +#define FREQUENCY_NOMINAL_JP 50.0f // Japan (50Hz East, 60Hz West) +#define FREQUENCY_NOMINAL_UK 50.0f // United Kingdom +#define FREQUENCY_NOMINAL_AU 50.0f // Australia + +// Frequency tolerance ranges (typical ±1% for power systems) +#define FREQUENCY_MIN_VALID 47.0f // Minimum valid frequency (50Hz -6%) +#define FREQUENCY_MAX_VALID 65.0f // Maximum valid frequency (60Hz +8%) + +// Specialized frequency applications +#define FREQUENCY_AIRCRAFT 400.0f // Aircraft power systems +#define FREQUENCY_RAILWAY 16.7f // Railway power systems (Europe) +#define FREQUENCY_RAILWAY_US 25.0f // Railway power systems (North America) + +// ============================================================================= +// Helper Macros for HID Usage Paths +// ============================================================================= + +// Create full 32-bit HID usage from page and usage ID +#define HID_USAGE(page, usage) (((uint32_t)(page) << 16) | (usage)) + +// Power Device usages +#define HID_USAGE_POW(usage) HID_USAGE(HID_USAGE_PAGE_POWER_DEVICE, usage) +#define HID_USAGE_BAT(usage) HID_USAGE(HID_USAGE_PAGE_BATTERY_SYSTEM, usage) + +// Common voltage usage paths (for NUT-style path matching) +#define HID_PATH_INPUT_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_VOLTAGE) +#define HID_PATH_INPUT_CONFIG_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_CONFIG_VOLTAGE) +#define HID_PATH_OUTPUT_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_VOLTAGE) +#define HID_PATH_BATTERY_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_VOLTAGE) \ No newline at end of file diff --git a/components/ups_hid/power_data.h b/components/ups_hid/power_data.h new file mode 100644 index 0000000..e33e220 --- /dev/null +++ b/components/ups_hid/power_data.h @@ -0,0 +1,75 @@ +#pragma once + +#include +#include +#include "hid_constants.h" + +namespace esphome { +namespace ups_hid { + +struct PowerData { + // Input power metrics + float input_voltage{NAN}; // Current input voltage (V) + float input_voltage_nominal{NAN}; // Nominal input voltage (V) + float input_transfer_low{NAN}; // Low transfer voltage threshold (V) + float input_transfer_high{NAN}; // High transfer voltage threshold (V) + float frequency{NAN}; // Input frequency (Hz) + + // Output power metrics + float output_voltage{NAN}; // Current output voltage (V) + float output_voltage_nominal{NAN}; // Nominal output voltage (V) + float load_percent{NAN}; // Current load percentage (0-100%) + + // Power ratings and capabilities + float realpower_nominal{NAN}; // Nominal real power rating (W) + float apparent_power_nominal{NAN}; // Nominal apparent power rating (VA) + + // Power status information + std::string status{}; // Power status text (Online, On Battery, etc.) + + // Power quality indicators + bool input_voltage_valid() const { + return !std::isnan(input_voltage) && input_voltage > 50.0f && input_voltage < 300.0f; + } + + bool output_voltage_valid() const { + return !std::isnan(output_voltage) && output_voltage > 50.0f && output_voltage < 300.0f; + } + + bool frequency_valid() const { + return !std::isnan(frequency) && frequency >= FREQUENCY_MIN_VALID && frequency <= FREQUENCY_MAX_VALID; + } + + bool is_input_out_of_range() const { + if (!input_voltage_valid()) return false; + return (!std::isnan(input_transfer_low) && input_voltage < input_transfer_low) || + (!std::isnan(input_transfer_high) && input_voltage > input_transfer_high); + } + + bool is_overloaded() const { + return !std::isnan(load_percent) && load_percent > 95.0f; + } + + bool has_load_info() const { + return !std::isnan(load_percent); + } + + // Validation and utility methods + bool is_valid() const { + return input_voltage_valid() || output_voltage_valid() || has_load_info(); + } + + void reset() { + *this = PowerData{}; + } + + // Copy constructor and assignment for safe copying + PowerData() = default; + PowerData(const PowerData&) = default; + PowerData& operator=(const PowerData&) = default; + PowerData(PowerData&&) = default; + PowerData& operator=(PowerData&&) = default; +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/protocol_factory.cpp b/components/ups_hid/protocol_factory.cpp new file mode 100644 index 0000000..6031018 --- /dev/null +++ b/components/ups_hid/protocol_factory.cpp @@ -0,0 +1,239 @@ +#include "protocol_factory.h" +#include "ups_hid.h" +#include "esphome/core/log.h" +#include + +namespace esphome { +namespace ups_hid { + +static const char *const FACTORY_TAG = "ups_hid.factory"; + +// Static registry implementations +std::unordered_map>& +ProtocolFactory::get_vendor_registry() { + static std::unordered_map> vendor_registry; + return vendor_registry; +} + +std::vector& +ProtocolFactory::get_fallback_registry() { + static std::vector fallback_registry; + return fallback_registry; +} + +void ProtocolFactory::ensure_initialized() { + // Registries are initialized on first access due to static storage + // This function exists for explicit initialization if needed + static bool initialized = false; + if (!initialized) { + ESP_LOGD(FACTORY_TAG, "Protocol factory registries initialized"); + initialized = true; + } +} + +void ProtocolFactory::register_protocol_for_vendor(uint16_t vendor_id, + const ProtocolInfo& info) { + ensure_initialized(); + + auto& registry = get_vendor_registry(); + registry[vendor_id].push_back(info); + + // Sort by priority (higher first) + std::sort(registry[vendor_id].begin(), registry[vendor_id].end(), + [](const ProtocolInfo& a, const ProtocolInfo& b) { + return a.priority > b.priority; + }); + + ESP_LOGI(FACTORY_TAG, "Registered protocol '%s' for vendor 0x%04X (priority %d)", + info.name.c_str(), vendor_id, info.priority); +} + +void ProtocolFactory::register_fallback_protocol(const ProtocolInfo& info) { + ensure_initialized(); + + auto& registry = get_fallback_registry(); + registry.push_back(info); + + // Sort by priority (higher first) + std::sort(registry.begin(), registry.end(), + [](const ProtocolInfo& a, const ProtocolInfo& b) { + return a.priority > b.priority; + }); + + ESP_LOGI(FACTORY_TAG, "Registered fallback protocol '%s' (priority %d)", + info.name.c_str(), info.priority); +} + +std::unique_ptr +ProtocolFactory::create_for_vendor(uint16_t vendor_id, UpsHidComponent* parent) { + ensure_initialized(); + + if (!parent) { + ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component"); + return nullptr; + } + + // Try vendor-specific protocols first + auto& vendor_registry = get_vendor_registry(); + auto vendor_it = vendor_registry.find(vendor_id); + + if (vendor_it != vendor_registry.end()) { + ESP_LOGD(FACTORY_TAG, "Found %zu vendor-specific protocols for 0x%04X", + vendor_it->second.size(), vendor_id); + + for (const auto& info : vendor_it->second) { + ESP_LOGD(FACTORY_TAG, "Trying vendor protocol '%s' for 0x%04X", + info.name.c_str(), vendor_id); + + auto protocol = info.creator(parent); + if (protocol && protocol->detect()) { + ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' for vendor 0x%04X", + info.name.c_str(), vendor_id); + return protocol; + } + } + } + + // Try fallback protocols + auto& fallback_registry = get_fallback_registry(); + ESP_LOGD(FACTORY_TAG, "Trying %zu fallback protocols for vendor 0x%04X", + fallback_registry.size(), vendor_id); + + for (const auto& info : fallback_registry) { + ESP_LOGD(FACTORY_TAG, "Trying fallback protocol '%s' for 0x%04X", + info.name.c_str(), vendor_id); + + auto protocol = info.creator(parent); + if (protocol && protocol->detect()) { + ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' for vendor 0x%04X", + info.name.c_str(), vendor_id); + return protocol; + } + } + + ESP_LOGW(FACTORY_TAG, "No suitable protocol found for vendor 0x%04X", vendor_id); + return nullptr; +} + +std::vector +ProtocolFactory::get_protocols_for_vendor(uint16_t vendor_id) { + ensure_initialized(); + + std::vector protocols; + + // Add vendor-specific protocols first + auto& vendor_registry = get_vendor_registry(); + auto vendor_it = vendor_registry.find(vendor_id); + + if (vendor_it != vendor_registry.end()) { + for (const auto& info : vendor_it->second) { + protocols.push_back(info); + } + } + + // Add fallback protocols + auto& fallback_registry = get_fallback_registry(); + for (const auto& info : fallback_registry) { + protocols.push_back(info); + } + + return protocols; +} + +std::vector> +ProtocolFactory::get_all_protocols() { + ensure_initialized(); + + std::vector> all_protocols; + + // Add vendor-specific protocols + auto& vendor_registry = get_vendor_registry(); + for (const auto& vendor_pair : vendor_registry) { + uint16_t vendor_id = vendor_pair.first; + for (const auto& info : vendor_pair.second) { + all_protocols.emplace_back(vendor_id, info); + } + } + + // Add fallback protocols (use 0x0000 as special vendor ID for fallbacks) + auto& fallback_registry = get_fallback_registry(); + for (const auto& info : fallback_registry) { + all_protocols.emplace_back(0x0000, info); + } + + return all_protocols; +} + +bool ProtocolFactory::has_vendor_support(uint16_t vendor_id) { + ensure_initialized(); + + auto& vendor_registry = get_vendor_registry(); + auto it = vendor_registry.find(vendor_id); + + // Has support if vendor-specific protocols exist OR fallback protocols exist + bool has_vendor_specific = (it != vendor_registry.end() && !it->second.empty()); + bool has_fallback = !get_fallback_registry().empty(); + + return has_vendor_specific || has_fallback; +} + +std::unique_ptr +ProtocolFactory::create_by_name(const std::string& protocol_name, UpsHidComponent* parent) { + ensure_initialized(); + + if (!parent) { + ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component"); + return nullptr; + } + + ESP_LOGD(FACTORY_TAG, "Creating protocol by name: %s", protocol_name.c_str()); + + // Search through all registered protocols to find one with matching name + auto& vendor_registry = get_vendor_registry(); + for (const auto& vendor_pair : vendor_registry) { + for (const auto& info : vendor_pair.second) { + // Match protocol name (case-insensitive) + std::string info_name_lower = info.name; + std::string protocol_name_lower = protocol_name; + std::transform(info_name_lower.begin(), info_name_lower.end(), info_name_lower.begin(), ::tolower); + std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(), ::tolower); + + if (info_name_lower.find(protocol_name_lower) != std::string::npos) { + ESP_LOGD(FACTORY_TAG, "Found matching protocol '%s' for name '%s'", + info.name.c_str(), protocol_name.c_str()); + auto protocol = info.creator(parent); + if (protocol) { + ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' by name", + protocol->get_protocol_name().c_str()); + return protocol; + } + } + } + } + + // Search through fallback protocols + auto& fallback_registry = get_fallback_registry(); + for (const auto& info : fallback_registry) { + std::string info_name_lower = info.name; + std::string protocol_name_lower = protocol_name; + std::transform(info_name_lower.begin(), info_name_lower.end(), info_name_lower.begin(), ::tolower); + std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(), ::tolower); + + if (info_name_lower.find(protocol_name_lower) != std::string::npos) { + ESP_LOGD(FACTORY_TAG, "Found matching fallback protocol '%s' for name '%s'", + info.name.c_str(), protocol_name.c_str()); + auto protocol = info.creator(parent); + if (protocol) { + ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' by name", + protocol->get_protocol_name().c_str()); + return protocol; + } + } + } + + ESP_LOGE(FACTORY_TAG, "No protocol found with name containing '%s'", protocol_name.c_str()); + return nullptr; +} + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/protocol_factory.h b/components/ups_hid/protocol_factory.h new file mode 100644 index 0000000..f542af6 --- /dev/null +++ b/components/ups_hid/protocol_factory.h @@ -0,0 +1,133 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace esphome { +namespace ups_hid { + +// Forward declarations +class UpsProtocolBase; +class UpsHidComponent; + +/** + * Protocol Factory with Self-Registration Support + * + * Enables protocols to register themselves automatically, following the + * Open/Closed Principle - new protocols can be added without modifying + * existing code. + * + * Design Pattern: Factory Method + Registry Pattern + */ +class ProtocolFactory { +public: + // Protocol creator function type + using CreatorFunc = std::function(UpsHidComponent*)>; + + // Protocol metadata for better selection + struct ProtocolInfo { + CreatorFunc creator; + std::string name; + std::string description; + std::vector supported_vendors; + int priority; // Higher priority = tried first + }; + + /** + * Register a protocol with specific vendor IDs + */ + static void register_protocol_for_vendor(uint16_t vendor_id, + const ProtocolInfo& info); + + /** + * Register a fallback protocol (tried when vendor-specific fails) + */ + static void register_fallback_protocol(const ProtocolInfo& info); + + /** + * Create protocol instance for specific vendor + */ + static std::unique_ptr create_for_vendor(uint16_t vendor_id, + UpsHidComponent* parent); + + /** + * Create protocol instance by name (manual selection) + */ + static std::unique_ptr create_by_name(const std::string& protocol_name, + UpsHidComponent* parent); + + /** + * Get ordered list of protocols to try for a vendor + * Returns vendor-specific first, then fallbacks by priority + */ + static std::vector get_protocols_for_vendor(uint16_t vendor_id); + + /** + * Get list of all registered protocols + */ + static std::vector> get_all_protocols(); + + /** + * Check if vendor has registered protocols + */ + static bool has_vendor_support(uint16_t vendor_id); + +private: + // Vendor-specific protocol registry + static std::unordered_map>& get_vendor_registry(); + + // Fallback protocol registry (sorted by priority) + static std::vector& get_fallback_registry(); + + // Ensure registries are initialized + static void ensure_initialized(); +}; + +/** + * Protocol Registration Helper Macros + * + * These macros enable automatic protocol registration at startup + */ + +// Forward declare for registration macros +class ProtocolFactory; + +// Register protocol for specific vendor +#define REGISTER_UPS_PROTOCOL_FOR_VENDOR(vendor_id, protocol_name, creator_func, name_str, desc_str, prio) \ + namespace { \ + struct protocol_name##_registrar { \ + protocol_name##_registrar() { \ + esphome::ups_hid::ProtocolFactory::ProtocolInfo info; \ + info.creator = creator_func; \ + info.name = name_str; \ + info.description = desc_str; \ + info.supported_vendors = {vendor_id}; \ + info.priority = prio; \ + esphome::ups_hid::ProtocolFactory::register_protocol_for_vendor(vendor_id, info); \ + } \ + }; \ + static protocol_name##_registrar protocol_name##_reg; \ + } + +// Register fallback protocol +#define REGISTER_UPS_FALLBACK_PROTOCOL(protocol_name, creator_func, name_str, desc_str, prio) \ + namespace { \ + struct protocol_name##_fallback_registrar { \ + protocol_name##_fallback_registrar() { \ + esphome::ups_hid::ProtocolFactory::ProtocolInfo info; \ + info.creator = creator_func; \ + info.name = name_str; \ + info.description = desc_str; \ + info.supported_vendors = {}; \ + info.priority = prio; \ + esphome::ups_hid::ProtocolFactory::register_fallback_protocol(info); \ + } \ + }; \ + static protocol_name##_fallback_registrar protocol_name##_fallback_reg; \ + } + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/sensor.py b/components/ups_hid/sensor.py index e11bc39..816a460 100644 --- a/components/ups_hid/sensor.py +++ b/components/ups_hid/sensor.py @@ -94,6 +94,11 @@ SENSOR_TYPES = { "device_class": DEVICE_CLASS_DURATION, "accuracy_decimals": 0, }, + "ups_delay_reboot": { + "unit": UNIT_SECOND, + "device_class": DEVICE_CLASS_DURATION, + "accuracy_decimals": 0, + }, # Additional missing sensor types from NUT analysis "battery_charge_low": { "unit": UNIT_PERCENT, diff --git a/components/ups_hid/simulated_transport.cpp b/components/ups_hid/simulated_transport.cpp new file mode 100644 index 0000000..77297ab --- /dev/null +++ b/components/ups_hid/simulated_transport.cpp @@ -0,0 +1,382 @@ +#include "simulated_transport.h" +#include "esphome/core/log.h" +#include +#include + +namespace esphome { +namespace ups_hid { + +static const char *const SIM_TRANSPORT_TAG = "ups_hid.simulation"; + +SimulatedTransport::SimulatedTransport() { + start_time_ = std::chrono::steady_clock::now(); +} + +esp_err_t SimulatedTransport::initialize() { + if (initialized_) { + return ESP_OK; + } + + ESP_LOGI(SIM_TRANSPORT_TAG, "Initializing simulated USB transport"); + ESP_LOGI(SIM_TRANSPORT_TAG, "Simulating APC Back-UPS ES (VID=0x051D, PID=0x0002)"); + + initialized_ = true; + connected_ = true; + + return ESP_OK; +} + +esp_err_t SimulatedTransport::deinitialize() { + if (!initialized_) { + return ESP_OK; + } + + ESP_LOGI(SIM_TRANSPORT_TAG, "Deinitializing simulated USB transport"); + + initialized_ = false; + connected_ = false; + + return ESP_OK; +} + +bool SimulatedTransport::is_connected() const { + return connected_ && initialized_; +} + +uint16_t SimulatedTransport::get_vendor_id() const { + return vendor_id_; +} + +uint16_t SimulatedTransport::get_product_id() const { + return product_id_; +} + +esp_err_t SimulatedTransport::hid_get_report(uint8_t report_type, uint8_t report_id, + uint8_t* data, size_t* data_len, + uint32_t timeout_ms) { + if (!is_connected()) { + last_error_ = "Simulated transport not connected"; + return ESP_ERR_INVALID_STATE; + } + + // Update dynamic simulation data + update_simulation_data(); + + ESP_LOGV(SIM_TRANSPORT_TAG, "Simulating HID GET_REPORT: type=0x%02X, id=0x%02X", + report_type, report_id); + + // Clear the buffer first + memset(data, 0, *data_len); + data[0] = report_id; // First byte is always report ID + + // Generate simulated data based on report ID + switch (report_id) { + case 0x01: // Status report + generate_status_report(report_id, data, data_len); + break; + + case 0x06: // Battery report + generate_battery_report(report_id, data, data_len); + break; + + case 0x07: // Load report + generate_power_report(report_id, data, data_len); + break; + + case 0x0C: // Power summary + generate_battery_report(report_id, data, data_len); + break; + + case 0x0E: // Voltage report + generate_power_report(report_id, data, data_len); + break; + + case 0x1F: // Beeper control + case 0x18: // Audible alarm + generate_beeper_report(report_id, data, data_len); + break; + + case 0x03: // Device info + case 0x04: // Firmware + generate_device_info_report(report_id, data, data_len); + break; + + case 0x35: // Sensitivity + *data_len = 2; + data[1] = 1; // Normal sensitivity + break; + + default: + // Return zeros for unknown reports + *data_len = 6; // Standard HID report size + ESP_LOGV(SIM_TRANSPORT_TAG, "Unknown report ID 0x%02X, returning zeros", report_id); + break; + } + + return ESP_OK; +} + +esp_err_t SimulatedTransport::hid_set_report(uint8_t report_type, uint8_t report_id, + const uint8_t* data, size_t data_len, + uint32_t timeout_ms) { + if (!is_connected()) { + last_error_ = "Simulated transport not connected"; + return ESP_ERR_INVALID_STATE; + } + + ESP_LOGV(SIM_TRANSPORT_TAG, "Simulating HID SET_REPORT: type=0x%02X, id=0x%02X, len=%zu", + report_type, report_id, data_len); + + // Simulate beeper control + if (report_id == 0x1F || report_id == 0x18) { + if (data_len >= 2) { + uint8_t beeper_value = data[1]; + switch (beeper_value) { + case 1: + beeper_status_ = "disabled"; + ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper disabled"); + break; + case 2: + beeper_status_ = "enabled"; + ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper enabled"); + break; + case 3: + beeper_status_ = "muted"; + ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper muted"); + break; + case 4: + beeper_status_ = "test"; + ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper test"); + break; + default: + ESP_LOGW(SIM_TRANSPORT_TAG, "Unknown beeper command: %d", beeper_value); + break; + } + } + } + + // Simulate test commands + if (report_id == 0x20 || report_id == 0x21) { // Battery test commands + if (data_len >= 2) { + uint8_t test_cmd = data[1]; + if (test_cmd == 1) { + test_running_ = true; + test_result_ = "Battery test in progress"; + ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated battery test started"); + } else if (test_cmd == 0) { + test_running_ = false; + test_result_ = "Battery test completed - Good"; + ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated battery test stopped"); + } + } + } + + return ESP_OK; +} + +esp_err_t SimulatedTransport::get_string_descriptor(uint8_t string_index, + std::string& result) { + if (!is_connected()) { + last_error_ = "Simulated transport not connected"; + return ESP_ERR_INVALID_STATE; + } + + // Simulate string descriptors + switch (string_index) { + case 1: // Manufacturer + result = "American Power Conversion"; + break; + case 2: // Product + result = "Back-UPS ES 700 FW:866.L4.I USB FW:L4"; + break; + case 3: // Serial number + result = "4B2037P30628"; + break; + case 4: // Firmware (custom) + result = "866.L4.I"; + break; + default: + result = "Unknown"; + ESP_LOGW(SIM_TRANSPORT_TAG, "Unknown string index: %d", string_index); + return ESP_ERR_NOT_FOUND; + } + + ESP_LOGV(SIM_TRANSPORT_TAG, "Simulated string descriptor %d: '%s'", + string_index, result.c_str()); + return ESP_OK; +} + +std::string SimulatedTransport::get_last_error() const { + return last_error_; +} + +// Private methods + +void SimulatedTransport::update_simulation_data() { + float elapsed = get_elapsed_seconds(); + + // Simulate battery level slowly decreasing when on battery + if (input_voltage_ < 100.0f) { // On battery + battery_level_ = std::max(10.0f, 95.0f - (elapsed * 0.5f)); // Decrease over time + runtime_minutes_ = static_cast(battery_level_ * 0.6f); // Runtime based on battery + } else { + // On mains - slowly charge if below 100% + if (battery_level_ < 100.0f) { + battery_level_ = std::min(100.0f, battery_level_ + (elapsed * 0.1f)); + } + runtime_minutes_ = static_cast(battery_level_ * 0.8f); + } + + // Simulate periodic power fluctuations + input_voltage_ = 120.0f + sin(elapsed * 0.1f) * 2.0f; // Slight voltage variation + output_voltage_ = 120.0f + sin(elapsed * 0.05f) * 1.0f; + + // Simulate load variations + load_percent_ = 25.0f + sin(elapsed * 0.2f) * 5.0f; // 20-30% load + + // Simulate brief battery switch every 5 minutes for testing + if (fmod(elapsed, 300.0f) < 30.0f) { // 30 seconds on battery every 5 minutes + input_voltage_ = 0.0f; // Simulate power outage + } +} + +float SimulatedTransport::get_elapsed_seconds() const { + auto now = std::chrono::steady_clock::now(); + auto duration = std::chrono::duration_cast(now - start_time_); + return static_cast(duration.count()); +} + +void SimulatedTransport::generate_battery_report(uint8_t report_id, uint8_t* data, size_t* data_len) { + *data_len = 6; + + if (report_id == 0x06) { + // Battery status report: [06 level runtime_low runtime_high 00 00] + data[1] = static_cast(battery_level_); + data[2] = runtime_minutes_ & 0xFF; + data[3] = (runtime_minutes_ >> 8) & 0xFF; + data[4] = 0x00; + data[5] = 0x00; + } else if (report_id == 0x0C) { + // Power summary: [0C level runtime_low runtime_high] + data[1] = static_cast(battery_level_); + data[2] = runtime_minutes_ & 0xFF; + data[3] = (runtime_minutes_ >> 8) & 0xFF; + } + + ESP_LOGV(SIM_TRANSPORT_TAG, "Generated battery report 0x%02X: level=%.0f%%, runtime=%d min", + report_id, battery_level_, runtime_minutes_); +} + +void SimulatedTransport::generate_power_report(uint8_t report_id, uint8_t* data, size_t* data_len) { + *data_len = 6; + + if (report_id == 0x07) { + // Load report: [07 load 00 00 00 00] + data[1] = static_cast(load_percent_); + data[2] = 0x00; + data[3] = 0x00; + data[4] = 0x00; + data[5] = 0x00; + } else if (report_id == 0x0E) { + // Voltage report: [0E voltage_low voltage_high 00 00 00] + uint16_t voltage = static_cast(input_voltage_); + data[1] = voltage & 0xFF; + data[2] = (voltage >> 8) & 0xFF; + data[3] = 0x00; + data[4] = 0x00; + data[5] = 0x00; + } + + ESP_LOGV(SIM_TRANSPORT_TAG, "Generated power report 0x%02X: load=%.0f%%, voltage=%.1fV", + report_id, load_percent_, input_voltage_); +} + +void SimulatedTransport::generate_status_report(uint8_t report_id, uint8_t* data, size_t* data_len) { + *data_len = 6; + + // Status bitmap: online, on_battery, low_battery, etc. + uint8_t status = 0x00; + if (input_voltage_ > 100.0f) { + status |= 0x01; // Online + } else { + status |= 0x02; // On battery + } + + if (battery_level_ < 20.0f) { + status |= 0x04; // Low battery + } + + if (load_percent_ > 80.0f) { + status |= 0x08; // Overload + } + + data[1] = status; + data[2] = 0x00; + data[3] = 0x00; + data[4] = 0x00; + data[5] = 0x00; + + ESP_LOGV(SIM_TRANSPORT_TAG, "Generated status report: 0x%02X", status); +} + +void SimulatedTransport::generate_beeper_report(uint8_t report_id, uint8_t* data, size_t* data_len) { + *data_len = 2; + + // Beeper status: 1=disabled, 2=enabled, 3=muted + if (beeper_status_ == "disabled") { + data[1] = 1; + } else if (beeper_status_ == "enabled") { + data[1] = 2; + } else if (beeper_status_ == "muted") { + data[1] = 3; + } else { + data[1] = 2; // Default enabled + } + + ESP_LOGV(SIM_TRANSPORT_TAG, "Generated beeper report: status=%s (value=%d)", + beeper_status_.c_str(), data[1]); +} + +void SimulatedTransport::generate_test_report(uint8_t report_id, uint8_t* data, size_t* data_len) { + *data_len = 6; + + if (test_running_) { + data[1] = 0x01; // Test in progress + data[2] = 0x50; // 80% progress (example) + } else { + data[1] = 0x00; // No test + data[2] = 0x00; + } + + data[3] = 0x00; + data[4] = 0x00; + data[5] = 0x00; + + ESP_LOGV(SIM_TRANSPORT_TAG, "Generated test report: running=%s", + test_running_ ? "true" : "false"); +} + +void SimulatedTransport::generate_device_info_report(uint8_t report_id, uint8_t* data, size_t* data_len) { + *data_len = 6; + + if (report_id == 0x03) { + // Device info - simulate some device characteristics + data[1] = 0x86; // Major version + data[2] = 0x6C; // Minor version + data[3] = 0x04; // Revision + data[4] = 0x00; + data[5] = 0x00; + } else if (report_id == 0x04) { + // Firmware version + data[1] = 0x08; // 866 (hex) + data[2] = 0x66; + data[3] = 0x4C; // L4 (hex) + data[4] = 0x34; + data[5] = 0x00; + } + + ESP_LOGV(SIM_TRANSPORT_TAG, "Generated device info report 0x%02X", report_id); +} + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/simulated_transport.h b/components/ups_hid/simulated_transport.h new file mode 100644 index 0000000..fe1a877 --- /dev/null +++ b/components/ups_hid/simulated_transport.h @@ -0,0 +1,74 @@ +#pragma once + +#include "usb_transport_interface.h" +#include +#include + +namespace esphome { +namespace ups_hid { + +/** + * Simulated USB Transport Implementation + * + * Provides realistic UPS data simulation for testing and development + * without requiring physical hardware + */ +class SimulatedTransport : public IUsbTransport { +public: + SimulatedTransport(); + ~SimulatedTransport() override = default; + + // IUsbTransport implementation + esp_err_t initialize() override; + esp_err_t deinitialize() override; + + bool is_connected() const override; + uint16_t get_vendor_id() const override; + uint16_t get_product_id() const override; + + esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id, + uint8_t* data, size_t* data_len, + uint32_t timeout_ms = 1000) override; + + esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, + const uint8_t* data, size_t data_len, + uint32_t timeout_ms = 1000) override; + + esp_err_t get_string_descriptor(uint8_t string_index, + std::string& result) override; + + std::string get_last_error() const override; + +private: + bool connected_{false}; + bool initialized_{false}; + uint16_t vendor_id_{0x051D}; // Default to APC + uint16_t product_id_{0x0002}; // APC Back-UPS ES + std::string last_error_; + + // Simulation state + std::chrono::steady_clock::time_point start_time_; + float battery_level_{85.0f}; + float input_voltage_{120.0f}; + float output_voltage_{120.0f}; + float load_percent_{25.0f}; + uint16_t runtime_minutes_{45}; + std::string beeper_status_{"enabled"}; + std::string test_result_{"No test initiated"}; + bool test_running_{false}; + + // Simulated report generation + void generate_battery_report(uint8_t report_id, uint8_t* data, size_t* data_len); + void generate_power_report(uint8_t report_id, uint8_t* data, size_t* data_len); + void generate_status_report(uint8_t report_id, uint8_t* data, size_t* data_len); + void generate_beeper_report(uint8_t report_id, uint8_t* data, size_t* data_len); + void generate_test_report(uint8_t report_id, uint8_t* data, size_t* data_len); + void generate_device_info_report(uint8_t report_id, uint8_t* data, size_t* data_len); + + // Dynamic data simulation + void update_simulation_data(); + float get_elapsed_seconds() const; +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/test_status.h b/components/ups_hid/test_status.h new file mode 100644 index 0000000..66fc77a --- /dev/null +++ b/components/ups_hid/test_status.h @@ -0,0 +1,180 @@ +#pragma once + +#include +#include + +namespace esphome { +namespace ups_hid { + +struct TestStatus { + // Test result information + std::string ups_test_result{}; // Current test result text + std::string last_test_result{}; // Last completed test result + + // Test timing information + int16_t timer_reboot{-1}; // Reboot timer (seconds, -1 = not set) + int16_t timer_shutdown{-1}; // Shutdown timer (seconds, -1 = not set) + int16_t timer_start{-1}; // Start timer (seconds, -1 = not set) + + // Test progress tracking + enum TestState { + TEST_STATE_IDLE = 0, + TEST_STATE_BATTERY_QUICK_RUNNING, + TEST_STATE_BATTERY_DEEP_RUNNING, + TEST_STATE_UPS_TEST_RUNNING, + TEST_STATE_PANEL_TEST_RUNNING, + TEST_STATE_COMPLETED, + TEST_STATE_FAILED, + TEST_STATE_ABORTED + }; + + TestState current_test_state{TEST_STATE_IDLE}; + uint32_t test_start_time{0}; // Test start time (millis) + uint32_t test_duration_ms{0}; // Current test duration + + // Test results enumeration (NUT compatible) + enum TestResult { + TEST_RESULT_UNKNOWN = 0, + TEST_RESULT_NO_TEST, + TEST_RESULT_PASSED, + TEST_RESULT_FAILED, + TEST_RESULT_IN_PROGRESS, + TEST_RESULT_NOT_SUPPORTED, + TEST_RESULT_ABORTED, + TEST_RESULT_BATTERY_GOOD, + TEST_RESULT_BATTERY_BAD, + TEST_RESULT_BATTERY_REPLACE + }; + + TestResult last_battery_test_result{TEST_RESULT_UNKNOWN}; + TestResult last_ups_test_result{TEST_RESULT_UNKNOWN}; + + // Test type tracking + enum TestType { + TEST_TYPE_NONE = 0, + TEST_TYPE_BATTERY_QUICK, + TEST_TYPE_BATTERY_DEEP, + TEST_TYPE_UPS_SELF_TEST, + TEST_TYPE_PANEL_TEST + }; + + TestType current_test_type{TEST_TYPE_NONE}; + + // Validation and utility methods + bool is_test_running() const { + return current_test_state == TEST_STATE_BATTERY_QUICK_RUNNING || + current_test_state == TEST_STATE_BATTERY_DEEP_RUNNING || + current_test_state == TEST_STATE_UPS_TEST_RUNNING || + current_test_state == TEST_STATE_PANEL_TEST_RUNNING; + } + + bool is_battery_test_running() const { + return current_test_state == TEST_STATE_BATTERY_QUICK_RUNNING || + current_test_state == TEST_STATE_BATTERY_DEEP_RUNNING; + } + + bool has_test_results() const { + return !ups_test_result.empty() || !last_test_result.empty(); + } + + bool has_timers() const { + return timer_reboot != -1 || timer_shutdown != -1 || timer_start != -1; + } + + std::string get_test_state_name() const { + switch (current_test_state) { + case TEST_STATE_IDLE: return "Idle"; + case TEST_STATE_BATTERY_QUICK_RUNNING: return "Battery Quick Test"; + case TEST_STATE_BATTERY_DEEP_RUNNING: return "Battery Deep Test"; + case TEST_STATE_UPS_TEST_RUNNING: return "UPS Self Test"; + case TEST_STATE_PANEL_TEST_RUNNING: return "Panel Test"; + case TEST_STATE_COMPLETED: return "Test Completed"; + case TEST_STATE_FAILED: return "Test Failed"; + case TEST_STATE_ABORTED: return "Test Aborted"; + default: return "Unknown"; + } + } + + std::string get_test_result_name(TestResult result) const { + switch (result) { + case TEST_RESULT_NO_TEST: return "No test"; + case TEST_RESULT_PASSED: return "Passed"; + case TEST_RESULT_FAILED: return "Failed"; + case TEST_RESULT_IN_PROGRESS: return "In progress"; + case TEST_RESULT_NOT_SUPPORTED: return "Not supported"; + case TEST_RESULT_ABORTED: return "Aborted"; + case TEST_RESULT_BATTERY_GOOD: return "Battery good"; + case TEST_RESULT_BATTERY_BAD: return "Battery bad"; + case TEST_RESULT_BATTERY_REPLACE: return "Replace battery"; + default: return "Unknown"; + } + } + + void start_test(TestType type, uint32_t start_time) { + current_test_type = type; + test_start_time = start_time; + test_duration_ms = 0; + + switch (type) { + case TEST_TYPE_BATTERY_QUICK: + current_test_state = TEST_STATE_BATTERY_QUICK_RUNNING; + break; + case TEST_TYPE_BATTERY_DEEP: + current_test_state = TEST_STATE_BATTERY_DEEP_RUNNING; + break; + case TEST_TYPE_UPS_SELF_TEST: + current_test_state = TEST_STATE_UPS_TEST_RUNNING; + break; + case TEST_TYPE_PANEL_TEST: + current_test_state = TEST_STATE_PANEL_TEST_RUNNING; + break; + default: + current_test_state = TEST_STATE_IDLE; + break; + } + } + + void update_test_progress(uint32_t current_time) { + if (is_test_running() && test_start_time > 0) { + test_duration_ms = current_time - test_start_time; + } + } + + void complete_test(TestResult result) { + current_test_state = TEST_STATE_COMPLETED; + + if (current_test_type == TEST_TYPE_BATTERY_QUICK || current_test_type == TEST_TYPE_BATTERY_DEEP) { + last_battery_test_result = result; + } else { + last_ups_test_result = result; + } + + // Move current result to last result + if (!ups_test_result.empty()) { + last_test_result = ups_test_result; + } + } + + void abort_test() { + current_test_state = TEST_STATE_ABORTED; + ups_test_result = "Test aborted"; + } + + bool is_valid() const { + return has_test_results() || is_test_running() || has_timers(); + } + + void reset() { + *this = TestStatus{}; + } + + // Copy constructor and assignment for safe copying + TestStatus() = default; + TestStatus(const TestStatus&) = default; + TestStatus& operator=(const TestStatus&) = default; + TestStatus(TestStatus&&) = default; + TestStatus& operator=(TestStatus&&) = default; +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/ups_composite_data.h b/components/ups_hid/ups_composite_data.h new file mode 100644 index 0000000..1b48cec --- /dev/null +++ b/components/ups_hid/ups_composite_data.h @@ -0,0 +1,59 @@ +#pragma once + +#include "battery_data.h" +#include "power_data.h" +#include "device_info.h" +#include "test_status.h" +#include "config_data.h" +#include +#include // For memcmp + +namespace esphome { +namespace ups_hid { + +/** + * Clean UPS Composite Data Structure + * + * Contains all UPS data organized into logical components following + * Single Responsibility Principle. No legacy compatibility code. + */ +struct UpsCompositeData { + // Specialized data components + BatteryData battery; + PowerData power; + DeviceInfo device; + TestStatus test; + ConfigData config; + + // Validation and utility methods + bool is_valid() const { + return battery.is_valid() || power.is_valid() || device.is_valid() || + test.is_valid() || config.is_valid(); + } + + bool has_core_data() const { + return battery.is_valid() && power.is_valid(); + } + + // Clean reset without legacy flags + void reset() { + battery.reset(); + power.reset(); + device.reset(); + test.reset(); + config.reset(); + } + + // Copy constructor and assignment for safe copying + UpsCompositeData() = default; + UpsCompositeData(const UpsCompositeData&) = default; + UpsCompositeData& operator=(const UpsCompositeData&) = default; + UpsCompositeData(UpsCompositeData&&) = default; + UpsCompositeData& operator=(UpsCompositeData&&) = default; +}; + +// Type alias for cleaner naming +using UpsData = UpsCompositeData; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/ups_hid.cpp b/components/ups_hid/ups_hid.cpp index e5b305b..420b7fd 100644 --- a/components/ups_hid/ups_hid.cpp +++ b/components/ups_hid/ups_hid.cpp @@ -1,2231 +1,496 @@ #include "ups_hid.h" #include "ups_vendors.h" +#include "usb_transport_factory.h" +#include "simulated_transport.h" +#ifdef USE_ESP32 +#include "esp32_usb_transport.h" +#endif +#include "protocol_factory.h" +#include "apc_hid_protocol.h" +#include "cyberpower_protocol.h" +#include "generic_hid_protocol.h" #include "esphome/core/log.h" #include "esphome/core/application.h" - -// Include protocol implementations -#include "apc_hid_protocol.h" -#include "cyberpower_protocol.h" - -// USB Host implementation for ESP-IDF v5.4+ - #include #include -#ifdef USE_ESP32 -#include "driver/gpio.h" -#include "esp_log.h" -#include "esp_system.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "freertos/semphr.h" -#include "freertos/portmacro.h" -#include "freertos/queue.h" -#include "usb/usb_host.h" -#include "usb/usb_types_ch9.h" -#include -#include "driver/gpio.h" +namespace esphome { +namespace ups_hid { -// USB HID Class defines -#ifndef USB_CLASS_HID -#define USB_CLASS_HID 0x03 -#endif +void UpsHidComponent::setup() { + ESP_LOGCONFIG(TAG, "Setting up UPS HID Component..."); + + if (!initialize_transport()) { + ESP_LOGE(TAG, "Failed to initialize transport"); + mark_failed(); + return; + } + + // Protocol detection is deferred to update() method to handle asynchronous USB enumeration + ESP_LOGCONFIG(TAG, "UPS HID Component setup complete - waiting for USB device connection"); +} -#endif - -namespace esphome -{ - namespace ups_hid - { - - void UpsHidComponent::setup() - { - ESP_LOGCONFIG(TAG, "Setting up UPS HID Component..."); - ESP_LOGI(TAG, "Setup method called - checking simulation mode: %s", simulation_mode_ ? "YES" : "NO"); - - if (simulation_mode_) - { - ESP_LOGW(TAG, "Running in simulation mode - no actual UPS communication"); - - // Initialize simulation data consistently - { - std::lock_guard lock(data_mutex_); - ups_data_.detected_protocol = PROTOCOL_APC_HID; - ups_data_.manufacturer = "Simulated"; - ups_data_.model = "Virtual UPS Pro"; - ups_data_.serial_number = "SIM123456789"; - ups_data_.firmware_version = "1.0.0-SIM"; - - // Initialize with reasonable default values - ups_data_.battery_level = 85.0f; - ups_data_.input_voltage = 120.0f; - ups_data_.output_voltage = 118.0f; - ups_data_.load_percent = 45.0f; - ups_data_.runtime_minutes = 35.0f; - ups_data_.frequency = 60.0f; - ups_data_.status_flags = UPS_STATUS_ONLINE | UPS_STATUS_CHARGING; - } - - connected_ = true; - last_successful_read_ = millis(); - ESP_LOGI(TAG, "Simulation mode initialized successfully"); - return; - } - - ESP_LOGI(TAG, "About to check USE_ESP32 define..."); -#ifdef USE_ESP32 - ESP_LOGI(TAG, "USE_ESP32 is defined - initializing USB..."); - if (!initialize_usb()) - { - ESP_LOGE(TAG, "Failed to initialize USB"); +void UpsHidComponent::update() { + if (!transport_ || !transport_->is_connected()) { + // Device not connected yet - normal during startup or after disconnection + ESP_LOGD(TAG, "USB transport not connected - waiting for device"); + return; + } + + // Check if protocol detection is needed + if (!active_protocol_) { + ESP_LOGI(TAG, "USB device connected - attempting protocol detection"); + if (detect_protocol()) { + ESP_LOGI(TAG, "UPS protocol detected and configured successfully"); + consecutive_failures_ = 0; + } else { + consecutive_failures_++; + ESP_LOGW(TAG, "Failed to detect UPS protocol (attempt #%u)", consecutive_failures_); + + if (consecutive_failures_ > max_consecutive_failures_) { + ESP_LOGE(TAG, "Too many consecutive protocol detection failures, marking component as failed"); mark_failed(); - return; } -#else - ESP_LOGE(TAG, "USE_ESP32 is NOT defined - cannot initialize USB!"); - mark_failed(); return; -#endif - - if (!detect_ups_protocol()) - { - ESP_LOGE(TAG, "Failed to detect UPS protocol"); - connected_ = false; - return; - } - - connected_ = true; - ESP_LOGI(TAG, "Successfully connected to UPS using %s", get_protocol_name().c_str()); } - - void UpsHidComponent::update() - { - if (simulation_mode_) - { - simulate_ups_data(); - update_sensors(); - return; - } - - if (!connected_) - { - // Throttle reconnection attempts - static uint32_t last_attempt = 0; - uint32_t now = millis(); - if (now - last_attempt < 5000) { - return; - } - last_attempt = now; - -#ifdef USE_ESP32 - // Try to enumerate USB devices - esp_err_t ret = usb_device_enumerate(); - if (ret == ESP_OK) { - // Device found, try protocol detection - if (detect_ups_protocol()) { - connected_ = true; - ESP_LOGI(TAG, "Connected to UPS using %s protocol", get_protocol_name().c_str()); - // Clear cached data to ensure fresh readings - { - std::lock_guard cache_lock(ups_data_cache_.mutex); - ups_data_cache_.data_valid = false; - ups_data_cache_.last_update_time = 0; - } - } else { - ESP_LOGW(TAG, "USB device enumerated but protocol detection failed"); - } - } else { - ESP_LOGW(TAG, "USB device enumeration failed: %s", esp_err_to_name(ret)); - // Ensure we're properly marked as disconnected and clear stale data - device_connected_ = false; - - // Clear any stale cached data when enumeration fails - { - std::lock_guard cache_lock(ups_data_cache_.mutex); - ups_data_cache_.data.reset(); - ups_data_cache_.data_valid = false; - ups_data_cache_.last_update_time = 0; - } - - // Also clear main data to prevent stale readings - { - std::lock_guard data_lock(data_mutex_); - ups_data_.reset(); - } - - // Force sensors to update with cleared data (NaN values) immediately - update_sensors(); - - ESP_LOGI(TAG, "Cleared stale UPS data and forced sensor updates after enumeration failure"); - } -#endif - return; - } - - // Use cached data from asynchronous USB operations instead of blocking reads - // This prevents task watchdog timeouts by avoiding long USB control transfers - bool data_updated = false; - - { - std::lock_guard cache_lock(ups_data_cache_.mutex); - - if (ups_data_cache_.data_valid) { - // Update main data with fresh cached data - { - std::lock_guard data_lock(data_mutex_); - ups_data_ = ups_data_cache_.data; - } - - last_successful_read_ = millis(); - consecutive_failures_ = 0; - data_updated = true; - - // Mark cache as processed - ups_data_cache_.data_valid = false; - - ESP_LOGV(TAG, "Updated from cached UPS data"); - } - } - - if (!data_updated) { - // No cached data available - try a quick non-blocking read - // But with reduced timeout to prevent watchdog issues - if (read_ups_data()) { - last_successful_read_ = millis(); - consecutive_failures_ = 0; - data_updated = true; - } else { - consecutive_failures_++; - if (should_log_error(protocol_error_limiter_)) { - ESP_LOGW(TAG, "Failed to read UPS data (failure #%u)", consecutive_failures_); - } - - // Implement limited retry logic with exponential backoff - if (consecutive_failures_ >= 3 && consecutive_failures_ <= max_consecutive_failures_) { - ESP_LOGE(TAG, "Multiple consecutive failures, attempting protocol re-detection"); - if (!detect_ups_protocol()) { - ESP_LOGE(TAG, "Protocol re-detection failed - device likely disconnected"); - // Mark as disconnected to trigger reconnection attempts - connected_ = false; - device_connected_ = false; - // Clear stale cached data - { - std::lock_guard cache_lock(ups_data_cache_.mutex); - ups_data_cache_.data_valid = false; - ups_data_cache_.last_update_time = 0; - } - } - } - else if (consecutive_failures_ > max_consecutive_failures_) { - ESP_LOGE(TAG, "Maximum re-detection attempts reached, giving up"); - } - - if (millis() - last_successful_read_ > protocol_timeout_ms_) { - ESP_LOGE(TAG, "UPS communication timeout, marking as disconnected"); - connected_ = false; - consecutive_failures_ = 0; - } - } - } - - // Always update sensors with current data (cached or fresh) - update_sensors(); + } + + // Normal data reading with active protocol + if (read_ups_data()) { + update_sensors(); + consecutive_failures_ = 0; + last_successful_read_ = millis(); + } else { + consecutive_failures_++; + ESP_LOGW(TAG, "Failed to read UPS data (failure #%u)", consecutive_failures_); + + if (consecutive_failures_ > max_consecutive_failures_) { + ESP_LOGW(TAG, "Too many consecutive read failures - resetting protocol to retry detection"); + active_protocol_.reset(); // Force protocol re-detection on next update + consecutive_failures_ = 0; } + } +} - void UpsHidComponent::dump_config() - { - ESP_LOGCONFIG(TAG, "UPS HID Component:"); - ESP_LOGCONFIG(TAG, " Simulation Mode: %s", simulation_mode_ ? "YES" : "NO"); - ESP_LOGCONFIG(TAG, " USB Vendor ID: 0x%04X", usb_vendor_id_); - ESP_LOGCONFIG(TAG, " USB Product ID: 0x%04X", usb_product_id_); - ESP_LOGCONFIG(TAG, " Protocol Timeout: %u ms", protocol_timeout_ms_); - ESP_LOGCONFIG(TAG, " Auto Detect Protocol: %s", auto_detect_protocol_ ? "YES" : "NO"); - ESP_LOGCONFIG(TAG, " Update Interval: %u ms", get_update_interval()); +void UpsHidComponent::dump_config() { + ESP_LOGCONFIG(TAG, "UPS HID Component:"); + ESP_LOGCONFIG(TAG, " Simulation Mode: %s", simulation_mode_ ? "YES" : "NO"); + + if (transport_ && transport_->is_connected()) { + ESP_LOGCONFIG(TAG, " USB Vendor ID: 0x%04X", transport_->get_vendor_id()); + ESP_LOGCONFIG(TAG, " USB Product ID: 0x%04X", transport_->get_product_id()); + } + + ESP_LOGCONFIG(TAG, " Protocol Timeout: %u ms", protocol_timeout_ms_); + ESP_LOGCONFIG(TAG, " Protocol Selection: %s", protocol_selection_.c_str()); + ESP_LOGCONFIG(TAG, " Update Interval: %u ms", get_update_interval()); - if (connected_) - { - ESP_LOGCONFIG(TAG, " Status: Connected"); - ESP_LOGCONFIG(TAG, " Protocol: %s", get_protocol_name().c_str()); - ESP_LOGCONFIG(TAG, " Manufacturer: %s", ups_data_.manufacturer.c_str()); - ESP_LOGCONFIG(TAG, " Model: %s", ups_data_.model.c_str()); - } - else - { - ESP_LOGCONFIG(TAG, " Status: Disconnected"); - } + if (transport_ && transport_->is_connected()) { + ESP_LOGCONFIG(TAG, " Status: Connected"); + if (active_protocol_) { + ESP_LOGCONFIG(TAG, " Active Protocol: %s", + active_protocol_->get_protocol_name().c_str()); + } else { + ESP_LOGCONFIG(TAG, " Protocol Status: Detection pending"); } + } else { + ESP_LOGCONFIG(TAG, " Status: Disconnected"); + } - std::string UpsHidComponent::get_protocol_name() const - { - if (active_protocol_) - { - return active_protocol_->get_protocol_name(); - } - return "Unknown"; + ESP_LOGCONFIG(TAG, " Registered Sensors: %zu", sensors_.size()); + ESP_LOGCONFIG(TAG, " Registered Binary Sensors: %zu", binary_sensors_.size()); + ESP_LOGCONFIG(TAG, " Registered Text Sensors: %zu", text_sensors_.size()); +} + +// Transport abstraction methods +esp_err_t UpsHidComponent::hid_get_report(uint8_t report_type, uint8_t report_id, + uint8_t* data, size_t* data_len, + uint32_t timeout_ms) { + if (!transport_) { + return ESP_ERR_INVALID_STATE; + } + return transport_->hid_get_report(report_type, report_id, data, data_len, timeout_ms); +} + +esp_err_t UpsHidComponent::hid_set_report(uint8_t report_type, uint8_t report_id, + const uint8_t* data, size_t data_len, + uint32_t timeout_ms) { + if (!transport_) { + return ESP_ERR_INVALID_STATE; + } + return transport_->hid_set_report(report_type, report_id, data, data_len, timeout_ms); +} + +esp_err_t UpsHidComponent::get_string_descriptor(uint8_t string_index, std::string& result) { + if (!transport_) { + return ESP_ERR_INVALID_STATE; + } + return transport_->get_string_descriptor(string_index, result); +} + +bool UpsHidComponent::is_connected() const { + return transport_ && transport_->is_connected(); +} + +uint16_t UpsHidComponent::get_vendor_id() const { + return transport_ ? transport_->get_vendor_id() : 0; +} + +uint16_t UpsHidComponent::get_product_id() const { + return transport_ ? transport_->get_product_id() : 0; +} + +// Core implementation methods +bool UpsHidComponent::initialize_transport() { + ESP_LOGD(TAG, "Initializing transport layer"); + + // Create appropriate transport + auto transport_type = simulation_mode_ ? + UsbTransportFactory::SIMULATION : + UsbTransportFactory::ESP32_HARDWARE; + + transport_ = UsbTransportFactory::create(transport_type, simulation_mode_); + + if (!transport_) { + ESP_LOGE(TAG, "Failed to create transport instance"); + return false; + } + + esp_err_t ret = transport_->initialize(); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "Transport initialization failed: %s", transport_->get_last_error().c_str()); + transport_.reset(); + return false; + } + + connected_ = transport_->is_connected(); + + ESP_LOGI(TAG, "Transport initialized successfully (VID=0x%04X, PID=0x%04X)", + transport_->get_vendor_id(), transport_->get_product_id()); + + return true; +} + +bool UpsHidComponent::detect_protocol() { + if (!transport_ || !transport_->is_connected()) { + ESP_LOGE(TAG, "Cannot detect protocol - transport not connected"); + return false; + } + + uint16_t vendor_id = transport_->get_vendor_id(); + + if (protocol_selection_ == "auto") { + // Automatic protocol detection based on vendor ID + ESP_LOGD(TAG, "Auto-detecting protocol for vendor 0x%04X using factory", vendor_id); + active_protocol_ = ProtocolFactory::create_for_vendor(vendor_id, this); + } else { + // Manual protocol selection via factory + ESP_LOGD(TAG, "Using manually selected protocol: %s", protocol_selection_.c_str()); + active_protocol_ = ProtocolFactory::create_by_name(protocol_selection_, this); + } + + if (!active_protocol_) { + ESP_LOGE(TAG, "Failed to create protocol (selection: %s, vendor: 0x%04X)", + protocol_selection_.c_str(), vendor_id); + return false; + } + + ESP_LOGI(TAG, "Successfully created protocol: %s", active_protocol_->get_protocol_name().c_str()); + + // Initialize the protocol (detection already done by factory) + if (!active_protocol_->initialize()) { + ESP_LOGE(TAG, "Protocol initialization failed"); + active_protocol_.reset(); + return false; + } + + ESP_LOGI(TAG, "Protocol initialized: %s", + active_protocol_->get_protocol_name().c_str()); + + // Set the detected protocol in ups_data_ after successful detection + { + std::lock_guard lock(data_mutex_); + ups_data_.device.detected_protocol = active_protocol_->get_protocol_type(); + } + + return true; +} + +bool UpsHidComponent::read_ups_data() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for reading data"); + return false; + } + + std::lock_guard lock(data_mutex_); + + // Preserve the detected protocol before reset + DeviceInfo::DetectedProtocol current_protocol = ups_data_.device.detected_protocol; + + // Reset data before reading + ups_data_.reset(); + + // Restore the detected protocol after reset + ups_data_.device.detected_protocol = current_protocol; + + // Read data through protocol + bool success = active_protocol_->read_data(ups_data_); + + if (success) { + ESP_LOGV(TAG, "Successfully read UPS data"); + } else { + ESP_LOGW(TAG, "Failed to read UPS data via protocol"); + } + + return success; +} + +void UpsHidComponent::update_sensors() { + std::lock_guard lock(data_mutex_); + + // Update all registered sensors with current data + for (auto& sensor_pair : sensors_) { + const std::string& type = sensor_pair.first; + sensor::Sensor* sensor = sensor_pair.second; + + // Extract appropriate value based on sensor type + float value = NAN; + + if (type == "battery_level" && ups_data_.battery.is_valid()) { + value = ups_data_.battery.level; + } else if (type == "battery_voltage" && !std::isnan(ups_data_.battery.voltage)) { + value = ups_data_.battery.voltage; + } else if (type == "battery_voltage_nominal" && !std::isnan(ups_data_.battery.voltage_nominal)) { + value = ups_data_.battery.voltage_nominal; + } else if (type == "runtime" && !std::isnan(ups_data_.battery.runtime_minutes)) { + value = ups_data_.battery.runtime_minutes; + } else if (type == "input_voltage" && !std::isnan(ups_data_.power.input_voltage)) { + value = ups_data_.power.input_voltage; + } else if (type == "input_voltage_nominal" && !std::isnan(ups_data_.power.input_voltage_nominal)) { + value = ups_data_.power.input_voltage_nominal; + } else if (type == "output_voltage" && !std::isnan(ups_data_.power.output_voltage)) { + value = ups_data_.power.output_voltage; + } else if (type == "load_percent" && !std::isnan(ups_data_.power.load_percent)) { + value = ups_data_.power.load_percent; + } else if (type == "frequency" && !std::isnan(ups_data_.power.frequency)) { + value = ups_data_.power.frequency; + } else if (type == "ups_realpower_nominal" && !std::isnan(ups_data_.power.realpower_nominal)) { + value = ups_data_.power.realpower_nominal; + } else if (type == "ups_delay_shutdown" && !std::isnan(ups_data_.config.delay_shutdown)) { + value = ups_data_.config.delay_shutdown; + } else if (type == "ups_delay_start" && !std::isnan(ups_data_.config.delay_start)) { + value = ups_data_.config.delay_start; + } else if (type == "ups_delay_reboot" && !std::isnan(ups_data_.config.delay_reboot)) { + value = ups_data_.config.delay_reboot; + } else if (type == "ups_timer_reboot" && ups_data_.test.timer_reboot != -1) { + value = ups_data_.test.timer_reboot; + } else if (type == "ups_timer_shutdown" && ups_data_.test.timer_shutdown != -1) { + value = ups_data_.test.timer_shutdown; + } else if (type == "ups_timer_start" && ups_data_.test.timer_start != -1) { + value = ups_data_.test.timer_start; } - - bool UpsHidComponent::initialize_usb() - { -#ifdef USE_ESP32 - ESP_LOGI(TAG, "Initializing USB HID Host communication..."); - ESP_LOGI(TAG, "ESP32-S3 USB OTG Host Mode Configuration:"); - ESP_LOGI(TAG, " Board: ESP32-S3-DevKitC-1"); - ESP_LOGI(TAG, " USB OTG Pins: D+ (GPIO20), D- (GPIO19)"); - ESP_LOGI(TAG, " USB Host Mode: Enabled with HID Host driver"); - - // Create mutex for USB synchronization - usb_mutex_ = xSemaphoreCreateMutex(); - if (usb_mutex_ == nullptr) { - ESP_LOGE(TAG, "Failed to create USB mutex"); - return false; - } - - // Initialize USB Host Library first - esp_err_t ret = usb_host_lib_init(); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "USB Host library initialization failed: %s", esp_err_to_name(ret)); - return false; - } - usb_host_initialized_ = true; - - // Register USB client - ret = usb_client_register(); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "USB client registration failed: %s", esp_err_to_name(ret)); - usb_deinit(); - return false; - } - - // Wait a moment for USB devices to be detected - vTaskDelay(pdMS_TO_TICKS(1000)); - - // Try initial device enumeration - ret = usb_device_enumerate(); - if (ret == ESP_OK) { - ESP_LOGI(TAG, "Initial USB device enumeration completed successfully"); - } else { - ESP_LOGW(TAG, "Initial USB device enumeration failed: %s", esp_err_to_name(ret)); - ESP_LOGW(TAG, "USB Troubleshooting if no devices found:"); - ESP_LOGW(TAG, " 1. Verify USB OTG pads are soldered correctly"); - ESP_LOGW(TAG, " 2. Check UPS is powered ON and connected"); - ESP_LOGW(TAG, " 3. Try different USB cable (must support data)"); - ESP_LOGW(TAG, " 4. Some UPS devices need to be 'awake' (press a button)"); - } - - ESP_LOGI(TAG, "USB Host initialized successfully"); - return true; -#else - ESP_LOGE(TAG, "USB HID Host only supported on ESP32 platform"); - return false; -#endif + + if (!std::isnan(value)) { + sensor->publish_state(value); } - - - bool UpsHidComponent::should_log_error(ErrorRateLimit &limiter) - { - uint32_t now = millis(); - - // Check if we're past the rate limit window - if (now - limiter.last_error_time > ErrorRateLimit::RATE_LIMIT_MS) - { - // Reset the limiter for new time window - if (limiter.suppressed_count > 0) - { - // Log how many errors we suppressed in the previous window - ESP_LOGW(TAG, "Suppressed %u similar error messages in the last %u ms", - limiter.suppressed_count, ErrorRateLimit::RATE_LIMIT_MS); - limiter.suppressed_count = 0; - } - limiter.error_count = 0; - limiter.last_error_time = now; - } - - limiter.error_count++; - - // Allow first few errors in burst, then rate limit - if (limiter.error_count <= ErrorRateLimit::MAX_BURST) - { - return true; - } - - // Rate limit subsequent errors - limiter.suppressed_count++; - return false; + } + + // Update binary sensors + for (auto& sensor_pair : binary_sensors_) { + const std::string& type = sensor_pair.first; + binary_sensor::BinarySensor* sensor = sensor_pair.second; + + bool state = false; + + if (type == "online" && ups_data_.power.input_voltage_valid()) { + state = true; + } else if (type == "on_battery" && ups_data_.power.input_voltage_valid()) { + state = false; // Opposite of online + } else if (type == "low_battery") { + state = ups_data_.battery.is_low(); } - - void UpsHidComponent::log_suppressed_errors(ErrorRateLimit &limiter) - { - if (limiter.suppressed_count > 0) - { - ESP_LOGW(TAG, "Suppressed %u similar error messages", limiter.suppressed_count); - limiter.suppressed_count = 0; - } + + sensor->publish_state(state); + } + + // Update text sensors + for (auto& sensor_pair : text_sensors_) { + const std::string& type = sensor_pair.first; + text_sensor::TextSensor* sensor = sensor_pair.second; + + std::string value = ""; + + if (type == "model" && !ups_data_.device.model.empty()) { + value = ups_data_.device.model; + } else if (type == "manufacturer" && !ups_data_.device.manufacturer.empty()) { + value = ups_data_.device.manufacturer; + } else if (type == "serial_number" && !ups_data_.device.serial_number.empty()) { + value = ups_data_.device.serial_number; + } else if (type == "firmware_version" && !ups_data_.device.firmware_version.empty()) { + value = ups_data_.device.firmware_version; + } else if (type == "battery_status" && !ups_data_.battery.status.empty()) { + value = ups_data_.battery.status; + } else if (type == "ups_test_result" && !ups_data_.test.ups_test_result.empty()) { + value = ups_data_.test.ups_test_result; + } else if (type == "ups_beeper_status" && !ups_data_.config.beeper_status.empty()) { + value = ups_data_.config.beeper_status; + } else if (type == "input_sensitivity" && !ups_data_.config.input_sensitivity.empty()) { + value = ups_data_.config.input_sensitivity; + } else if (type == "status" && !ups_data_.power.status.empty()) { + value = ups_data_.power.status; + } else if (type == "protocol") { + value = get_protocol_name(); } - - bool UpsHidComponent::detect_ups_protocol() - { - ESP_LOGD(TAG, "Detecting UPS protocol..."); - - // Always try auto-detection first to discover the actual device - ESP_LOGI(TAG, "Starting automatic protocol detection..."); - - // Get the actual USB device vendor/product IDs (may differ from configured defaults) - uint16_t detected_vid = usb_vendor_id_; - uint16_t detected_pid = usb_product_id_; - -#ifdef USE_ESP32 - // Try to get actual device IDs if USB device is connected - if (device_connected_ && usb_device_.dev_hdl) - { - detected_vid = usb_device_.vid; - detected_pid = usb_device_.pid; - ESP_LOGI(TAG, "Auto-detected USB device: VID=0x%04X, PID=0x%04X", detected_vid, detected_pid); - } - else - { - ESP_LOGW(TAG, "No USB device connected, using configured IDs: VID=0x%04X, PID=0x%04X", detected_vid, detected_pid); - } -#endif - - // Log vendor information for debugging - if (is_known_ups_vendor(detected_vid)) - { - const char *vendor_name = get_ups_vendor_name(detected_vid); - ESP_LOGI(TAG, "Detected known UPS vendor: %s (0x%04X)", vendor_name, detected_vid); - } - else - { - ESP_LOGI(TAG, "Unknown/Generic vendor ID: 0x%04X (trying all protocols)", detected_vid); - } - - // Always attempt auto-detection - try all protocols in intelligent order - std::vector>> protocol_attempts; - - if (detected_vid == 0x051D) { - // APC device detected - try APC HID first - ESP_LOGD(TAG, "APC device detected, trying APC HID protocol first"); - protocol_attempts.push_back({"APC HID", [this]() - { - auto protocol = std::make_unique(this); - if (protocol->detect() && protocol->initialize()) - { - active_protocol_ = std::move(protocol); - ups_data_.detected_protocol = PROTOCOL_APC_HID; - return true; - } - return false; - }}); - } else if (detected_vid == 0x0764) { - // CyberPower device detected - try CyberPower HID first - ESP_LOGD(TAG, "CyberPower device detected, trying CyberPower HID protocol first"); - protocol_attempts.push_back({"CyberPower HID", [this]() - { - auto protocol = std::make_unique(this); - if (protocol->detect() && protocol->initialize()) - { - active_protocol_ = std::move(protocol); - ups_data_.detected_protocol = PROTOCOL_CYBERPOWER_HID; - return true; - } - return false; - }}); - } - else if (detected_vid == 0x0463 || detected_vid == 0x047C || detected_vid == 0x04B3 || - detected_vid == 0x04D8 || detected_vid == 0x0483 || detected_vid == 0x050D || - detected_vid == 0x0592 || detected_vid == 0x05DD || detected_vid == 0x06DA || - detected_vid == 0x075D || detected_vid == 0x09AE || detected_vid == 0x09D6) - { - // Known UPS vendor with NUT HID driver support - try Generic HID first - ESP_LOGD(TAG, "Known UPS vendor detected (0x%04X), trying Generic HID first", detected_vid); - protocol_attempts.push_back({"Known UPS vendor - Generic HID", [this]() - { - auto protocol = std::make_unique(this); - if (protocol->detect() && protocol->initialize()) - { - active_protocol_ = std::move(protocol); - ups_data_.detected_protocol = PROTOCOL_GENERIC_HID; - return true; - } - return false; - }}); - } - else - { - // Always add Generic HID as final fallback (if not already added) - ESP_LOGD(TAG, "Unkown UPS vendor detected (0x%04X), using Generic HID", detected_vid); - protocol_attempts.push_back({"Unkown UPS vendor - Generic HID", [this]() - { - auto protocol = std::make_unique(this); - if (protocol->detect() && protocol->initialize()) - { - active_protocol_ = std::move(protocol); - ups_data_.detected_protocol = PROTOCOL_GENERIC_HID; - return true; - } - return false; - }}); - } - - // Try each protocol with timeout and retry logic - for (const auto &attempt : protocol_attempts) - { - // Yield to prevent task watchdog timeout during long protocol detection - vTaskDelay(pdMS_TO_TICKS(1)); - - ESP_LOGD(TAG, "Trying %s protocol...", attempt.first.c_str()); - - // Attempt detection with timeout - uint32_t start_time = millis(); - bool success = false; - - // Try detection with rate limiting - if (!should_log_error(protocol_error_limiter_)) - { - ESP_LOGV(TAG, "Protocol detection rate limited, skipping %s", attempt.first.c_str()); - continue; - } - - success = attempt.second(); - - uint32_t detection_time = millis() - start_time; - - if (success) - { - ESP_LOGI(TAG, "Successfully detected %s protocol (took %ums)", - attempt.first.c_str(), detection_time); - return true; - } - else - { - ESP_LOGD(TAG, "%s protocol detection failed (took %ums)", - attempt.first.c_str(), detection_time); - - // Small delay between attempts to prevent overwhelming the device - vTaskDelay(pdMS_TO_TICKS(100)); - } - } - - ESP_LOGW(TAG, "Auto-detection failed for vendor 0x%04X", detected_vid); - - return false; + + if (!value.empty()) { + sensor->publish_state(value); } - - bool UpsHidComponent::read_ups_data() - { - if (!active_protocol_) - { - ESP_LOGW(TAG, "No active protocol available for reading data"); - return false; - } - - // Create temporary data structure to avoid corrupting existing data on failure - UpsData temp_data; - { - std::lock_guard lock(data_mutex_); - temp_data = ups_data_; - } - - if (active_protocol_->read_data(temp_data)) - { - // Only update if we got valid data - if (temp_data.is_valid()) - { - std::lock_guard lock(data_mutex_); - ups_data_ = temp_data; - return true; - } - else - { - ESP_LOGW(TAG, "Protocol returned invalid data"); - return false; - } - } - - ESP_LOGV(TAG, "Failed to read data from protocol: %s", active_protocol_->get_protocol_name().c_str()); - return false; - } - - void UpsHidComponent::update_sensors() - { - // Create local copy of data under lock to minimize lock time - UpsData local_data; - { - std::lock_guard lock(data_mutex_); - local_data = ups_data_; - } - - // Update numeric sensors with validation - for (const auto &[type, sensor] : sensors_) - { - if (!sensor) - continue; // Safety check - - float value = NAN; - - if (type == "battery_level") - { - value = local_data.battery_level; - } - else if (type == "input_voltage") - { - value = local_data.input_voltage; - } - else if (type == "output_voltage") - { - value = local_data.output_voltage; - } - else if (type == "load_percent") - { - value = local_data.load_percent; - } - else if (type == "runtime") - { - value = local_data.runtime_minutes; - } - else if (type == "frequency") - { - value = local_data.frequency; - } - else if (type == "battery_voltage") - { - value = local_data.battery_voltage; - } - else if (type == "battery_voltage_nominal") - { - value = local_data.battery_voltage_nominal; - } - else if (type == "input_voltage_nominal") - { - value = local_data.input_voltage_nominal; - } - else if (type == "input_transfer_low") - { - value = local_data.input_transfer_low; - } - else if (type == "input_transfer_high") - { - value = local_data.input_transfer_high; - } - else if (type == "ups_realpower_nominal") - { - value = local_data.ups_realpower_nominal; - } - else if (type == "ups_delay_shutdown") - { - value = static_cast(local_data.ups_delay_shutdown); - } - else if (type == "ups_delay_start") - { - value = static_cast(local_data.ups_delay_start); - } - else if (type == "battery_charge_low") - { - value = local_data.battery_charge_low; - } - else if (type == "battery_charge_warning") - { - value = local_data.battery_charge_warning; - } - else if (type == "battery_runtime_low") - { - value = local_data.battery_runtime_low; - } - else if (type == "ups_timer_reboot") - { - value = static_cast(local_data.ups_timer_reboot); - } - else if (type == "ups_timer_shutdown") - { - value = static_cast(local_data.ups_timer_shutdown); - } - else if (type == "ups_timer_start") - { - value = static_cast(local_data.ups_timer_start); - } - - // Publish sensor state - handle both valid data and cleared/unavailable data - if (std::isnan(value)) - { - // Data is cleared/unavailable - force sensor to publish NAN to clear stale readings - ESP_LOGD(TAG, "Force-publishing NAN for cleared sensor '%s'", type.c_str()); - sensor->publish_state(std::numeric_limits::quiet_NaN()); - } - else - { - // Add bounds checking for safety - if (type == "battery_level" && (value < 0.0f || value > 100.0f)) - { - ESP_LOGW(TAG, "Battery level out of bounds: %.1f%%", value); - continue; - } - if (type == "load_percent" && (value < 0.0f || value > 100.0f)) - { - ESP_LOGW(TAG, "Load percentage out of bounds: %.1f%%", value); - continue; - } - - sensor->publish_state(value); - } - } - - // Update binary sensors - for (auto &pair : binary_sensors_) - { - const std::string &type = pair.first; - auto *sensor = pair.second; - - if (type == "online") - { - sensor->publish_state(local_data.status_flags & UPS_STATUS_ONLINE); - } - else if (type == "on_battery") - { - sensor->publish_state(local_data.status_flags & UPS_STATUS_ON_BATTERY); - } - else if (type == "low_battery") - { - sensor->publish_state(local_data.status_flags & UPS_STATUS_LOW_BATTERY); - } - else if (type == "fault") - { - sensor->publish_state(local_data.status_flags & UPS_STATUS_FAULT); - } - else if (type == "overload") - { - sensor->publish_state(local_data.status_flags & UPS_STATUS_OVERLOAD); - } - else if (type == "charging") - { - sensor->publish_state(local_data.status_flags & UPS_STATUS_CHARGING); - } - } - - // Update text sensors - for (auto &pair : text_sensors_) - { - const std::string &type = pair.first; - auto *sensor = pair.second; - - if (type == "model") - { - sensor->publish_state(local_data.model.empty() ? "Unknown" : local_data.model); - } - else if (type == "manufacturer") - { - sensor->publish_state(local_data.manufacturer.empty() ? "Unknown" : local_data.manufacturer); - } - else if (type == "protocol") - { - sensor->publish_state(get_protocol_name()); - } - else if (type == "serial_number") - { - sensor->publish_state(local_data.serial_number.empty() ? "Unknown" : local_data.serial_number); - } - else if (type == "firmware_version") - { - sensor->publish_state(local_data.firmware_version.empty() ? "Unknown" : local_data.firmware_version); - } - else if (type == "ups_beeper_status") - { - sensor->publish_state(local_data.ups_beeper_status.empty() ? "Unknown" : local_data.ups_beeper_status); - } - else if (type == "input_sensitivity") - { - sensor->publish_state(local_data.input_sensitivity.empty() ? "Unknown" : local_data.input_sensitivity); - } - else if (type == "battery_status") - { - sensor->publish_state(local_data.battery_status.empty() ? "Unknown" : local_data.battery_status); - } - else if (type == "battery_type") - { - sensor->publish_state(local_data.battery_type.empty() ? "Unknown" : local_data.battery_type); - } - else if (type == "battery_mfr_date") - { - sensor->publish_state(local_data.battery_mfr_date.empty() ? "Unknown" : local_data.battery_mfr_date); - } - else if (type == "ups_mfr_date") - { - sensor->publish_state(local_data.ups_mfr_date.empty() ? "Unknown" : local_data.ups_mfr_date); - } - else if (type == "ups_firmware_aux") - { - sensor->publish_state(local_data.ups_firmware_aux.empty() ? "Unknown" : local_data.ups_firmware_aux); - } - else if (type == "ups_test_result") - { - sensor->publish_state(local_data.ups_test_result.empty() ? "Unknown" : local_data.ups_test_result); - } - else if (type == "status") - { - std::string status_str = ""; - if (local_data.status_flags & UPS_STATUS_ONLINE) - status_str += "Online "; - if (local_data.status_flags & UPS_STATUS_ON_BATTERY) - status_str += "OnBattery "; - if (local_data.status_flags & UPS_STATUS_LOW_BATTERY) - status_str += "LowBattery "; - if (local_data.status_flags & UPS_STATUS_CHARGING) - status_str += "Charging "; - if (local_data.status_flags & UPS_STATUS_FAULT) - status_str += "Fault "; - if (status_str.empty()) - status_str = "Unknown"; - sensor->publish_state(status_str); - } - } - } - - void UpsHidComponent::simulate_ups_data() - { - uint32_t now_ms = millis(); - static uint32_t last_log_time = 0; - - // Use time-based simulation for consistent behavior - float time_sec = now_ms / 1000.0f; - - // Add some randomness for realistic variation - static uint32_t random_seed = now_ms; - random_seed = random_seed * 1103515245 + 12345; // Simple LCG - float random_factor = (random_seed % 1000) / 10000.0f; // 0.0 to 0.1 - - // Create simulation data with thread safety - { - std::lock_guard lock(data_mutex_); - - // Store previous values for change detection - float prev_battery = ups_data_.battery_level; - float prev_input = ups_data_.input_voltage; - float prev_load = ups_data_.load_percent; - - // Simulate realistic UPS data with faster, more visible changes - float battery_calc = 85.0f + sin(time_sec * 0.05f) * 12.0f + random_factor * 5.0f; - ups_data_.battery_level = battery_calc < 0.0f ? 0.0f : (battery_calc > 100.0f ? 100.0f : battery_calc); - - float input_calc = 120.0f + sin(time_sec * 0.08f) * 8.0f + random_factor * 3.0f; - ups_data_.input_voltage = input_calc < 100.0f ? 100.0f : (input_calc > 130.0f ? 130.0f : input_calc); - - float output_calc = 118.0f + sin(time_sec * 0.06f) * 5.0f + random_factor * 2.0f; - ups_data_.output_voltage = output_calc < 100.0f ? 100.0f : (output_calc > 125.0f ? 125.0f : output_calc); - - float load_calc = 45.0f + sin(time_sec * 0.03f) * 20.0f + random_factor * 8.0f; - ups_data_.load_percent = load_calc < 0.0f ? 0.0f : (load_calc > 100.0f ? 100.0f : load_calc); - - float runtime_calc = 35.0f + sin(time_sec * 0.02f) * 15.0f + random_factor * 5.0f; - ups_data_.runtime_minutes = runtime_calc < 0.0f ? 0.0f : (runtime_calc > 120.0f ? 120.0f : runtime_calc); - - float freq_calc = 60.0f + sin(time_sec * 0.4f) * 0.5f + random_factor * 0.3f; - ups_data_.frequency = freq_calc < 59.5f ? 59.5f : (freq_calc > 60.5f ? 60.5f : freq_calc); - - // Simulate realistic status changes with shorter, more dynamic cycles - uint32_t cycle_pos = (now_ms / 100) % 200; // 20 second total cycle - if (cycle_pos < 140) - { - ups_data_.status_flags = UPS_STATUS_ONLINE | UPS_STATUS_CHARGING; - } - else if (cycle_pos < 170) - { - ups_data_.status_flags = UPS_STATUS_ON_BATTERY; - } - else if (cycle_pos < 190) - { - ups_data_.status_flags = UPS_STATUS_ON_BATTERY | UPS_STATUS_LOW_BATTERY; - } - else - { - // Brief fault simulation - ups_data_.status_flags = UPS_STATUS_FAULT; - } - - // Keep device info consistent - ups_data_.manufacturer = "Simulated"; - ups_data_.model = "Virtual UPS Pro"; - ups_data_.serial_number = "SIM123456789"; - ups_data_.firmware_version = "1.0.0-SIM"; - - // Debug logging every 10 seconds to verify changes - if (now_ms - last_log_time > 10000) - { - ESP_LOGD(TAG, "Simulation values: Battery=%.1f%%, Input=%.1fV, Load=%.1f%%, Status=0x%X", - ups_data_.battery_level, ups_data_.input_voltage, ups_data_.load_percent, ups_data_.status_flags); - ESP_LOGD(TAG, "Value changes: Battery=%+.1f, Input=%+.1f, Load=%+.1f", - ups_data_.battery_level - prev_battery, - ups_data_.input_voltage - prev_input, - ups_data_.load_percent - prev_load); - last_log_time = now_ms; - } - } - - // Simulate connection issues for testing (less frequent) - uint32_t connection_cycle = (now_ms / 1000) % 300; // 5 minute cycle - if (connection_cycle == 299) - { - ESP_LOGD(TAG, "Simulating temporary connection loss"); - connected_ = false; - } - else if (connection_cycle == 5 && !connected_) - { - ESP_LOGD(TAG, "Simulating connection restoration"); - connected_ = true; - last_successful_read_ = millis(); - consecutive_failures_ = 0; - } - } - - void UpsHidComponent::register_sensor(sensor::Sensor *sens, const std::string &type) - { - sensors_[type] = sens; - } - - void UpsHidComponent::register_binary_sensor(binary_sensor::BinarySensor *sens, const std::string &type) - { - binary_sensors_[type] = sens; - } - - void UpsHidComponent::register_text_sensor(text_sensor::TextSensor *sens, const std::string &type) - { - text_sensors_[type] = sens; - } - - bool UpsHidComponent::usb_write(const std::vector &data) - { -#ifdef USE_ESP32 - if (data.empty()) - { - return false; - } - - // Take USB mutex for thread safety - if (xSemaphoreTake(usb_mutex_, pdMS_TO_TICKS(1000)) != pdTRUE) - { - if (should_log_error(usb_error_limiter_)) - { - ESP_LOGW(TAG, "Failed to acquire USB mutex for write"); - } - return false; - } - - // Check connection status inside mutex to prevent race conditions - if (!device_connected_) - { - xSemaphoreGive(usb_mutex_); - return false; - } - - std::vector dummy_response; - esp_err_t ret = usb_transfer_sync(data, dummy_response, 1000); - - xSemaphoreGive(usb_mutex_); - - if (ret != ESP_OK) - { - if (should_log_error(usb_error_limiter_)) - { - ESP_LOGW(TAG, "USB write failed: %s", esp_err_to_name(ret)); - } - return false; - } - - ESP_LOGV(TAG, "USB Write: %zu bytes", data.size()); - return true; -#else - return false; -#endif - } - - bool UpsHidComponent::usb_read(std::vector &data, uint32_t timeout_ms) - { -#ifdef USE_ESP32 - data.clear(); - - // Take USB mutex for thread safety - if (xSemaphoreTake(usb_mutex_, pdMS_TO_TICKS(timeout_ms)) != pdTRUE) - { - if (should_log_error(usb_error_limiter_)) - { - ESP_LOGW(TAG, "Failed to acquire USB mutex for read"); - } - return false; - } - - // Check connection status inside mutex to prevent race conditions - if (!device_connected_) - { - xSemaphoreGive(usb_mutex_); - return false; - } - - std::vector dummy_out; - esp_err_t ret = usb_transfer_sync(dummy_out, data, timeout_ms); - - xSemaphoreGive(usb_mutex_); - - if (ret != ESP_OK) - { - if (should_log_error(usb_error_limiter_)) - { - ESP_LOGW(TAG, "USB read failed: %s", esp_err_to_name(ret)); - } - data.clear(); - return false; - } - - ESP_LOGV(TAG, "USB Read: %zu bytes", data.size()); - return true; -#else - data.clear(); - return false; -#endif - } - -#ifdef USE_ESP32 - esp_err_t UpsHidComponent::usb_host_lib_init() - { - ESP_LOGD(TAG, "Creating USB Host Library task..."); - - // Create USB Host Library task - BaseType_t task_created = xTaskCreatePinnedToCore( - usb_host_lib_task, - "usb_events", - 4096, - xTaskGetCurrentTaskHandle(), // Pass current task handle for notification - 2, - &usb_lib_task_handle_, - 0); - - if (task_created != pdTRUE) { - ESP_LOGE(TAG, "Failed to create USB Host Library task"); - return ESP_FAIL; - } - - // Wait for notification from USB Host Library task that it's ready - uint32_t notification_value = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(5000)); - if (notification_value == 0) { - ESP_LOGE(TAG, "USB Host Library task startup timeout"); - return ESP_ERR_TIMEOUT; - } - - ESP_LOGI(TAG, "USB Host Library task started successfully"); - - // Create USB client task for asynchronous operations - usb_tasks_running_ = true; - task_created = xTaskCreatePinnedToCore( - usb_client_task, - "usb_client", - 4096, - this, - 3, // Higher priority than USB Host Library task - &usb_client_task_handle_, - 1); - - if (task_created != pdTRUE) { - ESP_LOGE(TAG, "Failed to create USB client task"); - usb_tasks_running_ = false; - return ESP_FAIL; - } - - ESP_LOGI(TAG, "USB client task started successfully"); - return ESP_OK; - } - - esp_err_t UpsHidComponent::usb_client_register() - { - ESP_LOGD(TAG, "Registering USB client..."); - - usb_host_client_config_t client_config = { - .is_synchronous = false, - .max_num_event_msg = 5, - .async = { - .client_event_callback = usb_client_event_callback, - .callback_arg = this, - }}; - - esp_err_t ret = usb_host_client_register(&client_config, &usb_device_.client_hdl); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "USB client register failed: %s", esp_err_to_name(ret)); - return ret; - } - - ESP_LOGI(TAG, "USB client registered successfully"); - return ESP_OK; - } - - - void UpsHidComponent::usb_deinit() - { - ESP_LOGD(TAG, "Deinitializing USB Host..."); - - // Stop USB tasks - usb_tasks_running_ = false; - - if (usb_client_task_handle_) { - vTaskDelete(usb_client_task_handle_); - usb_client_task_handle_ = nullptr; - } - - if (usb_host_initialized_) { - // Stop USB Host Library task - if (usb_lib_task_handle_) { - vTaskDelete(usb_lib_task_handle_); - usb_lib_task_handle_ = nullptr; - } - - // Uninstall USB Host Library - usb_host_uninstall(); - usb_host_initialized_ = false; - } - - // Delete mutex - if (usb_mutex_) { - vSemaphoreDelete(usb_mutex_); - usb_mutex_ = nullptr; - } - - device_connected_ = false; - ESP_LOGI(TAG, "USB Host deinitialized"); - } - - - - esp_err_t UpsHidComponent::usb_device_enumerate() - { - ESP_LOGD(TAG, "Enumerating USB devices..."); - - // Check and re-register USB client if needed - if (!usb_device_.client_hdl) { - ESP_LOGW(TAG, "USB client not registered, attempting re-registration"); - esp_err_t client_ret = usb_client_register(); - if (client_ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to re-register USB client: %s", esp_err_to_name(client_ret)); - return client_ret; - } - } - - // Test if we can get device list to check for USB Host Library state issues - // This is a quick check before attempting more expensive operations - - // Check USB host status first - ESP_LOGD(TAG, "Checking USB host library status..."); - - uint8_t dev_addr_list[10]; - int num_dev = 10; - - ESP_LOGD(TAG, "Calling usb_host_device_addr_list_fill with max_dev=%d", num_dev); - esp_err_t ret = usb_host_device_addr_list_fill(num_dev, dev_addr_list, &num_dev); - ESP_LOGD(TAG, "usb_host_device_addr_list_fill returned: %s, num_dev=%d", esp_err_to_name(ret), num_dev); - - if (ret != ESP_OK) - { - ESP_LOGE(TAG, "Failed to get device address list: %s", esp_err_to_name(ret)); - return ret; - } - - ESP_LOGI(TAG, "USB enumeration found %d devices", num_dev); - - // Add detailed logging for each device address - for (int i = 0; i < num_dev; i++) - { - ESP_LOGI(TAG, "Device %d: Address %d", i, dev_addr_list[i]); - } - - for (int i = 0; i < num_dev; i++) - { - usb_device_handle_t dev_hdl = nullptr; - ret = usb_host_device_open(usb_device_.client_hdl, dev_addr_list[i], &dev_hdl); - if (ret != ESP_OK) - { - if (ret == ESP_ERR_INVALID_STATE) { - ESP_LOGW(TAG, "USB device %d in invalid state - forcing cleanup and retry", dev_addr_list[i]); - - // Force cleanup of all devices to clear stale state - ESP_LOGI(TAG, "Calling usb_host_device_free_all() to clear stale device references"); - esp_err_t cleanup_ret = usb_host_device_free_all(); - if (cleanup_ret == ESP_OK) { - ESP_LOGI(TAG, "Device cleanup successful, retrying device open"); - - // Progressive delay to let USB stack stabilize - // First attempt: 200ms, second: 500ms, third: 1000ms - static uint32_t retry_count = 0; - uint32_t delay_ms = 200 + (retry_count * 300); // 200, 500, 800, 1100... - delay_ms = std::min(delay_ms, static_cast(2000)); // Cap at 2 seconds - - ESP_LOGI(TAG, "Waiting %ums for USB stack stabilization (retry #%u)", delay_ms, retry_count + 1); - vTaskDelay(pdMS_TO_TICKS(delay_ms)); - - // Retry opening the device after cleanup - ret = usb_host_device_open(usb_device_.client_hdl, dev_addr_list[i], &dev_hdl); - if (ret != ESP_OK) { - retry_count++; - ESP_LOGW(TAG, "Device open retry #%u failed: %s", retry_count, esp_err_to_name(ret)); - if (retry_count >= 3) { - ESP_LOGE(TAG, "Maximum USB cleanup retries reached, device may need power cycle"); - retry_count = 0; // Reset for next device - } - continue; - } else { - ESP_LOGI(TAG, "Device open retry succeeded after cleanup (attempt #%u)", retry_count + 1); - retry_count = 0; // Reset success counter - } - } else { - ESP_LOGE(TAG, "Device cleanup failed: %s - USB Host Library in corrupted state", esp_err_to_name(cleanup_ret)); - - if (cleanup_ret == ESP_ERR_INVALID_STATE) { - ESP_LOGW(TAG, "Attempting complete USB client re-registration to recover from corrupted state"); - - // Force complete USB client reset - if (usb_device_.client_hdl) { - ESP_LOGI(TAG, "Deregistering corrupted USB client"); - esp_err_t dereg_ret = usb_host_client_deregister(usb_device_.client_hdl); - ESP_LOGD(TAG, "USB client deregistration result: %s", esp_err_to_name(dereg_ret)); - usb_device_.client_hdl = nullptr; - } - - // Re-register USB client to get fresh state - ESP_LOGI(TAG, "Re-registering USB client for fresh start"); - esp_err_t rereg_ret = usb_client_register(); - if (rereg_ret == ESP_OK) { - ESP_LOGI(TAG, "USB client re-registration successful - will retry device enumeration"); - // Don't continue here - let the next enumeration cycle try again - } else { - ESP_LOGE(TAG, "USB client re-registration failed: %s", esp_err_to_name(rereg_ret)); - } - } - continue; - } - } else { - ESP_LOGW(TAG, "Failed to open USB device %d: %s", dev_addr_list[i], esp_err_to_name(ret)); - continue; - } - } - - const usb_device_desc_t *dev_desc; - ret = usb_host_get_device_descriptor(dev_hdl, &dev_desc); - if (ret == ESP_OK && usb_is_ups_device(dev_desc)) - { - // Found UPS device - usb_device_.dev_hdl = dev_hdl; - usb_device_.dev_addr = dev_addr_list[i]; - usb_device_.vid = dev_desc->idVendor; - usb_device_.pid = dev_desc->idProduct; - - ESP_LOGI(TAG, "Found UPS device: VID=0x%04X, PID=0x%04X", usb_device_.vid, usb_device_.pid); - - // Claim interface and get endpoints - esp_err_t claim_ret = usb_claim_interface(); - if (claim_ret == ESP_OK) - { - esp_err_t endpoint_ret = usb_get_endpoints(); - if (endpoint_ret == ESP_OK) - { - device_connected_ = true; - return ESP_OK; - } - if (should_log_error(usb_error_limiter_)) - { - ESP_LOGW(TAG, "Failed to get USB endpoints: %s", esp_err_to_name(endpoint_ret)); - } - } - else - { - if (should_log_error(usb_error_limiter_)) - { - ESP_LOGW(TAG, "Failed to claim USB interface: %s", esp_err_to_name(claim_ret)); - } - } - - // Clean up on failure - usb_device_.dev_hdl = nullptr; - usb_device_.dev_addr = 0; - } - - // Close device handle if we opened it but didn't use it - if (dev_hdl && dev_hdl != usb_device_.dev_hdl) { - usb_host_device_close(usb_device_.client_hdl, dev_hdl); - } - } - - return ESP_ERR_NOT_FOUND; - } - - bool UpsHidComponent::usb_is_ups_device(const usb_device_desc_t *desc) - { - uint16_t vid = desc->idVendor; - uint16_t pid = desc->idProduct; - - ESP_LOGV(TAG, "Checking device: VID=0x%04X, PID=0x%04X", vid, pid); - - // Check configured VID/PID first (highest priority) - if (vid == usb_vendor_id_ && pid == usb_product_id_) - { - ESP_LOGD(TAG, "Device matches configured VID/PID"); - return true; - } - - // Check against known UPS vendor list - if (is_known_ups_vendor(vid)) - { - const char *vendor_name = get_ups_vendor_name(vid); - ESP_LOGD(TAG, "Recognized UPS vendor: %s (0x%04X)", vendor_name, vid); - return true; - } - - // Check device class (some UPS devices use HID class) - if (desc->bDeviceClass == USB_CLASS_HID || - (desc->bDeviceClass == 0 && desc->bDeviceSubClass == 0)) - { - ESP_LOGV(TAG, "Device might be HID-compatible UPS (unknown vendor)"); - return true; // Could be a HID UPS from unknown vendor - } - - return false; - } - - esp_err_t UpsHidComponent::usb_claim_interface() - { - // Get active configuration - const usb_config_desc_t *config_desc; - esp_err_t ret = usb_host_get_active_config_descriptor(usb_device_.dev_hdl, &config_desc); - if (ret != ESP_OK) - { - ESP_LOGE(TAG, "Failed to get config descriptor: %s", esp_err_to_name(ret)); - return ret; - } - - // Find HID interface - const usb_intf_desc_t *intf_desc = nullptr; - int offset = 0; - - for (int i = 0; i < config_desc->bNumInterfaces; i++) - { - intf_desc = usb_parse_interface_descriptor(config_desc, i, 0, &offset); - if (intf_desc && intf_desc->bInterfaceClass == USB_CLASS_HID) - { - usb_device_.interface_num = intf_desc->bInterfaceNumber; - usb_device_.is_hid_device = true; - break; - } - } - - if (!intf_desc) - { - ESP_LOGE(TAG, "No HID interface found"); - return ESP_ERR_NOT_FOUND; - } - - // Claim the interface - ret = usb_host_interface_claim(usb_device_.client_hdl, usb_device_.dev_hdl, - usb_device_.interface_num, 0); - if (ret != ESP_OK) - { - if (ret == ESP_ERR_INVALID_STATE) { - ESP_LOGE(TAG, "Interface claim failed due to ESP-IDF v5.3 endpoint allocation bug"); - ESP_LOGW(TAG, "The USB Host Library has stale endpoint allocations from a previous session"); - ESP_LOGI(TAG, "This typically happens after USB disconnect/reconnect cycles"); - ESP_LOGI(TAG, "Solutions: 1) Power cycle the ESP32, 2) Upgrade to ESP-IDF v5.4+"); - } - - ESP_LOGE(TAG, "Failed to claim interface: %s", esp_err_to_name(ret)); - return ret; - } - - ESP_LOGD(TAG, "Claimed interface %d", usb_device_.interface_num); - return ESP_OK; - } - - esp_err_t UpsHidComponent::usb_get_endpoints() - { - // Get active configuration - const usb_config_desc_t *config_desc; - esp_err_t ret = usb_host_get_active_config_descriptor(usb_device_.dev_hdl, &config_desc); - if (ret != ESP_OK) - { - return ret; - } - - // Find HID interface first - const usb_intf_desc_t *intf_desc = nullptr; - int intf_offset = 0; - - for (int i = 0; i < config_desc->bNumInterfaces; i++) - { - intf_desc = usb_parse_interface_descriptor(config_desc, i, 0, &intf_offset); - if (intf_desc && intf_desc->bInterfaceClass == USB_CLASS_HID) - { - break; - } - } - - if (!intf_desc) - { - ESP_LOGE(TAG, "No HID interface found for endpoints"); - return ESP_ERR_NOT_FOUND; - } - - // Parse endpoints correctly using ESP-IDF approach - const usb_ep_desc_t *ep_desc = nullptr; - int ep_offset = intf_offset; - - ESP_LOGD(TAG, "Interface has %d endpoints", intf_desc->bNumEndpoints); - - for (int i = 0; i < intf_desc->bNumEndpoints; i++) { - ep_desc = usb_parse_endpoint_descriptor_by_index(intf_desc, i, config_desc->wTotalLength, &ep_offset); - if (ep_desc) { - if (USB_EP_DESC_GET_EP_DIR(ep_desc)) { - usb_device_.ep_in = ep_desc->bEndpointAddress; - usb_device_.max_packet_size = ep_desc->wMaxPacketSize; - ESP_LOGD(TAG, "Found IN endpoint: 0x%02X (max packet size: %d)", - usb_device_.ep_in, usb_device_.max_packet_size); - } else { - usb_device_.ep_out = ep_desc->bEndpointAddress; - ESP_LOGD(TAG, "Found OUT endpoint: 0x%02X", usb_device_.ep_out); - } - } else { - ESP_LOGW(TAG, "Failed to parse endpoint %d", i); - } - } - - if (usb_device_.ep_in == 0) - { - ESP_LOGE(TAG, "No IN endpoint found"); - return ESP_ERR_NOT_FOUND; - } - - // Detect input-only devices (no OUT endpoint) - if (usb_device_.ep_out == 0) { - usb_device_.is_input_only = true; - ESP_LOGW(TAG, "INPUT-ONLY HID device detected - no OUT endpoint available"); - ESP_LOGD(TAG, "Device can only send data to host, cannot receive commands"); - } else { - usb_device_.is_input_only = false; - ESP_LOGD(TAG, "Bidirectional device detected - has both IN and OUT endpoints"); - } - - return ESP_OK; - } - - void UpsHidComponent::usb_transfer_callback(usb_transfer_t *transfer) - { - TransferContext *ctx = static_cast(transfer->context); - if (!ctx) { - ESP_LOGE(TAG, "Transfer callback: NULL context"); - return; - } - - // Store transfer results - ctx->result = (transfer->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL; - ctx->actual_bytes = transfer->actual_num_bytes; - - // Copy data for IN transfers if successful - if (ctx->result == ESP_OK && ctx->buffer && transfer->actual_num_bytes > 0) { - // For control transfers, skip the setup packet (8 bytes) - size_t data_offset = 0; - size_t available_data = transfer->actual_num_bytes; - - // Check if this is a control transfer (endpoint 0) - if (transfer->bEndpointAddress == 0 && available_data >= sizeof(usb_setup_packet_t)) { - data_offset = sizeof(usb_setup_packet_t); - available_data -= sizeof(usb_setup_packet_t); - } - - if (available_data > 0 && ctx->buffer_size > 0) { - size_t copy_size = std::min(available_data, ctx->buffer_size); - memcpy(ctx->buffer, transfer->data_buffer + data_offset, copy_size); - ESP_LOGV(TAG, "Transfer callback: copied %zu bytes (offset %zu)", copy_size, data_offset); - } - } - - // Signal completion - if (ctx->done_sem) { - xSemaphoreGive(ctx->done_sem); - } - } - - esp_err_t UpsHidComponent::usb_transfer_sync(const std::vector &data_out, - std::vector &data_in, - uint32_t timeout_ms) - { - if (!device_connected_ || !usb_device_.dev_hdl) - { - ESP_LOGW(TAG, "USB device not connected for transfer"); - return ESP_ERR_INVALID_STATE; - } - - // Validate timeout - timeout_ms = std::clamp(timeout_ms, static_cast(100), static_cast(30000)); // 100ms to 30s - - esp_err_t ret = ESP_OK; - - // Send data if provided - if (!data_out.empty() && usb_device_.ep_out != 0) - { - if (data_out.size() > usb_device_.max_packet_size * 4) - { // Reasonable size check - ESP_LOGW(TAG, "Output data too large: %zu bytes", data_out.size()); - return ESP_ERR_INVALID_SIZE; - } - - // Ensure transfer size is multiple of MPS - size_t transfer_size = data_out.size(); - if (usb_device_.max_packet_size > 0) { - size_t remainder = transfer_size % usb_device_.max_packet_size; - if (remainder != 0) { - transfer_size += (usb_device_.max_packet_size - remainder); - } - } - ESP_LOGV(TAG, "OUT transfer: data_size=%zu, mps=%u, transfer_size=%zu", - data_out.size(), usb_device_.max_packet_size, transfer_size); - - // Create transfer context - TransferContext out_ctx = {}; - out_ctx.done_sem = xSemaphoreCreateBinary(); - if (!out_ctx.done_sem) { - ESP_LOGE(TAG, "Failed to create OUT transfer semaphore"); - return ESP_ERR_NO_MEM; - } - - usb_transfer_t *transfer_out = nullptr; - ret = usb_host_transfer_alloc(transfer_size, 0, &transfer_out); - if (ret != ESP_OK || !transfer_out) - { - ESP_LOGE(TAG, "Failed to allocate OUT transfer: %s", esp_err_to_name(ret)); - vSemaphoreDelete(out_ctx.done_sem); - return ret; - } - - transfer_out->device_handle = usb_device_.dev_hdl; - transfer_out->bEndpointAddress = usb_device_.ep_out; - transfer_out->callback = usb_transfer_callback; - transfer_out->context = &out_ctx; - transfer_out->num_bytes = transfer_size; - // Copy data and zero-pad the rest - std::memcpy(transfer_out->data_buffer, data_out.data(), data_out.size()); - if (transfer_size > data_out.size()) { - std::memset(transfer_out->data_buffer + data_out.size(), 0, transfer_size - data_out.size()); - } - - ret = usb_host_transfer_submit(transfer_out); - if (ret == ESP_OK) - { - // Wait for transfer completion - if (xSemaphoreTake(out_ctx.done_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) { - ret = out_ctx.result; - ESP_LOGV(TAG, "OUT transfer completed with result: %s", esp_err_to_name(ret)); - } else { - ESP_LOGW(TAG, "OUT transfer timeout after %ums", timeout_ms); - ret = ESP_ERR_TIMEOUT; - } - } - else - { - ESP_LOGW(TAG, "Failed to submit OUT transfer: %s", esp_err_to_name(ret)); - } - - usb_host_transfer_free(transfer_out); - vSemaphoreDelete(out_ctx.done_sem); - - if (ret != ESP_OK) - { - return ret; - } - } - - // Read data if IN endpoint exists - if (usb_device_.ep_in != 0) - { - size_t buffer_size = std::max(static_cast(64), static_cast(usb_device_.max_packet_size)); - buffer_size = std::min(buffer_size, static_cast(1024)); // Cap at 1KB - - // Ensure buffer size is multiple of MPS - if (usb_device_.max_packet_size > 0) { - size_t remainder = buffer_size % usb_device_.max_packet_size; - if (remainder != 0) { - buffer_size += (usb_device_.max_packet_size - remainder); - } - } - ESP_LOGV(TAG, "IN transfer: mps=%u, buffer_size=%zu", usb_device_.max_packet_size, buffer_size); - - // Prepare buffer for received data - std::vector temp_buffer(buffer_size); - - // Create transfer context - TransferContext in_ctx = {}; - in_ctx.done_sem = xSemaphoreCreateBinary(); - in_ctx.buffer = temp_buffer.data(); - in_ctx.buffer_size = buffer_size; - - if (!in_ctx.done_sem) { - ESP_LOGE(TAG, "Failed to create IN transfer semaphore"); - return ESP_ERR_NO_MEM; - } - - usb_transfer_t *transfer_in = nullptr; - ret = usb_host_transfer_alloc(buffer_size, 0, &transfer_in); - if (ret != ESP_OK || !transfer_in) - { - ESP_LOGE(TAG, "Failed to allocate IN transfer: %s", esp_err_to_name(ret)); - vSemaphoreDelete(in_ctx.done_sem); - return ret; - } - - transfer_in->device_handle = usb_device_.dev_hdl; - transfer_in->bEndpointAddress = usb_device_.ep_in; - transfer_in->callback = usb_transfer_callback; - transfer_in->context = &in_ctx; - transfer_in->num_bytes = buffer_size; - - ret = usb_host_transfer_submit(transfer_in); - if (ret == ESP_OK) - { - // Wait for transfer completion - if (xSemaphoreTake(in_ctx.done_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) { - ret = in_ctx.result; - - if (ret == ESP_OK && in_ctx.actual_bytes > 0) { - // Copy received data to output vector - data_in.resize(in_ctx.actual_bytes); - std::memcpy(data_in.data(), temp_buffer.data(), in_ctx.actual_bytes); - ESP_LOGV(TAG, "USB IN transfer received %zu bytes", in_ctx.actual_bytes); - } - } else { - ESP_LOGW(TAG, "IN transfer timeout after %ums", timeout_ms); - ret = ESP_ERR_TIMEOUT; - } - } - else - { - ESP_LOGW(TAG, "Failed to submit IN transfer: %s", esp_err_to_name(ret)); - } - - usb_host_transfer_free(transfer_in); - vSemaphoreDelete(in_ctx.done_sem); - } - - return ret; - } - - esp_err_t UpsHidComponent::hid_get_report(uint8_t report_type, uint8_t report_id, uint8_t* data, size_t* data_len) - { - if (!device_connected_) - { - ESP_LOGE(TAG, "HID GET_REPORT: Device not connected (device_connected_=false)"); - return ESP_ERR_INVALID_ARG; - } - if (!usb_device_.dev_hdl) - { - ESP_LOGE(TAG, "HID GET_REPORT: No device handle (usb_device_.dev_hdl=NULL)"); - return ESP_ERR_INVALID_ARG; - } - if (!data || !data_len || *data_len == 0) - { - ESP_LOGE(TAG, "HID GET_REPORT: Invalid parameters (data=%p, data_len=%p, *data_len=%zu)", - data, data_len, data_len ? *data_len : 0); - return ESP_ERR_INVALID_ARG; - } - - ESP_LOGD(TAG, "HID GET_REPORT: type=0x%02X, id=0x%02X, max_len=%zu", report_type, report_id, *data_len); - - // Use specific buffer sizes based on working NUT implementation - uint8_t buffer[8] = {0}; // Fixed size like working NUT implementation - size_t expected_len = 8; // Standard HID report size for APC UPS devices - - // Create USB control transfer for HID GET_REPORT - const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_IN | USB_BM_REQUEST_TYPE_TYPE_CLASS | USB_BM_REQUEST_TYPE_RECIP_INTERFACE; - const uint8_t bRequest = 0x01; // HID GET_REPORT - const uint16_t wValue = (report_type << 8) | report_id; - const uint16_t wIndex = usb_device_.interface_num; - const uint16_t wLength = expected_len; - - usb_transfer_t *transfer = nullptr; - size_t transfer_size = sizeof(usb_setup_packet_t) + expected_len; - esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to allocate transfer: %s", esp_err_to_name(ret)); - return ret; - } - - // Setup control transfer like working implementation - transfer->device_handle = usb_device_.dev_hdl; - transfer->bEndpointAddress = 0; - transfer->num_bytes = transfer_size; - transfer->timeout_ms = 500; // Reasonable timeout - - // Create setup packet - usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer; - setup->bmRequestType = bmRequestType; - setup->bRequest = bRequest; - setup->wValue = wValue; - setup->wIndex = wIndex; - setup->wLength = wLength; - - // Use semaphore for synchronous operation - SemaphoreHandle_t done_sem = xSemaphoreCreateBinary(); - if (!done_sem) { - usb_host_transfer_free(transfer); - return ESP_ERR_NO_MEM; - } - - // Simple context for completion - struct { - SemaphoreHandle_t sem; - esp_err_t result; - size_t actual_bytes; - } ctx = {done_sem, ESP_ERR_TIMEOUT, 0}; - - transfer->context = &ctx; - transfer->callback = [](usb_transfer_t *t) { - auto *c = static_cast(t->context); - c->result = (t->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL; - c->actual_bytes = t->actual_num_bytes; - xSemaphoreGive(c->sem); - }; - - ret = usb_host_transfer_submit_control(usb_device_.client_hdl, transfer); - if (ret == ESP_OK) { - if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(500)) == pdTRUE) { - ret = ctx.result; - if (ret == ESP_OK && ctx.actual_bytes > sizeof(usb_setup_packet_t)) { - size_t data_received = ctx.actual_bytes - sizeof(usb_setup_packet_t); - size_t copy_len = std::min(data_received, *data_len); - memcpy(data, transfer->data_buffer + sizeof(usb_setup_packet_t), copy_len); - *data_len = copy_len; - - ESP_LOGD(TAG, "HID GET_REPORT success: received %zu bytes", *data_len); - if (*data_len > 0) { - std::string hex_str; - for (size_t i = 0; i < std::min(*data_len, (size_t)8); i++) { - char hex_byte[4]; - snprintf(hex_byte, sizeof(hex_byte), "%02X ", data[i]); - hex_str += hex_byte; - } - ESP_LOGD(TAG, "Data: %s", hex_str.c_str()); - } - } else { - ESP_LOGW(TAG, "HID GET_REPORT: No data received"); - *data_len = 0; - ret = ESP_FAIL; - } - } else { - ESP_LOGW(TAG, "HID GET_REPORT timeout"); - ret = ESP_ERR_TIMEOUT; - } - } else { - ESP_LOGW(TAG, "Failed to submit HID GET_REPORT: %s", esp_err_to_name(ret)); - } - - vSemaphoreDelete(done_sem); - usb_host_transfer_free(transfer); - return ret; - } - - esp_err_t UpsHidComponent::hid_set_report(uint8_t report_type, uint8_t report_id, const uint8_t* data, size_t data_len) - { - if (!device_connected_ || !usb_device_.dev_hdl || !data) { - return ESP_ERR_INVALID_ARG; - } - - const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_OUT | USB_BM_REQUEST_TYPE_TYPE_CLASS | USB_BM_REQUEST_TYPE_RECIP_INTERFACE; - const uint8_t bRequest = 0x09; // HID SET_REPORT - const uint16_t wValue = (report_type << 8) | report_id; - const uint16_t wIndex = usb_device_.interface_num; - - usb_transfer_t *transfer = nullptr; - esp_err_t ret = usb_host_transfer_alloc(sizeof(usb_setup_packet_t) + data_len, 0, &transfer); - if (ret != ESP_OK || !transfer) { - ESP_LOGE(TAG, "Failed to allocate control transfer: %s", esp_err_to_name(ret)); - return ret; - } - - // Create transfer context for synchronization - TransferContext ctx = {}; - ctx.done_sem = xSemaphoreCreateBinary(); - - if (!ctx.done_sem) { - usb_host_transfer_free(transfer); - return ESP_ERR_NO_MEM; - } - - // Set up USB control transfer - transfer->device_handle = usb_device_.dev_hdl; - transfer->bEndpointAddress = 0; // Control endpoint - transfer->callback = usb_transfer_callback; - transfer->context = &ctx; - transfer->num_bytes = sizeof(usb_setup_packet_t) + data_len; - - // Create setup packet - usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer; - setup->bmRequestType = bmRequestType; - setup->bRequest = bRequest; - setup->wValue = wValue; - setup->wIndex = wIndex; - setup->wLength = data_len; - - // Copy data after setup packet - if (data_len > 0) { - memcpy(transfer->data_buffer + sizeof(usb_setup_packet_t), data, data_len); - } - - ESP_LOGV(TAG, "HID SET_REPORT: type=0x%02X, id=0x%02X, len=%zu", report_type, report_id, data_len); - - ret = usb_host_transfer_submit_control(usb_device_.client_hdl, transfer); - if (ret == ESP_OK) { - // Wait for completion - if (xSemaphoreTake(ctx.done_sem, pdMS_TO_TICKS(5000)) == pdTRUE) { - ret = ctx.result; - ESP_LOGV(TAG, "HID SET_REPORT success"); - } else { - ESP_LOGW(TAG, "HID SET_REPORT timeout"); - ret = ESP_ERR_TIMEOUT; - } - } else { - ESP_LOGW(TAG, "Failed to submit HID SET_REPORT: %s", esp_err_to_name(ret)); - } - - usb_host_transfer_free(transfer); - vSemaphoreDelete(ctx.done_sem); - return ret; - } - - esp_err_t UpsHidComponent::usb_get_string_descriptor(uint8_t string_index, std::string& result, uint16_t language_id) - { - result.clear(); - - if (!device_connected_ || !usb_device_.dev_hdl) { - ESP_LOGW(TAG, "USB GET_STRING_DESCRIPTOR: Device not ready - connected: %s, handle: %p", - device_connected_ ? "true" : "false", usb_device_.dev_hdl); - return ESP_ERR_INVALID_ARG; - } - - ESP_LOGD(TAG, "USB GET_STRING_DESCRIPTOR: index=%d, language_id=0x%04X", string_index, language_id); - - // USB string descriptors can be up to 255 bytes, but typically much smaller - const size_t max_string_len = 255; - - // USB string descriptor request parameters - const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_IN | USB_BM_REQUEST_TYPE_TYPE_STANDARD | USB_BM_REQUEST_TYPE_RECIP_DEVICE; - const uint8_t bRequest = USB_B_REQUEST_GET_DESCRIPTOR; - const uint16_t wValue = (USB_B_DESCRIPTOR_TYPE_STRING << 8) | string_index; - const uint16_t wIndex = language_id; // Language ID (0x0409 = English US) - const uint16_t wLength = max_string_len; - - usb_transfer_t *transfer = nullptr; - size_t transfer_size = sizeof(usb_setup_packet_t) + max_string_len; - esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to allocate string descriptor transfer: %s", esp_err_to_name(ret)); - return ret; - } - - // Setup control transfer - transfer->device_handle = usb_device_.dev_hdl; - transfer->bEndpointAddress = 0; // Control endpoint - transfer->num_bytes = transfer_size; - transfer->timeout_ms = 1000; // 1 second timeout for string descriptor - - // Create setup packet - usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer; - setup->bmRequestType = bmRequestType; - setup->bRequest = bRequest; - setup->wValue = wValue; - setup->wIndex = wIndex; - setup->wLength = wLength; - - // Create transfer context for synchronization - TransferContext ctx = {}; - ctx.done_sem = xSemaphoreCreateBinary(); - - if (!ctx.done_sem) { - usb_host_transfer_free(transfer); - return ESP_ERR_NO_MEM; - } - - transfer->context = &ctx; - transfer->callback = usb_transfer_callback; - - ESP_LOGV(TAG, "USB GET_STRING_DESCRIPTOR: setup packet created"); - - ret = usb_host_transfer_submit_control(usb_device_.client_hdl, transfer); - if (ret == ESP_OK) { - // Wait for completion with timeout - if (xSemaphoreTake(ctx.done_sem, pdMS_TO_TICKS(1000)) == pdTRUE) { - ret = ctx.result; - if (ret == ESP_OK && ctx.actual_bytes > sizeof(usb_setup_packet_t)) { - // Parse the USB string descriptor - uint8_t *desc_data = transfer->data_buffer + sizeof(usb_setup_packet_t); - size_t desc_len = ctx.actual_bytes - sizeof(usb_setup_packet_t); - - if (desc_len >= 2) { - uint8_t bLength = desc_data[0]; // Total length of descriptor - uint8_t bDescriptorType = desc_data[1]; // Should be USB_B_DESCRIPTOR_TYPE_STRING (0x03) - - if (bDescriptorType == USB_B_DESCRIPTOR_TYPE_STRING && bLength >= 2) { - // USB string descriptors are UTF-16LE encoded, skip the 2-byte header - size_t string_data_len = bLength - 2; - uint8_t *string_data = desc_data + 2; - - // Convert UTF-16LE to ASCII (simplified, only handles ASCII characters) - result.reserve(string_data_len / 2); - for (size_t i = 0; i < string_data_len; i += 2) { - uint16_t utf16_char = string_data[i] | (string_data[i + 1] << 8); - if (utf16_char < 128) { // ASCII range - result += static_cast(utf16_char); - } else { - result += '?'; // Non-ASCII character placeholder - } - } - - // Trim trailing whitespace - while (!result.empty() && std::isspace(result.back())) { - result.pop_back(); - } - - ESP_LOGI(TAG, "USB string descriptor %d: \"%s\"", string_index, result.c_str()); - } else { - ESP_LOGW(TAG, "Invalid string descriptor: type=0x%02X, length=%d", bDescriptorType, bLength); - ret = ESP_ERR_INVALID_RESPONSE; - } - } else { - ESP_LOGW(TAG, "String descriptor too short: %zu bytes", desc_len); - ret = ESP_ERR_INVALID_SIZE; - } - } else { - ESP_LOGW(TAG, "String descriptor transfer failed: %s, bytes=%zu", - esp_err_to_name(ret), ctx.actual_bytes); - } - } else { - ESP_LOGW(TAG, "String descriptor transfer timeout"); - ret = ESP_ERR_TIMEOUT; - } - } else { - ESP_LOGW(TAG, "Failed to submit string descriptor transfer: %s", esp_err_to_name(ret)); - } - - usb_host_transfer_free(transfer); - vSemaphoreDelete(ctx.done_sem); - return ret; - } - -#endif - - // Base Protocol Implementation - bool UpsProtocolBase::send_command(const std::vector &cmd, std::vector &response, uint32_t timeout_ms) - { - if (!parent_->usb_write(cmd)) - { - return false; - } - - return parent_->usb_read(response, timeout_ms); - } - - std::string UpsProtocolBase::bytes_to_string(const std::vector &data) - { - std::string result; - result.reserve(data.size()); - for (uint8_t byte : data) - { - if (byte >= 32 && byte <= 126) - { // Printable ASCII - result += static_cast(byte); - } - } - return result; - } - -#ifdef USE_ESP32 - // USB Host Library task - based on working ESP32 NUT server implementation - void UpsHidComponent::usb_host_lib_task(void *arg) - { - TaskHandle_t parent_task = static_cast(arg); - ESP_LOGI(TAG, "USB Host Library task starting..."); - - // Initialize USB Host library - const usb_host_config_t host_config = { - .skip_phy_setup = false, - .intr_flags = ESP_INTR_FLAG_LEVEL1, - }; - - esp_err_t ret = usb_host_install(&host_config); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "USB Host install failed: %s", esp_err_to_name(ret)); - vTaskDelete(nullptr); - return; - } - - ESP_LOGI(TAG, "USB Host library installed successfully"); - - // Notify parent task that USB Host is ready - xTaskNotifyGive(parent_task); - - // Main USB Host event loop - bool has_clients = true; - bool has_devices = false; - - while (has_clients) { - uint32_t event_flags; - ret = usb_host_lib_handle_events(portMAX_DELAY, &event_flags); - - if (ret != ESP_OK) { - ESP_LOGE(TAG, "USB Host event handling failed: %s", esp_err_to_name(ret)); - continue; - } - - // Handle USB Host events (following ESP-IDF v5.4 patterns) - if (event_flags & USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) { - ESP_LOGI(TAG, "No more USB clients"); - if (usb_host_device_free_all() == ESP_OK) { - ESP_LOGI(TAG, "All devices freed"); - has_clients = false; - } else { - ESP_LOGI(TAG, "Waiting for devices to be freed"); - has_devices = true; - } - } - - if (has_devices && (event_flags & USB_HOST_LIB_EVENT_FLAGS_ALL_FREE)) { - ESP_LOGI(TAG, "All devices freed"); - has_clients = false; - } - } - - ESP_LOGI(TAG, "USB Host Library task ending"); - vTaskDelete(nullptr); - } - - // USB client task for asynchronous operations - void UpsHidComponent::usb_client_task(void *arg) - { - UpsHidComponent *component = static_cast(arg); - ESP_LOGI(TAG, "USB client task started"); - - // Process USB client events in a loop - while (component->usb_tasks_running_) { - esp_err_t ret = usb_host_client_handle_events(component->usb_device_.client_hdl, 100); - - if (ret == ESP_ERR_TIMEOUT) { - // Timeout is normal - just continue processing - continue; - } else if (ret != ESP_OK) { - ESP_LOGW(TAG, "USB client event handling failed: %s", esp_err_to_name(ret)); - vTaskDelay(pdMS_TO_TICKS(100)); // Brief delay on error - continue; - } - - // Process any cached data updates - component->process_cached_data(); - - // Small delay to prevent busy-waiting - vTaskDelay(pdMS_TO_TICKS(10)); - } - - ESP_LOGI(TAG, "USB client task stopping"); - vTaskDelete(NULL); - } - - // Process cached UPS data from asynchronous operations - void UpsHidComponent::process_cached_data() - { - std::lock_guard cache_lock(ups_data_cache_.mutex); - - if (ups_data_cache_.data_valid) { - // Update main data with cached data - { - std::lock_guard data_lock(data_mutex_); - ups_data_ = ups_data_cache_.data; - } - - // Mark cache as processed - ups_data_cache_.data_valid = false; - - ESP_LOGV(TAG, "Processed cached UPS data"); - } - } - - // Test control method implementations - bool UpsHidComponent::start_battery_test_quick() - { - if (!connected_ || !active_protocol_) { - ESP_LOGW(TAG, "Cannot start battery test: UPS not connected"); - return false; - } - - ESP_LOGI(TAG, "Starting quick battery test"); - bool result = active_protocol_->start_battery_test_quick(); - if (result) { - ESP_LOGI(TAG, "Quick battery test initiated successfully"); - } else { - ESP_LOGW(TAG, "Failed to start quick battery test"); - } - return result; - } - - bool UpsHidComponent::start_battery_test_deep() - { - if (!connected_ || !active_protocol_) { - ESP_LOGW(TAG, "Cannot start battery test: UPS not connected"); - return false; - } - - ESP_LOGI(TAG, "Starting deep battery test"); - bool result = active_protocol_->start_battery_test_deep(); - if (result) { - ESP_LOGI(TAG, "Deep battery test initiated successfully"); - } else { - ESP_LOGW(TAG, "Failed to start deep battery test"); - } - return result; - } - - bool UpsHidComponent::stop_battery_test() - { - if (!connected_ || !active_protocol_) { - ESP_LOGW(TAG, "Cannot stop battery test: UPS not connected"); - return false; - } - - ESP_LOGI(TAG, "Stopping battery test"); - bool result = active_protocol_->stop_battery_test(); - if (result) { - ESP_LOGI(TAG, "Battery test stopped successfully"); - } else { - ESP_LOGW(TAG, "Failed to stop battery test"); - } - return result; - } - - bool UpsHidComponent::start_ups_test() - { - if (!connected_ || !active_protocol_) { - ESP_LOGW(TAG, "Cannot start UPS test: UPS not connected"); - return false; - } - - ESP_LOGI(TAG, "Starting UPS test"); - bool result = active_protocol_->start_ups_test(); - if (result) { - ESP_LOGI(TAG, "UPS test initiated successfully"); - } else { - ESP_LOGW(TAG, "Failed to start UPS test"); - } - return result; - } - - bool UpsHidComponent::stop_ups_test() - { - if (!connected_ || !active_protocol_) { - ESP_LOGW(TAG, "Cannot stop UPS test: UPS not connected"); - return false; - } - - ESP_LOGI(TAG, "Stopping UPS test"); - bool result = active_protocol_->stop_ups_test(); - if (result) { - ESP_LOGI(TAG, "UPS test stopped successfully"); - } else { - ESP_LOGW(TAG, "Failed to stop UPS test"); - } - return result; - } - - // Asynchronous HID GET_REPORT operation - esp_err_t UpsHidComponent::hid_get_report_async(uint8_t report_type, uint8_t report_id) - { - if (!device_connected_ || !usb_device_.dev_hdl) { - return ESP_ERR_INVALID_STATE; - } - - // For now, this is a placeholder for future async implementation - // The current synchronous hid_get_report will be replaced with proper - // async operations using queued transfers processed by usb_client_task - - ESP_LOGV(TAG, "Async HID GET_REPORT request: type=0x%02X, id=0x%02X", report_type, report_id); - - return ESP_OK; - } - - // USB client event callback - void UpsHidComponent::usb_client_event_callback(const usb_host_client_event_msg_t *event_msg, void *arg) - { - UpsHidComponent *component = static_cast(arg); - - switch (event_msg->event) { - case USB_HOST_CLIENT_EVENT_NEW_DEV: - ESP_LOGI(TAG, "USB_HOST_CLIENT_EVENT_NEW_DEV: device address %d", event_msg->new_dev.address); - // Mark that we need to re-enumerate devices - component->device_connected_ = false; - component->connected_ = false; - // Clear protocol to force re-detection - component->active_protocol_.reset(); - ESP_LOGI(TAG, "New USB device detected, will enumerate on next update cycle"); - break; - - case USB_HOST_CLIENT_EVENT_DEV_GONE: - ESP_LOGI(TAG, "USB_HOST_CLIENT_EVENT_DEV_GONE: device handle %p", event_msg->dev_gone.dev_hdl); - if (component->usb_device_.dev_hdl == event_msg->dev_gone.dev_hdl) { - ESP_LOGI(TAG, "UPS device disconnected"); - - // Mark device as disconnected - component->device_connected_ = false; - component->connected_ = false; - - // Clear device handle (interface will be auto-released by USB host) - component->usb_device_.dev_hdl = nullptr; - component->usb_device_.dev_addr = 0; - component->usb_device_.vid = 0; - component->usb_device_.pid = 0; - - // Clear active protocol - component->active_protocol_.reset(); - - // Reset UPS data - { - std::lock_guard data_lock(component->data_mutex_); - component->ups_data_.reset(); - } - - // Clear cached data - { - std::lock_guard cache_lock(component->ups_data_cache_.mutex); - component->ups_data_cache_.data.reset(); - component->ups_data_cache_.data_valid = false; - component->ups_data_cache_.last_update_time = 0; - } - - ESP_LOGI(TAG, "Device cleanup complete"); - } - break; - - default: - ESP_LOGD(TAG, "Unknown USB client event: %d", event_msg->event); - break; - } - } - - bool UpsHidComponent::test_device_communication() { - if (!usb_device_.dev_hdl || !active_protocol_) { - ESP_LOGD(TAG, "Cannot test communication: no device handle or protocol"); - return false; - } - - ESP_LOGD(TAG, "Testing device communication..."); - - // Try a simple HID communication test using the active protocol - UpsData test_data; - test_data.reset(); // Clear all data - - // Attempt to read some data from the device - bool success = active_protocol_->read_data(test_data); - - if (success) { - ESP_LOGD(TAG, "Device communication test successful"); - return true; - } else { - ESP_LOGD(TAG, "Device communication test failed"); - return false; - } - } -#endif - - } // namespace ups_hid + } + + ESP_LOGV(TAG, "Updated %zu sensors, %zu binary sensors, %zu text sensors", + sensors_.size(), binary_sensors_.size(), text_sensors_.size()); +} + +// Sensor registration methods +void UpsHidComponent::register_sensor(sensor::Sensor *sens, const std::string &type) { + sensors_[type] = sens; + ESP_LOGD(TAG, "Registered sensor: %s", type.c_str()); +} + +void UpsHidComponent::register_binary_sensor(binary_sensor::BinarySensor *sens, const std::string &type) { + binary_sensors_[type] = sens; + ESP_LOGD(TAG, "Registered binary sensor: %s", type.c_str()); +} + +void UpsHidComponent::register_text_sensor(text_sensor::TextSensor *sens, const std::string &type) { + text_sensors_[type] = sens; + ESP_LOGD(TAG, "Registered text sensor: %s", type.c_str()); +} + +// Test control methods +bool UpsHidComponent::start_battery_test_quick() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for battery test"); + return false; + } + return active_protocol_->start_battery_test_quick(); +} + +bool UpsHidComponent::start_battery_test_deep() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for battery test"); + return false; + } + return active_protocol_->start_battery_test_deep(); +} + +bool UpsHidComponent::stop_battery_test() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for battery test"); + return false; + } + return active_protocol_->stop_battery_test(); +} + +bool UpsHidComponent::start_ups_test() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for UPS test"); + return false; + } + return active_protocol_->start_ups_test(); +} + +bool UpsHidComponent::stop_ups_test() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for UPS test"); + return false; + } + return active_protocol_->stop_ups_test(); +} + +// Beeper control methods +bool UpsHidComponent::beeper_enable() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for beeper control"); + return false; + } + return active_protocol_->beeper_enable(); +} + +bool UpsHidComponent::beeper_disable() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for beeper control"); + return false; + } + return active_protocol_->beeper_disable(); +} + +bool UpsHidComponent::beeper_mute() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for beeper control"); + return false; + } + return active_protocol_->beeper_mute(); +} + +bool UpsHidComponent::beeper_test() { + if (!active_protocol_) { + ESP_LOGW(TAG, "No active protocol for beeper control"); + return false; + } + return active_protocol_->beeper_test(); +} + +// Additional protocol access method +std::string UpsHidComponent::get_protocol_name() const { + if (active_protocol_) { + return active_protocol_->get_protocol_name(); + } + return "None"; +} + + +// Error rate limiting helpers +bool UpsHidComponent::should_log_error(ErrorRateLimit& limiter) { + uint32_t now = millis(); + + if (limiter.error_count < ErrorRateLimit::MAX_BURST) { + limiter.error_count++; + limiter.last_error_time = now; + return true; + } + + if (now - limiter.last_error_time > ErrorRateLimit::RATE_LIMIT_MS) { + limiter.error_count = 1; + limiter.suppressed_count = 0; + limiter.last_error_time = now; + return true; + } + + limiter.suppressed_count++; + return false; +} + +void UpsHidComponent::log_suppressed_errors(ErrorRateLimit& limiter) { + if (limiter.suppressed_count > 0) { + ESP_LOGW(TAG, "Suppressed %u similar errors in the last %u ms", + limiter.suppressed_count, ErrorRateLimit::RATE_LIMIT_MS); + limiter.suppressed_count = 0; + } +} + +void UpsHidComponent::cleanup() { + if (transport_) { + transport_->deinitialize(); + transport_.reset(); + } + + active_protocol_.reset(); + connected_ = false; + + ESP_LOGD(TAG, "Component cleanup completed"); +} + + +} // namespace ups_hid } // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/ups_hid.h b/components/ups_hid/ups_hid.h index 616d6bc..419e47c 100644 --- a/components/ups_hid/ups_hid.h +++ b/components/ups_hid/ups_hid.h @@ -27,163 +27,32 @@ #include // USB HID Class defines -#ifndef USB_CLASS_HID -#define USB_CLASS_HID 0x03 -#endif +// USB HID Class constant is now defined in hid_constants.h #endif +// Include the clean refactored architecture +#include "ups_composite_data.h" +#include "usb_transport_interface.h" +#include "protocol_factory.h" +#include "hid_constants.h" + namespace esphome { namespace ups_hid { static const char *const TAG = "ups_hid"; - - // UPS status flags - enum UpsStatus - { - UPS_STATUS_UNKNOWN = 0, - UPS_STATUS_ONLINE = 1 << 0, - UPS_STATUS_ON_BATTERY = 1 << 1, - UPS_STATUS_LOW_BATTERY = 1 << 2, - UPS_STATUS_REPLACE_BATTERY = 1 << 3, - UPS_STATUS_CHARGING = 1 << 4, - UPS_STATUS_FAULT = 1 << 5, - UPS_STATUS_OVERLOAD = 1 << 6, - UPS_STATUS_CALIBRATING = 1 << 7, - UPS_STATUS_OFF = 1 << 8 - }; - - // UPS protocols - enum UpsProtocol - { - PROTOCOL_UNKNOWN = 0, - PROTOCOL_APC_HID, - PROTOCOL_CYBERPOWER_HID, - PROTOCOL_GENERIC_HID - }; - - // UPS data structure with proper initialization - struct UpsData - { - float battery_level{NAN}; - float input_voltage{NAN}; - float output_voltage{NAN}; - float load_percent{NAN}; - float runtime_minutes{NAN}; - float frequency{NAN}; - uint32_t status_flags{UPS_STATUS_UNKNOWN}; - std::string model{}; - std::string manufacturer{}; - std::string serial_number{}; - std::string firmware_version{}; - UpsProtocol detected_protocol{PROTOCOL_UNKNOWN}; - - // Additional sensor fields - float battery_voltage{NAN}; - float battery_voltage_nominal{NAN}; - float input_voltage_nominal{NAN}; - float input_transfer_low{NAN}; - float input_transfer_high{NAN}; - float ups_realpower_nominal{NAN}; - int16_t ups_delay_shutdown{-1}; - int16_t ups_delay_start{-1}; - std::string ups_beeper_status{}; - std::string input_sensitivity{}; - - // Additional missing fields from NUT analysis - float battery_charge_low{NAN}; // Battery low threshold (%) - float battery_charge_warning{NAN}; // Battery warning threshold (%) - float battery_runtime_low{NAN}; // Runtime low threshold (minutes) - std::string battery_status{}; // Battery status text - std::string battery_type{}; // Battery chemistry - std::string battery_mfr_date{}; // Battery manufacture date - std::string ups_mfr_date{}; // UPS manufacture date - std::string ups_firmware_aux{}; // Auxiliary firmware info - std::string ups_test_result{}; // Test result - int16_t ups_timer_reboot{-1}; // Reboot timer - int16_t ups_timer_shutdown{-1}; // Shutdown timer - int16_t ups_timer_start{-1}; // Start timer - - // Reset all data to default values - void reset() { - battery_level = NAN; - input_voltage = NAN; - output_voltage = NAN; - load_percent = NAN; - runtime_minutes = NAN; - frequency = NAN; - status_flags = UPS_STATUS_UNKNOWN; - model.clear(); - manufacturer.clear(); - serial_number.clear(); - firmware_version.clear(); - detected_protocol = PROTOCOL_UNKNOWN; - - // Reset additional sensor fields - battery_voltage = NAN; - battery_voltage_nominal = NAN; - input_voltage_nominal = NAN; - input_transfer_low = NAN; - input_transfer_high = NAN; - ups_realpower_nominal = NAN; - ups_delay_shutdown = -1; - ups_delay_start = -1; - ups_beeper_status.clear(); - input_sensitivity.clear(); - - // Reset additional missing fields - battery_charge_low = NAN; - battery_charge_warning = NAN; - battery_runtime_low = NAN; - battery_status.clear(); - battery_type.clear(); - battery_mfr_date.clear(); - ups_mfr_date.clear(); - ups_firmware_aux.clear(); - ups_test_result.clear(); - ups_timer_reboot = -1; - ups_timer_shutdown = -1; - ups_timer_start = -1; - } - - // Check if core data is valid - bool is_valid() const { - return !std::isnan(battery_level) || !std::isnan(input_voltage) || - !std::isnan(output_voltage) || status_flags != UPS_STATUS_UNKNOWN; - } - }; - + // Forward declarations class UpsProtocolBase; - class ApcHidProtocol; - class CyberPowerProtocol; - class GenericHidProtocol; + class IUsbTransport; class UpsHidComponent : public PollingComponent { public: - UpsHidComponent() { -#ifdef USE_ESP32 - memset(&usb_device_, 0, sizeof(usb_device_)); - usb_mutex_ = nullptr; - usb_lib_task_handle_ = nullptr; - usb_client_task_handle_ = nullptr; - usb_host_initialized_ = false; - device_connected_ = false; - usb_tasks_running_ = false; -#endif - } - - ~UpsHidComponent() { -#ifdef USE_ESP32 - // Log any remaining suppressed errors before cleanup - log_suppressed_errors(usb_error_limiter_); - log_suppressed_errors(protocol_error_limiter_); - usb_deinit(); -#endif - } + UpsHidComponent() = default; + ~UpsHidComponent() = default; void setup() override; void update() override; @@ -203,35 +72,17 @@ namespace esphome protocol_timeout_ms_ = std::max(static_cast(5000), std::min(timeout_ms, static_cast(300000))); } - void set_auto_detect_protocol(bool auto_detect) { auto_detect_protocol_ = auto_detect; } + void set_protocol_selection(const std::string &protocol) { protocol_selection_ = protocol; } + void set_fallback_nominal_voltage(float voltage) { fallback_nominal_voltage_ = voltage; } // Data getters for sensors (thread-safe) UpsData get_ups_data() const { std::lock_guard lock(data_mutex_); return ups_data_; } - bool is_connected() const { return connected_; } std::string get_protocol_name() const; - - // USB device info getters - uint16_t get_usb_vendor_id() const { return usb_vendor_id_; } - uint16_t get_usb_product_id() const { return usb_product_id_; } - bool is_input_only_device() const { -#ifdef USE_ESP32 - return usb_device_.is_input_only; -#else - return false; -#endif - } - - // Connection status for protocols - bool is_device_connected() const { -#ifdef USE_ESP32 - return device_connected_; -#else - return false; -#endif - } + uint32_t get_protocol_timeout() const { return protocol_timeout_ms_; } + float get_fallback_nominal_voltage() const { return fallback_nominal_voltage_; } // Test control methods bool start_battery_test_quick(); @@ -239,6 +90,12 @@ namespace esphome bool stop_battery_test(); bool start_ups_test(); bool stop_ups_test(); + + // Beeper control methods + bool beeper_enable(); + bool beeper_disable(); + bool beeper_mute(); + bool beeper_test(); // Sensor registration methods void register_sensor(sensor::Sensor *sens, const std::string &type); @@ -253,7 +110,8 @@ namespace esphome uint16_t usb_vendor_id_{0}; // 0 means auto-detect uint16_t usb_product_id_{0}; // 0 means auto-detect uint32_t protocol_timeout_ms_{10000}; - bool auto_detect_protocol_{true}; + std::string protocol_selection_{"auto"}; + float fallback_nominal_voltage_{230.0f}; // European standard (230V) for international compatibility bool connected_{false}; uint32_t last_successful_read_{0}; @@ -273,104 +131,48 @@ namespace esphome ErrorRateLimit usb_error_limiter_; ErrorRateLimit protocol_error_limiter_; + // Clean architecture members + std::unique_ptr transport_; std::unique_ptr active_protocol_; std::unordered_map sensors_; std::unordered_map binary_sensors_; std::unordered_map text_sensors_; // Core methods - bool initialize_usb(); - bool detect_ups_protocol(); + bool initialize_transport(); + bool detect_protocol(); bool read_ups_data(); void update_sensors(); - void simulate_ups_data(); - bool test_device_communication(); // Error rate limiting helpers bool should_log_error(ErrorRateLimit& limiter); void log_suppressed_errors(ErrorRateLimit& limiter); public: - // USB communication methods (accessible by protocol classes) - bool usb_write(const std::vector &data); - bool usb_read(std::vector &data, uint32_t timeout_ms = 1000); + // Transport abstraction methods (accessible by protocol classes) + esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id, + uint8_t* data, size_t* data_len, + uint32_t timeout_ms = 1000); + esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, + const uint8_t* data, size_t data_len, + uint32_t timeout_ms = 1000); + esp_err_t get_string_descriptor(uint8_t string_index, std::string& result); -#ifdef USE_ESP32 - // HID class requests (UPS-specific communication) - esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id, uint8_t* data, size_t* data_len); - esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, const uint8_t* data, size_t data_len); + // Transport information + bool is_connected() const; + uint16_t get_vendor_id() const; + uint16_t get_product_id() const; - // USB string descriptor reading - esp_err_t usb_get_string_descriptor(uint8_t string_index, std::string& result, uint16_t language_id = 0x0409); -#endif + // Legacy compatibility for protocols + bool is_device_connected() const { return is_connected(); } + esp_err_t usb_get_string_descriptor(uint8_t string_index, std::string& result) { + return get_string_descriptor(string_index, result); + } - protected: -#ifdef USE_ESP32 - // USB Host structures - struct UsbDevice { - usb_host_client_handle_t client_hdl; - usb_device_handle_t dev_hdl; - uint8_t dev_addr; - uint16_t vid; - uint16_t pid; - bool is_hid_device; - bool is_input_only; // True if device has no OUT endpoint (input-only HID device) - uint8_t interface_num; - uint8_t ep_in; - uint8_t ep_out; - uint16_t max_packet_size; - }; - - // USB Host member variables - UsbDevice usb_device_; - SemaphoreHandle_t usb_mutex_; - TaskHandle_t usb_lib_task_handle_; - TaskHandle_t usb_client_task_handle_; - bool usb_host_initialized_; - bool device_connected_; - volatile bool usb_tasks_running_; - - // Asynchronous data cache for non-blocking access - struct UpsDataCache { - UpsData data; - std::mutex mutex; - uint32_t last_update_time{0}; - bool data_valid{false}; - } ups_data_cache_; - - // ESP32-specific USB handling - esp_err_t usb_init(); - void usb_deinit(); - esp_err_t usb_host_lib_init(); - esp_err_t usb_client_register(); - esp_err_t usb_device_enumerate(); - bool usb_is_ups_device(const usb_device_desc_t *desc); - esp_err_t usb_claim_interface(); - esp_err_t usb_get_endpoints(); - - // USB communication - esp_err_t usb_transfer_sync(const std::vector &data_out, std::vector &data_in, uint32_t timeout_ms); - - // Transfer completion tracking - struct TransferContext { - SemaphoreHandle_t done_sem; - esp_err_t result; - size_t actual_bytes; - uint8_t* buffer; - size_t buffer_size; - }; - - // USB Host event handling - static void usb_host_lib_task(void *arg); - static void usb_client_task(void *arg); - static void usb_client_event_callback(const usb_host_client_event_msg_t *event_msg, void *arg); - static void usb_transfer_callback(usb_transfer_t *transfer); - - // Asynchronous USB operations - esp_err_t hid_get_report_async(uint8_t report_type, uint8_t report_id); - void process_cached_data(); -#endif + private: + // Internal helper methods + void cleanup(); }; // Base class for UPS protocols @@ -383,7 +185,7 @@ namespace esphome virtual bool detect() = 0; virtual bool initialize() = 0; virtual bool read_data(UpsData &data) = 0; - virtual UpsProtocol get_protocol_type() const = 0; + virtual DeviceInfo::DetectedProtocol get_protocol_type() const = 0; virtual std::string get_protocol_name() const = 0; // Beeper control methods @@ -407,47 +209,5 @@ namespace esphome }; - // Generic HID Protocol implementation - class GenericHidProtocol : public UpsProtocolBase - { - public: - explicit GenericHidProtocol(UpsHidComponent *parent) : UpsProtocolBase(parent) {} - - bool detect() override; - bool initialize() override; - bool read_data(UpsData &data) override; - UpsProtocol get_protocol_type() const override { return PROTOCOL_GENERIC_HID; } - std::string get_protocol_name() const override { return "Generic HID"; } - - // Test method overrides - bool start_battery_test_quick() override; - bool start_battery_test_deep() override; - bool stop_battery_test() override; - bool start_ups_test() override; - bool stop_ups_test() override; - - private: - // Report discovery and caching - std::set available_input_reports_; - std::set available_feature_reports_; - std::map report_sizes_; - - // Core methods - void enumerate_reports(); - bool read_report(uint8_t report_id, uint8_t* buffer, size_t& buffer_len); - - // Standard report parsers (based on NUT analysis) - void parse_power_summary(uint8_t* data, size_t len, UpsData& ups_data); - void parse_battery_status(uint8_t* data, size_t len, UpsData& ups_data); - void parse_present_status(uint8_t* data, size_t len, UpsData& ups_data); - void parse_general_status(uint8_t* data, size_t len, UpsData& ups_data); - void parse_voltage(uint8_t* data, size_t len, UpsData& ups_data, bool is_input); - void parse_load(uint8_t* data, size_t len, UpsData& ups_data); - void parse_input_sensitivity(uint8_t* data, size_t len, UpsData& ups_data, const char* style); - - // Heuristic parsing for unknown reports - bool parse_unknown_report(uint8_t* data, size_t len, UpsData& ups_data); - }; - } // namespace ups_hid } // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/usb_transport_factory.cpp b/components/ups_hid/usb_transport_factory.cpp new file mode 100644 index 0000000..99248c8 --- /dev/null +++ b/components/ups_hid/usb_transport_factory.cpp @@ -0,0 +1,27 @@ +#include "usb_transport_factory.h" +#include "usb_transport_interface.h" +#include "simulated_transport.h" +#ifdef USE_ESP32 +#include "esp32_usb_transport.h" +#endif + +namespace esphome { +namespace ups_hid { + +std::unique_ptr UsbTransportFactory::create(TransportType type, bool simulation_mode) { + if (simulation_mode || type == SIMULATION) { + return std::make_unique(); + } + +#ifdef USE_ESP32 + if (type == ESP32_HARDWARE) { + return std::make_unique(); + } +#endif + + // Default fallback to simulation if ESP32 not available + return std::make_unique(); +} + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/usb_transport_factory.h b/components/ups_hid/usb_transport_factory.h new file mode 100644 index 0000000..3ff34d3 --- /dev/null +++ b/components/ups_hid/usb_transport_factory.h @@ -0,0 +1,23 @@ +#pragma once + +#include "usb_transport_interface.h" + +namespace esphome { +namespace ups_hid { + +/** + * Factory for creating USB transport instances + */ +class UsbTransportFactory { +public: + enum TransportType { + ESP32_HARDWARE, + SIMULATION + }; + + static std::unique_ptr create(TransportType type, + bool simulation_mode = false); +}; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/usb_transport_interface.h b/components/ups_hid/usb_transport_interface.h new file mode 100644 index 0000000..84ec0ff --- /dev/null +++ b/components/ups_hid/usb_transport_interface.h @@ -0,0 +1,53 @@ +#pragma once + +#include "esp_err.h" +#include +#include +#include + +namespace esphome { +namespace ups_hid { + +/** + * Abstract USB Transport Interface + * + * Provides a clean abstraction over USB communication, allowing for + * different implementations (ESP32 hardware, simulation, etc.) + * + * Design Pattern: Strategy Pattern for transport selection + */ +class IUsbTransport { +public: + virtual ~IUsbTransport() = default; + + // Transport lifecycle + virtual esp_err_t initialize() = 0; + virtual esp_err_t deinitialize() = 0; + + // Device management + virtual bool is_connected() const = 0; + virtual uint16_t get_vendor_id() const = 0; + virtual uint16_t get_product_id() const = 0; + + // HID communication + virtual esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id, + uint8_t* data, size_t* data_len, + uint32_t timeout_ms = 1000) = 0; + + virtual esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, + const uint8_t* data, size_t data_len, + uint32_t timeout_ms = 1000) = 0; + + // String descriptors + virtual esp_err_t get_string_descriptor(uint8_t string_index, + std::string& result) = 0; + + // Error information + virtual std::string get_last_error() const = 0; +}; + +// Forward declaration - implementation in usb_transport_factory.h +class UsbTransportFactory; + +} // namespace ups_hid +} // namespace esphome \ No newline at end of file diff --git a/configs/README.md b/configs/README.md index 3065234..e6b28e9 100644 --- a/configs/README.md +++ b/configs/README.md @@ -1,56 +1,110 @@ # UPS HID Configuration Management -This directory provides a modular, maintainable approach to UPS HID device configuration using ESPHome packages. Instead of maintaining large, complex configuration files, you can compose configurations from reusable components. +This directory provides a modular, maintainable approach to UPS HID device configuration using ESPHome packages with the new Protocol Factory system. Instead of maintaining large, complex configuration files, you can compose configurations from reusable components. -## Modular Configuration Packages +## 📦 Modular Configuration Packages -### Core Packages +### **Core Packages** (Always Required) #### `base_ups.yaml` Essential foundation for all UPS devices: - ESP32-S3 hardware configuration - Network setup (WiFi, OTA, Web server) -- UPS HID component initialization -- Status LED with basic patterns -- Essential binary sensors for LED automation +- UPS HID component initialization with Protocol Factory +- Status LED with smart patterns +- Essential binary sensors: `online`, `on_battery`, `low_battery`, `fault` +- Essential text sensors: `status` (as "UPS Status"), `protocol` (as "Detected Protocol") #### `essential_sensors.yaml` -Core monitoring sensors available on all UPS protocols: -- Battery level, input/output voltage, load percentage -- Runtime remaining, basic device information -- System monitoring (uptime, WiFi signal) +Core monitoring sensors (5 sensors) available on all protocols: +- **Sensors**: `battery_level`, `input_voltage`, `output_voltage`, `load_percent`, `runtime` +- **Text Sensors**: `manufacturer`, `model` +- **Binary Sensors**: `charging`, `overload` +- **System Monitoring**: uptime, WiFi signal, IP address, ESPHome version - Compatible with APC, CyberPower, and Generic protocols +### **Optional Enhancement Packages** + #### `extended_sensors.yaml` -Advanced sensors for feature-rich devices: -- Battery voltage (actual and nominal) -- Input transfer limits and frequency -- UPS configuration parameters -- Power calculations and analysis -- Optimized for CyberPower devices +Advanced monitoring (17 additional sensors) for feature-rich devices: + +**Enhanced Voltage Monitoring**: +- `battery_voltage`, `battery_voltage_nominal`, `input_voltage_nominal` +- `input_transfer_low`, `input_transfer_high`, `frequency` + +**Power & Configuration**: +- `ups_realpower_nominal`, `ups_delay_shutdown`, `ups_delay_start`, `ups_delay_reboot` + +**Dynamic Timer Monitoring** (negative values = no active countdown): +- `ups_timer_shutdown`, `ups_timer_start`, `ups_timer_reboot` +- `battery_runtime_low` + +**Extended Device Information**: +- `serial_number`, `firmware_version`, `ups_beeper_status`, `input_sensitivity` +- `ups_mfr_date`, `battery_status`, `ups_firmware_aux` + +**Smart Template**: Calculated load power using HID nominal power when available #### `ups_controls.yaml` -Interactive control functionality: -- Beeper control (enable/disable/mute/test) -- Battery testing (quick/deep/stop) -- Panel testing (start/stop) -- Test result monitoring +Complete control functionality (10 buttons + test monitoring): -### Device-Specific Packages +**Beeper Control**: `enable`, `disable`, `mute`, `test` +**UPS Testing**: `battery_quick`, `battery_deep`, `battery_stop`, `ups_test`, `ups_stop` +**Test Monitoring**: `ups_test_result` text sensor + +### **Device-Specific Optimization Packages** #### `device_types/apc_backups_es.yaml` APC Back-UPS ES series optimizations: -- Slower update intervals (APC devices need more time) -- APC-specific power calculations (405W nominal) -- Enhanced protocol debugging -- Device-specific status monitoring +- Slower update intervals (15s - APC devices need more time) +- APC-specific power calculations (405W nominal for ES 700) +- Enhanced protocol debugging (`ups_hid.apc: DEBUG`) +- Fixed device-specific script references #### `device_types/cyberpower_cp1500.yaml` CyberPower CP1500 series optimizations: -- Fast update intervals (CyberPower responds quickly) -- Advanced threshold monitoring -- Extended device information -- Rich sensor data utilization +- Fast update intervals (10s - CyberPower responds quickly) +- **Additional sensor**: `battery_charge_low` threshold +- **Enhanced power calculation**: Uses HID nominal power when available (900W default) +- **Device-specific text sensor**: `battery_mfr_date` (separate from UPS date) +- Rich monitoring script with comprehensive status logging + +--- + +## 📊 **Complete Sensor Summary** + +### **Package Composition Options:** + +| Configuration Level | Packages Included | Total Sensors | Use Case | +|-------------------|------------------|--------------|----------| +| **Minimal** | `base_ups` + `essential_sensors` | **9 sensors** | Basic monitoring | +| **Complete** | + `extended_sensors` + `ups_controls` | **27 sensors + 10 controls** | Full featured | +| **Device-Optimized** | + device-specific package | **28+ sensors + 10 controls** | Production ready | + +### **Sensor Breakdown by Type:** + +#### **Numeric Sensors** (22 total available): +- **Essential (5)**: battery_level, input_voltage, output_voltage, load_percent, runtime +- **Extended (17)**: All enhanced voltage/power/timer/threshold monitoring + +#### **Text Sensors** (10 total available): +- **Base (2)**: status, protocol *(in base_ups.yaml)* +- **Essential (2)**: manufacturer, model +- **Extended (6)**: serial_number, firmware_version, ups_beeper_status, input_sensitivity, ups_mfr_date, battery_status, ups_firmware_aux +- **Controls (1)**: ups_test_result *(in ups_controls.yaml)* +- **Device-Specific (+1)**: battery_mfr_date *(CyberPower only)* + +#### **Binary Sensors** (6 total): +- **Base (4)**: online, on_battery, low_battery, fault +- **Essential (2)**: charging, overload + +#### **Button Controls** (10 total, all in ups_controls.yaml): +- **Beeper (4)**: enable, disable, mute, test +- **Testing (6)**: battery_quick, battery_deep, battery_stop, ups_test, ups_stop + +#### **Smart Templates** (2 calculated sensors): +- **Generic**: UPS Load Power (uses HID data when available) +- **Device-Specific**: Device-optimized power calculations ## Testing Configurations diff --git a/configs/base_ups.yaml b/configs/base_ups.yaml index 0e6563b..951258b 100644 --- a/configs/base_ups.yaml +++ b/configs/base_ups.yaml @@ -64,7 +64,8 @@ ups_hid: id: ups_monitor update_interval: ${update_interval} protocol_timeout: ${protocol_timeout} - auto_detect_protocol: true + protocol: auto + fallback_nominal_voltage: 230V # European standard (IEC 60038) for better international compatibility simulation_mode: ${simulation_mode} # Status LED configuration diff --git a/configs/device_types/apc_backups_es.yaml b/configs/device_types/apc_backups_es.yaml index cfb307d..b587be5 100644 --- a/configs/device_types/apc_backups_es.yaml +++ b/configs/device_types/apc_backups_es.yaml @@ -16,7 +16,7 @@ ups_hid: id: ups_monitor update_interval: ${update_interval} protocol_timeout: ${protocol_timeout} - auto_detect_protocol: true + protocol: apc simulation_mode: ${simulation_mode} # Uncomment if auto-detection fails: # usb_vendor_id: 0x051D diff --git a/configs/device_types/cyberpower_cp1500.yaml b/configs/device_types/cyberpower_cp1500.yaml index 3f47b67..4e0f3a0 100644 --- a/configs/device_types/cyberpower_cp1500.yaml +++ b/configs/device_types/cyberpower_cp1500.yaml @@ -16,7 +16,7 @@ ups_hid: id: ups_monitor update_interval: ${update_interval} protocol_timeout: ${protocol_timeout} - auto_detect_protocol: true + protocol: cyberpower simulation_mode: ${simulation_mode} # Uncomment if auto-detection fails: # usb_vendor_id: 0x0764 @@ -29,9 +29,9 @@ logger: ups_hid: DEBUG ups_hid.cyberpower: DEBUG -# CyberPower-specific threshold sensors +# CyberPower-specific sensors (complement extended_sensors.yaml) sensor: - # Battery threshold monitoring (available on CyberPower) + # CyberPower-specific battery threshold (not in extended pack) - platform: ups_hid ups_hid_id: ups_monitor name: "Battery Charge Low Threshold" @@ -42,72 +42,37 @@ sensor: state_class: measurement accuracy_decimals: 0 - - platform: ups_hid - ups_hid_id: ups_monitor - name: "Battery Runtime Low Threshold" - id: battery_runtime_low - type: battery_runtime_low - unit_of_measurement: "min" - device_class: duration + # CyberPower power calculation with actual HID nominal power + - platform: template + name: "UPS Load Power (CyberPower)" + id: ups_load_power_cp + unit_of_measurement: "W" + device_class: power state_class: measurement - accuracy_decimals: 0 + accuracy_decimals: 1 + lambda: |- + if (!std::isnan(id(load_percentage).state)) { + float cp_max_power = 900.0; // CP1500 default: 900W + + // Use HID nominal power if available (from extended sensors) + if (!std::isnan(id(ups_realpower_nominal).state)) { + cp_max_power = id(ups_realpower_nominal).state; + } + + return (cp_max_power * id(load_percentage).state) / 100.0; + } + return NAN; + update_interval: 30s - # CyberPower-specific timer values - - platform: ups_hid - ups_hid_id: ups_monitor - name: "UPS Timer Reboot" - id: ups_timer_reboot - type: ups_timer_reboot - unit_of_measurement: "s" - device_class: duration - state_class: measurement - accuracy_decimals: 0 - - - platform: ups_hid - ups_hid_id: ups_monitor - name: "UPS Timer Shutdown" - id: ups_timer_shutdown - type: ups_timer_shutdown - unit_of_measurement: "s" - device_class: duration - state_class: measurement - accuracy_decimals: 0 - - - platform: ups_hid - ups_hid_id: ups_monitor - name: "UPS Timer Start" - id: ups_timer_start - type: ups_timer_start - unit_of_measurement: "s" - device_class: duration - state_class: measurement - accuracy_decimals: 0 - -# CyberPower-specific enhanced device info +# CyberPower-specific text sensors (complement extended_sensors.yaml) text_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - name: "Battery Status" - id: battery_status - type: battery_status - - - platform: ups_hid - ups_hid_id: ups_monitor - name: "Battery Type" - id: battery_type - type: battery_type - + # Separate battery vs UPS manufacture dates (CyberPower provides both) - platform: ups_hid ups_hid_id: ups_monitor name: "Battery Manufacture Date" id: battery_mfr_date type: battery_mfr_date - - - platform: ups_hid - ups_hid_id: ups_monitor - name: "UPS Manufacture Date" - id: ups_mfr_date - type: ups_mfr_date + icon: "mdi:calendar-battery" # CyberPower-specific monitoring scripts script: @@ -120,7 +85,7 @@ script: - "id(battery_voltage).state" - "id(battery_voltage_nominal).state" - "id(load_percentage).state" - - "id(ups_load_power).state" + - "id(ups_load_power_cp).state" - "id(ups_realpower_nominal).state" - "id(input_voltage).state" - "id(runtime_remaining).state" diff --git a/configs/essential_sensors.yaml b/configs/essential_sensors.yaml index fef3830..c42a0a3 100644 --- a/configs/essential_sensors.yaml +++ b/configs/essential_sensors.yaml @@ -79,6 +79,7 @@ text_sensor: id: ups_model type: model + - platform: wifi_info ip_address: name: "IP Address" diff --git a/configs/examples/protocol-selection-demo.yaml b/configs/examples/protocol-selection-demo.yaml new file mode 100644 index 0000000..10d7933 --- /dev/null +++ b/configs/examples/protocol-selection-demo.yaml @@ -0,0 +1,52 @@ +# Protocol Selection Demo Configuration +# Demonstrates the new manual protocol selection feature + +substitutions: + name: "ups-protocol-demo" + friendly_name: "Protocol Demo" + simulation_mode: "true" + +esphome: + name: "${name}" + friendly_name: "${friendly_name}" + comment: "Demonstration of manual protocol selection" + +# Use base configuration package +packages: + base_ups: !include ../base_ups.yaml + essential: !include ../essential_sensors.yaml + +# Protocol Selection Examples +ups_hid: + id: ups_monitor + update_interval: 10s + protocol_timeout: 15s + simulation_mode: ${simulation_mode} + + # Protocol Options (uncomment one to test): + protocol: auto # Default: Auto-detect based on USB vendor ID + # protocol: apc # Force APC HID Protocol + # protocol: cyberpower # Force CyberPower HID Protocol + # protocol: generic # Force Generic HID Protocol + +# Enhanced logging to see protocol selection +logger: + level: DEBUG + logs: + ups_hid: DEBUG + +# Demo script to show active protocol +script: + - id: protocol_demo + then: + - logger.log: + format: "PROTOCOL DEMO - Active Protocol: %s" + args: + - "id(ups_protocol).state.c_str()" + level: INFO + +# Run demo every 60 seconds +interval: + - interval: 60s + then: + - script.execute: protocol_demo \ No newline at end of file diff --git a/configs/extended_sensors.yaml b/configs/extended_sensors.yaml index 0ed6fc7..274f39f 100644 --- a/configs/extended_sensors.yaml +++ b/configs/extended_sensors.yaml @@ -95,6 +95,61 @@ sensor: state_class: measurement accuracy_decimals: 0 + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Delay Reboot" + id: ups_delay_reboot + type: ups_delay_reboot + unit_of_measurement: "s" + device_class: duration + state_class: measurement + accuracy_decimals: 0 + + # Enhanced dynamic timer sensors (countdown when active) + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Timer Shutdown" + id: ups_timer_shutdown + type: ups_timer_shutdown + unit_of_measurement: "s" + device_class: duration + state_class: measurement + accuracy_decimals: 0 + # Negative values indicate no active countdown + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Timer Start" + id: ups_timer_start + type: ups_timer_start + unit_of_measurement: "s" + device_class: duration + state_class: measurement + accuracy_decimals: 0 + # Negative values indicate no active countdown + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Timer Reboot" + id: ups_timer_reboot + type: ups_timer_reboot + unit_of_measurement: "s" + device_class: duration + state_class: measurement + accuracy_decimals: 0 + # Negative values indicate no active countdown + + # Enhanced battery threshold monitoring + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Runtime Low Threshold" + id: battery_runtime_low + type: battery_runtime_low + unit_of_measurement: "min" + device_class: duration + state_class: measurement + accuracy_decimals: 0 + # Calculated power consumption - platform: template name: "UPS Load Power" @@ -141,4 +196,26 @@ text_sensor: ups_hid_id: ups_monitor name: "Input Sensitivity" id: input_sensitivity - type: input_sensitivity \ No newline at end of file + type: input_sensitivity + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Manufacture Date" + id: ups_manufacture_date + type: ups_mfr_date + icon: "mdi:calendar-clock" + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Status" + id: battery_status + type: battery_status + icon: "mdi:battery-heart" + + # Additional enhanced text sensors from protocols + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Firmware Auxiliary" + id: firmware_aux + type: ups_firmware_aux + icon: "mdi:chip" \ No newline at end of file diff --git a/configs/regional/european_defaults.yaml b/configs/regional/european_defaults.yaml new file mode 100644 index 0000000..4fe0c3f --- /dev/null +++ b/configs/regional/european_defaults.yaml @@ -0,0 +1,66 @@ +# European Voltage Defaults +# Configuration template for European electrical standards (IEC 60038) +# Use this as a base for European installations + +substitutions: + # European electrical standards + nominal_voltage: "230V" # Standard European single-phase voltage (IEC 60038) + frequency: "50Hz" # European frequency standard + + # Regional timezone examples (adjust for your location) + timezone: "Europe/Berlin" # Germany + # timezone: "Europe/London" # United Kingdom + # timezone: "Europe/Paris" # France + # timezone: "Europe/Rome" # Italy + # timezone: "Europe/Madrid" # Spain + +# Base UPS configuration with European defaults +ups_hid: + id: ups_monitor + update_interval: 30s + protocol_timeout: 15s + protocol: auto + fallback_nominal_voltage: ${nominal_voltage} + simulation_mode: false + +# Time configuration with European timezone +time: + - platform: sntp + id: sntp_time + timezone: ${timezone} + servers: + - "pool.ntp.org" + - "time.nist.gov" + +# Logging optimized for European users +logger: + level: INFO + logs: + ups_hid: INFO + +# WiFi configuration template +wifi: + # Configure your WiFi credentials + ssid: !secret wifi_ssid + password: !secret wifi_password + + # European WiFi channel optimization (1-13 allowed in EU) + channel: 6 + + # Enable fast connect for better reconnection + fast_connect: true + + # Access point fallback (if main WiFi fails) + ap: + ssid: "${friendly_name} AP" + password: !secret ap_password + +# Optional: Home Assistant API with encryption +api: + encryption: + key: !secret api_encryption_key + +# Optional: Over-the-air updates +ota: + - platform: esphome + password: !secret ota_password \ No newline at end of file diff --git a/configs/regional/north_american_defaults.yaml b/configs/regional/north_american_defaults.yaml new file mode 100644 index 0000000..49da2a6 --- /dev/null +++ b/configs/regional/north_american_defaults.yaml @@ -0,0 +1,65 @@ +# North American Voltage Defaults +# Configuration template for North American electrical standards (NEMA) +# Use this as a base for US/Canada installations + +substitutions: + # North American electrical standards + nominal_voltage: "120V" # Standard North American single-phase voltage + frequency: "60Hz" # North American frequency standard + + # Regional timezone examples (adjust for your location) + timezone: "America/New_York" # Eastern Time + # timezone: "America/Chicago" # Central Time + # timezone: "America/Denver" # Mountain Time + # timezone: "America/Los_Angeles" # Pacific Time + +# Base UPS configuration with North American defaults +ups_hid: + id: ups_monitor + update_interval: 30s + protocol_timeout: 15s + protocol: auto + fallback_nominal_voltage: ${nominal_voltage} + simulation_mode: false + +# Time configuration with North American timezone +time: + - platform: sntp + id: sntp_time + timezone: ${timezone} + servers: + - "pool.ntp.org" + - "time.nist.gov" + +# Logging optimized for North American users +logger: + level: INFO + logs: + ups_hid: INFO + +# WiFi configuration template +wifi: + # Configure your WiFi credentials + ssid: !secret wifi_ssid + password: !secret wifi_password + + # North American WiFi channel optimization (1-11 allowed in US/Canada) + channel: 6 + + # Enable fast connect for better reconnection + fast_connect: true + + # Access point fallback (if main WiFi fails) + ap: + ssid: "${friendly_name} AP" + password: !secret ap_password + +# Optional: Home Assistant API with encryption +api: + encryption: + key: !secret api_encryption_key + +# Optional: Over-the-air updates +ota: + - platform: esphome + password: !secret ota_password \ No newline at end of file diff --git a/configs/testing/basic_test.yaml b/configs/testing/basic_test.yaml index c370a9a..19e6c38 100644 --- a/configs/testing/basic_test.yaml +++ b/configs/testing/basic_test.yaml @@ -23,7 +23,7 @@ ups_hid: id: ups_monitor update_interval: 5s protocol_timeout: 10s - auto_detect_protocol: true + protocol: auto simulation_mode: ${simulation_mode} # Enhanced logging for testing diff --git a/configs/testing/beeper_test.yaml b/configs/testing/beeper_test.yaml index ddfd7d6..7751965 100644 --- a/configs/testing/beeper_test.yaml +++ b/configs/testing/beeper_test.yaml @@ -25,7 +25,7 @@ ups_hid: id: ups_monitor update_interval: 5s protocol_timeout: 10s - auto_detect_protocol: true + protocol: auto simulation_mode: ${simulation_mode} # Beeper-focused logging diff --git a/configs/testing/minimal_simulation.yaml b/configs/testing/minimal_simulation.yaml index 4f3281e..4ac2014 100644 --- a/configs/testing/minimal_simulation.yaml +++ b/configs/testing/minimal_simulation.yaml @@ -38,7 +38,7 @@ ups_hid: id: ups_monitor update_interval: 10s protocol_timeout: 5s - auto_detect_protocol: true + protocol: auto simulation_mode: true # Required platform components (fix compilation errors) diff --git a/configs/testing/simulation_test.yaml b/configs/testing/simulation_test.yaml index a15f5e2..39557c1 100644 --- a/configs/testing/simulation_test.yaml +++ b/configs/testing/simulation_test.yaml @@ -26,7 +26,7 @@ ups_hid: id: ups_monitor update_interval: 5s # Fast updates for demo protocol_timeout: 5s - auto_detect_protocol: true + protocol: auto simulation_mode: ${simulation_mode} # Reduced logging for simulation