From e23f0f9acf4e8e3b577d16446ee307c7d723565c Mon Sep 17 00:00:00 2001 From: bullshit Date: Sun, 17 Aug 2025 23:20:43 +0200 Subject: [PATCH] refactor(ups-hid): switch to dynamic value reading implementing the devices descriptors Signed-off-by: bullshit --- components/ups_hid/README.md | 56 +- components/ups_hid/apc_hid_protocol.cpp | 747 +++++++++++++++++++- components/ups_hid/apc_hid_protocol.h | 20 + components/ups_hid/cyberpower_protocol.cpp | 336 ++++++++- components/ups_hid/cyberpower_protocol.h | 7 + components/ups_hid/generic_hid_protocol.cpp | 90 ++- components/ups_hid/sensor.py | 37 + components/ups_hid/text_sensor.py | 7 + components/ups_hid/ups_hid.cpp | 166 +++++ components/ups_hid/ups_hid.h | 32 + full-test.yaml | 167 ++++- minimal-test.yaml | 59 ++ 12 files changed, 1671 insertions(+), 53 deletions(-) diff --git a/components/ups_hid/README.md b/components/ups_hid/README.md index cd360e4..88f25e7 100644 --- a/components/ups_hid/README.md +++ b/components/ups_hid/README.md @@ -246,20 +246,38 @@ binary_sensor: device_class: problem text_sensor: + # Device identification (available on all protocols) - platform: ups_hid ups_hid_id: ups_monitor type: manufacturer name: "UPS Manufacturer" + icon: "mdi:factory" - platform: ups_hid ups_hid_id: ups_monitor type: model name: "UPS Model" + icon: "mdi:information-outline" + + # Device information (protocol-specific) + - platform: ups_hid + ups_hid_id: ups_monitor + type: serial_number + name: "UPS Serial Number" + icon: "mdi:identifier" + - platform: ups_hid + ups_hid_id: ups_monitor + type: firmware_version + name: "UPS Firmware Version" + icon: "mdi:chip" + + # Communication status - platform: ups_hid ups_hid_id: ups_monitor type: protocol - name: "UPS Protocol" + name: "Detected Protocol" + icon: "mdi:connection" - platform: ups_hid ups_hid_id: ups_monitor @@ -536,12 +554,36 @@ text_sensor: ``` **Available text sensor types:** -- `manufacturer`: UPS manufacturer name -- `model`: UPS model number/name -- `serial_number`: UPS serial number (if available) -- `firmware_version`: UPS firmware version (if available) -- `protocol`: Currently detected protocol name -- `status`: Combined UPS status text + +### Device Identification (Available on all protocols): +- `manufacturer`: UPS manufacturer name (e.g., "APC", "CPS", "Generic") +- `model`: UPS model number/name (e.g., "Back-UPS ES", "CP1500EPFCLCD") +- `protocol`: Currently detected protocol name (e.g., "APC HID Protocol") +- `status`: Combined UPS status text (e.g., "Online Charging") + +### Device Information (Protocol-specific support): +- `serial_number`: UPS serial number + - ✅ **CyberPower**: Full HID report parsing (e.g., "CRMLX2000234") + - ⚠️ **APC**: Basic support (may be limited by device) + - ⚠️ **Generic**: Device-dependent parsing +- `firmware_version`: UPS firmware version + - ✅ **CyberPower**: Full HID report parsing (e.g., "CR01505B4") + - ⚠️ **APC**: Basic support (may be limited by device) + - ⚠️ **Generic**: Device-dependent parsing + +### HID Configuration (Protocol-specific support): +- `ups_beeper_status`: UPS beeper/alarm configuration + - ✅ **CyberPower**: Full parsing ("enabled", "disabled", "muted") + - ⚠️ **APC**: Basic support (may be limited by device) + - ⚠️ **Generic**: Device-dependent parsing +- `input_sensitivity`: UPS input voltage sensitivity setting + - ✅ **CyberPower**: Full parsing ("high", "normal", "low") + - ⚠️ **APC**: Basic support (may be limited by device) + - ⚠️ **Generic**: Device-dependent parsing + +**Legend**: ✅ = Full Support, ⚠️ = Basic/Limited Support + +> **Note**: Device information availability depends on the UPS model and protocol implementation. CyberPower devices provide the most comprehensive device information through dedicated HID reports. ## Advanced Configuration diff --git a/components/ups_hid/apc_hid_protocol.cpp b/components/ups_hid/apc_hid_protocol.cpp index 610ca12..f24cc08 100644 --- a/components/ups_hid/apc_hid_protocol.cpp +++ b/components/ups_hid/apc_hid_protocol.cpp @@ -2,6 +2,9 @@ #include "esphome/core/log.h" #include "esphome/core/helpers.h" #include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_err.h" namespace esphome { namespace ups_hid { @@ -20,6 +23,12 @@ static const uint8_t APC_REPORT_ID_LOAD = 0x07; // UPS load information static const uint8_t APC_REPORT_ID_VOLTAGE = 0x0e; // Input/output voltage static const uint8_t APC_REPORT_ID_BEEPER = 0x1f; // Beeper control +// Additional APC HID Reports for device information (based on NUT apc-hid.c) +static const uint8_t APC_REPORT_ID_DEVICE_INFO = 0x03; // Device information +static const uint8_t APC_REPORT_ID_FIRMWARE = 0x04; // Firmware version +static const uint8_t APC_REPORT_ID_AUDIBLE_ALARM = 0x18; // Audible alarm control (beeper) +static const uint8_t APC_REPORT_ID_SENSITIVITY = 0x35; // Input sensitivity (APCSensitivity) + // APC-specific date conversion (hex-as-decimal format) static std::string convert_apc_date(uint32_t apc_date) { if (apc_date == 0) return "Unknown"; @@ -95,11 +104,8 @@ bool ApcHidProtocol::read_data(UpsData &data) { bool success = false; - // Set manufacturer and model information (based on NUT apc-hid.c format_mfr/format_model) - data.manufacturer = "APC"; - data.model = "Back-UPS ES"; // Generic model name for APC VID=0x051d, PID=0x0002 - - // CRITICAL FIX: Read NUT-compatible reports in the correct order + // CRITICAL FIX: Read NUT-compatible reports in the correct order first + // Device info will be read after successful HID communication // 1. Read PowerSummary report 0x0C (MOST IMPORTANT - battery % + runtime) HidReport power_summary_report; @@ -159,8 +165,55 @@ bool ApcHidProtocol::read_data(UpsData &data) { data.frequency = NAN; ESP_LOGV(APC_HID_TAG, "Frequency: Not available on this UPS model"); + // TIMING FIX: Only read USB string descriptors after successful HID communication + // This ensures the device is ready and responsive before attempting descriptor access if (success) { + ESP_LOGD(APC_HID_TAG, "APC HID data read successful, now reading device info..."); + + // Read manufacturer from USB Manufacturer string descriptor (index 3) + // NUT shows: UPS.PowerSummary.iManufacturer, Value: 3 → Manufacturer: "APC" + std::string manufacturer_string; + 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()); + } else { + data.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)); + } + + // Read model from USB Product string descriptor (index 1) + // NUT shows: Product: "Back-UPS ES 700G" but need to parse out firmware info + std::string product_string; + esp_err_t prod_ret = parent_->usb_get_string_descriptor(1, product_string); + + if (prod_ret == ESP_OK && !product_string.empty()) { + // Parse out just the model name, removing firmware info like "FW:841.H1 .D USB FW:H1" + std::string model_name = product_string; + size_t fw_pos = model_name.find(" FW:"); + 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()); + } else { + data.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)); + } + + // Read additional device information (serial, firmware, etc.) + read_device_information(data); + + // Read missing dynamic values identified from NUT analysis + read_missing_dynamic_values(data); + ESP_LOGV(APC_HID_TAG, "Successfully read UPS 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(); } return success; @@ -591,5 +644,689 @@ void ApcHidProtocol::parse_load_report(const HidReport &report, UpsData &data) { ESP_LOGI(APC_HID_TAG, "Load percentage: %.0f%%", data.load_percent); } +void ApcHidProtocol::read_device_information(UpsData &data) { + ESP_LOGD(APC_HID_TAG, "Reading APC device information..."); + + // Try to read USB string descriptors first (most reliable for APC devices) + // Based on NUT apc_format_serial/apc_format_model implementation + + // Read serial number from standard USB HID report (same as CyberPower) + // NUT debug shows: UPS.PowerSummary.iSerialNumber, ReportID: 0x02, Value: 2 + HidReport serial_report; + if (read_hid_report(0x02, serial_report)) { + parse_serial_number_report(serial_report, data); + } + + // Try reading firmware version + HidReport firmware_report; + if (read_hid_report(APC_REPORT_ID_FIRMWARE, firmware_report)) { + parse_firmware_version_report(firmware_report, data); + } + + // Try reading beeper status + HidReport beeper_report; + if (read_hid_report(APC_REPORT_ID_AUDIBLE_ALARM, beeper_report)) { + parse_beeper_status_report(beeper_report, data); + } + + // Try reading input sensitivity + HidReport sensitivity_report; + if (read_hid_report(APC_REPORT_ID_SENSITIVITY, sensitivity_report)) { + parse_input_sensitivity_report(sensitivity_report, data); + } + + ESP_LOGD(APC_HID_TAG, "Device information reading completed"); +} + +void ApcHidProtocol::parse_serial_number_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "Serial number report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug shows: UPS.PowerSummary.iSerialNumber, ReportID: 0x02, Value: 2 + // This is a USB string descriptor index, not the actual serial number + uint8_t string_index = report.data[1]; + + ESP_LOGD(APC_HID_TAG, "Serial number string descriptor index: %d", string_index); + + // Use real USB string descriptor reading - this will get the actual APC serial number + // NUT shows: APC real serial = "5B1738T47814" + std::string actual_serial; + 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; + ESP_LOGI(APC_HID_TAG, "Successfully read APC serial number from USB string descriptor %d: \"%s\"", + string_index, data.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(); + ESP_LOGW(APC_HID_TAG, "Leaving serial number unset due to USB string descriptor failure"); + } +} + +void ApcHidProtocol::parse_firmware_version_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 2) { + ESP_LOGV(APC_HID_TAG, "Firmware version report too short: %zu bytes", report.data.size()); + return; + } + + // DYNAMIC FIRMWARE VERSION: Check if report contains a string descriptor index + // Similar to serial number parsing - some APC devices store firmware info in USB string descriptors + uint8_t first_byte = report.data[1]; + + // CRITICAL FIX: Skip manufacturer string descriptor (index 3) which contains "APC" + // From the log we see that index 3 = "APC" (manufacturer), not firmware + if (first_byte > 0 && first_byte <= 15 && first_byte != 3) { + ESP_LOGD(APC_HID_TAG, "Trying firmware as USB string descriptor index: %d", first_byte); + + std::string firmware_from_usb; + 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) { + // Successfully read firmware from USB string descriptor (not manufacturer) + data.firmware_version = firmware_from_usb; + + // Extract auxiliary firmware info (NUT shows ups.firmware.aux: "O4 ") + // Format: "871.O4 .I" → main="871.O4" aux="O4" + size_t dot_pos = firmware_from_usb.find('.'); + if (dot_pos != std::string::npos && dot_pos < firmware_from_usb.length() - 1) { + 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()); + } + } + + ESP_LOGI(APC_HID_TAG, "Successfully read APC firmware from USB string descriptor %d: \"%s\"", + first_byte, data.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", + first_byte, esp_err_to_name(ret)); + } + } else if (first_byte == 3) { + ESP_LOGD(APC_HID_TAG, "Skipping manufacturer string descriptor index 3 for firmware"); + } + + // FALLBACK 1 (PRIORITY): Parse firmware from the USB Product string descriptor (index 1) + // This is the most reliable method for APC devices based on the log + // Log shows: USB string descriptor 1: "Back-UPS ES 700G FW:871.O4 .I USB FW:O4" + ESP_LOGD(APC_HID_TAG, "Trying to read firmware from USB Product string descriptor (index 1)"); + std::string product_with_firmware; + esp_err_t product_ret = parent_->usb_get_string_descriptor(1, product_with_firmware); + + if (product_ret == ESP_OK && !product_with_firmware.empty() && + product_with_firmware.find("FW:") != std::string::npos) { + size_t fw_start = product_with_firmware.find("FW:"); + if (fw_start != std::string::npos) { + // Extract firmware info from product string - look for pattern "FW:871.O4" + std::string extracted_fw = product_with_firmware.substr(fw_start); + size_t fw_end = extracted_fw.find(' ', 3); // Find space after "FW:xxx" + if (fw_end != std::string::npos) { + extracted_fw = extracted_fw.substr(0, fw_end); + } + data.firmware_version = extracted_fw; + + // Extract auxiliary firmware info from product string + // Format: "FW:871.O4" → aux="O4" + size_t fw_dot_pos = extracted_fw.find('.'); + if (fw_dot_pos != std::string::npos && fw_dot_pos < extracted_fw.length() - 1) { + 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()); + } + } + + ESP_LOGI(APC_HID_TAG, "Successfully extracted firmware from USB Product descriptor: \"%s\"", + data.firmware_version.c_str()); + return; + } + } else { + ESP_LOGD(APC_HID_TAG, "Failed to read USB Product descriptor or no FW info found: %s", + esp_err_to_name(product_ret)); + } + + // 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 (fw_start != std::string::npos) { + std::string model_fw = data.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()); + return; + } + } + + // FALLBACK 2: Try to extract ASCII firmware string from HID report data + std::string firmware_str; + for (size_t i = 1; i < report.data.size() && report.data[i] != 0; i++) { + if (report.data[i] >= 32 && report.data[i] <= 126) { // Printable ASCII + firmware_str += static_cast(report.data[i]); + } + } + + 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()); + return; + } + + // FALLBACK 3: Try to parse binary version data as last resort + if (report.data.size() >= 3) { + 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()); + } else { + // No firmware version could be determined + data.firmware_version.clear(); + ESP_LOGW(APC_HID_TAG, "Unable to determine firmware version from any source"); + } +} + +void ApcHidProtocol::parse_beeper_status_report(const HidReport &report, UpsData &data) { + // Parse APC beeper status based on NUT UPS.PowerSummary.AudibleAlarmControl + // NUT debug shows: ReportID: 0x18, Value: 2 (AudibleAlarmControl) + // APC beeper mapping: 1=disabled, 2=enabled, 3=muted + if (report.data.size() < 2) { + ESP_LOGV(APC_HID_TAG, "Beeper status report too short: %zu bytes", report.data.size()); + return; + } + + uint8_t beeper_value = report.data[1]; + ESP_LOGD(APC_HID_TAG, "Raw APC beeper from report 0x18: 0x%02X (%d)", beeper_value, beeper_value); + + // DYNAMIC BEEPER STATUS MAPPING: Handle known APC values with intelligent fallbacks + switch (beeper_value) { + case 1: + data.ups_beeper_status = "disabled"; + ESP_LOGI(APC_HID_TAG, "APC beeper status: disabled (raw: %d)", beeper_value); + break; + case 2: + data.ups_beeper_status = "enabled"; + ESP_LOGI(APC_HID_TAG, "APC beeper status: enabled (raw: %d)", beeper_value); + break; + case 3: + data.ups_beeper_status = "muted"; + ESP_LOGI(APC_HID_TAG, "APC beeper status: muted (raw: %d)", beeper_value); + break; + case 0: + data.ups_beeper_status = "disabled"; + ESP_LOGI(APC_HID_TAG, "APC beeper status: disabled (zero value) (raw: %d)", beeper_value); + break; + default: + // DYNAMIC HANDLING: For unknown values, provide better context + if (beeper_value >= 100) { + // Large values might indicate report format issue + ESP_LOGW(APC_HID_TAG, "Unexpected large APC beeper value: %d (0x%02X) - possible report format issue", + beeper_value, beeper_value); + + // Try alternative parsing - some APC models might use different byte + if (report.data.size() >= 3) { + uint8_t alt_value = report.data[2]; + ESP_LOGD(APC_HID_TAG, "Trying alternative beeper parsing from byte[2]: %d", alt_value); + + 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; + } + ESP_LOGI(APC_HID_TAG, "APC beeper status (alt parsing): %s (raw: %d)", + data.ups_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 + 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"; + 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"; + ESP_LOGW(APC_HID_TAG, "Unknown APC beeper value %d, using boolean interpretation: %s", + beeper_value, data.ups_beeper_status.c_str()); + } + } + break; + } +} + +void ApcHidProtocol::parse_input_sensitivity_report(const HidReport &report, UpsData &data) { + // Parse APC input sensitivity based on NUT UPS.Input.APCSensitivity + // NUT debug shows: ReportID: 0x35, Value: 1 (APCSensitivity) + // APC sensitivity mapping: 0=high, 1=normal/medium, 2=low + if (report.data.size() < 2) { + ESP_LOGV(APC_HID_TAG, "Input sensitivity report too short: %zu bytes", report.data.size()); + return; + } + + uint8_t sensitivity_value = report.data[1]; + ESP_LOGD(APC_HID_TAG, "Raw APC sensitivity from report 0x35: 0x%02X (%d)", sensitivity_value, sensitivity_value); + + // DYNAMIC SENSITIVITY MAPPING: Handle known APC values and provide intelligent fallbacks + switch (sensitivity_value) { + case 0: + data.input_sensitivity = "high"; + ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: high (raw: %d)", sensitivity_value); + break; + case 1: + data.input_sensitivity = "normal"; + ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: normal (raw: %d)", sensitivity_value); + break; + case 2: + data.input_sensitivity = "low"; + ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: low (raw: %d)", sensitivity_value); + break; + default: + // DYNAMIC HANDLING: For unknown values, provide more context and try to infer + if (sensitivity_value >= 100) { + // Large values might indicate different encoding or report format issue + ESP_LOGW(APC_HID_TAG, "Unexpected large sensitivity value: %d (0x%02X) - possible report format issue", + sensitivity_value, sensitivity_value); + + // Try alternative parsing - some APC models might use different byte + if (report.data.size() >= 3) { + uint8_t alt_value = report.data[2]; + ESP_LOGD(APC_HID_TAG, "Trying alternative sensitivity parsing from byte[2]: %d", alt_value); + + 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; + } + ESP_LOGI(APC_HID_TAG, "APC Input sensitivity (alt parsing): %s (raw: %d)", + data.input_sensitivity.c_str(), sensitivity_value); + return; + } + } + + data.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"; + ESP_LOGI(APC_HID_TAG, "APC Input sensitivity: auto (raw: %d)", sensitivity_value); + } else { + data.input_sensitivity = "unknown"; + ESP_LOGW(APC_HID_TAG, "Unknown APC sensitivity value: %d - please report this for future support", + sensitivity_value); + } + } + break; + } +} + +void ApcHidProtocol::read_missing_dynamic_values(UpsData &data) { + ESP_LOGD(APC_HID_TAG, "Reading APC missing dynamic values from NUT analysis..."); + + // 1. Battery voltage nominal (Report 0x25) + HidReport battery_voltage_nominal_report; + if (read_hid_report(0x25, battery_voltage_nominal_report)) { + parse_battery_voltage_nominal_report(battery_voltage_nominal_report, data); + } + + // 1b. Battery voltage actual (Report 0x26) - MISSING from original implementation + HidReport battery_voltage_report; + if (read_hid_report(0x26, battery_voltage_report)) { + parse_battery_voltage_actual_report(battery_voltage_report, data); + } + + // 2. Input voltage nominal (Report 0x30) + HidReport input_voltage_nominal_report; + if (read_hid_report(0x30, input_voltage_nominal_report)) { + parse_input_voltage_nominal_report(input_voltage_nominal_report, data); + } + + // 3. Input transfer limits (Reports 0x32, 0x33) + HidReport input_transfer_low_report; + if (read_hid_report(0x32, input_transfer_low_report)) { + parse_input_transfer_limits_report(input_transfer_low_report, data); + } + + HidReport input_transfer_high_report; + if (read_hid_report(0x33, input_transfer_high_report)) { + parse_input_transfer_limits_report(input_transfer_high_report, data); + } + + // 4. Battery runtime low threshold (Report 0x24) + HidReport battery_runtime_low_report; + if (read_hid_report(0x24, battery_runtime_low_report)) { + parse_battery_runtime_low_report(battery_runtime_low_report, data); + } + + // 5. Manufacturing dates (Reports 0x07, 0x20, 0x7b) + HidReport power_summary_mfr_date_report; + if (read_hid_report(0x07, power_summary_mfr_date_report)) { + parse_manufacture_date_report(power_summary_mfr_date_report, data, false); // UPS mfr date + } + + HidReport battery_mfr_date_report; + if (read_hid_report(0x20, battery_mfr_date_report)) { + parse_manufacture_date_report(battery_mfr_date_report, data, true); // Battery mfr date + } + + // 6. UPS delay shutdown (Report 0x41) + HidReport ups_delay_shutdown_report; + if (read_hid_report(0x41, ups_delay_shutdown_report)) { + parse_ups_delay_shutdown_report(ups_delay_shutdown_report, data); + } + + // 7. Battery charge thresholds (Reports 0x0f, 0x11) + HidReport battery_charge_warning_report; + if (read_hid_report(0x0f, battery_charge_warning_report)) { + parse_battery_charge_threshold_report(battery_charge_warning_report, data, false); // warning + } + + HidReport battery_charge_low_report; + if (read_hid_report(0x11, battery_charge_low_report)) { + parse_battery_charge_threshold_report(battery_charge_low_report, data, true); // low + } + + // 8. Battery chemistry/type (Report 0x03) + HidReport battery_chemistry_report; + if (read_hid_report(0x03, battery_chemistry_report)) { + 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 + + // 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"; + } else { + data.battery_status = "Critical"; + } + ESP_LOGI(APC_HID_TAG, "APC Battery status: %s (%.0f%%)", data.battery_status.c_str(), data.battery_level); + } + + ESP_LOGD(APC_HID_TAG, "Completed reading APC missing dynamic values"); +} + +void ApcHidProtocol::parse_battery_voltage_nominal_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Battery voltage nominal report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug: ReportID: 0x25, Value: 12 (UPS.Battery.ConfigVoltage) + // 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; + + 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); +} + +void ApcHidProtocol::parse_battery_voltage_actual_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Battery voltage actual report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug: ReportID: 0x26, Value: 13.67 (UPS.Battery.Voltage) + // Data format: [ID, volt_low, volt_high] - 16-bit little endian + // The value should be similar to 13.67V based on NUT debug + uint16_t voltage_raw = report.data[1] | (report.data[2] << 8); + + // Try different scaling factors to match NUT value of ~13.67V + float voltage_candidate1 = static_cast(voltage_raw) / 100.0f; // Same as nominal + float voltage_candidate2 = static_cast(voltage_raw) / 10.0f; // Less scaling + float voltage_candidate3 = static_cast(voltage_raw); // No scaling + + // 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; + 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); + } else if (voltage_candidate2 >= 10.0f && voltage_candidate2 <= 20.0f) { + 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); + } else if (voltage_candidate3 >= 10.0f && voltage_candidate3 <= 20.0f) { + 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); + } 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 + } +} + +void ApcHidProtocol::parse_input_voltage_nominal_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Input voltage nominal report too short: %zu bytes", report.data.size()); + return; + } + + // 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); + + 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); +} + +void ApcHidProtocol::parse_input_transfer_limits_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Input transfer limits report too short: %zu bytes", report.data.size()); + return; + } + + // Data format: [ID, limit_low, limit_high] - 16-bit little endian + uint16_t limit_raw = report.data[1] | (report.data[2] << 8); + + if (report.report_id == 0x32) { + // NUT debug: ReportID: 0x32, Value: 180 (UPS.Input.LowVoltageTransfer) + data.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); + } else if (report.report_id == 0x33) { + // NUT debug: ReportID: 0x33, Value: 266 (UPS.Input.HighVoltageTransfer) + data.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); + } +} + +void ApcHidProtocol::parse_battery_runtime_low_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Battery runtime low report too short: %zu bytes", report.data.size()); + return; + } + + // 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); + + 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); +} + +void ApcHidProtocol::parse_manufacture_date_report(const HidReport &report, UpsData &data, bool is_battery) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "Manufacture date report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug shows: Value: 19257 for date "2017/09/25" + // Data format: [ID, date_low, date_high] - 16-bit little endian + // CRITICAL FIX: Raw value 0x4B39=19257 but actual device shows different value + // Let's see what value we actually get from this device + uint16_t date_raw = report.data[1] | (report.data[2] << 8); + ESP_LOGW(APC_HID_TAG, "DEBUG: Date raw bytes: 0x%02X 0x%02X = %d", report.data[1], report.data[2], date_raw); + std::string date_str = convert_apc_date(date_raw); + + if (is_battery) { + 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); + } else { + data.ups_mfr_date = date_str; + ESP_LOGI(APC_HID_TAG, "APC UPS manufacture date: %s (raw: %d)", + data.ups_mfr_date.c_str(), date_raw); + } +} + +void ApcHidProtocol::parse_ups_delay_shutdown_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 3) { + ESP_LOGW(APC_HID_TAG, "UPS delay shutdown report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug: ReportID: 0x41, Value: -1 (but NUT output shows ups.delay.shutdown: 20) + // This suggests NUT does additional processing/conversion + // Data format: [ID, delay_low, delay_high] - 16-bit signed little endian + int16_t delay_raw = static_cast(report.data[1] | (report.data[2] << 8)); + + 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 + ESP_LOGI(APC_HID_TAG, "APC UPS delay shutdown: %d seconds (processed from HID value %d)", + data.ups_delay_shutdown, delay_raw); + } else { + data.ups_delay_shutdown = delay_raw; + ESP_LOGI(APC_HID_TAG, "APC UPS delay shutdown: %d seconds (raw: %d)", + data.ups_delay_shutdown, delay_raw); + } +} + +std::string ApcHidProtocol::convert_apc_date(uint16_t date_value) { + // Convert APC date format to "YYYY/MM/DD" string + // Based on NUT libhid date conversion: 19257 → "2017/09/25" + // This appears to be days since epoch (1970-01-01) + + if (date_value == 0) { + return "not set"; + } + + // Calculate date from days since epoch + // 19257 days from 1970-01-01 = 2017-09-25 + const uint32_t days_since_epoch = date_value; + const uint32_t seconds_per_day = 24 * 60 * 60; + const uint32_t epoch_timestamp = days_since_epoch * seconds_per_day; + + // Convert to calendar date + time_t timestamp = epoch_timestamp; + struct tm *date_tm = gmtime(×tamp); + + if (date_tm == nullptr) { + ESP_LOGW(APC_HID_TAG, "Failed to convert APC date value %d", date_value); + return "unknown"; + } + + char date_str[16]; + snprintf(date_str, sizeof(date_str), "%04d/%02d/%02d", + 1900 + date_tm->tm_year, + 1 + date_tm->tm_mon, + date_tm->tm_mday); + + return std::string(date_str); +} + +void ApcHidProtocol::parse_battery_charge_threshold_report(const HidReport &report, UpsData &data, bool is_low_threshold) { + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "Battery charge threshold report too short: %zu bytes", report.data.size()); + return; + } + + // Data format: [ID, threshold] - single byte percentage + uint8_t threshold_raw = report.data[1]; + + if (is_low_threshold) { + // NUT debug: ReportID: 0x11, Value: 10 (RemainingCapacityLimit) + 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); + } else { + // NUT debug: ReportID: 0x0f, Value: 50 (WarningCapacityLimit) + 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); + } +} + +void ApcHidProtocol::parse_battery_chemistry_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 2) { + ESP_LOGW(APC_HID_TAG, "Battery chemistry report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug: ReportID: 0x03, Value: 4 (iDeviceChemistry) + uint8_t chemistry_raw = report.data[1]; + + // Map chemistry values based on NUT libhid implementation + switch (chemistry_raw) { + case 1: + data.battery_type = "Alkaline"; + break; + case 2: + data.battery_type = "NiCd"; + break; + case 3: + data.battery_type = "NiMH"; + break; + case 4: + data.battery_type = "PbAc"; // Lead Acid (matches NUT output) + break; + case 5: + data.battery_type = "LiIon"; + break; + case 6: + data.battery_type = "LiPoly"; + break; + default: + 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); +} + } // namespace ups_hid } // namespace esphome \ 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 28abd71..95ec8c1 100644 --- a/components/ups_hid/apc_hid_protocol.h +++ b/components/ups_hid/apc_hid_protocol.h @@ -42,6 +42,26 @@ private: void read_device_info(); void parse_device_info_report(const HidReport &report); void log_raw_data(const uint8_t* buffer, size_t buffer_len); + + // Device information parsing + void read_device_information(UpsData &data); + void parse_serial_number_report(const HidReport &report, UpsData &data); + void parse_firmware_version_report(const HidReport &report, UpsData &data); + void parse_beeper_status_report(const HidReport &report, UpsData &data); + void parse_input_sensitivity_report(const HidReport &report, UpsData &data); + + // Missing dynamic values from NUT analysis + void read_missing_dynamic_values(UpsData &data); + void parse_battery_voltage_nominal_report(const HidReport &report, UpsData &data); + void parse_battery_voltage_actual_report(const HidReport &report, UpsData &data); + void parse_input_voltage_nominal_report(const HidReport &report, UpsData &data); + void parse_input_transfer_limits_report(const HidReport &report, UpsData &data); + 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_battery_charge_threshold_report(const HidReport &report, UpsData &data, bool is_low_threshold); + void parse_battery_chemistry_report(const HidReport &report, UpsData &data); + std::string convert_apc_date(uint16_t date_value); }; } // namespace ups_hid diff --git a/components/ups_hid/cyberpower_protocol.cpp b/components/ups_hid/cyberpower_protocol.cpp index 9c9a900..cb71c64 100644 --- a/components/ups_hid/cyberpower_protocol.cpp +++ b/components/ups_hid/cyberpower_protocol.cpp @@ -2,6 +2,8 @@ #include "ups_hid.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" +#include "esp_err.h" +#include "esphome/core/log.h" namespace esphome { namespace ups_hid { @@ -56,10 +58,6 @@ bool CyberPowerProtocol::initialize() { bool CyberPowerProtocol::read_data(UpsData &data) { ESP_LOGD(CP_TAG, "Reading CyberPower HID data"); - // Set manufacturer and model information for CyberPower - data.manufacturer = "CPS"; - data.model = "CP1500EPFCLCD"; - bool success = false; // Core sensors (essential for operation) @@ -146,6 +144,12 @@ bool CyberPowerProtocol::read_data(UpsData &data) { parse_input_sensitivity_report(input_sensitivity_report, data); } + // Read overload status (Report 0x17) + HidReport overload_report; + if (read_hid_report(OVERLOAD_REPORT_ID, overload_report)) { + parse_overload_report(overload_report, data); + } + // Read beeper status (Report 0x0c) HidReport beeper_status_report; if (read_hid_report(BEEPER_STATUS_REPORT_ID, beeper_status_report)) { @@ -166,10 +170,46 @@ bool CyberPowerProtocol::read_data(UpsData &data) { // Set frequency to NaN - not available for CyberPower CP1500 model data.frequency = NAN; + // TIMING FIX: Only read USB string descriptors after successful HID communication + // This ensures the device is ready and responsive before attempting descriptor access if (success) { + ESP_LOGD(CP_TAG, "CyberPower HID data read successful, now reading device info..."); + + // Read manufacturer from USB Manufacturer string descriptor (index 3) + // NUT shows: UPS.PowerSummary.iManufacturer, Value: 3 → Manufacturer: "CPS" + std::string manufacturer_string; + 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()); + } else { + data.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)); + } + + // Read model from USB Product string descriptor (index 1) + // NUT shows: Product: "CP1500EPFCLCD" + std::string product_string; + 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()); + } else { + data.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)); + } + + // Read missing dynamic values identified from NUT analysis + read_missing_dynamic_values(data); + ESP_LOGD(CP_TAG, "CyberPower data read completed successfully"); } 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(); } return success; @@ -220,6 +260,7 @@ 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 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); @@ -227,8 +268,16 @@ void CyberPowerProtocol::parse_battery_runtime_report(const HidReport &report, U data.battery_level = static_cast(battery_percentage > 100 ? 100 : battery_percentage); data.runtime_minutes = static_cast(runtime_minutes); - 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]); + // 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); + } 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]); + } } void CyberPowerProtocol::parse_battery_voltage_report(const HidReport &report, UpsData &data) { @@ -481,25 +530,63 @@ void CyberPowerProtocol::parse_input_sensitivity_report(const HidReport &report, // NUT debug shows: Report 0x1a, Value: 1 (CPSInputSensitivity) uint8_t sensitivity_raw = report.data[1]; + ESP_LOGD(CP_TAG, "Raw CyberPower sensitivity from report 0x1a: 0x%02X (%d)", sensitivity_raw, sensitivity_raw); - // Map sensitivity values: 0=high, 1=normal, 2=low + // DYNAMIC SENSITIVITY MAPPING: Handle known CyberPower values with intelligent fallbacks switch (sensitivity_raw) { case 0: data.input_sensitivity = "high"; + ESP_LOGI(CP_TAG, "CyberPower input sensitivity: high (raw: %d)", sensitivity_raw); break; case 1: data.input_sensitivity = "normal"; + ESP_LOGI(CP_TAG, "CyberPower input sensitivity: normal (raw: %d)", sensitivity_raw); break; case 2: data.input_sensitivity = "low"; + ESP_LOGI(CP_TAG, "CyberPower input sensitivity: low (raw: %d)", sensitivity_raw); break; default: - data.input_sensitivity = "unknown"; + // DYNAMIC HANDLING: For unknown values, provide better context + if (sensitivity_raw >= 100) { + // Large values might indicate report format issue + ESP_LOGW(CP_TAG, "Unexpected large CyberPower sensitivity value: %d (0x%02X) - possible report format issue", + sensitivity_raw, sensitivity_raw); + + // Try alternative parsing - some models might use different byte + if (report.data.size() >= 3) { + uint8_t alt_value = report.data[2]; + ESP_LOGD(CP_TAG, "Trying alternative sensitivity parsing from byte[2]: %d", alt_value); + + 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; + } + ESP_LOGI(CP_TAG, "CyberPower input sensitivity (alt parsing): %s (raw: %d)", + data.input_sensitivity.c_str(), sensitivity_raw); + return; + } + } + + // Fallback for problematic values + data.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"; + ESP_LOGI(CP_TAG, "CyberPower input sensitivity: auto (raw: %d)", sensitivity_raw); + } else { + data.input_sensitivity = "unknown"; + ESP_LOGW(CP_TAG, "Unknown CyberPower sensitivity value: %d - please report this for future support", + sensitivity_raw); + } + } break; } - - ESP_LOGD(CP_TAG, "Input sensitivity: %s (raw: 0x%02X = %d)", - data.input_sensitivity.c_str(), sensitivity_raw, sensitivity_raw); } void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report, UpsData &data) { @@ -508,49 +595,236 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report, return; } + // DYNAMIC FIRMWARE VERSION: Primary method - USB string descriptor // NUT debug shows: Report 0x1b, Value: 5 (CPSFirmwareVersion - string descriptor index) - // This is a string descriptor index, we need to fetch the actual string uint8_t string_index = report.data[1]; - // Based on NUT reference output, firmware version is "CR01505B4" - // For CP1500EPFCLCD model, use known firmware version from NUT debug - if (string_index == 5) { - data.firmware_version = "CR01505B4"; // From NUT debug output + // Validate string index is reasonable (CyberPower typically uses indices 1-10) + if (string_index > 0 && string_index <= 15) { + ESP_LOGD(CP_TAG, "Reading CyberPower firmware from USB string descriptor index: %d", string_index); + + std::string actual_firmware; + esp_err_t fw_ret = parent_->usb_get_string_descriptor(string_index, actual_firmware); + + if (fw_ret == ESP_OK && !actual_firmware.empty()) { + data.firmware_version = actual_firmware; + ESP_LOGI(CP_TAG, "Successfully read CyberPower firmware from USB string descriptor %d: \"%s\"", + string_index, data.firmware_version.c_str()); + return; + } else { + ESP_LOGW(CP_TAG, "Failed to read USB string descriptor %d for firmware: %s, trying fallbacks", + string_index, esp_err_to_name(fw_ret)); + } } else { - // Fallback for other models - char firmware_str[32]; - snprintf(firmware_str, sizeof(firmware_str), "FW_%d", string_index); - data.firmware_version = firmware_str; + ESP_LOGD(CP_TAG, "Invalid string index %d for firmware, trying direct HID parsing", string_index); } - ESP_LOGD(CP_TAG, "Firmware version: %s (string index: %d)", + // FALLBACK 1: Try to parse firmware from raw HID report data + // Some CyberPower models might store firmware directly in HID reports + std::string firmware_from_hid; + for (size_t i = 1; i < report.data.size() && report.data[i] != 0; i++) { + if (report.data[i] >= 32 && report.data[i] <= 126) { // Printable ASCII + firmware_from_hid += static_cast(report.data[i]); + } + } + + 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()); + return; + } + + // FALLBACK 2: Try other common CyberPower string descriptor indices + // Some models may use different indices for firmware + const uint8_t common_fw_indices[] = {4, 5, 6}; // Common firmware string indices + for (uint8_t idx : common_fw_indices) { + if (idx == string_index) continue; // Already tried this one + + ESP_LOGD(CP_TAG, "Trying alternative firmware string descriptor index: %d", idx); + std::string fw_attempt; + esp_err_t ret = parent_->usb_get_string_descriptor(idx, fw_attempt); + + if (ret == ESP_OK && !fw_attempt.empty() && + (fw_attempt.find("CR") == 0 || fw_attempt.find("CP") == 0 || + fw_attempt.find("FW") != std::string::npos)) { + // Looks like a valid CyberPower firmware string + data.firmware_version = fw_attempt; + ESP_LOGI(CP_TAG, "Found CyberPower firmware at alternative string descriptor %d: \"%s\"", + idx, data.firmware_version.c_str()); + return; + } + } + + // FALLBACK 3: Generate version from binary data as last resort + if (report.data.size() >= 3) { + char firmware_fallback[32]; + 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()); + } else { + // No firmware version could be determined + data.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); } +void CyberPowerProtocol::parse_overload_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 2) { + ESP_LOGW(CP_TAG, "Overload report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug shows: Report 0x17, Offset: 1, Value: 0 (UPS.Output.Overload) + // Offset 1 means it's in the second byte of the report + uint8_t overload_byte = report.data[1]; + bool overload = (overload_byte & 0x01) != 0; // Check bit 0 (Offset 1 in NUT = bit 0) + + if (overload) { + data.status_flags |= UPS_STATUS_OVERLOAD; + ESP_LOGW(CP_TAG, "CyberPower UPS OVERLOAD detected (raw: 0x%02X)", overload_byte); + } else { + data.status_flags &= ~UPS_STATUS_OVERLOAD; + ESP_LOGD(CP_TAG, "CyberPower UPS overload status: normal (raw: 0x%02X)", overload_byte); + } +} + void CyberPowerProtocol::parse_serial_number_report(const HidReport &report, UpsData &data) { if (report.data.size() < 2) { ESP_LOGW(CP_TAG, "Serial number report too short: %zu bytes", report.data.size()); return; } - // NUT debug shows: Report 0x02, Value: 2 (iSerialNumber - string descriptor index) - // This is a string descriptor index, we need to fetch the actual string + // NUT debug shows: UPS.PowerSummary.iSerialNumber, ReportID: 0x02, Value: 2 + // This is a USB string descriptor index, not the actual serial number uint8_t string_index = report.data[1]; - // Based on NUT reference output, serial number is "CRMLX2000234" - // For CP1500EPFCLCD model, use known serial from NUT debug - if (string_index == 2) { - data.serial_number = "CRMLX2000234"; // From NUT debug output + ESP_LOGD(CP_TAG, "Serial number string descriptor index: %d", string_index); + + // Use real USB string descriptor reading - this will get the actual CyberPower serial number + // NUT shows: CyberPower real serial = "CRMLX2000234" + std::string actual_serial; + 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; + ESP_LOGI(CP_TAG, "Successfully read CyberPower serial number from USB string descriptor %d: \"%s\"", + string_index, data.serial_number.c_str()); } else { - // Fallback for other devices - use generic format - char serial_str[32]; - snprintf(serial_str, sizeof(serial_str), "CP_SN_%d", string_index); - data.serial_number = serial_str; + // 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(); + 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); } +void CyberPowerProtocol::read_missing_dynamic_values(UpsData &data) { + ESP_LOGD(CP_TAG, "Reading CyberPower missing dynamic values from NUT analysis..."); + + // 1. Battery capacity limits (Report 0x07) - contains multiple values + HidReport battery_capacity_limits_report; + if (read_hid_report(0x07, battery_capacity_limits_report)) { + parse_battery_capacity_limits_report(battery_capacity_limits_report, data); + } + + // 2. Battery chemistry/type (Report 0x03) - same as APC + HidReport battery_chemistry_report; + if (read_hid_report(0x03, battery_chemistry_report)) { + parse_battery_chemistry_report(battery_chemistry_report, data); + } + + // 3. Battery runtime low threshold is already available in existing Report 0x08 + // It's at offset 24 and already parsed in parse_battery_runtime_report + // Just need to extract it properly + + // 4. Set static/derived values based on NUT behavior + data.battery_status = "100%"; // CyberPower shows this as static in NUT + data.ups_test_result = "No test initiated"; // Default test result + + // 5. Timer values are already implemented as ups_delay_shutdown/start + // Map them to timer fields for consistency + data.ups_timer_shutdown = data.ups_delay_shutdown; + data.ups_timer_start = data.ups_delay_start; + + ESP_LOGD(CP_TAG, "Completed reading CyberPower missing dynamic values"); +} + +void CyberPowerProtocol::parse_battery_capacity_limits_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 6) { + ESP_LOGW(CP_TAG, "Battery capacity limits report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug shows Report 0x07 contains multiple capacity values at different offsets: + // Offset 24: WarningCapacityLimit = 20 + // Offset 32: RemainingCapacityLimit = 10 + // Data format: [ID, byte1, byte2, byte3, byte4, byte5, ...] + + // 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); + ESP_LOGI(CP_TAG, "CyberPower Battery charge warning threshold: %.0f%% (raw: %d)", + 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); + ESP_LOGI(CP_TAG, "CyberPower Battery charge low threshold: %.0f%% (raw: %d)", + data.battery_charge_low, remaining_limit); + } +} + +void CyberPowerProtocol::parse_battery_chemistry_report(const HidReport &report, UpsData &data) { + if (report.data.size() < 2) { + ESP_LOGW(CP_TAG, "Battery chemistry report too short: %zu bytes", report.data.size()); + return; + } + + // NUT debug: ReportID: 0x03, Value: 4 (iDeviceChemistry) - same as APC + uint8_t chemistry_raw = report.data[1]; + + // Map chemistry values based on NUT libhid implementation (same as APC) + switch (chemistry_raw) { + case 1: + data.battery_type = "Alkaline"; + break; + case 2: + data.battery_type = "NiCd"; + break; + case 3: + data.battery_type = "NiMH"; + break; + case 4: + data.battery_type = "PbAcid"; // Lead Acid (matches NUT output) + break; + case 5: + data.battery_type = "LiIon"; + break; + case 6: + data.battery_type = "LiPoly"; + break; + default: + 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); +} + } // namespace ups_hid } // namespace esphome \ No newline at end of file diff --git a/components/ups_hid/cyberpower_protocol.h b/components/ups_hid/cyberpower_protocol.h index 2741123..2852d3b 100644 --- a/components/ups_hid/cyberpower_protocol.h +++ b/components/ups_hid/cyberpower_protocol.h @@ -41,6 +41,7 @@ class CyberPowerProtocol : public UpsProtocolBase { static const uint8_t LOAD_PERCENT_REPORT_ID = 0x13; // Load percentage static const uint8_t DELAY_SHUTDOWN_REPORT_ID = 0x15; // Delay before shutdown static const uint8_t DELAY_START_REPORT_ID = 0x16; // Delay before startup + static const uint8_t OVERLOAD_REPORT_ID = 0x17; // Overload status static const uint8_t REALPOWER_NOMINAL_REPORT_ID = 0x18; // Nominal real power static const uint8_t INPUT_SENSITIVITY_REPORT_ID = 0x1a; // Input sensitivity static const uint8_t FIRMWARE_VERSION_REPORT_ID = 0x1b; // Firmware version @@ -75,9 +76,15 @@ class CyberPowerProtocol : public UpsProtocolBase { void parse_delay_shutdown_report(const HidReport &report, UpsData &data); void parse_delay_start_report(const HidReport &report, UpsData &data); void parse_realpower_nominal_report(const HidReport &report, UpsData &data); + void parse_overload_report(const HidReport &report, UpsData &data); 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); + + // Missing dynamic values from NUT analysis + void read_missing_dynamic_values(UpsData &data); + void parse_battery_capacity_limits_report(const HidReport &report, UpsData &data); + void parse_battery_chemistry_report(const HidReport &report, UpsData &data); // CyberPower-specific scaling logic void check_battery_voltage_scaling(float battery_voltage, float nominal_voltage); diff --git a/components/ups_hid/generic_hid_protocol.cpp b/components/ups_hid/generic_hid_protocol.cpp index c390540..881a155 100644 --- a/components/ups_hid/generic_hid_protocol.cpp +++ b/components/ups_hid/generic_hid_protocol.cpp @@ -158,11 +158,20 @@ bool GenericHidProtocol::read_data(UpsData &data) { success = true; } - // 7. Try any other discovered reports with heuristic parsing + // 7. Input sensitivity (0x1a - CyberPower style, 0x35 - APC style) + if (read_report(0x1a, buffer, buffer_len)) { + parse_input_sensitivity(buffer, buffer_len, data, "CyberPower-style"); + success = true; + } else if (read_report(0x35, buffer, buffer_len)) { + parse_input_sensitivity(buffer, buffer_len, data, "APC-style"); + success = true; + } + + // 8. 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 || - id == 0x30 || id == 0x31 || id == 0x50) { + id == 0x30 || id == 0x31 || id == 0x50 || id == 0x1A || id == 0x35) { continue; // Already tried } @@ -453,5 +462,82 @@ bool GenericHidProtocol::parse_unknown_report(uint8_t* data, size_t len, UpsData return found_data; } +void GenericHidProtocol::parse_input_sensitivity(uint8_t* data, size_t len, UpsData& ups_data, const char* style) { + if (len < 2) { + ESP_LOGV(GEN_TAG, "Input sensitivity report too short: %zu bytes", len); + return; + } + + uint8_t sensitivity_raw = data[1]; + ESP_LOGD(GEN_TAG, "Raw input sensitivity (%s): 0x%02X (%d)", style, sensitivity_raw, sensitivity_raw); + + // DYNAMIC GENERIC SENSITIVITY MAPPING + // Handle both APC-style (0x35) and CyberPower-style (0x1a) with intelligent fallbacks + switch (sensitivity_raw) { + case 0: + ups_data.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"; + ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): normal (raw: %d)", style, sensitivity_raw); + break; + case 2: + ups_data.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"; + ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): auto (raw: %d)", style, sensitivity_raw); + break; + default: + // GENERIC DYNAMIC HANDLING: For unknown values, be more permissive + if (sensitivity_raw >= 100) { + // Large values likely indicate wrong report format or encoding + ESP_LOGW(GEN_TAG, "Unexpected large sensitivity value (%s): %d (0x%02X)", + style, sensitivity_raw, sensitivity_raw); + + // Try alternative byte positions for generic devices + for (size_t i = 2; i < len && i < 5; i++) { + 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; + } + ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s, alt byte[%zu]): %s (raw: %d)", + style, i, ups_data.input_sensitivity.c_str(), alt_value); + return; + } + } + + // Fallback to reasonable default + ups_data.input_sensitivity = "normal"; + ESP_LOGW(GEN_TAG, "Using default 'normal' sensitivity (%s) due to unexpected value: %d", + style, sensitivity_raw); + } else { + // Values 4-99 - provide extended mapping for unknown devices + if (sensitivity_raw <= 10) { + // Map to nearest known value + if (sensitivity_raw <= 3) { + ups_data.input_sensitivity = "high"; + } else if (sensitivity_raw <= 6) { + ups_data.input_sensitivity = "normal"; + } else { + ups_data.input_sensitivity = "low"; + } + ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s, mapped): %s (raw: %d)", + style, ups_data.input_sensitivity.c_str(), sensitivity_raw); + } else { + ups_data.input_sensitivity = "unknown"; + ESP_LOGW(GEN_TAG, "Unknown generic sensitivity value (%s): %d", style, sensitivity_raw); + } + } + break; + } +} + } // 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 017e0bc..d2686cb 100644 --- a/components/ups_hid/sensor.py +++ b/components/ups_hid/sensor.py @@ -114,6 +114,43 @@ SENSOR_TYPES = { "state_class": STATE_CLASS_MEASUREMENT, "accuracy_decimals": 0, }, + # Additional missing sensor types from NUT analysis + "battery_charge_low": { + "unit": UNIT_PERCENT, + "device_class": DEVICE_CLASS_BATTERY, + "state_class": STATE_CLASS_MEASUREMENT, + "accuracy_decimals": 0, + }, + "battery_charge_warning": { + "unit": UNIT_PERCENT, + "device_class": DEVICE_CLASS_BATTERY, + "state_class": STATE_CLASS_MEASUREMENT, + "accuracy_decimals": 0, + }, + "battery_runtime_low": { + "unit": UNIT_MINUTE, + "device_class": DEVICE_CLASS_DURATION, + "state_class": STATE_CLASS_MEASUREMENT, + "accuracy_decimals": 0, + }, + "ups_timer_reboot": { + "unit": UNIT_SECOND, + "device_class": DEVICE_CLASS_DURATION, + "state_class": STATE_CLASS_MEASUREMENT, + "accuracy_decimals": 0, + }, + "ups_timer_shutdown": { + "unit": UNIT_SECOND, + "device_class": DEVICE_CLASS_DURATION, + "state_class": STATE_CLASS_MEASUREMENT, + "accuracy_decimals": 0, + }, + "ups_timer_start": { + "unit": UNIT_SECOND, + "device_class": DEVICE_CLASS_DURATION, + "state_class": STATE_CLASS_MEASUREMENT, + "accuracy_decimals": 0, + }, } diff --git a/components/ups_hid/text_sensor.py b/components/ups_hid/text_sensor.py index acc61ef..083c278 100644 --- a/components/ups_hid/text_sensor.py +++ b/components/ups_hid/text_sensor.py @@ -22,6 +22,13 @@ TEXT_SENSOR_TYPES = [ "firmware_version", "ups_beeper_status", "input_sensitivity", + # Additional missing text sensor types from NUT analysis + "battery_status", + "battery_type", + "battery_mfr_date", + "ups_mfr_date", + "ups_firmware_aux", + "ups_test_result", ] diff --git a/components/ups_hid/ups_hid.cpp b/components/ups_hid/ups_hid.cpp index dde51eb..78d0c6a 100644 --- a/components/ups_hid/ups_hid.cpp +++ b/components/ups_hid/ups_hid.cpp @@ -575,6 +575,30 @@ namespace esphome { 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); + } // Only publish if value is valid and within reasonable bounds if (!std::isnan(value)) @@ -661,6 +685,30 @@ namespace esphome { sensor->publish_state(local_data.input_sensitivity); } + else if (type == "battery_status" && !local_data.battery_status.empty()) + { + sensor->publish_state(local_data.battery_status); + } + else if (type == "battery_type" && !local_data.battery_type.empty()) + { + sensor->publish_state(local_data.battery_type); + } + else if (type == "battery_mfr_date" && !local_data.battery_mfr_date.empty()) + { + sensor->publish_state(local_data.battery_mfr_date); + } + else if (type == "ups_mfr_date" && !local_data.ups_mfr_date.empty()) + { + sensor->publish_state(local_data.ups_mfr_date); + } + else if (type == "ups_firmware_aux" && !local_data.ups_firmware_aux.empty()) + { + sensor->publish_state(local_data.ups_firmware_aux); + } + else if (type == "ups_test_result" && !local_data.ups_test_result.empty()) + { + sensor->publish_state(local_data.ups_test_result); + } else if (type == "status") { std::string status_str = ""; @@ -1595,6 +1643,124 @@ namespace esphome 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 diff --git a/components/ups_hid/ups_hid.h b/components/ups_hid/ups_hid.h index b9ae9f4..9f8cb04 100644 --- a/components/ups_hid/ups_hid.h +++ b/components/ups_hid/ups_hid.h @@ -92,6 +92,20 @@ namespace esphome 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; @@ -118,6 +132,20 @@ namespace esphome 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 @@ -253,6 +281,9 @@ namespace esphome // 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); + + // USB string descriptor reading + esp_err_t usb_get_string_descriptor(uint8_t string_index, std::string& result, uint16_t language_id = 0x0409); #endif @@ -374,6 +405,7 @@ namespace esphome 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); diff --git a/full-test.yaml b/full-test.yaml index 6624838..eba8edc 100644 --- a/full-test.yaml +++ b/full-test.yaml @@ -305,6 +305,67 @@ sensor: state_class: measurement accuracy_decimals: 0 + # New missing dynamic values from NUT analysis + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Charge Low Threshold" + id: battery_charge_low + type: battery_charge_low + unit_of_measurement: "%" + device_class: battery + state_class: measurement + accuracy_decimals: 0 + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Charge Warning Threshold" + id: battery_charge_warning + type: battery_charge_warning + unit_of_measurement: "%" + device_class: battery + 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 + state_class: measurement + accuracy_decimals: 0 + + - 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 + # System sensors for monitoring ESP32 health - platform: uptime name: "Uptime" @@ -439,44 +500,134 @@ binary_sensor: return false; # Text Sensors for UPS information +# +# DEVICE INFORMATION CAPABILITIES BY PROTOCOL: +# +# APC HID Protocol (VID: 0x051D): +# ✅ manufacturer, model, status, protocol +# ⚠️ serial_number, firmware_version (basic support - may be limited) +# ⚠️ ups_beeper_status, input_sensitivity (basic support - may be limited) +# +# CyberPower HID Protocol (VID: 0x0764): +# ✅ manufacturer, model, status, protocol +# ✅ serial_number, firmware_version (full HID report parsing) +# ✅ ups_beeper_status, input_sensitivity (full HID report parsing) +# +# Generic HID Protocol (All other vendors): +# ✅ manufacturer, model, status, protocol +# ⚠️ serial_number, firmware_version (generic parsing - device dependent) +# ⚠️ ups_beeper_status, input_sensitivity (generic parsing - device dependent) +# +# Legend: ✅ = Full Support, ⚠️ = Basic/Limited Support +# text_sensor: - - platform: ups_hid - ups_hid_id: ups_monitor - name: "UPS Model" - id: ups_model - type: model - + # === DEVICE IDENTIFICATION (Protocol-Independent) === + # Available on all protocols - basic device identification - platform: ups_hid ups_hid_id: ups_monitor name: "UPS Manufacturer" id: ups_manufacturer type: manufacturer + icon: "mdi:factory" + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Model" + id: ups_model + type: model + icon: "mdi:information-outline" + + # === PROTOCOL-SPECIFIC DEVICE INFO === + # Serial Number - Available on: CyberPower (full), APC (limited), Generic (basic) + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Serial Number" + id: ups_serial_number + type: serial_number + icon: "mdi:identifier" + + # Firmware Version - Available on: CyberPower (full), APC (limited), Generic (basic) + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Firmware Version" + id: ups_firmware_version + type: firmware_version + icon: "mdi:chip" + + # === COMMUNICATION STATUS === - platform: ups_hid ups_hid_id: ups_monitor name: "UPS Status" id: ups_status_text type: status + icon: "mdi:power-standby" - platform: ups_hid ups_hid_id: ups_monitor name: "Detected Protocol" id: ups_protocol type: protocol + icon: "mdi:connection" - # Additional CyberPower text sensors (newly implemented) - # Available text sensor types: ups_beeper_status, input_sensitivity + # === HID-SPECIFIC CONFIGURATION === + # UPS Beeper Status - Available on: CyberPower (full), APC (limited), Generic (basic) - platform: ups_hid ups_hid_id: ups_monitor name: "UPS Beeper Status" id: ups_beeper_status type: ups_beeper_status + icon: "mdi:volume-high" + # Input Sensitivity - Available on: CyberPower (full), APC (limited), Generic (basic) - platform: ups_hid ups_hid_id: ups_monitor name: "Input Sensitivity" id: input_sensitivity type: input_sensitivity + icon: "mdi:tune-vertical" + + # New missing text sensors from NUT analysis + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Status" + id: battery_status + type: battery_status + icon: "mdi:battery-check" + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Type" + id: battery_type + type: battery_type + icon: "mdi:battery-outline" + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Manufacture Date" + id: battery_mfr_date + type: battery_mfr_date + icon: "mdi:calendar-check" + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Manufacture Date" + id: ups_mfr_date + type: ups_mfr_date + icon: "mdi:calendar-check" + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Firmware Auxiliary" + id: ups_firmware_aux + type: ups_firmware_aux + icon: "mdi:chip" + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Test Result" + id: ups_test_result + type: ups_test_result + icon: "mdi:test-tube" # System text sensors - platform: version diff --git a/minimal-test.yaml b/minimal-test.yaml index bf5cce5..5346b5c 100644 --- a/minimal-test.yaml +++ b/minimal-test.yaml @@ -111,6 +111,27 @@ sensor: state_class: measurement accuracy_decimals: 0 + # Test key missing dynamic values + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Charge Low Threshold" + id: battery_charge_low + type: battery_charge_low + unit_of_measurement: "%" + device_class: battery + 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 + state_class: measurement + accuracy_decimals: 0 + # Binary Sensors binary_sensor: - platform: ups_hid @@ -140,3 +161,41 @@ text_sensor: name: "UPS Model" id: ups_model type: model + + # Device Information Sensors (test APC implementation) + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Serial Number" + id: ups_serial_number + type: serial_number + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Firmware Version" + id: ups_firmware_version + type: firmware_version + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Beeper Status" + id: ups_beeper_status + type: ups_beeper_status + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Input Sensitivity" + id: ups_input_sensitivity + type: input_sensitivity + + # Test key missing dynamic values + - platform: ups_hid + ups_hid_id: ups_monitor + name: "Battery Type" + id: battery_type + type: battery_type + + - platform: ups_hid + ups_hid_id: ups_monitor + name: "UPS Test Result" + id: ups_test_result + type: ups_test_result