refactor(ups-hid): auto detect device and protocol logic

Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
bullshit committed 2025-08-17 19:43:14 +02:00
1 parent 753b015139
commit ed284af812
9 files changed
+142 -128

No files matched your search

+38 -17
View File
@@ -20,15 +20,19 @@ CONF_UPS_HID_ID = "ups_hid_id"
# Known UPS vendor IDs for validation
KNOWN_VENDOR_IDS = {
0x0463: "MGE Office Protection Systems",
0x047C: "Dell",
0x0483: "STMicroelectronics",
0x04B3: "IBM",
0x04D8: "OpenUPS",
0x050D: "Belkin",
0x051D: "APC",
0x05B8: "SVEN",
0x0665: "Cypress/Belkin",
0x0592: "Powerware",
0x05DD: "Delta Electronics",
0x06DA: "MGE UPS Systems",
0x075D: "Idowell",
0x0764: "CyberPower",
0x0925: "Richcomm",
0x09AE: "Tripp Lite",
0x09D6: "Micropower",
0x09D6: "KSTAR",
}
ups_hid_ns = cg.esphome_ns.namespace("ups_hid")
@@ -36,17 +40,27 @@ UpsHidComponent = ups_hid_ns.class_("UpsHidComponent", cg.PollingComponent)
def validate_usb_config(config):
"""Validate USB configuration with helpful warnings."""
vendor_id = config.get(CONF_USB_VENDOR_ID, 0x051D)
product_id = config.get(CONF_USB_PRODUCT_ID, 0x0002)
"""Validate USB configuration. Manual IDs are now troubleshooting fallbacks only."""
vendor_id = config.get(CONF_USB_VENDOR_ID)
product_id = config.get(CONF_USB_PRODUCT_ID)
# Validate non-zero IDs
if vendor_id == 0 or product_id == 0:
raise cv.Invalid("USB vendor and product IDs must be non-zero")
# If either ID is specified, both must be provided for troubleshooting mode
if vendor_id is not None or product_id is not None:
if vendor_id is None or product_id is None:
raise cv.Invalid("When using manual USB IDs for troubleshooting, both vendor_id and product_id must be specified")
# Validate non-zero IDs
if vendor_id == 0 or product_id == 0:
raise cv.Invalid("USB vendor and product IDs must be non-zero")
# Warn about unknown vendor IDs
if vendor_id not in KNOWN_VENDOR_IDS:
raise cv.Invalid("Unknown vendor id")
# Warn about unknown vendor IDs
if vendor_id not in KNOWN_VENDOR_IDS:
# Just log a warning instead of failing - this is for troubleshooting
import logging
logging.getLogger(__name__).warning(
f"Unknown USB vendor ID 0x{vendor_id:04X}. "
"Component will attempt auto-detection first, then fall back to manual settings."
)
return config
@@ -87,11 +101,13 @@ CONFIG_SCHEMA = cv.All(
{
cv.GenerateID(): cv.declare_id(UpsHidComponent),
cv.Optional(CONF_SIMULATION_MODE, default=False): cv.boolean,
cv.Optional(CONF_USB_VENDOR_ID, default=0x051D): cv.hex_uint16_t,
cv.Optional(CONF_USB_PRODUCT_ID, default=0x0002): cv.hex_uint16_t,
# Manual USB IDs are now primarily for troubleshooting when auto-detection fails
cv.Optional(CONF_USB_VENDOR_ID): cv.hex_uint16_t,
cv.Optional(CONF_USB_PRODUCT_ID): cv.hex_uint16_t,
cv.Optional(
CONF_PROTOCOL_TIMEOUT, default="15s"
): validate_protocol_timeout,
# Auto-detection is now always attempted first, this controls fallback behavior
cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean,
}
).extend(cv.polling_component_schema("30s"))
@@ -105,7 +121,12 @@ async def to_code(config):
await cg.register_component(var, config)
cg.add(var.set_simulation_mode(config[CONF_SIMULATION_MODE]))
cg.add(var.set_usb_vendor_id(config[CONF_USB_VENDOR_ID]))
cg.add(var.set_usb_product_id(config[CONF_USB_PRODUCT_ID]))
# USB IDs are now optional - only set if provided for troubleshooting
if CONF_USB_VENDOR_ID in config:
cg.add(var.set_usb_vendor_id(config[CONF_USB_VENDOR_ID]))
if CONF_USB_PRODUCT_ID in config:
cg.add(var.set_usb_product_id(config[CONF_USB_PRODUCT_ID]))
cg.add(var.set_protocol_timeout(config[CONF_PROTOCOL_TIMEOUT]))
cg.add(var.set_auto_detect_protocol(config[CONF_AUTO_DETECT_PROTOCOL]))
+42 -74
View File
@@ -323,18 +323,8 @@ namespace esphome
{
ESP_LOGD(TAG, "Detecting UPS protocol...");
if (!auto_detect_protocol_)
{
// Use APC HID Protocol as default when auto-detection is disabled
active_protocol_ = std::make_unique<ApcHidProtocol>(this);
if (active_protocol_->initialize())
{
ESP_LOGI(TAG, "Using pre-configured protocol: %s", active_protocol_->get_protocol_name().c_str());
ups_data_.detected_protocol = active_protocol_->get_protocol_type();
return true;
}
return false;
}
// Always try auto-detection first to discover the actual device
ESP_LOGI(TAG, "Starting automatic protocol detection...");
// Get the actual USB device vendor/product IDs (may differ from configured defaults)
uint16_t detected_vid = usb_vendor_id_;
@@ -346,6 +336,11 @@ namespace esphome
{
detected_vid = usb_device_.vid;
detected_pid = usb_device_.pid;
ESP_LOGI(TAG, "Auto-detected USB device: VID=0x%04X, PID=0x%04X", detected_vid, detected_pid);
}
else
{
ESP_LOGW(TAG, "No USB device connected, using configured IDs: VID=0x%04X, PID=0x%04X", detected_vid, detected_pid);
}
#endif
@@ -353,21 +348,19 @@ namespace esphome
if (is_known_ups_vendor(detected_vid))
{
const char *vendor_name = get_ups_vendor_name(detected_vid);
ESP_LOGD(TAG, "Detected known UPS vendor: %s (0x%04X)", vendor_name, detected_vid);
ESP_LOGI(TAG, "Detected known UPS vendor: %s (0x%04X)", vendor_name, detected_vid);
}
else
{
ESP_LOGD(TAG, "Unknown vendor ID: 0x%04X (trying generic protocols)", detected_vid);
ESP_LOGI(TAG, "Unknown/Generic vendor ID: 0x%04X (trying all protocols)", detected_vid);
}
// Vendor-specific protocol detection with retry logic
// Always attempt auto-detection - try all protocols in intelligent order
std::vector<std::pair<std::string, std::function<bool()>>> protocol_attempts;
// Build protocol detection list based on vendor ID
switch (detected_vid)
{
case 0x051D: // APC
ESP_LOGD(TAG, "APC device detected, trying HID protocol");
if (detected_vid == 0x051D) {
// APC device detected - try APC HID first
ESP_LOGD(TAG, "APC device detected, trying APC HID protocol first");
protocol_attempts.push_back({"APC HID", [this]()
{
auto protocol = std::make_unique<ApcHidProtocol>(this);
@@ -379,10 +372,9 @@ namespace esphome
}
return false;
}});
break;
case 0x0764: // CyberPower
ESP_LOGD(TAG, "CyberPower device detected, trying CyberPower HID protocol");
} else if (detected_vid == 0x0764) {
// CyberPower device detected - try CyberPower HID first
ESP_LOGD(TAG, "CyberPower device detected, trying CyberPower HID protocol first");
protocol_attempts.push_back({"CyberPower HID", [this]()
{
auto protocol = std::make_unique<CyberPowerProtocol>(this);
@@ -394,15 +386,15 @@ namespace esphome
}
return false;
}});
break;
case 0x09AE: // Tripp Lite
case 0x06DA: // MGE UPS Systems (now Eaton)
case 0x0463: // MGE Office Protection Systems
case 0x050D: // Belkin
case 0x0665: // Cypress/Belkin
ESP_LOGD(TAG, "Known UPS vendor detected (0x%04X), trying Generic HID", detected_vid);
protocol_attempts.push_back({"Generic HID", [this]()
}
else if (detected_vid == 0x0463 || detected_vid == 0x047C || detected_vid == 0x04B3 ||
detected_vid == 0x04D8 || detected_vid == 0x0483 || detected_vid == 0x050D ||
detected_vid == 0x0592 || detected_vid == 0x05DD || detected_vid == 0x06DA ||
detected_vid == 0x075D || detected_vid == 0x09AE || detected_vid == 0x09D6)
{
// Known UPS vendor with NUT HID driver support - try Generic HID first
ESP_LOGD(TAG, "Known UPS vendor detected (0x%04X), trying Generic HID first", detected_vid);
protocol_attempts.push_back({"Known UPS vendor - Generic HID", [this]()
{
auto protocol = std::make_unique<GenericHidProtocol>(this);
if (protocol->detect() && protocol->initialize())
@@ -413,48 +405,23 @@ namespace esphome
}
return false;
}});
break;
default:
// Unknown vendor - try all protocols with enhanced detection
ESP_LOGD(TAG, "Unknown vendor (0x%04X), trying all protocols", detected_vid);
protocol_attempts.push_back({"APC HID", [this]()
{
auto protocol = std::make_unique<ApcHidProtocol>(this);
if (protocol->detect() && protocol->initialize())
{
active_protocol_ = std::move(protocol);
ups_data_.detected_protocol = PROTOCOL_APC_HID;
return true;
}
return false;
}});
protocol_attempts.push_back({"CyberPower HID", [this]()
{
auto protocol = std::make_unique<CyberPowerProtocol>(this);
if (protocol->detect() && protocol->initialize())
{
active_protocol_ = std::move(protocol);
ups_data_.detected_protocol = PROTOCOL_CYBERPOWER_HID;
return true;
}
return false;
}});
break;
}
// Always add Generic HID as final fallback
protocol_attempts.push_back({"Generic HID", [this]()
{
auto protocol = std::make_unique<GenericHidProtocol>(this);
if (protocol->detect() && protocol->initialize())
else
{
// Always add Generic HID as final fallback (if not already added)
ESP_LOGD(TAG, "Unkown UPS vendor detected (0x%04X), using Generic HID", detected_vid);
protocol_attempts.push_back({"Unkown UPS vendor - Generic HID", [this]()
{
active_protocol_ = std::move(protocol);
ups_data_.detected_protocol = PROTOCOL_GENERIC_HID;
return true;
}
return false;
}});
auto protocol = std::make_unique<GenericHidProtocol>(this);
if (protocol->detect() && protocol->initialize())
{
active_protocol_ = std::move(protocol);
ups_data_.detected_protocol = PROTOCOL_GENERIC_HID;
return true;
}
return false;
}});
}
// Try each protocol with timeout and retry logic
for (const auto &attempt : protocol_attempts)
@@ -495,7 +462,8 @@ namespace esphome
}
}
ESP_LOGE(TAG, "No compatible UPS protocol detected for vendor 0x%04X", detected_vid);
ESP_LOGW(TAG, "Auto-detection failed for vendor 0x%04X", detected_vid);
return false;
}
+20 -8
View File
@@ -136,11 +136,15 @@ namespace esphome
class UpsHidComponent : public PollingComponent
{
public:
UpsHidComponent() : usb_device_{}, usb_mutex_(nullptr), usb_lib_task_handle_(nullptr),
usb_client_task_handle_(nullptr), usb_host_initialized_(false),
device_connected_(false), usb_tasks_running_(false) {
UpsHidComponent() {
#ifdef USE_ESP32
memset(&usb_device_, 0, sizeof(usb_device_));
usb_mutex_ = nullptr;
usb_lib_task_handle_ = nullptr;
usb_client_task_handle_ = nullptr;
usb_host_initialized_ = false;
device_connected_ = false;
usb_tasks_running_ = false;
ups_data_cache_.last_update_time = 0;
ups_data_cache_.data_valid = false;
#endif
@@ -163,10 +167,10 @@ namespace esphome
// Configuration setters with validation
void set_simulation_mode(bool simulation_mode) { simulation_mode_ = simulation_mode; }
void set_usb_vendor_id(uint16_t vendor_id) {
if (vendor_id != 0) usb_vendor_id_ = vendor_id;
usb_vendor_id_ = vendor_id;
}
void set_usb_product_id(uint16_t product_id) {
if (product_id != 0) usb_product_id_ = product_id;
usb_product_id_ = product_id;
}
void set_protocol_timeout(uint32_t timeout_ms) {
// Bound timeout between 5 seconds and 5 minutes for safety
@@ -186,7 +190,13 @@ namespace esphome
// USB device info getters
uint16_t get_usb_vendor_id() const { return usb_vendor_id_; }
uint16_t get_usb_product_id() const { return usb_product_id_; }
bool is_input_only_device() const { return usb_device_.is_input_only; }
bool is_input_only_device() const {
#ifdef USE_ESP32
return usb_device_.is_input_only;
#else
return false;
#endif
}
// Sensor registration methods
void register_sensor(sensor::Sensor *sens, const std::string &type);
@@ -195,8 +205,8 @@ namespace esphome
protected:
bool simulation_mode_{false};
uint16_t usb_vendor_id_{0x051D}; // APC default
uint16_t usb_product_id_{0x0002}; // Back-UPS ES series default
uint16_t usb_vendor_id_{0}; // 0 means auto-detect
uint16_t usb_product_id_{0}; // 0 means auto-detect
uint32_t protocol_timeout_ms_{10000};
bool auto_detect_protocol_{true};
@@ -239,9 +249,11 @@ namespace esphome
bool usb_write(const std::vector<uint8_t> &data);
bool usb_read(std::vector<uint8_t> &data, uint32_t timeout_ms = 1000);
#ifdef USE_ESP32
// HID class requests (UPS-specific communication)
esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id, uint8_t* data, size_t* data_len);
esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, const uint8_t* data, size_t data_len);
#endif
protected:
+20 -12
View File
@@ -21,19 +21,27 @@ namespace esphome
const char *description;
};
// Definitive list of known UPS vendors (based on NUT project driver.list)
// Definitive list of known UPS vendors (based on NUT project HID driver support)
static constexpr UpsVendor KNOWN_UPS_VENDORS[] = {
//{0x0001, "Generic/Other", "Generic UPS vendors (multiple brands)"},
{0x0463, "MGE Office Protection Systems", "MGE Office Protection Systems"},
{0x050D, "Belkin", "Belkin (older USB UPS models)"},
{0x051D, "APC", "American Power Conversion"},
{0x05B8, "SVEN", "SVEN UPS devices"},
{0x0665, "Cypress/Belkin", "Cypress or Belkin UPS devices"},
{0x06DA, "MGE UPS Systems", "MGE UPS Systems (now Eaton)"},
{0x0764, "CyberPower", "CyberPower Systems"},
{0x0925, "Richcomm", "Richcomm Technologies (Digitus, Sweex)"},
{0x09AE, "Tripp Lite", "Tripp Lite"},
{0x09D6, "Micropower", "Micropower UPS devices"},
// Vendors with dedicated HID drivers and ESPHome implementations
{0x051D, "APC", "American Power Conversion (dedicated ESPHome protocol)"},
{0x0764, "CyberPower", "CyberPower Systems (dedicated ESPHome protocol)"},
// Vendors with dedicated NUT HID drivers (Generic HID protocol support)
{0x0463, "MGE Office Protection Systems", "MGE Office Protection Systems (Eaton)"},
{0x047C, "Dell", "Dell UPS devices (via MGE HID driver)"},
{0x04B3, "IBM", "IBM UPS devices (via MGE HID driver)"},
{0x04D8, "OpenUPS", "OpenUPS HID devices"},
{0x050D, "Belkin", "Belkin USB UPS models"},
{0x0592, "Powerware", "Powerware UPS devices (via MGE HID driver)"},
{0x05DD, "Delta Electronics", "Delta UPS devices (Tripp Lite OEM)"},
{0x06DA, "MGE UPS Systems", "MGE UPS Systems / Liebert / Phoenixtec (now Eaton)"},
{0x075D, "Idowell", "Idowell HID UPS devices"},
{0x09AE, "Tripp Lite", "Tripp Lite UPS devices"},
{0x09D6, "KSTAR", "KSTAR/Micropower UPS devices"},
// STMicroelectronics OEM vendor (used by multiple UPS manufacturers)
{0x0483, "STMicroelectronics", "STMicro OEM UPS devices (CPS, Ever, others)"},
};
static constexpr size_t KNOWN_UPS_VENDORS_COUNT = sizeof(KNOWN_UPS_VENDORS) / sizeof(KNOWN_UPS_VENDORS[0]);