From 0c1e24b5250abbcd52895e2e5cc6ef660b7bbc36 Mon Sep 17 00:00:00 2001 From: bullshit Date: Mon, 18 Aug 2025 14:53:45 +0200 Subject: [PATCH] fix(ups-hid): handle wonky esp32-idf disconnect/reconnect issues with v5.3 Signed-off-by: bullshit --- components/ups_hid/apc_hid_protocol.cpp | 24 ++++++ components/ups_hid/cyberpower_protocol.cpp | 24 ++++++ components/ups_hid/generic_hid_protocol.cpp | 36 ++++++++ components/ups_hid/ups_hid.cpp | 95 +++++++++++++++++++-- components/ups_hid/ups_hid.h | 9 ++ 5 files changed, 179 insertions(+), 9 deletions(-) diff --git a/components/ups_hid/apc_hid_protocol.cpp b/components/ups_hid/apc_hid_protocol.cpp index 2a989ee..c01173a 100644 --- a/components/ups_hid/apc_hid_protocol.cpp +++ b/components/ups_hid/apc_hid_protocol.cpp @@ -52,6 +52,12 @@ ApcHidProtocol::ApcHidProtocol(UpsHidComponent *parent) : UpsProtocolBase(parent bool ApcHidProtocol::detect() { ESP_LOGD(APC_HID_TAG, "Detecting APC HID Protocol..."); + // Check device connection status first + if (!parent_->is_device_connected()) { + ESP_LOGD(APC_HID_TAG, "Device not connected, skipping protocol detection"); + return false; + } + // Give device time to initialize after connection vTaskDelay(pdMS_TO_TICKS(100)); @@ -67,6 +73,12 @@ bool ApcHidProtocol::detect() { HidReport test_report; for (uint8_t report_id : test_report_ids) { + // Check device connection before each report attempt + if (!parent_->is_device_connected()) { + ESP_LOGD(APC_HID_TAG, "Device disconnected during protocol detection"); + return false; + } + ESP_LOGD(APC_HID_TAG, "Testing report ID 0x%02X...", report_id); if (read_hid_report(report_id, test_report)) { @@ -226,6 +238,12 @@ bool ApcHidProtocol::init_hid_communication() { } bool ApcHidProtocol::read_hid_report(uint8_t report_id, HidReport &report) { + // Check device connection before any HID communication + if (!parent_->is_device_connected()) { + ESP_LOGV(APC_HID_TAG, "Device not connected, skipping HID report 0x%02X", report_id); + return false; + } + uint8_t buffer[64]; // Maximum HID report size size_t buffer_len = sizeof(buffer); esp_err_t ret; @@ -242,6 +260,12 @@ bool ApcHidProtocol::read_hid_report(uint8_t report_id, HidReport &report) { return true; } + // Check connection again before trying Feature report + if (!parent_->is_device_connected()) { + ESP_LOGV(APC_HID_TAG, "Device disconnected during HID communication for report 0x%02X", report_id); + return false; + } + // 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); diff --git a/components/ups_hid/cyberpower_protocol.cpp b/components/ups_hid/cyberpower_protocol.cpp index b364e94..b6fb9cd 100644 --- a/components/ups_hid/cyberpower_protocol.cpp +++ b/components/ups_hid/cyberpower_protocol.cpp @@ -15,6 +15,12 @@ static const char *const CP_TAG = "ups_hid.cyberpower_hid"; bool CyberPowerProtocol::detect() { ESP_LOGD(CP_TAG, "Detecting CyberPower HID protocol"); + // Check device connection status first + if (!parent_->is_device_connected()) { + ESP_LOGD(CP_TAG, "Device not connected, skipping protocol detection"); + return false; + } + // Give device time to initialize after connection (same as APC) vTaskDelay(pdMS_TO_TICKS(100)); @@ -31,6 +37,12 @@ bool CyberPowerProtocol::detect() { HidReport test_report; for (uint8_t report_id : test_report_ids) { + // Check device connection before each report attempt + if (!parent_->is_device_connected()) { + ESP_LOGD(CP_TAG, "Device disconnected during protocol detection"); + return false; + } + ESP_LOGD(CP_TAG, "Testing report ID 0x%02X...", report_id); if (read_hid_report(report_id, test_report)) { @@ -225,6 +237,12 @@ bool CyberPowerProtocol::read_data(UpsData &data) { } bool CyberPowerProtocol::read_hid_report(uint8_t report_id, HidReport &report) { + // Check device connection before any HID communication + if (!parent_->is_device_connected()) { + ESP_LOGV(CP_TAG, "Device not connected, skipping HID report 0x%02X", report_id); + return false; + } + uint8_t buffer[64]; // Maximum HID report size size_t buffer_len = sizeof(buffer); esp_err_t ret; @@ -244,6 +262,12 @@ bool CyberPowerProtocol::read_hid_report(uint8_t report_id, HidReport &report) { // Log the specific error for Feature Report ESP_LOGD(CP_TAG, "Feature Report 0x%02X failed: %s", report_id, esp_err_to_name(ret)); + // Check connection again before trying Input report + if (!parent_->is_device_connected()) { + ESP_LOGV(CP_TAG, "Device disconnected during HID communication for report 0x%02X", report_id); + return false; + } + // Fallback: try Input Report (0x01) for real-time data buffer_len = sizeof(buffer); ret = parent_->hid_get_report(0x01, report_id, buffer, &buffer_len); diff --git a/components/ups_hid/generic_hid_protocol.cpp b/components/ups_hid/generic_hid_protocol.cpp index 881a155..a3a3e87 100644 --- a/components/ups_hid/generic_hid_protocol.cpp +++ b/components/ups_hid/generic_hid_protocol.cpp @@ -38,6 +38,12 @@ static const uint8_t HID_REPORT_TYPE_FEATURE = 0x03; bool GenericHidProtocol::detect() { ESP_LOGD(GEN_TAG, "Detecting Generic HID Protocol..."); + // Check device connection status first + if (!parent_->is_device_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(); if (vid == 0x051D || vid == 0x0764) { // APC or CyberPower @@ -50,6 +56,12 @@ bool GenericHidProtocol::detect() { size_t buffer_len; for (uint8_t report_id : COMMON_REPORT_IDS) { + // Check connection status before each attempt + if (!parent_->is_device_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); @@ -60,6 +72,12 @@ bool GenericHidProtocol::detect() { return true; } + // Check connection again before trying Feature report + if (!parent_->is_device_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); @@ -215,6 +233,12 @@ 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()) { + 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); @@ -225,6 +249,12 @@ void GenericHidProtocol::enumerate_reports() { ESP_LOGV(GEN_TAG, "Found Input report 0x%02X (%zu bytes)", id, buffer_len); } + // Check connection again before Feature report + if (!parent_->is_device_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); @@ -249,6 +279,12 @@ void GenericHidProtocol::enumerate_reports() { // Extended search for less common report IDs 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()) { + ESP_LOGD(GEN_TAG, "Device disconnected during extended report search"); + return; + } + // Limit total discovery time if (discovered_count >= 10) { break; diff --git a/components/ups_hid/ups_hid.cpp b/components/ups_hid/ups_hid.cpp index 3fbea92..1e4cce5 100644 --- a/components/ups_hid/ups_hid.cpp +++ b/components/ups_hid/ups_hid.cpp @@ -7,6 +7,20 @@ #include "apc_hid_protocol.h" #include "cyberpower_protocol.h" +// ============================================================================== +// ESP-IDF v5.3 KNOWN ISSUES: +// +// The ESP-IDF v5.3 USB Host Library has fundamental bugs that cannot be fully +// worked around: +// +// 1. ESP_ERR_INVALID_STATE from usb_host_device_open after disconnect/reconnect +// 2. Endpoint allocation corruption preventing interface claims +// 3. USB Host Library state corruption during device enumeration +// +// These issues are fixed in ESP-IDF v5.4+. With v5.3, a power cycle may be +// required after USB disconnect/reconnect cycles. +// ============================================================================== + #include #include @@ -114,18 +128,26 @@ namespace esphome if (ret == ESP_OK) { ESP_LOGI(TAG, "USB device enumeration successful, attempting protocol detection"); - } -#endif - - if (detect_ups_protocol()) - { - connected_ = true; - ESP_LOGI(TAG, "Reconnected to UPS"); + + if (detect_ups_protocol()) + { + connected_ = true; + ESP_LOGI(TAG, "Reconnected to UPS"); + } + else + { + ESP_LOGW(TAG, "Protocol detection failed after successful USB enumeration"); + return; + } } else { + ESP_LOGW(TAG, "USB device enumeration failed: %s", esp_err_to_name(ret)); return; } +#else + return; // Non-ESP32 platforms can't reconnect +#endif } // Use cached data from asynchronous USB operations instead of blocking reads @@ -1044,6 +1066,19 @@ namespace esphome { 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..."); @@ -1074,7 +1109,19 @@ namespace esphome ret = usb_host_device_open(usb_device_.client_hdl, dev_addr_list[i], &dev_hdl); if (ret != ESP_OK) { - continue; + if (ret == ESP_ERR_INVALID_STATE) { + ESP_LOGW(TAG, "USB Host Library in invalid state for device %d", dev_addr_list[i]); + ESP_LOGI(TAG, "This is a known ESP-IDF v5.3 issue"); + + // Simple handling: just skip the device and continue + // The ESP-IDF v5.3 USB Host Library has fundamental bugs with device state + // management that cannot be reliably worked around. The best approach is + // to log the issue and continue operation. + 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; @@ -1194,6 +1241,13 @@ namespace esphome 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; } @@ -1928,8 +1982,31 @@ namespace esphome 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, "Cleaning up disconnected UPS device"); component->device_connected_ = false; - component->usb_device_.dev_hdl = nullptr; + component->connected_ = false; + + // Clear USB device state completely + memset(&component->usb_device_, 0, sizeof(component->usb_device_)); + + // Clear active protocol to force re-detection on reconnect + component->active_protocol_.reset(); + + // Reset UPS data to avoid showing stale values + { + std::lock_guard data_lock(component->data_mutex_); + component->ups_data_.reset(); // Reset to default/invalid values + } + + // Also clear the 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, "USB device state and UPS data cleared, ready for reconnection"); } break; diff --git a/components/ups_hid/ups_hid.h b/components/ups_hid/ups_hid.h index bbde65d..d9dc3f8 100644 --- a/components/ups_hid/ups_hid.h +++ b/components/ups_hid/ups_hid.h @@ -225,6 +225,15 @@ namespace esphome return false; #endif } + + // Connection status for protocols + bool is_device_connected() const { +#ifdef USE_ESP32 + return device_connected_; +#else + return false; +#endif + } // Sensor registration methods void register_sensor(sensor::Sensor *sens, const std::string &type);