refactor(ups-hid): clean abstraction layers, strategy pattern for protocol selection and proper data structure

Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
bullshit committed 2025-08-23 14:22:02 +02:00
1 parent 0c1e540bb9
commit 7015fd2239
41 files changed
+4768 -3013

No files matched your search

+38 -6
View File
@@ -147,7 +147,7 @@ ups_hid:
usb_vendor_id: 0x051D # APC vendor ID (auto-detected if omitted)
usb_product_id: 0x0002 # Optional: specific product ID
protocol_timeout: 15s # USB communication timeout
auto_detect_protocol: true # Enable automatic protocol detection
protocol: auto # Protocol selection: auto, apc, cyberpower, generic
simulation_mode: false # Set to true for testing without UPS
# Define sensors (each sensor requires separate platform entry)
@@ -427,7 +427,7 @@ ups_hid:
usb_product_id: 0x0002 # USB Product ID (hex), optional
# Protocol Settings
auto_detect_protocol: true # Enable automatic protocol detection
protocol: auto # Protocol selection: auto, apc, cyberpower, generic
protocol_timeout: 15s # Communication timeout (5s-60s)
# Testing Options
@@ -794,14 +794,46 @@ logger:
## Advanced Configuration
### Custom Protocol Priority
### Protocol Selection
You can now manually select which UPS protocol to use instead of relying on auto-detection:
```yaml
ups_hid:
auto_detect_protocol: false # Disable auto-detection
# Component will use APC HID Protocol by default
protocol: auto # Default: automatic selection based on USB vendor ID
# protocol: apc # Force APC HID protocol
# protocol: cyberpower # Force CyberPower HID protocol
# protocol: generic # Force Generic HID protocol
```
**Protocol Options:**
- **`auto`** (default): Automatically select protocol based on USB vendor ID
- APC devices (0x051D): Uses APC HID Protocol
- CyberPower (0x0764): Uses CyberPower HID Protocol
- Unknown devices: Falls back to Generic HID Protocol
- **`apc`**: Force APC HID Protocol
- Use for APC devices: Back-UPS ES, Smart-UPS series
- Comprehensive sensor support with 20+ HID reports
- Battery and beeper testing (device-dependent)
- **`cyberpower`**: Force CyberPower HID Protocol
- Use for CyberPower CP series devices
- Enhanced sensor support with 12+ additional sensors
- Runtime scaling and advanced thresholds
- **`generic`**: Force Generic HID Protocol
- Universal fallback for unknown UPS brands
- Basic 5-sensor support with intelligent detection
- Limited beeper/testing functionality
**When to use manual selection:**
- Testing different protocols on the same device
- Troubleshooting protocol detection issues
- Using non-standard USB vendor/product IDs
- Forcing generic protocol for maximum compatibility
### Performance Tuning
```yaml
@@ -846,7 +878,7 @@ logger:
**Solutions**:
- Check if your UPS model is in the supported devices list
- Enable debug logging: `logger: level: DEBUG`
- Try manual protocol selection: `auto_detect_protocol: false`
- Try manual protocol selection: `protocol: generic` or `protocol: apc`
- Verify USB vendor/product IDs in logs
#### 3. "Failed to acquire USB mutex" errors
+22 -4
View File
@@ -14,7 +14,8 @@ CONF_SIMULATION_MODE = "simulation_mode"
CONF_USB_VENDOR_ID = "usb_vendor_id"
CONF_USB_PRODUCT_ID = "usb_product_id"
CONF_PROTOCOL_TIMEOUT = "protocol_timeout"
CONF_AUTO_DETECT_PROTOCOL = "auto_detect_protocol"
CONF_PROTOCOL = "protocol"
CONF_FALLBACK_NOMINAL_VOLTAGE = "fallback_nominal_voltage"
CONF_UPS_HID_ID = "ups_hid_id"
# Known UPS vendor IDs for validation
@@ -96,6 +97,18 @@ def validate_update_interval(value):
return value
def validate_fallback_nominal_voltage(value):
"""Validate fallback nominal voltage for international compatibility."""
value = cv.voltage(value)
if value < 80.0:
raise cv.Invalid("Fallback nominal voltage must be at least 80V")
if value > 300.0:
raise cv.Invalid("Fallback nominal voltage must be at most 300V")
return value
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
@@ -107,8 +120,12 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(
CONF_PROTOCOL_TIMEOUT, default="15s"
): validate_protocol_timeout,
# Auto-detection is now always attempted first, this controls fallback behavior
cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean,
# Protocol selection: auto (default), apc, cyberpower, generic
cv.Optional(CONF_PROTOCOL, default="auto"): cv.one_of(
"auto", "apc", "cyberpower", "generic", lower=True
),
# Fallback nominal voltage (European 230V default for international compatibility)
cv.Optional(CONF_FALLBACK_NOMINAL_VOLTAGE, default="230V"): validate_fallback_nominal_voltage,
}
).extend(cv.polling_component_schema("30s"))
.extend(cv.COMPONENT_SCHEMA),
@@ -129,4 +146,5 @@ async def to_code(config):
cg.add(var.set_usb_product_id(config[CONF_USB_PRODUCT_ID]))
cg.add(var.set_protocol_timeout(config[CONF_PROTOCOL_TIMEOUT]))
cg.add(var.set_auto_detect_protocol(config[CONF_AUTO_DETECT_PROTOCOL]))
cg.add(var.set_protocol_selection(config[CONF_PROTOCOL]))
cg.add(var.set_fallback_nominal_voltage(config[CONF_FALLBACK_NOMINAL_VOLTAGE]))
File diff suppressed because it is too large. Load diff
+9 -1
View File
@@ -13,7 +13,7 @@ public:
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
UpsProtocol get_protocol_type() const override { return PROTOCOL_APC_HID; }
DeviceInfo::DetectedProtocol get_protocol_type() const override { return DeviceInfo::PROTOCOL_APC_HID; }
std::string get_protocol_name() const override { return "APC HID Protocol"; }
// Beeper control methods
@@ -72,10 +72,18 @@ private:
void parse_battery_runtime_low_report(const HidReport &report, UpsData &data);
void parse_manufacture_date_report(const HidReport &report, UpsData &data, bool is_battery);
void parse_ups_delay_shutdown_report(const HidReport &report, UpsData &data);
void parse_ups_delay_reboot_report(const HidReport &report, UpsData &data);
void parse_battery_charge_threshold_report(const HidReport &report, UpsData &data, bool is_low_threshold);
void parse_battery_chemistry_report(const HidReport &report, UpsData &data);
void parse_test_result_report(const HidReport &report, UpsData &data);
std::string convert_apc_date(uint16_t date_value);
// Device model detection and configuration
void detect_nominal_power_rating(const std::string& model_name, UpsData &data);
// Frequency reading methods
void read_frequency_data(UpsData &data);
float parse_frequency_from_report(const HidReport &report);
};
} // namespace ups_hid
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include <string>
#include <cmath>
namespace esphome {
namespace ups_hid {
struct BatteryData {
// Core battery metrics
float level{NAN}; // Battery charge level (0-100%)
float voltage{NAN}; // Current battery voltage (V)
float voltage_nominal{NAN}; // Nominal battery voltage (V)
float runtime_minutes{NAN}; // Estimated runtime (minutes)
// Battery thresholds
float charge_low{NAN}; // Low battery threshold (%)
float charge_warning{NAN}; // Warning battery threshold (%)
float runtime_low{NAN}; // Low runtime threshold (minutes)
// Battery status information
std::string status{}; // Battery status text
std::string type{}; // Battery chemistry type
std::string mfr_date{}; // Battery manufacture date
// Validation and utility methods
bool is_valid() const {
return !std::isnan(level) || !std::isnan(voltage) || !std::isnan(runtime_minutes);
}
bool is_low() const {
return !std::isnan(level) && !std::isnan(charge_low) && level <= charge_low;
}
bool is_warning() const {
return !std::isnan(level) && !std::isnan(charge_warning) && level <= charge_warning;
}
bool has_runtime_estimate() const {
return !std::isnan(runtime_minutes) && runtime_minutes > 0;
}
void reset() {
*this = BatteryData{};
}
// Copy constructor and assignment for safe copying
BatteryData() = default;
BatteryData(const BatteryData&) = default;
BatteryData& operator=(const BatteryData&) = default;
BatteryData(BatteryData&&) = default;
BatteryData& operator=(BatteryData&&) = default;
};
} // namespace ups_hid
} // namespace esphome
+1 -1
View File
@@ -32,7 +32,7 @@ void UpsHidButton::press_action() {
// Get the current protocol from the parent component
UpsData ups_data = parent_->get_ups_data();
if (ups_data.detected_protocol == PROTOCOL_UNKNOWN) {
if (ups_data.device.detected_protocol == DeviceInfo::PROTOCOL_UNKNOWN) {
ESP_LOGW(BUTTON_TAG, "UPS protocol not detected, cannot execute button action");
return;
}
+150
View File
@@ -0,0 +1,150 @@
#pragma once
#include <string>
#include <cstdint>
namespace esphome {
namespace ups_hid {
struct ConfigData {
// Timing configuration
int16_t delay_shutdown{-1}; // Shutdown delay (seconds, -1 = not set)
int16_t delay_start{-1}; // Start delay (seconds, -1 = not set)
int16_t delay_reboot{-1}; // Reboot delay (seconds, -1 = not set)
// Beeper configuration
std::string beeper_status{}; // Current beeper status
enum BeeperState {
BEEPER_UNKNOWN = 0,
BEEPER_ENABLED,
BEEPER_DISABLED,
BEEPER_MUTED
};
BeeperState beeper_state{BEEPER_UNKNOWN};
// Input sensitivity configuration
std::string input_sensitivity{}; // Input sensitivity setting
enum SensitivityLevel {
SENSITIVITY_UNKNOWN = 0,
SENSITIVITY_LOW,
SENSITIVITY_MEDIUM,
SENSITIVITY_HIGH,
SENSITIVITY_AUTO
};
SensitivityLevel sensitivity_level{SENSITIVITY_UNKNOWN};
// Power management thresholds (configurable on some UPS models)
float low_battery_threshold{NAN}; // Low battery warning threshold (%)
float critical_battery_threshold{NAN}; // Critical battery threshold (%)
float high_temperature_threshold{NAN}; // High temperature warning (°C)
// Advanced configuration options
bool auto_restart_enabled{false}; // Auto restart after power restoration
bool cold_start_enabled{false}; // Cold start capability
bool audible_alarm_enabled{true}; // Audible alarm on events
// Communication settings
uint16_t protocol_timeout_ms{15000}; // Protocol communication timeout
uint16_t retry_count{3}; // Number of communication retries
bool auto_detect_protocol{true}; // Automatic protocol detection
// Validation and utility methods
bool has_timing_config() const {
return delay_shutdown != -1 || delay_start != -1 || delay_reboot != -1;
}
bool has_beeper_config() const {
return !beeper_status.empty() || beeper_state != BEEPER_UNKNOWN;
}
bool has_sensitivity_config() const {
return !input_sensitivity.empty() || sensitivity_level != SENSITIVITY_UNKNOWN;
}
bool has_thresholds() const {
return !std::isnan(low_battery_threshold) ||
!std::isnan(critical_battery_threshold) ||
!std::isnan(high_temperature_threshold);
}
std::string get_beeper_state_name() const {
switch (beeper_state) {
case BEEPER_ENABLED: return "Enabled";
case BEEPER_DISABLED: return "Disabled";
case BEEPER_MUTED: return "Muted";
default: return "Unknown";
}
}
std::string get_sensitivity_name() const {
switch (sensitivity_level) {
case SENSITIVITY_LOW: return "Low";
case SENSITIVITY_MEDIUM: return "Medium";
case SENSITIVITY_HIGH: return "High";
case SENSITIVITY_AUTO: return "Auto";
default: return "Unknown";
}
}
void parse_beeper_status(const std::string& status) {
beeper_status = status;
// Convert string to enum for easier handling
if (status == "enabled" || status == "on" || status == "1") {
beeper_state = BEEPER_ENABLED;
} else if (status == "disabled" || status == "off" || status == "0") {
beeper_state = BEEPER_DISABLED;
} else if (status == "muted") {
beeper_state = BEEPER_MUTED;
} else {
beeper_state = BEEPER_UNKNOWN;
}
}
void parse_input_sensitivity(const std::string& sensitivity) {
input_sensitivity = sensitivity;
// Convert string to enum for easier handling
if (sensitivity == "low" || sensitivity == "L") {
sensitivity_level = SENSITIVITY_LOW;
} else if (sensitivity == "medium" || sensitivity == "M" || sensitivity == "normal") {
sensitivity_level = SENSITIVITY_MEDIUM;
} else if (sensitivity == "high" || sensitivity == "H") {
sensitivity_level = SENSITIVITY_HIGH;
} else if (sensitivity == "auto" || sensitivity == "A") {
sensitivity_level = SENSITIVITY_AUTO;
} else {
sensitivity_level = SENSITIVITY_UNKNOWN;
}
}
bool is_beeper_enabled() const {
return beeper_state == BEEPER_ENABLED;
}
bool is_beeper_muted() const {
return beeper_state == BEEPER_MUTED;
}
bool is_valid() const {
return has_timing_config() || has_beeper_config() || has_sensitivity_config() || has_thresholds();
}
void reset() {
*this = ConfigData{};
}
// Copy constructor and assignment for safe copying
ConfigData() = default;
ConfigData(const ConfigData&) = default;
ConfigData& operator=(const ConfigData&) = default;
ConfigData(ConfigData&&) = default;
ConfigData& operator=(ConfigData&&) = default;
};
} // namespace ups_hid
} // namespace esphome
+293 -131
View File
@@ -1,5 +1,6 @@
#include "cyberpower_protocol.h"
#include "ups_hid.h"
#include "hid_constants.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/portmacro.h"
@@ -189,8 +190,15 @@ bool CyberPowerProtocol::read_data(UpsData &data) {
parse_firmware_version_report(firmware_version_report, data);
}
// Read test result (Report 0x14) - same report ID used for test commands
HidReport test_result_report;
if (read_hid_report(TEST_RESULT_REPORT_ID, test_result_report)) {
parse_test_result_report(test_result_report, data);
}
// Set frequency to NaN - not available for CyberPower CP1500 model
data.frequency = NAN;
// Try to read frequency from HID reports
read_frequency_data(data);
// TIMING FIX: Only read USB string descriptors after successful HID communication
// This ensures the device is ready and responsive before attempting descriptor access
@@ -203,10 +211,10 @@ bool CyberPowerProtocol::read_data(UpsData &data) {
esp_err_t mfr_ret = parent_->usb_get_string_descriptor(3, manufacturer_string);
if (mfr_ret == ESP_OK && !manufacturer_string.empty()) {
data.manufacturer = manufacturer_string;
ESP_LOGI(CP_TAG, "Successfully read manufacturer from USB descriptor: \"%s\"", data.manufacturer.c_str());
data.device.manufacturer = manufacturer_string;
ESP_LOGI(CP_TAG, "Successfully read manufacturer from USB descriptor: \"%s\"", data.device.manufacturer.c_str());
} else {
data.manufacturer.clear(); // Set to unset state instead of hardcoded fallback
data.device.manufacturer.clear(); // Set to unset state instead of hardcoded fallback
ESP_LOGW(CP_TAG, "Failed to read USB Manufacturer descriptor: %s, leaving unset", esp_err_to_name(mfr_ret));
}
@@ -216,10 +224,10 @@ bool CyberPowerProtocol::read_data(UpsData &data) {
esp_err_t prod_ret = parent_->usb_get_string_descriptor(1, product_string);
if (prod_ret == ESP_OK && !product_string.empty()) {
data.model = product_string;
ESP_LOGI(CP_TAG, "Successfully read CyberPower model from USB Product descriptor: \"%s\"", data.model.c_str());
data.device.model = product_string;
ESP_LOGI(CP_TAG, "Successfully read CyberPower model from USB Product descriptor: \"%s\"", data.device.model.c_str());
} else {
data.model.clear(); // Set to unset state instead of hardcoded fallback
data.device.model.clear(); // Set to unset state instead of hardcoded fallback
ESP_LOGW(CP_TAG, "Failed to read USB Product descriptor: %s, leaving model unset", esp_err_to_name(prod_ret));
}
@@ -230,8 +238,8 @@ bool CyberPowerProtocol::read_data(UpsData &data) {
} else {
ESP_LOGW(CP_TAG, "Failed to read any CyberPower HID reports");
// Leave manufacturer and model unset when HID communication fails
data.manufacturer.clear();
data.model.clear();
data.device.manufacturer.clear();
data.device.model.clear();
}
return success;
@@ -252,7 +260,7 @@ bool CyberPowerProtocol::read_hid_report(uint8_t report_id, HidReport &report) {
ESP_LOGD(CP_TAG, "Attempting to read report 0x%02X from parent device", report_id);
// CyberPower devices primarily use Feature Reports (0x03) - based on NUT debug logs
ret = parent_->hid_get_report(0x03, report_id, buffer, &buffer_len);
ret = parent_->hid_get_report(0x03, report_id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
report.report_id = report_id;
report.data.assign(buffer, buffer + buffer_len);
@@ -271,7 +279,7 @@ bool CyberPowerProtocol::read_hid_report(uint8_t report_id, HidReport &report) {
// Fallback: try Input Report (0x01) for real-time data
buffer_len = sizeof(buffer);
ret = parent_->hid_get_report(0x01, report_id, buffer, &buffer_len);
ret = parent_->hid_get_report(0x01, report_id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
report.report_id = report_id;
report.data.assign(buffer, buffer + buffer_len);
@@ -293,24 +301,27 @@ void CyberPowerProtocol::parse_battery_runtime_report(const HidReport &report, U
// NUT mapping:
// Offset 0 (byte 1): RemainingCapacity (battery %) - Size: 8
// Offset 8 (bytes 2-3): RunTimeToEmpty - Size: 16, little-endian
// Offset 8 (bytes 2-3): RunTimeToEmpty - Size: 16, little-endian (IN SECONDS)
// Offset 24 (bytes 4-5): RemainingTimeLimit - Size: 16, little-endian
uint8_t battery_percentage = report.data[1];
uint16_t runtime_minutes = report.data[2] | (report.data[3] << 8);
uint16_t runtime_seconds = report.data[2] | (report.data[3] << 8);
// Clamp battery to 100% like NUT does
data.battery_level = static_cast<float>(battery_percentage > 100 ? 100 : battery_percentage);
data.runtime_minutes = static_cast<float>(runtime_minutes);
data.battery.level = static_cast<float>(battery_percentage > 100 ? 100 : battery_percentage);
// CRITICAL FIX: Convert runtime from seconds to minutes
// CyberPower reports runtime in seconds, but ESPHome expects minutes
data.battery.runtime_minutes = static_cast<float>(runtime_seconds) / 60.0f;
// Extract runtime low threshold if available (offset 24 = bytes 4-5)
if (report.data.size() >= 6) {
uint16_t runtime_low_minutes = report.data[4] | (report.data[5] << 8);
data.battery_runtime_low = static_cast<float>(runtime_low_minutes);
ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.0f min, Runtime Low: %.0f min",
data.battery_level, data.runtime_minutes, data.battery_runtime_low);
uint16_t runtime_low_seconds = report.data[4] | (report.data[5] << 8);
data.battery.runtime_low = static_cast<float>(runtime_low_seconds) / 60.0f; // Convert to minutes
ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.1f min (%.0f sec), Runtime Low: %.1f min",
data.battery.level, data.battery.runtime_minutes, static_cast<float>(runtime_seconds), data.battery.runtime_low);
} else {
ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.0f min (raw: %02X %02X%02X)",
data.battery_level, data.runtime_minutes, battery_percentage, report.data[3], report.data[2]);
ESP_LOGD(CP_TAG, "Battery: %.0f%%, Runtime: %.1f min (%.0f sec raw: %02X %02X%02X)",
data.battery.level, data.battery.runtime_minutes, static_cast<float>(runtime_seconds), battery_percentage, report.data[3], report.data[2]);
}
}
@@ -324,10 +335,10 @@ void CyberPowerProtocol::parse_battery_voltage_report(const HidReport &report, U
// Current raw value: 0xF0 (240) should become 24V
// So scaling factor is 24/240 = 0.1 (divide by 10)
uint8_t voltage_raw = report.data[1];
data.battery_voltage = static_cast<float>(voltage_raw) / 10.0f; // Scale by 0.1
data.battery.voltage = static_cast<float>(voltage_raw) / 10.0f; // Scale by 0.1
ESP_LOGD(CP_TAG, "Battery voltage: %.1fV (raw: 0x%02X = %d)",
data.battery_voltage, voltage_raw, voltage_raw);
data.battery.voltage, voltage_raw, voltage_raw);
}
void CyberPowerProtocol::parse_present_status_report(const HidReport &report, UpsData &data) {
@@ -347,44 +358,40 @@ void CyberPowerProtocol::parse_present_status_report(const HidReport &report, Up
bool fully_charged = (status_byte & 0x10) != 0; // Offset 4
bool time_limit_expired = (status_byte & 0x20) != 0; // Offset 5
// Build status flags
uint32_t status_flags = 0;
if (ac_present) {
status_flags |= UPS_STATUS_ONLINE;
}
if (!ac_present || discharging) {
status_flags |= UPS_STATUS_ON_BATTERY;
}
if (charging) {
status_flags |= UPS_STATUS_CHARGING;
}
if (low_battery || time_limit_expired) {
status_flags |= UPS_STATUS_LOW_BATTERY;
}
data.status_flags = status_flags;
// Set battery status based on charging/discharging state (not FullChargeCapacity)
if (charging) {
data.battery_status = "charging";
} else if (discharging || !ac_present) {
data.battery_status = "discharging";
} else if (fully_charged) {
data.battery_status = "fully charged";
// Update power status based on AC presence
if (ac_present && !discharging) {
data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage when AC present
data.power.status = "Online";
} else {
data.battery_status = "normal";
data.power.input_voltage = NAN; // No AC input
data.power.status = "On Battery";
}
// Set battery status based on charging/discharging state
if (charging) {
data.battery.status = "Charging";
} else if (discharging || !ac_present) {
data.battery.status = "Discharging";
} else if (fully_charged) {
data.battery.status = "Fully Charged";
} else {
data.battery.status = "Normal";
}
// Set low battery indicators
if (low_battery || time_limit_expired) {
data.battery.charge_low = 10.0f; // Indicate low battery threshold
if (time_limit_expired) {
data.battery.status += " - Time Limit Expired";
}
}
ESP_LOGD(CP_TAG, "Status: AC:%s Charging:%s OnBatt:%s LowBatt:%s BattStatus:\"%s\"",
ac_present ? "Yes" : "No",
charging ? "Yes" : "No",
(status_flags & UPS_STATUS_ON_BATTERY) ? "Yes" : "No",
(status_flags & UPS_STATUS_LOW_BATTERY) ? "Yes" : "No",
data.battery_status.c_str());
(!ac_present || discharging) ? "Yes" : "No",
(low_battery || time_limit_expired) ? "Yes" : "No",
data.battery.status.c_str());
}
void CyberPowerProtocol::parse_input_voltage_report(const HidReport &report, UpsData &data) {
@@ -396,10 +403,10 @@ void CyberPowerProtocol::parse_input_voltage_report(const HidReport &report, Ups
// NUT debug: Report 0x0f, Value: 231 (matches our 0x00E6 = 230)
// Data format: [ID, volt_low, volt_high] - 16-bit little endian
uint16_t voltage_raw = report.data[1] | (report.data[2] << 8);
data.input_voltage = static_cast<float>(voltage_raw);
data.power.input_voltage = static_cast<float>(voltage_raw);
ESP_LOGD(CP_TAG, "Input voltage: %.1fV (raw: 0x%02X%02X = %d)",
data.input_voltage, report.data[2], report.data[1], voltage_raw);
data.power.input_voltage, report.data[2], report.data[1], voltage_raw);
}
void CyberPowerProtocol::parse_output_voltage_report(const HidReport &report, UpsData &data) {
@@ -411,10 +418,10 @@ void CyberPowerProtocol::parse_output_voltage_report(const HidReport &report, Up
// NUT debug: Report 0x12, Value: 231 (matches our 0x00E6 = 230)
// Data format: [ID, volt_low, volt_high] - 16-bit little endian
uint16_t voltage_raw = report.data[1] | (report.data[2] << 8);
data.output_voltage = static_cast<float>(voltage_raw);
data.power.output_voltage = static_cast<float>(voltage_raw);
ESP_LOGD(CP_TAG, "Output voltage: %.1fV (raw: 0x%02X%02X = %d)",
data.output_voltage, report.data[2], report.data[1], voltage_raw);
data.power.output_voltage, report.data[2], report.data[1], voltage_raw);
}
void CyberPowerProtocol::parse_load_percent_report(const HidReport &report, UpsData &data) {
@@ -426,10 +433,10 @@ void CyberPowerProtocol::parse_load_percent_report(const HidReport &report, UpsD
// NUT debug: Report 0x13, Value: 8 (our raw: 0x07 = 7%)
// Data format: [ID, load%] - single byte
uint8_t load_percent = report.data[1];
data.load_percent = static_cast<float>(load_percent);
data.power.load_percent = static_cast<float>(load_percent);
ESP_LOGD(CP_TAG, "Load: %.0f%% (raw: 0x%02X = %d)",
data.load_percent, load_percent, load_percent);
data.power.load_percent, load_percent, load_percent);
}
void CyberPowerProtocol::check_battery_voltage_scaling(float battery_voltage, float nominal_voltage) {
@@ -462,10 +469,10 @@ void CyberPowerProtocol::parse_battery_voltage_nominal_report(const HidReport &r
// NUT debug shows: Report 0x09, Value: 24 (ConfigVoltage)
// Some CyberPower models report in decivolts (240 = 24.0V)
uint8_t voltage_raw = report.data[1];
data.battery_voltage_nominal = static_cast<float>(voltage_raw) / 10.0f;
data.battery.voltage_nominal = static_cast<float>(voltage_raw) / 10.0f;
ESP_LOGD(CP_TAG, "Battery voltage nominal: %.0fV (raw: 0x%02X = %d)",
data.battery_voltage_nominal, voltage_raw, voltage_raw);
data.battery.voltage_nominal, voltage_raw, voltage_raw);
}
void CyberPowerProtocol::parse_beeper_status_report(const HidReport &report, UpsData &data) {
@@ -480,21 +487,21 @@ void CyberPowerProtocol::parse_beeper_status_report(const HidReport &report, Ups
// Map NUT values: 1=disabled, 2=enabled, 3=muted
switch (beeper_raw) {
case 1:
data.ups_beeper_status = "disabled";
data.config.beeper_status = "disabled";
break;
case 2:
data.ups_beeper_status = "enabled";
data.config.beeper_status = "enabled";
break;
case 3:
data.ups_beeper_status = "muted";
data.config.beeper_status = "muted";
break;
default:
data.ups_beeper_status = "unknown";
data.config.beeper_status = "unknown";
break;
}
ESP_LOGD(CP_TAG, "Beeper status: %s (raw: 0x%02X = %d)",
data.ups_beeper_status.c_str(), beeper_raw, beeper_raw);
data.config.beeper_status.c_str(), beeper_raw, beeper_raw);
}
void CyberPowerProtocol::parse_input_voltage_nominal_report(const HidReport &report, UpsData &data) {
@@ -505,10 +512,10 @@ void CyberPowerProtocol::parse_input_voltage_nominal_report(const HidReport &rep
// NUT debug shows: Report 0x0e, Value: 230 (ConfigVoltage)
uint8_t voltage_raw = report.data[1];
data.input_voltage_nominal = static_cast<float>(voltage_raw);
data.power.input_voltage_nominal = static_cast<float>(voltage_raw);
ESP_LOGD(CP_TAG, "Input voltage nominal: %.0fV (raw: 0x%02X = %d)",
data.input_voltage_nominal, voltage_raw, voltage_raw);
data.power.input_voltage_nominal, voltage_raw, voltage_raw);
}
void CyberPowerProtocol::parse_input_transfer_report(const HidReport &report, UpsData &data) {
@@ -523,11 +530,11 @@ void CyberPowerProtocol::parse_input_transfer_report(const HidReport &report, Up
uint16_t low_transfer = report.data[1] | (report.data[2] << 8);
uint16_t high_transfer = report.data[3] | (report.data[4] << 8);
data.input_transfer_low = static_cast<float>(low_transfer);
data.input_transfer_high = static_cast<float>(high_transfer);
data.power.input_transfer_low = static_cast<float>(low_transfer);
data.power.input_transfer_high = static_cast<float>(high_transfer);
ESP_LOGD(CP_TAG, "Input transfer limits: Low=%.0fV, High=%.0fV",
data.input_transfer_low, data.input_transfer_high);
data.power.input_transfer_low, data.power.input_transfer_high);
}
void CyberPowerProtocol::parse_delay_shutdown_report(const HidReport &report, UpsData &data) {
@@ -541,12 +548,12 @@ void CyberPowerProtocol::parse_delay_shutdown_report(const HidReport &report, Up
uint16_t delay_raw_unsigned = report.data[1] | (report.data[2] << 8);
if (delay_raw_unsigned == 0xFFFF) {
// When disabled, use NUT default for CyberPower (DEFAULT_OFFDELAY_CPS = 60)
data.ups_delay_shutdown = 60;
data.config.delay_shutdown = 60;
ESP_LOGD(CP_TAG, "UPS delay shutdown: 60 seconds (default, raw: 0xFFFF)");
} else {
int16_t delay_raw = static_cast<int16_t>(delay_raw_unsigned);
data.ups_delay_shutdown = delay_raw;
ESP_LOGD(CP_TAG, "UPS delay shutdown: %d seconds", data.ups_delay_shutdown);
data.config.delay_shutdown = delay_raw;
ESP_LOGD(CP_TAG, "UPS delay shutdown: %d seconds", data.config.delay_shutdown);
}
}
@@ -561,12 +568,12 @@ void CyberPowerProtocol::parse_delay_start_report(const HidReport &report, UpsDa
uint16_t delay_raw_unsigned = report.data[1] | (report.data[2] << 8);
if (delay_raw_unsigned == 0xFFFF) {
// When disabled, use NUT default for CyberPower (DEFAULT_ONDELAY_CPS = 120)
data.ups_delay_start = 120;
data.config.delay_start = 120;
ESP_LOGD(CP_TAG, "UPS delay start: 120 seconds (default, raw: 0xFFFF)");
} else {
int16_t delay_raw = static_cast<int16_t>(delay_raw_unsigned);
data.ups_delay_start = delay_raw;
ESP_LOGD(CP_TAG, "UPS delay start: %d seconds", data.ups_delay_start);
data.config.delay_start = delay_raw;
ESP_LOGD(CP_TAG, "UPS delay start: %d seconds", data.config.delay_start);
}
}
@@ -578,9 +585,9 @@ void CyberPowerProtocol::parse_realpower_nominal_report(const HidReport &report,
// NUT debug shows: Report 0x18, Value: 900 (ConfigActivePower)
uint16_t power_raw = report.data[1] | (report.data[2] << 8);
data.ups_realpower_nominal = static_cast<float>(power_raw);
data.power.realpower_nominal = static_cast<float>(power_raw);
ESP_LOGD(CP_TAG, "UPS nominal real power: %.0fW", data.ups_realpower_nominal);
ESP_LOGD(CP_TAG, "UPS nominal real power: %.0fW", data.power.realpower_nominal);
}
void CyberPowerProtocol::parse_input_sensitivity_report(const HidReport &report, UpsData &data) {
@@ -596,15 +603,15 @@ void CyberPowerProtocol::parse_input_sensitivity_report(const HidReport &report,
// DYNAMIC SENSITIVITY MAPPING: Handle known CyberPower values with intelligent fallbacks
switch (sensitivity_raw) {
case 0:
data.input_sensitivity = "high";
data.config.input_sensitivity = "high";
ESP_LOGI(CP_TAG, "CyberPower input sensitivity: high (raw: %d)", sensitivity_raw);
break;
case 1:
data.input_sensitivity = "normal";
data.config.input_sensitivity = "normal";
ESP_LOGI(CP_TAG, "CyberPower input sensitivity: normal (raw: %d)", sensitivity_raw);
break;
case 2:
data.input_sensitivity = "low";
data.config.input_sensitivity = "low";
ESP_LOGI(CP_TAG, "CyberPower input sensitivity: low (raw: %d)", sensitivity_raw);
break;
default:
@@ -622,26 +629,26 @@ void CyberPowerProtocol::parse_input_sensitivity_report(const HidReport &report,
if (alt_value <= 2) {
sensitivity_raw = alt_value;
switch (sensitivity_raw) {
case 0: data.input_sensitivity = "high"; break;
case 1: data.input_sensitivity = "normal"; break;
case 2: data.input_sensitivity = "low"; break;
case 0: data.config.input_sensitivity = "high"; break;
case 1: data.config.input_sensitivity = "normal"; break;
case 2: data.config.input_sensitivity = "low"; break;
}
ESP_LOGI(CP_TAG, "CyberPower input sensitivity (alt parsing): %s (raw: %d)",
data.input_sensitivity.c_str(), sensitivity_raw);
data.config.input_sensitivity.c_str(), sensitivity_raw);
return;
}
}
// Fallback for problematic values
data.input_sensitivity = "normal";
data.config.input_sensitivity = "normal";
ESP_LOGW(CP_TAG, "Using default 'normal' sensitivity due to unexpected value: %d", sensitivity_raw);
} else {
// Values 3-99 - extend mapping for future CyberPower models
if (sensitivity_raw == 3) {
data.input_sensitivity = "auto";
data.config.input_sensitivity = "auto";
ESP_LOGI(CP_TAG, "CyberPower input sensitivity: auto (raw: %d)", sensitivity_raw);
} else {
data.input_sensitivity = "unknown";
data.config.input_sensitivity = "unknown";
ESP_LOGW(CP_TAG, "Unknown CyberPower sensitivity value: %d - please report this for future support",
sensitivity_raw);
}
@@ -670,9 +677,9 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report,
if (fw_ret == ESP_OK && !actual_firmware.empty()) {
// Clean up firmware string - remove invalid characters and trim
std::string cleaned_firmware = clean_firmware_string(actual_firmware);
data.firmware_version = cleaned_firmware;
data.device.firmware_version = cleaned_firmware;
ESP_LOGI(CP_TAG, "Successfully read CyberPower firmware from USB string descriptor %d: \"%s\"",
string_index, data.firmware_version.c_str());
string_index, data.device.firmware_version.c_str());
if (cleaned_firmware != actual_firmware) {
ESP_LOGD(CP_TAG, "Cleaned firmware string from \"%s\" to \"%s\"",
actual_firmware.c_str(), cleaned_firmware.c_str());
@@ -696,8 +703,8 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report,
}
if (!firmware_from_hid.empty() && firmware_from_hid.length() >= 3) {
data.firmware_version = firmware_from_hid;
ESP_LOGI(CP_TAG, "Firmware version from HID report data: %s", data.firmware_version.c_str());
data.device.firmware_version = firmware_from_hid;
ESP_LOGI(CP_TAG, "Firmware version from HID report data: %s", data.device.firmware_version.c_str());
return;
}
@@ -716,9 +723,9 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report,
if ((cleaned_fw.find("CR") == 0 || cleaned_fw.find("CP") == 0 ||
cleaned_fw.find("FW") != std::string::npos)) {
// Looks like a valid CyberPower firmware string
data.firmware_version = cleaned_fw;
data.device.firmware_version = cleaned_fw;
ESP_LOGI(CP_TAG, "Found CyberPower firmware at alternative string descriptor %d: \"%s\"",
idx, data.firmware_version.c_str());
idx, data.device.firmware_version.c_str());
if (cleaned_fw != fw_attempt) {
ESP_LOGD(CP_TAG, "Cleaned alternative firmware string from \"%s\" to \"%s\"",
fw_attempt.c_str(), cleaned_fw.c_str());
@@ -734,16 +741,16 @@ void CyberPowerProtocol::parse_firmware_version_report(const HidReport &report,
snprintf(firmware_fallback, sizeof(firmware_fallback), "CP-%02X.%02X.%02X",
report.data[1], report.data[2],
(report.data.size() > 3) ? report.data[3] : 0);
data.firmware_version = firmware_fallback;
ESP_LOGD(CP_TAG, "Using binary firmware version fallback: %s", data.firmware_version.c_str());
data.device.firmware_version = firmware_fallback;
ESP_LOGD(CP_TAG, "Using binary firmware version fallback: %s", data.device.firmware_version.c_str());
} else {
// No firmware version could be determined
data.firmware_version.clear();
data.device.firmware_version.clear();
ESP_LOGW(CP_TAG, "Unable to determine CyberPower firmware version from any source");
}
ESP_LOGD(CP_TAG, "Final firmware version: %s (original string index: %d)",
data.firmware_version.c_str(), string_index);
data.device.firmware_version.c_str(), string_index);
}
void CyberPowerProtocol::parse_overload_report(const HidReport &report, UpsData &data) {
@@ -758,10 +765,14 @@ void CyberPowerProtocol::parse_overload_report(const HidReport &report, UpsData
bool overload = (overload_byte & 0x01) != 0; // Check bit 0 (Offset 1 in NUT = bit 0)
if (overload) {
data.status_flags |= UPS_STATUS_OVERLOAD;
data.power.status += " - Overload";
ESP_LOGW(CP_TAG, "CyberPower UPS OVERLOAD detected (raw: 0x%02X)", overload_byte);
} else {
data.status_flags &= ~UPS_STATUS_OVERLOAD;
// Remove overload from status if it was there
size_t pos = data.power.status.find(" - Overload");
if (pos != std::string::npos) {
data.power.status.erase(pos, 11); // Length of " - Overload"
}
ESP_LOGD(CP_TAG, "CyberPower UPS overload status: normal (raw: 0x%02X)", overload_byte);
}
}
@@ -784,21 +795,21 @@ void CyberPowerProtocol::parse_serial_number_report(const HidReport &report, Ups
esp_err_t ret = parent_->usb_get_string_descriptor(string_index, actual_serial);
if (ret == ESP_OK && !actual_serial.empty()) {
data.serial_number = actual_serial;
data.device.serial_number = actual_serial;
ESP_LOGI(CP_TAG, "Successfully read CyberPower serial number from USB string descriptor %d: \"%s\"",
string_index, data.serial_number.c_str());
string_index, data.device.serial_number.c_str());
} else {
// Fallback if USB string descriptor reading fails
ESP_LOGW(CP_TAG, "Failed to read USB string descriptor %d: %s",
string_index, esp_err_to_name(ret));
// Set to unset state instead of generating fallback ID
data.serial_number.clear();
data.device.serial_number.clear();
ESP_LOGW(CP_TAG, "Leaving serial number unset due to USB string descriptor failure");
}
ESP_LOGD(CP_TAG, "Serial number: %s (string index: %d)",
data.serial_number.c_str(), string_index);
data.device.serial_number.c_str(), string_index);
}
void CyberPowerProtocol::read_missing_dynamic_values(UpsData &data) {
@@ -821,15 +832,15 @@ void CyberPowerProtocol::read_missing_dynamic_values(UpsData &data) {
// Just need to extract it properly
// 4. Set static/derived values based on NUT behavior
data.ups_test_result = "No test initiated"; // Default test result
data.test.ups_test_result = "No test initiated"; // Default test result
// NOTE: battery_status is now properly set based on charging state in parse_present_status_report
// 5. Timer values represent active countdown (negative when no countdown active)
// NUT shows: ups.timer.shutdown: -60, ups.timer.start: -60
data.ups_timer_shutdown = -data.ups_delay_shutdown; // Negative indicates no active countdown
data.ups_timer_start = -data.ups_delay_start; // Negative indicates no active countdown
data.ups_timer_reboot = -10; // CyberPower doesn't have separate reboot timer, use default
data.test.timer_shutdown = -data.config.delay_shutdown; // Negative indicates no active countdown
data.test.timer_start = -data.config.delay_start; // Negative indicates no active countdown
data.test.timer_reboot = -10; // CyberPower doesn't have separate reboot timer, use default
ESP_LOGD(CP_TAG, "Completed reading CyberPower missing dynamic values");
}
@@ -853,17 +864,17 @@ void CyberPowerProtocol::parse_battery_capacity_limits_report(const HidReport &r
// Extract warning capacity limit (offset 24 = byte 4)
if (report.data.size() > 4) {
uint8_t warning_limit = report.data[4]; // Offset 24 bits = byte 3 + 1
data.battery_charge_warning = static_cast<float>(warning_limit);
data.battery.charge_warning = static_cast<float>(warning_limit);
ESP_LOGI(CP_TAG, "CyberPower Battery charge warning threshold: %.0f%% (raw: %d)",
data.battery_charge_warning, warning_limit);
data.battery.charge_warning, warning_limit);
}
// Extract remaining capacity limit (offset 32 = byte 5)
if (report.data.size() > 5) {
uint8_t remaining_limit = report.data[5]; // Offset 32 bits = byte 4 + 1
data.battery_charge_low = static_cast<float>(remaining_limit);
data.battery.charge_low = static_cast<float>(remaining_limit);
ESP_LOGI(CP_TAG, "CyberPower Battery charge low threshold: %.0f%% (raw: %d)",
data.battery_charge_low, remaining_limit);
data.battery.charge_low, remaining_limit);
}
// Extract full charge capacity (offset 40 = byte 6) - this is NOT used for battery.status
@@ -887,31 +898,31 @@ void CyberPowerProtocol::parse_battery_chemistry_report(const HidReport &report,
// Map chemistry values based on NUT libhid implementation (same as APC)
switch (chemistry_raw) {
case 1:
data.battery_type = "Alkaline";
data.battery.type = "Alkaline";
break;
case 2:
data.battery_type = "NiCd";
data.battery.type = "NiCd";
break;
case 3:
data.battery_type = "NiMH";
data.battery.type = "NiMH";
break;
case 4:
data.battery_type = "PbAcid"; // Lead Acid (matches NUT output)
data.battery.type = "PbAcid"; // Lead Acid (matches NUT output)
break;
case 5:
data.battery_type = "LiIon";
data.battery.type = "LiIon";
break;
case 6:
data.battery_type = "LiPoly";
data.battery.type = "LiPoly";
break;
default:
data.battery_type = "Unknown";
data.battery.type = "Unknown";
ESP_LOGW(CP_TAG, "Unknown CyberPower battery chemistry value: %d", chemistry_raw);
break;
}
ESP_LOGI(CP_TAG, "CyberPower Battery chemistry: %s (raw: %d)",
data.battery_type.c_str(), chemistry_raw);
data.battery.type.c_str(), chemistry_raw);
}
std::string CyberPowerProtocol::clean_firmware_string(const std::string &raw_firmware) {
@@ -956,7 +967,7 @@ bool CyberPowerProtocol::beeper_enable() {
uint8_t beeper_data[2] = {BEEPER_STATUS_REPORT_ID, 0x02}; // Report ID, Value=2 (enabled)
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data));
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(CP_TAG, "CyberPower beeper enabled successfully with report ID 0x%02X", BEEPER_STATUS_REPORT_ID);
return true;
@@ -974,7 +985,7 @@ bool CyberPowerProtocol::beeper_disable() {
uint8_t beeper_data[2] = {BEEPER_STATUS_REPORT_ID, 0x01}; // Report ID, Value=1 (disabled)
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data));
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(CP_TAG, "CyberPower beeper disabled successfully with report ID 0x%02X", BEEPER_STATUS_REPORT_ID);
return true;
@@ -993,7 +1004,7 @@ bool CyberPowerProtocol::beeper_mute() {
// - Different from DISABLE (1) which turns off beeper completely
uint8_t beeper_data[2] = {0x0c, 0x03}; // Report ID, Value=3 (muted/acknowledged)
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data));
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, beeper_data, sizeof(beeper_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(CP_TAG, "CyberPower beeper muted (current alarms acknowledged) successfully");
return true;
@@ -1045,7 +1056,7 @@ bool CyberPowerProtocol::beeper_test() {
// Step 4: Restore original beeper state
ESP_LOGI(CP_TAG, "Step 4: Restoring original beeper state: %d", original_state);
uint8_t restore_data[2] = {0x0c, original_state};
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, restore_data, sizeof(restore_data));
esp_err_t ret = parent_->hid_set_report(0x03, BEEPER_STATUS_REPORT_ID, restore_data, sizeof(restore_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(CP_TAG, "CyberPower beeper test sequence completed successfully");
@@ -1064,7 +1075,7 @@ bool CyberPowerProtocol::start_battery_test_quick() {
// Quick test command value is 1 (from NUT test_write_info)
uint8_t test_data[2] = {0x14, 1}; // Report ID 0x14, value 1 = Quick test
esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2);
esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2, parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(CP_TAG, "Quick battery test command sent successfully");
return true;
@@ -1080,7 +1091,7 @@ bool CyberPowerProtocol::start_battery_test_deep() {
// Deep test command value is 2 (from NUT test_write_info)
uint8_t test_data[2] = {0x14, 2}; // Report ID 0x14, value 2 = Deep test
esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2);
esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2, parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(CP_TAG, "Deep battery test command sent successfully");
return true;
@@ -1096,7 +1107,7 @@ bool CyberPowerProtocol::stop_battery_test() {
// Abort test command value is 3 (from NUT test_write_info)
uint8_t test_data[2] = {0x14, 3}; // Report ID 0x14, value 3 = Abort test
esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2);
esp_err_t ret = parent_->hid_set_report(0x03, 0x14, test_data, 2, parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(CP_TAG, "Battery test stop command sent successfully");
return true;
@@ -1119,5 +1130,156 @@ bool CyberPowerProtocol::stop_ups_test() {
return stop_battery_test();
}
void CyberPowerProtocol::parse_test_result_report(const HidReport &report, UpsData &data) {
// Parse test result from Report 0x14 (UPS.Output.Test)
// Based on NUT test_read_info lookup table
if (report.data.size() < 2) {
data.test.ups_test_result = "Error reading test result";
return;
}
// Based on NUT test_read_info lookup table for CyberPower:
// 1 = "Done and passed", 2 = "Done and warning", 3 = "Done and error"
// 4 = "Aborted", 5 = "In progress", 6 = "No test initiated", 7 = "Test scheduled"
uint8_t test_result_value = report.data[1];
ESP_LOGD(CP_TAG, "Raw test result from report 0x14: 0x%02X (%d)", test_result_value, test_result_value);
switch (test_result_value) {
case 1:
data.test.ups_test_result = "Done and passed";
break;
case 2:
data.test.ups_test_result = "Done and warning";
break;
case 3:
data.test.ups_test_result = "Done and error";
break;
case 4:
data.test.ups_test_result = "Aborted";
break;
case 5:
data.test.ups_test_result = "In progress";
break;
case 6:
data.test.ups_test_result = "No test initiated";
break;
case 7:
data.test.ups_test_result = "Test scheduled";
break;
default:
data.test.ups_test_result = "Unknown test result (" + std::to_string(test_result_value) + ")";
ESP_LOGW(CP_TAG, "Unknown CyberPower test result value: %d", test_result_value);
break;
}
ESP_LOGI(CP_TAG, "CyberPower Test result: %s (raw: %d)", data.test.ups_test_result.c_str(), test_result_value);
}
void CyberPowerProtocol::read_frequency_data(UpsData &data) {
// Initialize frequency to NaN
data.power.frequency = NAN;
// Try to read frequency from various HID report IDs
// CyberPower devices may have frequency in input/output measurement reports
// Report IDs commonly used for frequency measurements:
const std::vector<uint8_t> frequency_report_ids = {
HID_USAGE_POW_FREQUENCY, // 0x32 - Standard HID frequency usage
HID_USAGE_POW_VOLTAGE, // 0x30 - Input measurements (may include frequency)
HID_USAGE_POW_CURRENT, // 0x31 - Output measurements (may include frequency)
0x11, // CyberPower-specific frequency report (based on NUT analysis)
INPUT_VOLTAGE_REPORT_ID, // 0x0F - might contain frequency data
OUTPUT_VOLTAGE_REPORT_ID, // 0x12 - might contain frequency data
};
for (uint8_t report_id : frequency_report_ids) {
HidReport freq_report;
if (read_hid_report(report_id, freq_report)) {
float frequency_value = parse_frequency_from_report(freq_report);
if (!std::isnan(frequency_value)) {
data.power.frequency = frequency_value;
ESP_LOGD(CP_TAG, "Found frequency %.1f Hz in report 0x%02X", frequency_value, report_id);
return;
}
}
}
ESP_LOGV(CP_TAG, "Frequency data not available from any HID report");
}
float CyberPowerProtocol::parse_frequency_from_report(const HidReport &report) {
if (report.data.size() < 2) {
return NAN;
}
// Try different byte positions and formats commonly used for frequency
// CyberPower devices may use 0.1 Hz scaling (report 501 becomes 50.1 Hz)
// Method 1: Single byte at position 1 (common for simple frequency reports)
if (report.data.size() >= 2) {
uint8_t freq_byte = report.data[1];
if (freq_byte >= FREQUENCY_MIN_VALID && freq_byte <= FREQUENCY_MAX_VALID) {
return static_cast<float>(freq_byte);
}
}
// Method 2: 16-bit little-endian value at position 1-2
if (report.data.size() >= 3) {
uint16_t freq_word = report.data[1] | (report.data[2] << 8);
if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) {
return static_cast<float>(freq_word);
}
}
// Method 3: 16-bit big-endian value at position 1-2
if (report.data.size() >= 3) {
uint16_t freq_word = (report.data[1] << 8) | report.data[2];
if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) {
return static_cast<float>(freq_word);
}
}
// Method 4: CyberPower-specific scaled frequency (0.1 factor)
// Some CyberPower models report frequency * 10 (e.g., 500 for 50.0 Hz, 600 for 60.0 Hz)
if (report.data.size() >= 3) {
uint16_t freq_scaled = report.data[1] | (report.data[2] << 8);
float freq_value = static_cast<float>(freq_scaled) / 10.0f;
if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) {
ESP_LOGD(CP_TAG, "Applied CyberPower 0.1x frequency scaling: %d -> %.1f Hz", freq_scaled, freq_value);
return freq_value;
}
}
// Method 5: Check for hundreds scaling (e.g., 5000 for 50.0 Hz)
if (report.data.size() >= 3) {
uint16_t freq_scaled = report.data[1] | (report.data[2] << 8);
float freq_value = static_cast<float>(freq_scaled) / 100.0f;
if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) {
ESP_LOGD(CP_TAG, "Applied CyberPower 0.01x frequency scaling: %d -> %.1f Hz", freq_scaled, freq_value);
return freq_value;
}
}
return NAN;
}
} // namespace ups_hid
} // namespace esphome
} // namespace esphome
// Protocol Factory Self-Registration
#include "protocol_factory.h"
namespace esphome {
namespace ups_hid {
// Creator function for CyberPower protocol
std::unique_ptr<UpsProtocolBase> create_cyberpower_protocol(UpsHidComponent* parent) {
return std::make_unique<CyberPowerProtocol>(parent);
}
} // namespace ups_hid
} // namespace esphome
// Register CyberPower protocol for vendor ID 0x0764
REGISTER_UPS_PROTOCOL_FOR_VENDOR(0x0764, cyberpower_hid_protocol, esphome::ups_hid::create_cyberpower_protocol, "CyberPower HID Protocol", "CyberPower CP series HID protocol with comprehensive sensor support and test functionality", 100);
+7 -1
View File
@@ -24,7 +24,7 @@ class CyberPowerProtocol : public UpsProtocolBase {
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
UpsProtocol get_protocol_type() const override { return PROTOCOL_CYBERPOWER_HID; }
DeviceInfo::DetectedProtocol get_protocol_type() const override { return DeviceInfo::PROTOCOL_CYBERPOWER_HID; }
std::string get_protocol_name() const override { return "CyberPower HID"; }
// Beeper control methods
@@ -60,6 +60,7 @@ class CyberPowerProtocol : public UpsProtocolBase {
static const uint8_t INPUT_SENSITIVITY_REPORT_ID = 0x1a; // Input sensitivity
static const uint8_t FIRMWARE_VERSION_REPORT_ID = 0x1b; // Firmware version
static const uint8_t SERIAL_NUMBER_REPORT_ID = 0x02; // Serial number
static const uint8_t TEST_RESULT_REPORT_ID = 0x14; // UPS test result (same as test command)
// HID Report structure
struct HidReport {
@@ -95,6 +96,7 @@ class CyberPowerProtocol : public UpsProtocolBase {
void parse_input_sensitivity_report(const HidReport &report, UpsData &data);
void parse_firmware_version_report(const HidReport &report, UpsData &data);
void parse_serial_number_report(const HidReport &report, UpsData &data);
void parse_test_result_report(const HidReport &report, UpsData &data);
// Missing dynamic values from NUT analysis
void read_missing_dynamic_values(UpsData &data);
@@ -106,6 +108,10 @@ class CyberPowerProtocol : public UpsProtocolBase {
// CyberPower-specific scaling logic
void check_battery_voltage_scaling(float battery_voltage, float nominal_voltage);
// Frequency reading methods
void read_frequency_data(UpsData &data);
float parse_frequency_from_report(const HidReport &report);
};
} // namespace ups_hid
+101
View File
@@ -0,0 +1,101 @@
#pragma once
#include <string>
namespace esphome {
namespace ups_hid {
struct DeviceInfo {
// Basic device identification
std::string manufacturer{}; // Device manufacturer
std::string model{}; // Device model name
std::string serial_number{}; // Device serial number
std::string firmware_version{}; // Primary firmware version
std::string firmware_aux{}; // Auxiliary firmware info
std::string mfr_date{}; // Device manufacture date
// USB device identification
uint16_t usb_vendor_id{0}; // USB Vendor ID
uint16_t usb_product_id{0}; // USB Product ID
// Protocol information
enum DetectedProtocol {
PROTOCOL_UNKNOWN = 0,
PROTOCOL_APC_HID,
PROTOCOL_CYBERPOWER_HID,
PROTOCOL_GENERIC_HID
};
DetectedProtocol detected_protocol{PROTOCOL_UNKNOWN};
// Device capabilities flags
struct Capabilities {
bool supports_hid_get_report{false};
bool supports_hid_set_report{false};
bool supports_beeper_control{false};
bool supports_battery_test{false};
bool supports_ups_test{false};
bool is_input_only_device{false};
bool supports_runtime_estimation{false};
bool supports_configuration_queries{false};
};
Capabilities capabilities{};
// Validation and utility methods
bool is_valid() const {
return !manufacturer.empty() || !model.empty() || !serial_number.empty();
}
bool has_basic_info() const {
return !manufacturer.empty() && !model.empty();
}
bool has_usb_info() const {
return usb_vendor_id != 0;
}
std::string get_protocol_name() const {
switch (detected_protocol) {
case PROTOCOL_APC_HID: return "APC HID";
case PROTOCOL_CYBERPOWER_HID: return "CyberPower HID";
case PROTOCOL_GENERIC_HID: return "Generic HID";
default: return "Unknown";
}
}
std::string get_device_description() const {
if (has_basic_info()) {
return manufacturer + " " + model;
} else if (!model.empty()) {
return model;
} else if (!manufacturer.empty()) {
return manufacturer + " Device";
} else {
return "Unknown UPS";
}
}
std::string get_usb_description() const {
if (has_usb_info()) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "0x%04X:0x%04X", usb_vendor_id, usb_product_id);
return std::string(buffer);
}
return "Unknown USB ID";
}
void reset() {
*this = DeviceInfo{};
}
// Copy constructor and assignment for safe copying
DeviceInfo() = default;
DeviceInfo(const DeviceInfo&) = default;
DeviceInfo& operator=(const DeviceInfo&) = default;
DeviceInfo(DeviceInfo&&) = default;
DeviceInfo& operator=(DeviceInfo&&) = default;
};
} // namespace ups_hid
} // namespace esphome
+881
View File
@@ -0,0 +1,881 @@
#include "esp32_usb_transport.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#ifdef USE_ESP32
namespace esphome {
namespace ups_hid {
static const char *const ESP32_USB_TAG = "ups_hid.esp32_usb";
// USB HID Class defines
#ifndef USB_CLASS_HID
#define USB_CLASS_HID 0x03
#endif
Esp32UsbTransport::Esp32UsbTransport() {
memset(&device_, 0, sizeof(device_));
}
Esp32UsbTransport::~Esp32UsbTransport() {
deinitialize();
}
esp_err_t Esp32UsbTransport::initialize() {
std::lock_guard<std::mutex> lock(device_mutex_);
if (initialized_.load()) {
return ESP_OK;
}
ESP_LOGI(ESP32_USB_TAG, "Initializing ESP32 USB transport");
esp_err_t ret = setup_usb_host();
if (ret != ESP_OK) {
set_last_error("Failed to setup USB host: " + std::string(esp_err_to_name(ret)));
return ret;
}
// Register USB client for device events - connection will be asynchronous
ret = find_and_open_device();
if (ret != ESP_OK) {
teardown_usb_host();
return ret;
}
initialized_ = true;
ESP_LOGI(ESP32_USB_TAG, "ESP32 USB transport initialized - waiting for USB device connection events");
return ESP_OK;
}
esp_err_t Esp32UsbTransport::deinitialize() {
std::lock_guard<std::mutex> lock(device_mutex_);
if (!initialized_.load()) {
return ESP_OK;
}
ESP_LOGI(ESP32_USB_TAG, "Deinitializing ESP32 USB transport");
connected_ = false;
initialized_ = false;
esp_err_t ret = teardown_usb_host();
if (ret != ESP_OK) {
ESP_LOGW(ESP32_USB_TAG, "USB teardown had issues: %s", esp_err_to_name(ret));
}
return ret;
}
bool Esp32UsbTransport::is_connected() const {
return connected_.load() && initialized_.load();
}
uint16_t Esp32UsbTransport::get_vendor_id() const {
std::lock_guard<std::mutex> lock(device_mutex_);
return device_.vendor_id;
}
uint16_t Esp32UsbTransport::get_product_id() const {
std::lock_guard<std::mutex> lock(device_mutex_);
return device_.product_id;
}
esp_err_t Esp32UsbTransport::hid_get_report(uint8_t report_type, uint8_t report_id,
uint8_t* data, size_t* data_len,
uint32_t timeout_ms) {
if (!device_.dev_hdl) {
ESP_LOGE(ESP32_USB_TAG, "HID GET_REPORT: No device handle");
return ESP_ERR_INVALID_ARG;
}
if (!data || !data_len || *data_len == 0) {
ESP_LOGE(ESP32_USB_TAG, "HID GET_REPORT: Invalid parameters");
return ESP_ERR_INVALID_ARG;
}
ESP_LOGD(ESP32_USB_TAG, "HID GET_REPORT: type=0x%02X, id=0x%02X, max_len=%zu",
report_type, report_id, *data_len);
// Use fixed buffer sizes like working implementation
uint8_t buffer[64] = {0}; // Fixed size buffer
size_t expected_len = std::min(*data_len, sizeof(buffer));
// Create USB control transfer for HID GET_REPORT
const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_IN |
USB_BM_REQUEST_TYPE_TYPE_CLASS |
USB_BM_REQUEST_TYPE_RECIP_INTERFACE;
const uint8_t bRequest = 0x01; // HID GET_REPORT
const uint16_t wValue = (report_type << 8) | report_id;
const uint16_t wIndex = device_.interface_num;
const uint16_t wLength = expected_len;
usb_transfer_t *transfer = nullptr;
size_t transfer_size = sizeof(usb_setup_packet_t) + expected_len;
esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer);
if (ret != ESP_OK) {
ESP_LOGE(ESP32_USB_TAG, "Failed to allocate transfer: %s", esp_err_to_name(ret));
return ret;
}
// Setup control transfer
transfer->device_handle = device_.dev_hdl;
transfer->bEndpointAddress = 0;
transfer->num_bytes = transfer_size;
transfer->timeout_ms = timeout_ms;
// Create setup packet
usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer;
setup->bmRequestType = bmRequestType;
setup->bRequest = bRequest;
setup->wValue = wValue;
setup->wIndex = wIndex;
setup->wLength = wLength;
// Use semaphore for synchronous operation
SemaphoreHandle_t done_sem = xSemaphoreCreateBinary();
if (!done_sem) {
usb_host_transfer_free(transfer);
return ESP_ERR_NO_MEM;
}
// Simple context for completion
struct {
SemaphoreHandle_t sem;
esp_err_t result;
size_t actual_bytes;
} ctx = {done_sem, ESP_ERR_TIMEOUT, 0};
transfer->context = &ctx;
transfer->callback = [](usb_transfer_t *t) {
auto *c = static_cast<decltype(ctx)*>(t->context);
c->result = (t->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL;
c->actual_bytes = t->actual_num_bytes;
xSemaphoreGive(c->sem);
};
ret = usb_host_transfer_submit_control(device_.client_hdl, transfer);
if (ret == ESP_OK) {
if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) {
ret = ctx.result;
if (ret == ESP_OK && ctx.actual_bytes > sizeof(usb_setup_packet_t)) {
size_t data_received = ctx.actual_bytes - sizeof(usb_setup_packet_t);
size_t copy_len = std::min(data_received, *data_len);
memcpy(data, transfer->data_buffer + sizeof(usb_setup_packet_t), copy_len);
*data_len = copy_len;
ESP_LOGD(ESP32_USB_TAG, "HID GET_REPORT success: received %zu bytes", *data_len);
} else {
ESP_LOGW(ESP32_USB_TAG, "HID GET_REPORT: No data received");
*data_len = 0;
ret = ESP_FAIL;
}
} else {
ESP_LOGW(ESP32_USB_TAG, "HID GET_REPORT timeout");
ret = ESP_ERR_TIMEOUT;
}
} else {
ESP_LOGW(ESP32_USB_TAG, "Failed to submit HID GET_REPORT: %s", esp_err_to_name(ret));
}
vSemaphoreDelete(done_sem);
usb_host_transfer_free(transfer);
return ret;
}
esp_err_t Esp32UsbTransport::hid_set_report(uint8_t report_type, uint8_t report_id,
const uint8_t* data, size_t data_len,
uint32_t timeout_ms) {
if (!device_.dev_hdl) {
ESP_LOGE(ESP32_USB_TAG, "HID SET_REPORT: No device handle");
return ESP_ERR_INVALID_ARG;
}
if (!data || data_len == 0) {
ESP_LOGE(ESP32_USB_TAG, "HID SET_REPORT: Invalid parameters");
return ESP_ERR_INVALID_ARG;
}
ESP_LOGD(ESP32_USB_TAG, "HID SET_REPORT: type=0x%02X, id=0x%02X, len=%zu",
report_type, report_id, data_len);
// Create USB control transfer for HID SET_REPORT
const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_OUT |
USB_BM_REQUEST_TYPE_TYPE_CLASS |
USB_BM_REQUEST_TYPE_RECIP_INTERFACE;
const uint8_t bRequest = 0x09; // HID SET_REPORT
const uint16_t wValue = (report_type << 8) | report_id;
const uint16_t wIndex = device_.interface_num;
const uint16_t wLength = data_len;
usb_transfer_t *transfer = nullptr;
size_t transfer_size = sizeof(usb_setup_packet_t) + data_len;
esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer);
if (ret != ESP_OK) {
ESP_LOGE(ESP32_USB_TAG, "Failed to allocate transfer: %s", esp_err_to_name(ret));
return ret;
}
// Setup control transfer
transfer->device_handle = device_.dev_hdl;
transfer->bEndpointAddress = 0;
transfer->num_bytes = transfer_size;
transfer->timeout_ms = timeout_ms;
// Create setup packet
usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer;
setup->bmRequestType = bmRequestType;
setup->bRequest = bRequest;
setup->wValue = wValue;
setup->wIndex = wIndex;
setup->wLength = wLength;
// Copy data to transfer buffer
memcpy(transfer->data_buffer + sizeof(usb_setup_packet_t), data, data_len);
// Use semaphore for synchronous operation
SemaphoreHandle_t done_sem = xSemaphoreCreateBinary();
if (!done_sem) {
usb_host_transfer_free(transfer);
return ESP_ERR_NO_MEM;
}
// Simple context for completion
struct {
SemaphoreHandle_t sem;
esp_err_t result;
} ctx = {done_sem, ESP_ERR_TIMEOUT};
transfer->context = &ctx;
transfer->callback = [](usb_transfer_t *t) {
auto *c = static_cast<decltype(ctx)*>(t->context);
c->result = (t->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL;
xSemaphoreGive(c->sem);
};
ret = usb_host_transfer_submit_control(device_.client_hdl, transfer);
if (ret == ESP_OK) {
if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) {
ret = ctx.result;
if (ret == ESP_OK) {
ESP_LOGD(ESP32_USB_TAG, "HID SET_REPORT success");
} else {
ESP_LOGW(ESP32_USB_TAG, "HID SET_REPORT failed");
}
} else {
ESP_LOGW(ESP32_USB_TAG, "HID SET_REPORT timeout");
ret = ESP_ERR_TIMEOUT;
}
} else {
ESP_LOGW(ESP32_USB_TAG, "Failed to submit HID SET_REPORT: %s", esp_err_to_name(ret));
}
vSemaphoreDelete(done_sem);
usb_host_transfer_free(transfer);
return ret;
}
esp_err_t Esp32UsbTransport::get_string_descriptor(uint8_t string_index,
std::string& result) {
result.clear();
if (!device_.dev_hdl) {
set_last_error("USB device not ready");
return ESP_ERR_INVALID_STATE;
}
ESP_LOGD(ESP32_USB_TAG, "USB GET_STRING_DESCRIPTOR: index=%d, language_id=0x0409", string_index);
// USB string descriptors can be up to 255 bytes, but typically much smaller
const size_t max_string_len = 255;
const uint16_t language_id = 0x0409; // English US
// USB string descriptor request parameters
const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_IN |
USB_BM_REQUEST_TYPE_TYPE_STANDARD |
USB_BM_REQUEST_TYPE_RECIP_DEVICE;
const uint8_t bRequest = USB_B_REQUEST_GET_DESCRIPTOR;
const uint16_t wValue = (USB_B_DESCRIPTOR_TYPE_STRING << 8) | string_index;
const uint16_t wIndex = language_id;
const uint16_t wLength = max_string_len;
usb_transfer_t *transfer = nullptr;
size_t transfer_size = sizeof(usb_setup_packet_t) + max_string_len;
esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer);
if (ret != ESP_OK) {
set_last_error("Failed to allocate string descriptor transfer: " + std::string(esp_err_to_name(ret)));
return ret;
}
// Setup control transfer
transfer->device_handle = device_.dev_hdl;
transfer->bEndpointAddress = 0; // Control endpoint
transfer->num_bytes = transfer_size;
transfer->timeout_ms = 1000;
// Create setup packet
usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer;
setup->bmRequestType = bmRequestType;
setup->bRequest = bRequest;
setup->wValue = wValue;
setup->wIndex = wIndex;
setup->wLength = wLength;
// Use semaphore for synchronous operation
SemaphoreHandle_t done_sem = xSemaphoreCreateBinary();
if (!done_sem) {
usb_host_transfer_free(transfer);
return ESP_ERR_NO_MEM;
}
// Context for completion
struct {
SemaphoreHandle_t sem;
esp_err_t result;
size_t actual_bytes;
} ctx = {done_sem, ESP_ERR_TIMEOUT, 0};
transfer->context = &ctx;
transfer->callback = [](usb_transfer_t *t) {
auto *c = static_cast<decltype(ctx)*>(t->context);
c->result = (t->status == USB_TRANSFER_STATUS_COMPLETED) ? ESP_OK : ESP_FAIL;
c->actual_bytes = t->actual_num_bytes;
xSemaphoreGive(c->sem);
};
ret = usb_host_transfer_submit_control(device_.client_hdl, transfer);
if (ret == ESP_OK) {
if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(1000)) == pdTRUE) {
ret = ctx.result;
if (ret == ESP_OK && ctx.actual_bytes > sizeof(usb_setup_packet_t)) {
// Parse the USB string descriptor
uint8_t *desc_data = transfer->data_buffer + sizeof(usb_setup_packet_t);
size_t desc_len = ctx.actual_bytes - sizeof(usb_setup_packet_t);
if (desc_len >= 2) {
uint8_t bLength = desc_data[0]; // Total length of descriptor
uint8_t bDescriptorType = desc_data[1]; // Should be USB_B_DESCRIPTOR_TYPE_STRING (0x03)
if (bDescriptorType == USB_B_DESCRIPTOR_TYPE_STRING && bLength >= 2) {
// USB string descriptors are UTF-16LE encoded, skip the 2-byte header
size_t string_data_len = std::min(static_cast<size_t>(bLength - 2), desc_len - 2);
uint8_t *string_data = desc_data + 2;
// Convert UTF-16LE to ASCII (simplified, handles ASCII characters)
result.reserve(string_data_len / 2);
for (size_t i = 0; i < string_data_len; i += 2) {
if (i + 1 < string_data_len) {
uint16_t utf16_char = string_data[i] | (string_data[i + 1] << 8);
if (utf16_char < 128 && utf16_char > 0) { // ASCII range, non-null
result += static_cast<char>(utf16_char);
} else if (utf16_char >= 128) {
result += '?'; // Non-ASCII character placeholder
}
}
}
// Trim trailing whitespace
while (!result.empty() && std::isspace(result.back())) {
result.pop_back();
}
ESP_LOGI(ESP32_USB_TAG, "USB string descriptor %d: \"%s\"", string_index, result.c_str());
} else {
ESP_LOGW(ESP32_USB_TAG, "Invalid string descriptor: type=0x%02X, length=%d", bDescriptorType, bLength);
ret = ESP_ERR_INVALID_RESPONSE;
}
} else {
ESP_LOGW(ESP32_USB_TAG, "String descriptor too short: %zu bytes", desc_len);
ret = ESP_ERR_INVALID_SIZE;
}
} else {
ESP_LOGW(ESP32_USB_TAG, "USB string descriptor request failed or no data received");
ret = ESP_FAIL;
}
} else {
ESP_LOGW(ESP32_USB_TAG, "USB string descriptor request timeout");
ret = ESP_ERR_TIMEOUT;
}
} else {
ESP_LOGW(ESP32_USB_TAG, "Failed to submit string descriptor request: %s", esp_err_to_name(ret));
}
vSemaphoreDelete(done_sem);
usb_host_transfer_free(transfer);
return ret;
}
std::string Esp32UsbTransport::get_last_error() const {
std::lock_guard<std::mutex> lock(error_mutex_);
return last_error_;
}
// Private methods implementation
void Esp32UsbTransport::set_last_error(const std::string& error) {
std::lock_guard<std::mutex> lock(error_mutex_);
last_error_ = error;
ESP_LOGW(ESP32_USB_TAG, "%s", error.c_str());
}
esp_err_t Esp32UsbTransport::setup_usb_host() {
// Create USB library task - USB Host installation happens inside the task
if (!usb_tasks_running_.load()) {
usb_tasks_running_ = true;
// Create USB Host Library task first
BaseType_t task_created = xTaskCreate(usb_lib_task, "usb_lib_task", 4096, this, 2, &usb_lib_task_handle_);
if (task_created != pdTRUE) {
ESP_LOGE(ESP32_USB_TAG, "Failed to create USB Host Library task");
usb_tasks_running_ = false;
return ESP_FAIL;
}
// Give USB Host Library task time to initialize
vTaskDelay(pdMS_TO_TICKS(100));
// Create USB client task
task_created = xTaskCreate(usb_client_task, "usb_client_task", 6144, this, 3, &usb_client_task_handle_);
if (task_created != pdTRUE) {
ESP_LOGE(ESP32_USB_TAG, "Failed to create USB client task");
usb_tasks_running_ = false;
return ESP_FAIL;
}
ESP_LOGI(ESP32_USB_TAG, "USB Host tasks created successfully");
}
return ESP_OK;
}
esp_err_t Esp32UsbTransport::teardown_usb_host() {
// Signal tasks to stop (they will self-terminate and handle USB cleanup)
if (usb_tasks_running_.load()) {
ESP_LOGI(ESP32_USB_TAG, "Stopping USB Host tasks...");
usb_tasks_running_ = false;
// Wait for tasks to self-terminate
vTaskDelay(pdMS_TO_TICKS(500)); // Give tasks time to exit cleanly
usb_client_task_handle_ = nullptr;
usb_lib_task_handle_ = nullptr;
ESP_LOGI(ESP32_USB_TAG, "USB Host tasks stopped");
}
// Release interface and device
if (device_.dev_hdl) {
ESP_LOGI(ESP32_USB_TAG, "Cleaning up device resources");
usb_host_interface_release(device_.client_hdl, device_.dev_hdl, device_.interface_num);
usb_host_device_close(device_.client_hdl, device_.dev_hdl);
device_.dev_hdl = nullptr;
}
if (device_.client_hdl) {
ESP_LOGI(ESP32_USB_TAG, "Deregistering USB client");
usb_host_client_deregister(device_.client_hdl);
device_.client_hdl = nullptr;
}
// USB Host uninstallation happens inside usb_lib_task now
return ESP_OK;
}
esp_err_t Esp32UsbTransport::find_and_open_device() {
// Register USB client in asynchronous mode for event-driven device detection
usb_host_client_config_t client_config = {
.is_synchronous = false, // Use asynchronous mode for USB_HOST_CLIENT_EVENT_NEW_DEV events
.max_num_event_msg = 5,
.async = {
.client_event_callback = usb_client_event_callback,
.callback_arg = this
}
};
esp_err_t ret = usb_host_client_register(&client_config, &device_.client_hdl);
if (ret != ESP_OK) {
set_last_error("Client register failed: " + std::string(esp_err_to_name(ret)));
return ret;
}
ESP_LOGI(ESP32_USB_TAG, "USB client registered (handle=0x%p), waiting for device connection events...",
device_.client_hdl);
// Force immediate device enumeration check in addition to event-driven detection
ESP_LOGI(ESP32_USB_TAG, "Performing immediate device enumeration check...");
vTaskDelay(pdMS_TO_TICKS(100)); // Small delay for USB stack to stabilize
int num_dev = 10;
uint8_t dev_addr_list[10];
esp_err_t enum_ret = usb_host_device_addr_list_fill(num_dev, dev_addr_list, &num_dev);
if (enum_ret == ESP_OK && num_dev > 0) {
ESP_LOGI(ESP32_USB_TAG, "Found %d existing USB devices during initial enumeration:", num_dev);
for (int i = 0; i < num_dev; i++) {
ESP_LOGI(ESP32_USB_TAG, " Attempting to handle existing device at address %d", dev_addr_list[i]);
handle_new_device(dev_addr_list[i]);
}
} else {
ESP_LOGI(ESP32_USB_TAG, "No existing USB devices found - waiting for connection events");
}
return ESP_OK;
}
esp_err_t Esp32UsbTransport::claim_interface() {
const usb_config_desc_t *config_desc;
esp_err_t ret = usb_host_get_active_config_descriptor(device_.dev_hdl, &config_desc);
if (ret != ESP_OK) {
set_last_error("Failed to get config descriptor");
return ret;
}
// Find HID interface
const usb_intf_desc_t *intf_desc = nullptr;
int offset = 0;
for (int i = 0; i < config_desc->bNumInterfaces; i++) {
intf_desc = usb_parse_interface_descriptor(config_desc, i, 0, &offset);
if (intf_desc && intf_desc->bInterfaceClass == USB_CLASS_HID) {
device_.interface_num = intf_desc->bInterfaceNumber;
break;
}
}
if (!intf_desc || intf_desc->bInterfaceClass != USB_CLASS_HID) {
set_last_error("No HID interface found");
return ESP_ERR_NOT_FOUND;
}
ret = usb_host_interface_claim(device_.client_hdl, device_.dev_hdl,
device_.interface_num, 0);
if (ret != ESP_OK) {
set_last_error("Failed to claim interface: " + std::string(esp_err_to_name(ret)));
return ret;
}
return ESP_OK;
}
esp_err_t Esp32UsbTransport::find_endpoints() {
const usb_config_desc_t *config_desc;
esp_err_t ret = usb_host_get_active_config_descriptor(device_.dev_hdl, &config_desc);
if (ret != ESP_OK) {
return ret;
}
int offset = 0;
const usb_intf_desc_t *intf_desc = usb_parse_interface_descriptor(
config_desc, device_.interface_num, 0, &offset);
if (!intf_desc) {
set_last_error("Interface descriptor not found");
return ESP_ERR_NOT_FOUND;
}
// Parse endpoints correctly using ESP-IDF approach
const usb_ep_desc_t *ep_desc = nullptr;
int ep_offset = offset;
ESP_LOGD(ESP32_USB_TAG, "Interface has %d endpoints", intf_desc->bNumEndpoints);
for (int i = 0; i < intf_desc->bNumEndpoints; i++) {
ep_desc = usb_parse_endpoint_descriptor_by_index(intf_desc, i, config_desc->wTotalLength, &ep_offset);
if (ep_desc) {
if (USB_EP_DESC_GET_EP_DIR(ep_desc)) {
// IN endpoint (device to host)
device_.ep_in = ep_desc->bEndpointAddress;
device_.max_packet_size_in = ep_desc->wMaxPacketSize;
ESP_LOGD(ESP32_USB_TAG, "Found IN endpoint: 0x%02X (max packet size: %d)",
device_.ep_in, device_.max_packet_size_in);
} else {
// OUT endpoint (host to device)
device_.ep_out = ep_desc->bEndpointAddress;
device_.max_packet_size_out = ep_desc->wMaxPacketSize;
ESP_LOGD(ESP32_USB_TAG, "Found OUT endpoint: 0x%02X (max packet size: %d)",
device_.ep_out, device_.max_packet_size_out);
}
} else {
ESP_LOGW(ESP32_USB_TAG, "Failed to parse endpoint %d", i);
}
}
if (device_.ep_in == 0) {
set_last_error("No IN endpoint found");
return ESP_ERR_NOT_FOUND;
}
// Detect input-only devices (no OUT endpoint)
if (device_.ep_out == 0) {
ESP_LOGW(ESP32_USB_TAG, "INPUT-ONLY HID device detected - no OUT endpoint available");
ESP_LOGI(ESP32_USB_TAG, "Device supports HID GET_REPORT only (no SET_REPORT)");
} else {
ESP_LOGD(ESP32_USB_TAG, "Bidirectional device detected - has both IN and OUT endpoints");
}
return ESP_OK;
}
esp_err_t Esp32UsbTransport::submit_control_transfer(uint8_t bmRequestType, uint8_t bRequest,
uint16_t wValue, uint16_t wIndex,
uint8_t* data, size_t data_len,
uint32_t timeout_ms) {
std::lock_guard<std::mutex> lock(device_mutex_);
if (!device_.dev_hdl) {
return ESP_ERR_INVALID_STATE;
}
usb_transfer_t *transfer;
esp_err_t ret = usb_host_transfer_alloc(sizeof(usb_setup_packet_t) + data_len, 0, &transfer);
if (ret != ESP_OK) {
set_last_error("Transfer alloc failed: " + std::string(esp_err_to_name(ret)));
return ret;
}
// Setup packet
usb_setup_packet_t *setup = (usb_setup_packet_t *)transfer->data_buffer;
setup->bmRequestType = bmRequestType;
setup->bRequest = bRequest;
setup->wValue = wValue;
setup->wIndex = wIndex;
setup->wLength = data_len;
if (data_len > 0 && data) {
if (bmRequestType & USB_BM_REQUEST_TYPE_DIR_IN) {
// IN transfer - device to host
memset(transfer->data_buffer + sizeof(usb_setup_packet_t), 0, data_len);
} else {
// OUT transfer - host to device
memcpy(transfer->data_buffer + sizeof(usb_setup_packet_t), data, data_len);
}
}
transfer->device_handle = device_.dev_hdl;
transfer->bEndpointAddress = 0; // Control endpoint
transfer->callback = nullptr;
transfer->context = nullptr;
transfer->num_bytes = sizeof(usb_setup_packet_t) + data_len;
transfer->timeout_ms = timeout_ms;
ret = usb_host_transfer_submit_control(device_.client_hdl, transfer);
if (ret != ESP_OK) {
usb_host_transfer_free(transfer);
set_last_error("Control transfer submit failed: " + std::string(esp_err_to_name(ret)));
return ret;
}
// Copy response data back
if (data_len > 0 && data && (bmRequestType & USB_BM_REQUEST_TYPE_DIR_IN)) {
memcpy(data, transfer->data_buffer + sizeof(usb_setup_packet_t), data_len);
}
usb_host_transfer_free(transfer);
return ESP_OK;
}
void Esp32UsbTransport::usb_client_event_callback(const usb_host_client_event_msg_t* event_msg, void* arg) {
Esp32UsbTransport* transport = static_cast<Esp32UsbTransport*>(arg);
switch (event_msg->event) {
case USB_HOST_CLIENT_EVENT_NEW_DEV:
ESP_LOGI(ESP32_USB_TAG, "New USB device detected: address=%d", event_msg->new_dev.address);
transport->handle_new_device(event_msg->new_dev.address);
break;
case USB_HOST_CLIENT_EVENT_DEV_GONE:
ESP_LOGI(ESP32_USB_TAG, "USB device disconnected");
transport->handle_device_gone(event_msg->dev_gone.dev_hdl);
break;
default:
ESP_LOGW(ESP32_USB_TAG, "Unhandled USB client event: %d", event_msg->event);
break;
}
}
void Esp32UsbTransport::handle_new_device(uint8_t dev_addr) {
ESP_LOGI(ESP32_USB_TAG, "Handling new USB device at address %d", dev_addr);
std::lock_guard<std::mutex> lock(device_mutex_);
// Check if we already have a device connected
if (device_.dev_hdl != nullptr) {
ESP_LOGW(ESP32_USB_TAG, "Device already connected - skipping new device at address %d", dev_addr);
return;
}
// Open the device
esp_err_t ret = usb_host_device_open(device_.client_hdl, dev_addr, &device_.dev_hdl);
if (ret != ESP_OK) {
ESP_LOGE(ESP32_USB_TAG, "Failed to open device at address %d: %s", dev_addr, esp_err_to_name(ret));
return;
}
ESP_LOGI(ESP32_USB_TAG, "Successfully opened USB device at address %d", dev_addr);
// Get device information
usb_device_info_t dev_info;
ret = usb_host_device_info(device_.dev_hdl, &dev_info);
if (ret != ESP_OK) {
ESP_LOGE(ESP32_USB_TAG, "Failed to get device info: %s", esp_err_to_name(ret));
usb_host_device_close(device_.client_hdl, device_.dev_hdl);
device_.dev_hdl = nullptr;
return;
}
device_.address = dev_addr;
device_.speed = dev_info.speed;
// Get device descriptor to extract VID/PID
const usb_device_desc_t* device_desc;
ret = usb_host_get_device_descriptor(device_.dev_hdl, &device_desc);
if (ret == ESP_OK) {
device_.vendor_id = device_desc->idVendor;
device_.product_id = device_desc->idProduct;
ESP_LOGI(ESP32_USB_TAG, "USB device opened: VID=0x%04X, PID=0x%04X, Speed=%d",
device_.vendor_id, device_.product_id, dev_info.speed);
// Check if this is a UPS device (HID class)
if (device_desc->bDeviceClass == USB_CLASS_HID ||
device_desc->bDeviceClass == 0x00) { // Device class defined at interface level
// Try to claim HID interface and find endpoints
ret = claim_interface();
if (ret == ESP_OK) {
ret = find_endpoints();
if (ret == ESP_OK) {
connected_ = true;
ESP_LOGI(ESP32_USB_TAG, "UPS device successfully configured and ready");
return;
}
}
} else {
ESP_LOGW(ESP32_USB_TAG, "Connected device is not a HID device (class=0x%02X)", device_desc->bDeviceClass);
}
}
// Clean up on failure
usb_host_device_close(device_.client_hdl, device_.dev_hdl);
device_.dev_hdl = nullptr;
}
void Esp32UsbTransport::handle_device_gone(usb_device_handle_t dev_hdl) {
ESP_LOGI(ESP32_USB_TAG, "Handling USB device disconnection");
std::lock_guard<std::mutex> lock(device_mutex_);
if (device_.dev_hdl == dev_hdl) {
connected_ = false;
// Clean up device resources
if (device_.dev_hdl) {
usb_host_interface_release(device_.client_hdl, device_.dev_hdl, device_.interface_num);
usb_host_device_close(device_.client_hdl, device_.dev_hdl);
device_.dev_hdl = nullptr;
}
// Reset device info
device_.address = 0;
device_.vendor_id = 0;
device_.product_id = 0;
ESP_LOGI(ESP32_USB_TAG, "USB device disconnected and cleaned up");
}
}
void Esp32UsbTransport::usb_lib_task(void* arg) {
Esp32UsbTransport* transport = static_cast<Esp32UsbTransport*>(arg);
ESP_LOGI(ESP32_USB_TAG, "USB Host Library task starting...");
// Initialize USB Host library inside task (following working prototype)
usb_host_config_t host_config = {
.skip_phy_setup = false,
.intr_flags = ESP_INTR_FLAG_LEVEL1
};
esp_err_t ret = usb_host_install(&host_config);
if (ret != ESP_OK) {
ESP_LOGE(ESP32_USB_TAG, "USB Host install failed: %s", esp_err_to_name(ret));
transport->usb_tasks_running_ = false; // Stop other tasks
vTaskDelete(nullptr);
return;
}
ESP_LOGI(ESP32_USB_TAG, "USB Host library installed successfully");
// Main USB Host event loop - following working prototype pattern
bool has_clients = true;
bool has_devices = false;
while (has_clients && transport->usb_tasks_running_.load()) {
uint32_t event_flags;
ret = usb_host_lib_handle_events(portMAX_DELAY, &event_flags);
if (ret != ESP_OK) {
ESP_LOGE(ESP32_USB_TAG, "USB Host event handling failed: %s", esp_err_to_name(ret));
continue;
}
// Handle USB Host events (following ESP-IDF v5.4 patterns)
if (event_flags & USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) {
ESP_LOGI(ESP32_USB_TAG, "No more USB clients");
if (usb_host_device_free_all() == ESP_OK) {
ESP_LOGI(ESP32_USB_TAG, "All devices freed");
has_clients = false;
} else {
ESP_LOGI(ESP32_USB_TAG, "Waiting for devices to be freed");
has_devices = true;
}
}
if (has_devices && (event_flags & USB_HOST_LIB_EVENT_FLAGS_ALL_FREE)) {
ESP_LOGI(ESP32_USB_TAG, "All devices freed");
has_clients = false;
}
}
// Cleanup USB Host library
ESP_LOGI(ESP32_USB_TAG, "Uninstalling USB Host library");
usb_host_uninstall();
ESP_LOGI(ESP32_USB_TAG, "USB Host Library task ending");
vTaskDelete(nullptr);
}
void Esp32UsbTransport::usb_client_task(void* arg) {
Esp32UsbTransport* transport = static_cast<Esp32UsbTransport*>(arg);
ESP_LOGI(ESP32_USB_TAG, "USB client task started");
while (transport->usb_tasks_running_.load()) {
if (transport->device_.client_hdl) {
// Use shorter timeout for more responsive event processing
esp_err_t ret = usb_host_client_handle_events(transport->device_.client_hdl, 100);
if (ret == ESP_ERR_TIMEOUT) {
// Timeout is normal - continue processing
} else if (ret != ESP_OK) {
ESP_LOGW(ESP32_USB_TAG, "USB client event handling failed: %s", esp_err_to_name(ret));
vTaskDelay(pdMS_TO_TICKS(100)); // Brief delay on error
}
} else {
ESP_LOGD(ESP32_USB_TAG, "No USB client handle available");
vTaskDelay(pdMS_TO_TICKS(100));
}
// Small delay to prevent busy-waiting
vTaskDelay(pdMS_TO_TICKS(10));
}
ESP_LOGI(ESP32_USB_TAG, "USB client task stopping");
vTaskDelete(nullptr);
}
} // namespace ups_hid
} // namespace esphome
#endif // USE_ESP32
+104
View File
@@ -0,0 +1,104 @@
#pragma once
#include "usb_transport_interface.h"
#ifdef USE_ESP32
#include "usb/usb_host.h"
#include "usb/usb_types_ch9.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include <mutex>
#include <set>
#include <atomic>
namespace esphome {
namespace ups_hid {
/**
* ESP32 USB Transport Implementation
*
* Concrete implementation using ESP-IDF USB Host API
* Handles all ESP32-specific USB communication details
*/
class Esp32UsbTransport : public IUsbTransport {
public:
Esp32UsbTransport();
~Esp32UsbTransport() override;
// IUsbTransport implementation
esp_err_t initialize() override;
esp_err_t deinitialize() override;
bool is_connected() const override;
uint16_t get_vendor_id() const override;
uint16_t get_product_id() const override;
esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id,
uint8_t* data, size_t* data_len,
uint32_t timeout_ms = 1000) override;
esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id,
const uint8_t* data, size_t data_len,
uint32_t timeout_ms = 1000) override;
esp_err_t get_string_descriptor(uint8_t string_index,
std::string& result) override;
std::string get_last_error() const override;
private:
// USB device structure
struct UsbDevice {
usb_host_client_handle_t client_hdl{nullptr};
usb_device_handle_t dev_hdl{nullptr};
uint8_t address{0};
uint8_t interface_num{0};
uint8_t ep_in{0};
uint8_t ep_out{0};
uint16_t vendor_id{0};
uint16_t product_id{0};
uint16_t max_packet_size_in{0};
uint16_t max_packet_size_out{0};
usb_speed_t speed{USB_SPEED_LOW};
};
UsbDevice device_;
mutable std::mutex device_mutex_;
std::atomic<bool> connected_{false};
std::atomic<bool> initialized_{false};
// USB Host Library management
TaskHandle_t usb_lib_task_handle_{nullptr};
TaskHandle_t usb_client_task_handle_{nullptr};
std::atomic<bool> usb_tasks_running_{false};
// Error handling
mutable std::mutex error_mutex_;
std::string last_error_;
// Private methods
static void usb_lib_task(void* arg);
static void usb_client_task(void* arg);
static void usb_client_event_callback(const usb_host_client_event_msg_t* event_msg, void* arg);
void handle_new_device(uint8_t dev_addr);
void handle_device_gone(usb_device_handle_t dev_hdl);
esp_err_t setup_usb_host();
esp_err_t teardown_usb_host();
esp_err_t find_and_open_device();
esp_err_t claim_interface();
esp_err_t find_endpoints();
void set_last_error(const std::string& error);
esp_err_t submit_control_transfer(uint8_t bmRequestType, uint8_t bRequest,
uint16_t wValue, uint16_t wIndex,
uint8_t* data, size_t data_len,
uint32_t timeout_ms);
};
} // namespace ups_hid
} // namespace esphome
#endif // USE_ESP32
+252 -86
View File
@@ -1,4 +1,6 @@
#include "generic_hid_protocol.h"
#include "ups_hid.h"
#include "hid_constants.h"
#include "esphome/core/log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
@@ -34,21 +36,19 @@ static const uint8_t EXTENDED_REPORT_IDS[] = {
};
// Report type constants for HID
static const uint8_t HID_REPORT_TYPE_INPUT = 0x01;
static const uint8_t HID_REPORT_TYPE_OUTPUT = 0x02;
static const uint8_t HID_REPORT_TYPE_FEATURE = 0x03;
// HID report types are now defined in hid_constants.h
bool GenericHidProtocol::detect() {
ESP_LOGD(GEN_TAG, "Detecting Generic HID Protocol...");
// Check device connection status first
if (!parent_->is_device_connected()) {
if (!parent_->is_connected()) {
ESP_LOGD(GEN_TAG, "Device not connected, skipping protocol detection");
return false;
}
// Check if this is a known vendor that should use a specific protocol
uint16_t vid = parent_->get_usb_vendor_id();
uint16_t vid = parent_->get_vendor_id();
if (vid == 0x051D || vid == 0x0764) { // APC or CyberPower
ESP_LOGD(GEN_TAG, "Known vendor 0x%04X should use specific protocol", vid);
return false;
@@ -60,14 +60,14 @@ bool GenericHidProtocol::detect() {
for (uint8_t report_id : COMMON_REPORT_IDS) {
// Check connection status before each attempt
if (!parent_->is_device_connected()) {
if (!parent_->is_connected()) {
ESP_LOGD(GEN_TAG, "Device disconnected during protocol detection");
return false;
}
// Try Input Report first (real-time data)
buffer_len = sizeof(buffer);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
available_input_reports_.insert(report_id);
ESP_LOGI(GEN_TAG, "Found Input report 0x%02X (%zu bytes)", report_id, buffer_len);
@@ -76,14 +76,14 @@ bool GenericHidProtocol::detect() {
}
// Check connection again before trying Feature report
if (!parent_->is_device_connected()) {
if (!parent_->is_connected()) {
ESP_LOGD(GEN_TAG, "Device disconnected during protocol detection");
return false;
}
// Try Feature Report (static/configuration data)
buffer_len = sizeof(buffer);
ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len);
ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
available_feature_reports_.insert(report_id);
ESP_LOGI(GEN_TAG, "Found Feature report 0x%02X (%zu bytes)", report_id, buffer_len);
@@ -188,7 +188,10 @@ bool GenericHidProtocol::read_data(UpsData &data) {
success = true;
}
// 8. Try any other discovered reports with heuristic parsing
// 8. Try to read frequency data
read_frequency_data(data);
// 9. Try any other discovered reports with heuristic parsing
if (!success) {
for (uint8_t id : available_input_reports_) {
if (id == 0x01 || id == 0x06 || id == 0x0C || id == 0x16 ||
@@ -207,25 +210,26 @@ bool GenericHidProtocol::read_data(UpsData &data) {
}
// Set generic manufacturer/model if not already set
if (data.manufacturer.empty()) {
data.manufacturer = "Generic";
if (data.device.manufacturer.empty()) {
data.device.manufacturer = "Generic";
}
if (data.model.empty()) {
uint16_t vid = parent_->get_usb_vendor_id();
uint16_t pid = parent_->get_usb_product_id();
if (data.device.model.empty()) {
uint16_t vid = parent_->get_vendor_id();
uint16_t pid = parent_->get_product_id();
char model_str[32];
snprintf(model_str, sizeof(model_str), "HID UPS %04X:%04X", vid, pid);
data.model = model_str;
data.device.model = model_str;
}
// Ensure we have at least basic status
if (success && data.status_flags == 0) {
// If we got data but no status flags, assume online
data.status_flags = UPS_STATUS_ONLINE;
// Ensure we have at least basic power status
if (success && data.power.status.empty()) {
// If we got data but no power status, assume online
data.power.status = "Online";
data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage
}
// Set default test result
data.ups_test_result = "No test initiated";
data.test.ups_test_result = "No test initiated";
return success;
}
@@ -240,14 +244,14 @@ void GenericHidProtocol::enumerate_reports() {
// First try common report IDs
for (uint8_t id : COMMON_REPORT_IDS) {
// Check device connection before each report
if (!parent_->is_device_connected()) {
if (!parent_->is_connected()) {
ESP_LOGD(GEN_TAG, "Device disconnected during report enumeration");
return;
}
// Check Input reports
buffer_len = sizeof(buffer);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
available_input_reports_.insert(id);
report_sizes_[id] = buffer_len;
@@ -256,14 +260,14 @@ void GenericHidProtocol::enumerate_reports() {
}
// Check connection again before Feature report
if (!parent_->is_device_connected()) {
if (!parent_->is_connected()) {
ESP_LOGD(GEN_TAG, "Device disconnected during report enumeration");
return;
}
// Check Feature reports
buffer_len = sizeof(buffer);
ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, id, buffer, &buffer_len);
ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
available_feature_reports_.insert(id);
if (report_sizes_.find(id) == report_sizes_.end()) {
@@ -286,7 +290,7 @@ void GenericHidProtocol::enumerate_reports() {
ESP_LOGD(GEN_TAG, "Performing extended report search...");
for (uint8_t id : EXTENDED_REPORT_IDS) {
// Check device connection before each extended report
if (!parent_->is_device_connected()) {
if (!parent_->is_connected()) {
ESP_LOGD(GEN_TAG, "Device disconnected during extended report search");
return;
}
@@ -297,7 +301,7 @@ void GenericHidProtocol::enumerate_reports() {
}
buffer_len = sizeof(buffer);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
available_input_reports_.insert(id);
report_sizes_[id] = buffer_len;
@@ -315,7 +319,7 @@ bool GenericHidProtocol::read_report(uint8_t report_id, uint8_t* buffer, size_t&
// Try Input report first if available (real-time data)
if (available_input_reports_.count(report_id)) {
buffer_len = 64;
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_INPUT, report_id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
ESP_LOGV(GEN_TAG, "Read Input report 0x%02X: %zu bytes", report_id, buffer_len);
return true;
@@ -325,7 +329,7 @@ bool GenericHidProtocol::read_report(uint8_t report_id, uint8_t* buffer, size_t&
// Try Feature report (static/configuration data)
if (available_feature_reports_.count(report_id)) {
buffer_len = 64;
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len);
esp_err_t ret = parent_->hid_get_report(HID_REPORT_TYPE_FEATURE, report_id, buffer, &buffer_len, parent_->get_protocol_timeout());
if (ret == ESP_OK && buffer_len > 0) {
ESP_LOGV(GEN_TAG, "Read Feature report 0x%02X: %zu bytes", report_id, buffer_len);
return true;
@@ -343,12 +347,12 @@ void GenericHidProtocol::parse_power_summary(uint8_t* data, size_t len, UpsData&
// Battery percentage typically at byte 1
uint8_t battery = data[1];
if (battery <= 100) {
ups_data.battery_level = static_cast<float>(battery);
ups_data.battery.level = static_cast<float>(battery);
ESP_LOGD(GEN_TAG, "Power summary: Battery %d%%", battery);
} else if (battery <= 200 && battery > 100) {
// Some devices use 0-200 scale
ups_data.battery_level = static_cast<float>(battery) / 2.0f;
ESP_LOGD(GEN_TAG, "Power summary: Battery %.1f%% (scaled from %d)", ups_data.battery_level, battery);
ups_data.battery.level = static_cast<float>(battery) / 2.0f;
ESP_LOGD(GEN_TAG, "Power summary: Battery %.1f%% (scaled from %d)", ups_data.battery.level, battery);
}
}
@@ -356,7 +360,7 @@ void GenericHidProtocol::parse_power_summary(uint8_t* data, size_t len, UpsData&
// Runtime in minutes (16-bit little-endian at bytes 2-3)
uint16_t runtime = data[2] | (data[3] << 8);
if (runtime > 0 && runtime < 10000) {
ups_data.runtime_minutes = static_cast<float>(runtime);
ups_data.battery.runtime_minutes = static_cast<float>(runtime);
ESP_LOGD(GEN_TAG, "Power summary: Runtime %d minutes", runtime);
}
}
@@ -369,20 +373,39 @@ void GenericHidProtocol::parse_battery_status(uint8_t* data, size_t len, UpsData
// Common battery status bits (varies by vendor)
if (status != 0xFF && status != 0x00) { // Valid status
if (status & 0x01) ups_data.status_flags |= UPS_STATUS_ONLINE;
if (status & 0x02) ups_data.status_flags |= UPS_STATUS_ON_BATTERY;
if (status & 0x04) ups_data.status_flags |= UPS_STATUS_LOW_BATTERY;
if (status & 0x08) ups_data.status_flags |= UPS_STATUS_CHARGING;
if (status & 0x10) ups_data.status_flags |= UPS_STATUS_REPLACE_BATTERY;
ESP_LOGD(GEN_TAG, "Battery status: 0x%02X -> flags 0x%08X", status, ups_data.status_flags);
// Update power status
if (status & 0x01) {
ups_data.power.status = "Online";
ups_data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage
}
if (status & 0x02) {
ups_data.power.status = "On Battery";
ups_data.power.input_voltage = NAN;
}
// Update battery status
if (status & 0x08) {
ups_data.battery.status = "Charging";
}
if (status & 0x04) {
ups_data.battery.charge_low = 10.0f; // Low battery
}
if (status & 0x10) {
ups_data.battery.status += " - Replace Battery";
}
ESP_LOGD(GEN_TAG, "Battery status: 0x%02X -> Power: \"%s\", Battery: \"%s\"",
status, ups_data.power.status.c_str(), ups_data.battery.status.c_str());
}
}
// Some devices include battery level here too
if (len >= 3 && std::isnan(ups_data.battery_level)) {
if (len >= 3 && std::isnan(ups_data.battery.level)) {
uint8_t battery = data[2];
if (battery <= 100) {
ups_data.battery_level = static_cast<float>(battery);
ups_data.battery.level = static_cast<float>(battery);
ESP_LOGD(GEN_TAG, "Battery status: Battery %d%%", battery);
}
}
@@ -393,18 +416,40 @@ void GenericHidProtocol::parse_present_status(uint8_t* data, size_t len, UpsData
// Based on HID Power Device spec, these are common bit positions
if (len >= 2) {
uint8_t status = data[1];
ups_data.status_flags = 0;
// Standard HID Power Device status bits
if (status & 0x01) ups_data.status_flags |= UPS_STATUS_CHARGING;
if (status & 0x02) ups_data.status_flags |= UPS_STATUS_ON_BATTERY;
if (status & 0x04) ups_data.status_flags |= UPS_STATUS_ONLINE;
if (status & 0x08) ups_data.status_flags |= UPS_STATUS_LOW_BATTERY;
if (status & 0x10) ups_data.status_flags |= UPS_STATUS_REPLACE_BATTERY;
if (status & 0x20) ups_data.status_flags |= UPS_STATUS_OVERLOAD;
if (status & 0x40) ups_data.status_flags |= UPS_STATUS_FAULT;
// Standard HID Power Device status bits - map to data structures
if (status & 0x01) {
ups_data.battery.status = "Charging";
}
ESP_LOGD(GEN_TAG, "Present status: 0x%02X -> flags 0x%08X", status, ups_data.status_flags);
if (status & 0x02) {
ups_data.power.status = "On Battery";
ups_data.power.input_voltage = NAN;
}
if (status & 0x04) {
ups_data.power.status = "Online";
ups_data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage
}
if (status & 0x08) {
ups_data.battery.charge_low = 10.0f; // Low battery
}
if (status & 0x10) {
ups_data.battery.status += " - Replace Battery";
}
if (status & 0x20) {
ups_data.power.status += " - Overload";
}
if (status & 0x40) {
ups_data.battery.status += " - Fault";
}
ESP_LOGD(GEN_TAG, "Present status: 0x%02X -> Power: \"%s\", Battery: \"%s\"",
status, ups_data.power.status.c_str(), ups_data.battery.status.c_str());
}
}
@@ -416,13 +461,15 @@ void GenericHidProtocol::parse_general_status(uint8_t* data, size_t len, UpsData
// Different vendors use different bit patterns, try common ones
if (byte1 & 0x01) {
ups_data.status_flags |= UPS_STATUS_ONLINE;
ups_data.power.status = "Online";
ups_data.power.input_voltage = parent_->get_fallback_nominal_voltage(); // Use configured fallback voltage
}
if (byte1 & 0x10) {
ups_data.status_flags |= UPS_STATUS_ON_BATTERY;
ups_data.power.status = "On Battery";
ups_data.power.input_voltage = NAN;
}
ESP_LOGV(GEN_TAG, "General status byte: 0x%02X", byte1);
ESP_LOGV(GEN_TAG, "General status byte: 0x%02X -> Power: \"%s\"", byte1, ups_data.power.status.c_str());
}
}
@@ -440,10 +487,10 @@ void GenericHidProtocol::parse_voltage(uint8_t* data, size_t len, UpsData& ups_d
// Sanity check
if (voltage >= 80.0f && voltage <= 300.0f) {
if (is_input) {
ups_data.input_voltage = voltage;
ups_data.power.input_voltage = voltage;
ESP_LOGD(GEN_TAG, "Input voltage: %.1fV", voltage);
} else {
ups_data.output_voltage = voltage;
ups_data.power.output_voltage = voltage;
ESP_LOGD(GEN_TAG, "Output voltage: %.1fV", voltage);
}
}
@@ -454,12 +501,12 @@ void GenericHidProtocol::parse_load(uint8_t* data, size_t len, UpsData& ups_data
if (len >= 2) {
uint8_t load = data[1];
if (load <= 100) {
ups_data.load_percent = static_cast<float>(load);
ups_data.power.load_percent = static_cast<float>(load);
ESP_LOGD(GEN_TAG, "Load: %d%%", load);
} else if (load <= 200) {
// Some devices use 0-200 scale
ups_data.load_percent = static_cast<float>(load) / 2.0f;
ESP_LOGD(GEN_TAG, "Load: %.1f%% (scaled from %d)", ups_data.load_percent, load);
ups_data.power.load_percent = static_cast<float>(load) / 2.0f;
ESP_LOGD(GEN_TAG, "Load: %.1f%% (scaled from %d)", ups_data.power.load_percent, load);
}
}
}
@@ -471,12 +518,12 @@ bool GenericHidProtocol::parse_unknown_report(uint8_t* data, size_t len, UpsData
// Look for percentage values (0-100)
for (size_t i = 1; i < len && i < 4; i++) {
if (data[i] <= 100 && data[i] > 0) {
if (std::isnan(ups_data.battery_level)) {
ups_data.battery_level = static_cast<float>(data[i]);
if (std::isnan(ups_data.battery.level)) {
ups_data.battery.level = static_cast<float>(data[i]);
ESP_LOGV(GEN_TAG, "Heuristic: Found possible battery level %d%% at byte %zu", data[i], i);
found_data = true;
} else if (std::isnan(ups_data.load_percent)) {
ups_data.load_percent = static_cast<float>(data[i]);
} else if (std::isnan(ups_data.power.load_percent)) {
ups_data.power.load_percent = static_cast<float>(data[i]);
ESP_LOGV(GEN_TAG, "Heuristic: Found possible load %d%% at byte %zu", data[i], i);
found_data = true;
}
@@ -492,8 +539,8 @@ bool GenericHidProtocol::parse_unknown_report(uint8_t* data, size_t len, UpsData
if (voltage > 1000) voltage /= 10.0f;
if (voltage >= 80.0f && voltage <= 300.0f) {
if (std::isnan(ups_data.input_voltage)) {
ups_data.input_voltage = voltage;
if (std::isnan(ups_data.power.input_voltage)) {
ups_data.power.input_voltage = voltage;
ESP_LOGV(GEN_TAG, "Heuristic: Found possible voltage %.1fV at bytes %zu-%zu",
voltage, i, i+1);
found_data = true;
@@ -517,19 +564,19 @@ void GenericHidProtocol::parse_input_sensitivity(uint8_t* data, size_t len, UpsD
// Handle both APC-style (0x35) and CyberPower-style (0x1a) with intelligent fallbacks
switch (sensitivity_raw) {
case 0:
ups_data.input_sensitivity = "high";
ups_data.config.input_sensitivity = "high";
ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): high (raw: %d)", style, sensitivity_raw);
break;
case 1:
ups_data.input_sensitivity = "normal";
ups_data.config.input_sensitivity = "normal";
ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): normal (raw: %d)", style, sensitivity_raw);
break;
case 2:
ups_data.input_sensitivity = "low";
ups_data.config.input_sensitivity = "low";
ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): low (raw: %d)", style, sensitivity_raw);
break;
case 3:
ups_data.input_sensitivity = "auto";
ups_data.config.input_sensitivity = "auto";
ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s): auto (raw: %d)", style, sensitivity_raw);
break;
default:
@@ -544,19 +591,19 @@ void GenericHidProtocol::parse_input_sensitivity(uint8_t* data, size_t len, UpsD
uint8_t alt_value = data[i];
if (alt_value <= 3) {
switch (alt_value) {
case 0: ups_data.input_sensitivity = "high"; break;
case 1: ups_data.input_sensitivity = "normal"; break;
case 2: ups_data.input_sensitivity = "low"; break;
case 3: ups_data.input_sensitivity = "auto"; break;
case 0: ups_data.config.input_sensitivity = "high"; break;
case 1: ups_data.config.input_sensitivity = "normal"; break;
case 2: ups_data.config.input_sensitivity = "low"; break;
case 3: ups_data.config.input_sensitivity = "auto"; break;
}
ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s, alt byte[%zu]): %s (raw: %d)",
style, i, ups_data.input_sensitivity.c_str(), alt_value);
style, i, ups_data.config.input_sensitivity.c_str(), alt_value);
return;
}
}
// Fallback to reasonable default
ups_data.input_sensitivity = "normal";
ups_data.config.input_sensitivity = "normal";
ESP_LOGW(GEN_TAG, "Using default 'normal' sensitivity (%s) due to unexpected value: %d",
style, sensitivity_raw);
} else {
@@ -564,16 +611,16 @@ void GenericHidProtocol::parse_input_sensitivity(uint8_t* data, size_t len, UpsD
if (sensitivity_raw <= 10) {
// Map to nearest known value
if (sensitivity_raw <= 3) {
ups_data.input_sensitivity = "high";
ups_data.config.input_sensitivity = "high";
} else if (sensitivity_raw <= 6) {
ups_data.input_sensitivity = "normal";
ups_data.config.input_sensitivity = "normal";
} else {
ups_data.input_sensitivity = "low";
ups_data.config.input_sensitivity = "low";
}
ESP_LOGI(GEN_TAG, "Generic input sensitivity (%s, mapped): %s (raw: %d)",
style, ups_data.input_sensitivity.c_str(), sensitivity_raw);
style, ups_data.config.input_sensitivity.c_str(), sensitivity_raw);
} else {
ups_data.input_sensitivity = "unknown";
ups_data.config.input_sensitivity = "unknown";
ESP_LOGW(GEN_TAG, "Unknown generic sensitivity value (%s): %d", style, sensitivity_raw);
}
}
@@ -594,7 +641,7 @@ bool GenericHidProtocol::start_battery_test_quick() {
uint8_t test_data[2] = {report_id, 1}; // Command value 1 = Quick test
ESP_LOGD(GEN_TAG, "Trying quick battery test with report ID 0x%02X", report_id);
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data));
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(GEN_TAG, "Generic quick battery test command sent with report ID 0x%02X", report_id);
@@ -619,7 +666,7 @@ bool GenericHidProtocol::start_battery_test_deep() {
uint8_t test_data[2] = {report_id, 2}; // Command value 2 = Deep test
ESP_LOGD(GEN_TAG, "Trying deep battery test with report ID 0x%02X", report_id);
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data));
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(GEN_TAG, "Generic deep battery test command sent with report ID 0x%02X", report_id);
@@ -644,7 +691,7 @@ bool GenericHidProtocol::stop_battery_test() {
uint8_t test_data[2] = {report_id, 3}; // Command value 3 = Abort test
ESP_LOGD(GEN_TAG, "Trying battery test stop with report ID 0x%02X", report_id);
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data));
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(GEN_TAG, "Generic battery test stop command sent with report ID 0x%02X", report_id);
@@ -669,7 +716,7 @@ bool GenericHidProtocol::start_ups_test() {
uint8_t test_data[2] = {report_id, 1}; // Command value 1 = Start test
ESP_LOGD(GEN_TAG, "Trying UPS test with report ID 0x%02X", report_id);
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data));
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(GEN_TAG, "Generic UPS test command sent with report ID 0x%02X", report_id);
@@ -694,7 +741,7 @@ bool GenericHidProtocol::stop_ups_test() {
uint8_t test_data[2] = {report_id, 0}; // Command value 0 = Stop test
ESP_LOGD(GEN_TAG, "Trying UPS test stop with report ID 0x%02X", report_id);
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data));
esp_err_t ret = parent_->hid_set_report(0x03, report_id, test_data, sizeof(test_data), parent_->get_protocol_timeout());
if (ret == ESP_OK) {
ESP_LOGI(GEN_TAG, "Generic UPS test stop command sent with report ID 0x%02X", report_id);
@@ -708,5 +755,124 @@ bool GenericHidProtocol::stop_ups_test() {
return false;
}
void GenericHidProtocol::read_frequency_data(UpsData &data) {
// Initialize frequency to NaN
data.power.frequency = NAN;
// Try to read frequency from common HID report IDs used across different vendors
// Generic protocol attempts broader range of report IDs
const std::vector<uint8_t> frequency_report_ids = {
HID_USAGE_POW_FREQUENCY, // 0x32 - Standard HID frequency usage
HID_USAGE_POW_VOLTAGE, // 0x30 - Input measurements (may include frequency)
HID_USAGE_POW_CURRENT, // 0x31 - Output measurements (may include frequency)
HID_USAGE_POW_OUTPUT, // 0x1C - Output collection
HID_USAGE_POW_INPUT, // 0x1A - Input collection
0x11, // Common alternative frequency report
0x0F, // Input voltage report (might contain frequency)
0x12, // Output voltage report (might contain frequency)
};
uint8_t buffer[64];
size_t buffer_len;
for (uint8_t report_id : frequency_report_ids) {
if (read_report(report_id, buffer, buffer_len)) {
float frequency_value = parse_frequency_from_report(buffer, buffer_len);
if (!std::isnan(frequency_value)) {
data.power.frequency = frequency_value;
ESP_LOGD(GEN_TAG, "Found frequency %.1f Hz in report 0x%02X", frequency_value, report_id);
return;
}
}
}
ESP_LOGV(GEN_TAG, "Frequency data not available from any HID report");
}
float GenericHidProtocol::parse_frequency_from_report(uint8_t* data, size_t len) {
if (len < 2) {
return NAN;
}
// Try different byte positions and formats commonly used for frequency across vendors
// Generic protocol uses broader heuristics than vendor-specific protocols
// Method 1: Single byte at position 1 (simple frequency reports)
if (len >= 2) {
uint8_t freq_byte = data[1];
if (freq_byte >= FREQUENCY_MIN_VALID && freq_byte <= FREQUENCY_MAX_VALID) {
ESP_LOGD(GEN_TAG, "Found frequency %d Hz (single byte)", freq_byte);
return static_cast<float>(freq_byte);
}
}
// Method 2: Check all byte positions for valid frequency values
for (size_t i = 1; i < len; i++) {
uint8_t freq_byte = data[i];
if ((freq_byte == 50 || freq_byte == 60) && freq_byte <= FREQUENCY_MAX_VALID) {
ESP_LOGD(GEN_TAG, "Found standard frequency %d Hz at byte %zu", freq_byte, i);
return static_cast<float>(freq_byte);
}
}
// Method 3: 16-bit little-endian values
for (size_t i = 1; i <= len - 2; i++) {
uint16_t freq_word = data[i] | (data[i + 1] << 8);
if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) {
ESP_LOGD(GEN_TAG, "Found frequency %d Hz (16-bit LE) at bytes %zu-%zu", freq_word, i, i + 1);
return static_cast<float>(freq_word);
}
}
// Method 4: 16-bit big-endian values
for (size_t i = 1; i <= len - 2; i++) {
uint16_t freq_word = (data[i] << 8) | data[i + 1];
if (freq_word >= FREQUENCY_MIN_VALID && freq_word <= FREQUENCY_MAX_VALID) {
ESP_LOGD(GEN_TAG, "Found frequency %d Hz (16-bit BE) at bytes %zu-%zu", freq_word, i, i + 1);
return static_cast<float>(freq_word);
}
}
// Method 5: Scaled frequencies (0.1x factor common in some devices)
for (size_t i = 1; i <= len - 2; i++) {
uint16_t freq_scaled = data[i] | (data[i + 1] << 8);
float freq_value = static_cast<float>(freq_scaled) / 10.0f;
if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) {
ESP_LOGD(GEN_TAG, "Found scaled frequency %.1f Hz (0.1x) at bytes %zu-%zu", freq_value, i, i + 1);
return freq_value;
}
}
// Method 6: Check for hundreds scaling (0.01x factor)
for (size_t i = 1; i <= len - 2; i++) {
uint16_t freq_scaled = data[i] | (data[i + 1] << 8);
float freq_value = static_cast<float>(freq_scaled) / 100.0f;
if (freq_value >= FREQUENCY_MIN_VALID && freq_value <= FREQUENCY_MAX_VALID) {
ESP_LOGD(GEN_TAG, "Found scaled frequency %.1f Hz (0.01x) at bytes %zu-%zu", freq_value, i, i + 1);
return freq_value;
}
}
return NAN;
}
} // namespace ups_hid
} // namespace esphome
} // namespace esphome
// Protocol Factory Self-Registration
#include "protocol_factory.h"
namespace esphome {
namespace ups_hid {
// Creator function for Generic protocol
std::unique_ptr<UpsProtocolBase> create_generic_protocol(UpsHidComponent* parent) {
return std::make_unique<GenericHidProtocol>(parent);
}
} // namespace ups_hid
} // namespace esphome
// Register Generic protocol as fallback for all unknown vendors
REGISTER_UPS_FALLBACK_PROTOCOL(generic_hid_protocol, esphome::ups_hid::create_generic_protocol, "Generic HID Protocol", "Universal HID protocol fallback for unknown UPS vendors with basic monitoring capabilities", 10);
+79
View File
@@ -0,0 +1,79 @@
#pragma once
#include "ups_hid.h"
#include "ups_composite_data.h"
#include "device_info.h"
#include <set>
#include <map>
namespace esphome {
namespace ups_hid {
/**
* Generic HID Protocol Implementation
*
* Provides fallback support for unknown UPS vendors by attempting to
* discover and parse common HID Power Device report IDs.
*
* This protocol uses a discovery-based approach, testing standard report IDs
* that are commonly used across different UPS manufacturers based on NUT
* (Network UPS Tools) analysis.
*/
class GenericHidProtocol : public UpsProtocolBase {
public:
explicit GenericHidProtocol(UpsHidComponent* parent) : UpsProtocolBase(parent) {}
~GenericHidProtocol() override = default;
// Protocol identification
DeviceInfo::DetectedProtocol get_protocol_type() const override {
return DeviceInfo::PROTOCOL_GENERIC_HID;
}
std::string get_protocol_name() const override {
return "Generic HID";
}
// Core protocol interface
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
// Report discovery and enumeration
void enumerate_reports();
bool read_report(uint8_t report_id, uint8_t* buffer, size_t& buffer_len);
// Data parsing methods for different report types
void parse_power_summary(uint8_t* data, size_t len, UpsData& ups_data);
void parse_battery_status(uint8_t* data, size_t len, UpsData& ups_data);
void parse_present_status(uint8_t* data, size_t len, UpsData& ups_data);
void parse_general_status(uint8_t* data, size_t len, UpsData& ups_data);
void parse_voltage(uint8_t* data, size_t len, UpsData& ups_data, bool is_input);
void parse_load(uint8_t* data, size_t len, UpsData& ups_data);
void parse_input_sensitivity(uint8_t* data, size_t len, UpsData& ups_data, const char* style);
bool parse_unknown_report(uint8_t* data, size_t len, UpsData& ups_data);
// Frequency reading methods
void read_frequency_data(UpsData &data);
float parse_frequency_from_report(uint8_t* data, size_t len);
// Test control methods (generic implementations)
bool start_battery_test_quick() override;
bool start_battery_test_deep() override;
bool stop_battery_test() override;
bool start_ups_test() override;
bool stop_ups_test() override;
// Beeper control - not implemented for generic protocol
bool beeper_enable() override { return false; }
bool beeper_disable() override { return false; }
bool beeper_mute() override { return false; }
bool beeper_test() override { return false; }
private:
// Report discovery state
std::set<uint8_t> available_input_reports_;
std::set<uint8_t> available_feature_reports_;
std::map<uint8_t, size_t> report_sizes_;
};
} // namespace ups_hid
} // namespace esphome
+173
View File
@@ -0,0 +1,173 @@
#pragma once
/**
* @file hid_constants.h
* @brief HID Constants for UPS Power Device Class
*
* Standard USB HID constants following USB HID Usage Tables v1.6
* and USB Device Class Definition for HID Power Devices v1.1
*
* References:
* - USB HID Usage Tables v1.6: https://usb.org/document-library/hid-usage-tables-16
* - USB Power Device Class v1.1: https://usb.org/sites/default/files/pdcv11.pdf
* - NUT HID Implementation: drivers/hidtypes.h
*/
// =============================================================================
// USB HID Class and Report Types (USB HID Specification v1.11)
// =============================================================================
#define USB_CLASS_HID 0x03
#define HID_REPORT_TYPE_INPUT 0x01
#define HID_REPORT_TYPE_OUTPUT 0x02
#define HID_REPORT_TYPE_FEATURE 0x03
// =============================================================================
// HID Usage Pages (USB HID Usage Tables v1.12)
// =============================================================================
#define HID_USAGE_PAGE_POWER_DEVICE 0x84
#define HID_USAGE_PAGE_BATTERY_SYSTEM 0x85
// =============================================================================
// Power Device Usage IDs (HID Power Device Class v1.1)
// =============================================================================
// Device Identification
#define HID_USAGE_POW_I_NAME 0x0001
#define HID_USAGE_POW_PRESENT_STATUS 0x0002
#define HID_USAGE_POW_UPS 0x0004
#define HID_USAGE_POW_POWER_SUPPLY 0x0005
// Power Components
#define HID_USAGE_POW_BATTERY_SYSTEM 0x0010
#define HID_USAGE_POW_BATTERY 0x0012
#define HID_USAGE_POW_INPUT 0x001A
#define HID_USAGE_POW_OUTPUT 0x001C
#define HID_USAGE_POW_POWER_SUMMARY 0x0024
// Measurements
#define HID_USAGE_POW_VOLTAGE 0x0030
#define HID_USAGE_POW_CURRENT 0x0031
#define HID_USAGE_POW_FREQUENCY 0x0032
#define HID_USAGE_POW_APPARENT_POWER 0x0033
#define HID_USAGE_POW_ACTIVE_POWER 0x0034
#define HID_USAGE_POW_PERCENT_LOAD 0x0035
#define HID_USAGE_POW_TEMPERATURE 0x0036
// Configuration Values (Nominal/Reference)
#define HID_USAGE_POW_CONFIG_VOLTAGE 0x0040
#define HID_USAGE_POW_CONFIG_CURRENT 0x0041
#define HID_USAGE_POW_CONFIG_FREQUENCY 0x0042
#define HID_USAGE_POW_CONFIG_APPARENT_POWER 0x0043
#define HID_USAGE_POW_CONFIG_ACTIVE_POWER 0x0044
#define HID_USAGE_POW_CONFIG_PERCENT_LOAD 0x0045
// Control Operations
#define HID_USAGE_POW_SWITCH_ON_CONTROL 0x0050
#define HID_USAGE_POW_SWITCH_OFF_CONTROL 0x0051
#define HID_USAGE_POW_LOW_VOLTAGE_TRANSFER 0x0053
#define HID_USAGE_POW_HIGH_VOLTAGE_TRANSFER 0x0054
#define HID_USAGE_POW_DELAY_BEFORE_REBOOT 0x0055
#define HID_USAGE_POW_DELAY_BEFORE_STARTUP 0x0056
#define HID_USAGE_POW_DELAY_BEFORE_SHUTDOWN 0x0057
#define HID_USAGE_POW_TEST 0x0058
#define HID_USAGE_POW_AUDIBLE_ALARM_CONTROL 0x005A
// Status Indicators
#define HID_USAGE_POW_PRESENT 0x0060
#define HID_USAGE_POW_GOOD 0x0061
#define HID_USAGE_POW_INTERNAL_FAILURE 0x0062
#define HID_USAGE_POW_VOLTAGE_OUT_OF_RANGE 0x0063
#define HID_USAGE_POW_OVERLOAD 0x0065
#define HID_USAGE_POW_OVER_CHARGED 0x0066
#define HID_USAGE_POW_SHUTDOWN_REQUESTED 0x0068
#define HID_USAGE_POW_SHUTDOWN_IMMINENT 0x0069
// Device Information
#define HID_USAGE_POW_I_MANUFACTURER 0x00FD
#define HID_USAGE_POW_I_PRODUCT 0x00FE
#define HID_USAGE_POW_I_SERIAL_NUMBER 0x00FF
// =============================================================================
// Battery System Usage IDs (HID Power Device Class v1.1)
// =============================================================================
// Battery Status
#define HID_USAGE_BAT_CHARGING 0x0044
#define HID_USAGE_BAT_DISCHARGING 0x0045
#define HID_USAGE_BAT_FULLY_CHARGED 0x0046
#define HID_USAGE_BAT_NEED_REPLACEMENT 0x004B
// Battery Measurements
#define HID_USAGE_BAT_REMAINING_CAPACITY 0x0066
#define HID_USAGE_BAT_FULL_CHARGE_CAPACITY 0x0067
#define HID_USAGE_BAT_RUN_TIME_TO_EMPTY 0x0068
#define HID_USAGE_BAT_AVERAGE_TIME_TO_EMPTY 0x0069
#define HID_USAGE_BAT_AVERAGE_TIME_TO_FULL 0x006A
// Battery Configuration
#define HID_USAGE_BAT_DESIGN_CAPACITY 0x0083
#define HID_USAGE_BAT_WARNING_CAPACITY_LIMIT 0x008C
// Battery Information
#define HID_USAGE_BAT_I_MANUFACTURER_NAME 0x0087
#define HID_USAGE_BAT_I_DEVICE_NAME 0x0088
#define HID_USAGE_BAT_I_DEVICE_CHEMISTRY 0x0089
// =============================================================================
// Regional Voltage Standards (IEC 60038)
// =============================================================================
// Single-phase nominal voltages (RMS)
#define VOLTAGE_NOMINAL_EU 230.0f // Europe (IEC 60038)
#define VOLTAGE_NOMINAL_US 120.0f // North America
#define VOLTAGE_NOMINAL_JP 100.0f // Japan
#define VOLTAGE_NOMINAL_UK 230.0f // United Kingdom
#define VOLTAGE_NOMINAL_AU 230.0f // Australia
// Voltage tolerance ranges (±10% typical)
#define VOLTAGE_MIN_VALID 80.0f // Minimum valid voltage
#define VOLTAGE_MAX_VALID 300.0f // Maximum valid voltage
// Three-phase nominal voltages (for industrial UPS)
#define VOLTAGE_NOMINAL_3P_EU 400.0f // Europe 3-phase
#define VOLTAGE_NOMINAL_3P_US 208.0f // North America 3-phase
// =============================================================================
// Regional Frequency Standards (IEC 60038)
// =============================================================================
// Standard AC frequencies (Hz)
#define FREQUENCY_NOMINAL_EU 50.0f // Europe (IEC 60038)
#define FREQUENCY_NOMINAL_US 60.0f // North America
#define FREQUENCY_NOMINAL_JP 50.0f // Japan (50Hz East, 60Hz West)
#define FREQUENCY_NOMINAL_UK 50.0f // United Kingdom
#define FREQUENCY_NOMINAL_AU 50.0f // Australia
// Frequency tolerance ranges (typical ±1% for power systems)
#define FREQUENCY_MIN_VALID 47.0f // Minimum valid frequency (50Hz -6%)
#define FREQUENCY_MAX_VALID 65.0f // Maximum valid frequency (60Hz +8%)
// Specialized frequency applications
#define FREQUENCY_AIRCRAFT 400.0f // Aircraft power systems
#define FREQUENCY_RAILWAY 16.7f // Railway power systems (Europe)
#define FREQUENCY_RAILWAY_US 25.0f // Railway power systems (North America)
// =============================================================================
// Helper Macros for HID Usage Paths
// =============================================================================
// Create full 32-bit HID usage from page and usage ID
#define HID_USAGE(page, usage) (((uint32_t)(page) << 16) | (usage))
// Power Device usages
#define HID_USAGE_POW(usage) HID_USAGE(HID_USAGE_PAGE_POWER_DEVICE, usage)
#define HID_USAGE_BAT(usage) HID_USAGE(HID_USAGE_PAGE_BATTERY_SYSTEM, usage)
// Common voltage usage paths (for NUT-style path matching)
#define HID_PATH_INPUT_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_VOLTAGE)
#define HID_PATH_INPUT_CONFIG_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_CONFIG_VOLTAGE)
#define HID_PATH_OUTPUT_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_VOLTAGE)
#define HID_PATH_BATTERY_VOLTAGE HID_USAGE_POW(HID_USAGE_POW_VOLTAGE)
+75
View File
@@ -0,0 +1,75 @@
#pragma once
#include <string>
#include <cmath>
#include "hid_constants.h"
namespace esphome {
namespace ups_hid {
struct PowerData {
// Input power metrics
float input_voltage{NAN}; // Current input voltage (V)
float input_voltage_nominal{NAN}; // Nominal input voltage (V)
float input_transfer_low{NAN}; // Low transfer voltage threshold (V)
float input_transfer_high{NAN}; // High transfer voltage threshold (V)
float frequency{NAN}; // Input frequency (Hz)
// Output power metrics
float output_voltage{NAN}; // Current output voltage (V)
float output_voltage_nominal{NAN}; // Nominal output voltage (V)
float load_percent{NAN}; // Current load percentage (0-100%)
// Power ratings and capabilities
float realpower_nominal{NAN}; // Nominal real power rating (W)
float apparent_power_nominal{NAN}; // Nominal apparent power rating (VA)
// Power status information
std::string status{}; // Power status text (Online, On Battery, etc.)
// Power quality indicators
bool input_voltage_valid() const {
return !std::isnan(input_voltage) && input_voltage > 50.0f && input_voltage < 300.0f;
}
bool output_voltage_valid() const {
return !std::isnan(output_voltage) && output_voltage > 50.0f && output_voltage < 300.0f;
}
bool frequency_valid() const {
return !std::isnan(frequency) && frequency >= FREQUENCY_MIN_VALID && frequency <= FREQUENCY_MAX_VALID;
}
bool is_input_out_of_range() const {
if (!input_voltage_valid()) return false;
return (!std::isnan(input_transfer_low) && input_voltage < input_transfer_low) ||
(!std::isnan(input_transfer_high) && input_voltage > input_transfer_high);
}
bool is_overloaded() const {
return !std::isnan(load_percent) && load_percent > 95.0f;
}
bool has_load_info() const {
return !std::isnan(load_percent);
}
// Validation and utility methods
bool is_valid() const {
return input_voltage_valid() || output_voltage_valid() || has_load_info();
}
void reset() {
*this = PowerData{};
}
// Copy constructor and assignment for safe copying
PowerData() = default;
PowerData(const PowerData&) = default;
PowerData& operator=(const PowerData&) = default;
PowerData(PowerData&&) = default;
PowerData& operator=(PowerData&&) = default;
};
} // namespace ups_hid
} // namespace esphome
+239
View File
@@ -0,0 +1,239 @@
#include "protocol_factory.h"
#include "ups_hid.h"
#include "esphome/core/log.h"
#include <algorithm>
namespace esphome {
namespace ups_hid {
static const char *const FACTORY_TAG = "ups_hid.factory";
// Static registry implementations
std::unordered_map<uint16_t, std::vector<ProtocolFactory::ProtocolInfo>>&
ProtocolFactory::get_vendor_registry() {
static std::unordered_map<uint16_t, std::vector<ProtocolInfo>> vendor_registry;
return vendor_registry;
}
std::vector<ProtocolFactory::ProtocolInfo>&
ProtocolFactory::get_fallback_registry() {
static std::vector<ProtocolInfo> fallback_registry;
return fallback_registry;
}
void ProtocolFactory::ensure_initialized() {
// Registries are initialized on first access due to static storage
// This function exists for explicit initialization if needed
static bool initialized = false;
if (!initialized) {
ESP_LOGD(FACTORY_TAG, "Protocol factory registries initialized");
initialized = true;
}
}
void ProtocolFactory::register_protocol_for_vendor(uint16_t vendor_id,
const ProtocolInfo& info) {
ensure_initialized();
auto& registry = get_vendor_registry();
registry[vendor_id].push_back(info);
// Sort by priority (higher first)
std::sort(registry[vendor_id].begin(), registry[vendor_id].end(),
[](const ProtocolInfo& a, const ProtocolInfo& b) {
return a.priority > b.priority;
});
ESP_LOGI(FACTORY_TAG, "Registered protocol '%s' for vendor 0x%04X (priority %d)",
info.name.c_str(), vendor_id, info.priority);
}
void ProtocolFactory::register_fallback_protocol(const ProtocolInfo& info) {
ensure_initialized();
auto& registry = get_fallback_registry();
registry.push_back(info);
// Sort by priority (higher first)
std::sort(registry.begin(), registry.end(),
[](const ProtocolInfo& a, const ProtocolInfo& b) {
return a.priority > b.priority;
});
ESP_LOGI(FACTORY_TAG, "Registered fallback protocol '%s' (priority %d)",
info.name.c_str(), info.priority);
}
std::unique_ptr<UpsProtocolBase>
ProtocolFactory::create_for_vendor(uint16_t vendor_id, UpsHidComponent* parent) {
ensure_initialized();
if (!parent) {
ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component");
return nullptr;
}
// Try vendor-specific protocols first
auto& vendor_registry = get_vendor_registry();
auto vendor_it = vendor_registry.find(vendor_id);
if (vendor_it != vendor_registry.end()) {
ESP_LOGD(FACTORY_TAG, "Found %zu vendor-specific protocols for 0x%04X",
vendor_it->second.size(), vendor_id);
for (const auto& info : vendor_it->second) {
ESP_LOGD(FACTORY_TAG, "Trying vendor protocol '%s' for 0x%04X",
info.name.c_str(), vendor_id);
auto protocol = info.creator(parent);
if (protocol && protocol->detect()) {
ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' for vendor 0x%04X",
info.name.c_str(), vendor_id);
return protocol;
}
}
}
// Try fallback protocols
auto& fallback_registry = get_fallback_registry();
ESP_LOGD(FACTORY_TAG, "Trying %zu fallback protocols for vendor 0x%04X",
fallback_registry.size(), vendor_id);
for (const auto& info : fallback_registry) {
ESP_LOGD(FACTORY_TAG, "Trying fallback protocol '%s' for 0x%04X",
info.name.c_str(), vendor_id);
auto protocol = info.creator(parent);
if (protocol && protocol->detect()) {
ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' for vendor 0x%04X",
info.name.c_str(), vendor_id);
return protocol;
}
}
ESP_LOGW(FACTORY_TAG, "No suitable protocol found for vendor 0x%04X", vendor_id);
return nullptr;
}
std::vector<ProtocolFactory::ProtocolInfo>
ProtocolFactory::get_protocols_for_vendor(uint16_t vendor_id) {
ensure_initialized();
std::vector<ProtocolInfo> protocols;
// Add vendor-specific protocols first
auto& vendor_registry = get_vendor_registry();
auto vendor_it = vendor_registry.find(vendor_id);
if (vendor_it != vendor_registry.end()) {
for (const auto& info : vendor_it->second) {
protocols.push_back(info);
}
}
// Add fallback protocols
auto& fallback_registry = get_fallback_registry();
for (const auto& info : fallback_registry) {
protocols.push_back(info);
}
return protocols;
}
std::vector<std::pair<uint16_t, ProtocolFactory::ProtocolInfo>>
ProtocolFactory::get_all_protocols() {
ensure_initialized();
std::vector<std::pair<uint16_t, ProtocolInfo>> all_protocols;
// Add vendor-specific protocols
auto& vendor_registry = get_vendor_registry();
for (const auto& vendor_pair : vendor_registry) {
uint16_t vendor_id = vendor_pair.first;
for (const auto& info : vendor_pair.second) {
all_protocols.emplace_back(vendor_id, info);
}
}
// Add fallback protocols (use 0x0000 as special vendor ID for fallbacks)
auto& fallback_registry = get_fallback_registry();
for (const auto& info : fallback_registry) {
all_protocols.emplace_back(0x0000, info);
}
return all_protocols;
}
bool ProtocolFactory::has_vendor_support(uint16_t vendor_id) {
ensure_initialized();
auto& vendor_registry = get_vendor_registry();
auto it = vendor_registry.find(vendor_id);
// Has support if vendor-specific protocols exist OR fallback protocols exist
bool has_vendor_specific = (it != vendor_registry.end() && !it->second.empty());
bool has_fallback = !get_fallback_registry().empty();
return has_vendor_specific || has_fallback;
}
std::unique_ptr<UpsProtocolBase>
ProtocolFactory::create_by_name(const std::string& protocol_name, UpsHidComponent* parent) {
ensure_initialized();
if (!parent) {
ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component");
return nullptr;
}
ESP_LOGD(FACTORY_TAG, "Creating protocol by name: %s", protocol_name.c_str());
// Search through all registered protocols to find one with matching name
auto& vendor_registry = get_vendor_registry();
for (const auto& vendor_pair : vendor_registry) {
for (const auto& info : vendor_pair.second) {
// Match protocol name (case-insensitive)
std::string info_name_lower = info.name;
std::string protocol_name_lower = protocol_name;
std::transform(info_name_lower.begin(), info_name_lower.end(), info_name_lower.begin(), ::tolower);
std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(), ::tolower);
if (info_name_lower.find(protocol_name_lower) != std::string::npos) {
ESP_LOGD(FACTORY_TAG, "Found matching protocol '%s' for name '%s'",
info.name.c_str(), protocol_name.c_str());
auto protocol = info.creator(parent);
if (protocol) {
ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' by name",
protocol->get_protocol_name().c_str());
return protocol;
}
}
}
}
// Search through fallback protocols
auto& fallback_registry = get_fallback_registry();
for (const auto& info : fallback_registry) {
std::string info_name_lower = info.name;
std::string protocol_name_lower = protocol_name;
std::transform(info_name_lower.begin(), info_name_lower.end(), info_name_lower.begin(), ::tolower);
std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(), ::tolower);
if (info_name_lower.find(protocol_name_lower) != std::string::npos) {
ESP_LOGD(FACTORY_TAG, "Found matching fallback protocol '%s' for name '%s'",
info.name.c_str(), protocol_name.c_str());
auto protocol = info.creator(parent);
if (protocol) {
ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' by name",
protocol->get_protocol_name().c_str());
return protocol;
}
}
}
ESP_LOGE(FACTORY_TAG, "No protocol found with name containing '%s'", protocol_name.c_str());
return nullptr;
}
} // namespace ups_hid
} // namespace esphome
+133
View File
@@ -0,0 +1,133 @@
#pragma once
#include <memory>
#include <functional>
#include <unordered_map>
#include <vector>
#include <string>
namespace esphome {
namespace ups_hid {
// Forward declarations
class UpsProtocolBase;
class UpsHidComponent;
/**
* Protocol Factory with Self-Registration Support
*
* Enables protocols to register themselves automatically, following the
* Open/Closed Principle - new protocols can be added without modifying
* existing code.
*
* Design Pattern: Factory Method + Registry Pattern
*/
class ProtocolFactory {
public:
// Protocol creator function type
using CreatorFunc = std::function<std::unique_ptr<UpsProtocolBase>(UpsHidComponent*)>;
// Protocol metadata for better selection
struct ProtocolInfo {
CreatorFunc creator;
std::string name;
std::string description;
std::vector<uint16_t> supported_vendors;
int priority; // Higher priority = tried first
};
/**
* Register a protocol with specific vendor IDs
*/
static void register_protocol_for_vendor(uint16_t vendor_id,
const ProtocolInfo& info);
/**
* Register a fallback protocol (tried when vendor-specific fails)
*/
static void register_fallback_protocol(const ProtocolInfo& info);
/**
* Create protocol instance for specific vendor
*/
static std::unique_ptr<UpsProtocolBase> create_for_vendor(uint16_t vendor_id,
UpsHidComponent* parent);
/**
* Create protocol instance by name (manual selection)
*/
static std::unique_ptr<UpsProtocolBase> create_by_name(const std::string& protocol_name,
UpsHidComponent* parent);
/**
* Get ordered list of protocols to try for a vendor
* Returns vendor-specific first, then fallbacks by priority
*/
static std::vector<ProtocolInfo> get_protocols_for_vendor(uint16_t vendor_id);
/**
* Get list of all registered protocols
*/
static std::vector<std::pair<uint16_t, ProtocolInfo>> get_all_protocols();
/**
* Check if vendor has registered protocols
*/
static bool has_vendor_support(uint16_t vendor_id);
private:
// Vendor-specific protocol registry
static std::unordered_map<uint16_t, std::vector<ProtocolInfo>>& get_vendor_registry();
// Fallback protocol registry (sorted by priority)
static std::vector<ProtocolInfo>& get_fallback_registry();
// Ensure registries are initialized
static void ensure_initialized();
};
/**
* Protocol Registration Helper Macros
*
* These macros enable automatic protocol registration at startup
*/
// Forward declare for registration macros
class ProtocolFactory;
// Register protocol for specific vendor
#define REGISTER_UPS_PROTOCOL_FOR_VENDOR(vendor_id, protocol_name, creator_func, name_str, desc_str, prio) \
namespace { \
struct protocol_name##_registrar { \
protocol_name##_registrar() { \
esphome::ups_hid::ProtocolFactory::ProtocolInfo info; \
info.creator = creator_func; \
info.name = name_str; \
info.description = desc_str; \
info.supported_vendors = {vendor_id}; \
info.priority = prio; \
esphome::ups_hid::ProtocolFactory::register_protocol_for_vendor(vendor_id, info); \
} \
}; \
static protocol_name##_registrar protocol_name##_reg; \
}
// Register fallback protocol
#define REGISTER_UPS_FALLBACK_PROTOCOL(protocol_name, creator_func, name_str, desc_str, prio) \
namespace { \
struct protocol_name##_fallback_registrar { \
protocol_name##_fallback_registrar() { \
esphome::ups_hid::ProtocolFactory::ProtocolInfo info; \
info.creator = creator_func; \
info.name = name_str; \
info.description = desc_str; \
info.supported_vendors = {}; \
info.priority = prio; \
esphome::ups_hid::ProtocolFactory::register_fallback_protocol(info); \
} \
}; \
static protocol_name##_fallback_registrar protocol_name##_fallback_reg; \
}
} // namespace ups_hid
} // namespace esphome
+5
View File
@@ -94,6 +94,11 @@ SENSOR_TYPES = {
"device_class": DEVICE_CLASS_DURATION,
"accuracy_decimals": 0,
},
"ups_delay_reboot": {
"unit": UNIT_SECOND,
"device_class": DEVICE_CLASS_DURATION,
"accuracy_decimals": 0,
},
# Additional missing sensor types from NUT analysis
"battery_charge_low": {
"unit": UNIT_PERCENT,
+382
View File
@@ -0,0 +1,382 @@
#include "simulated_transport.h"
#include "esphome/core/log.h"
#include <cstring>
#include <cmath>
namespace esphome {
namespace ups_hid {
static const char *const SIM_TRANSPORT_TAG = "ups_hid.simulation";
SimulatedTransport::SimulatedTransport() {
start_time_ = std::chrono::steady_clock::now();
}
esp_err_t SimulatedTransport::initialize() {
if (initialized_) {
return ESP_OK;
}
ESP_LOGI(SIM_TRANSPORT_TAG, "Initializing simulated USB transport");
ESP_LOGI(SIM_TRANSPORT_TAG, "Simulating APC Back-UPS ES (VID=0x051D, PID=0x0002)");
initialized_ = true;
connected_ = true;
return ESP_OK;
}
esp_err_t SimulatedTransport::deinitialize() {
if (!initialized_) {
return ESP_OK;
}
ESP_LOGI(SIM_TRANSPORT_TAG, "Deinitializing simulated USB transport");
initialized_ = false;
connected_ = false;
return ESP_OK;
}
bool SimulatedTransport::is_connected() const {
return connected_ && initialized_;
}
uint16_t SimulatedTransport::get_vendor_id() const {
return vendor_id_;
}
uint16_t SimulatedTransport::get_product_id() const {
return product_id_;
}
esp_err_t SimulatedTransport::hid_get_report(uint8_t report_type, uint8_t report_id,
uint8_t* data, size_t* data_len,
uint32_t timeout_ms) {
if (!is_connected()) {
last_error_ = "Simulated transport not connected";
return ESP_ERR_INVALID_STATE;
}
// Update dynamic simulation data
update_simulation_data();
ESP_LOGV(SIM_TRANSPORT_TAG, "Simulating HID GET_REPORT: type=0x%02X, id=0x%02X",
report_type, report_id);
// Clear the buffer first
memset(data, 0, *data_len);
data[0] = report_id; // First byte is always report ID
// Generate simulated data based on report ID
switch (report_id) {
case 0x01: // Status report
generate_status_report(report_id, data, data_len);
break;
case 0x06: // Battery report
generate_battery_report(report_id, data, data_len);
break;
case 0x07: // Load report
generate_power_report(report_id, data, data_len);
break;
case 0x0C: // Power summary
generate_battery_report(report_id, data, data_len);
break;
case 0x0E: // Voltage report
generate_power_report(report_id, data, data_len);
break;
case 0x1F: // Beeper control
case 0x18: // Audible alarm
generate_beeper_report(report_id, data, data_len);
break;
case 0x03: // Device info
case 0x04: // Firmware
generate_device_info_report(report_id, data, data_len);
break;
case 0x35: // Sensitivity
*data_len = 2;
data[1] = 1; // Normal sensitivity
break;
default:
// Return zeros for unknown reports
*data_len = 6; // Standard HID report size
ESP_LOGV(SIM_TRANSPORT_TAG, "Unknown report ID 0x%02X, returning zeros", report_id);
break;
}
return ESP_OK;
}
esp_err_t SimulatedTransport::hid_set_report(uint8_t report_type, uint8_t report_id,
const uint8_t* data, size_t data_len,
uint32_t timeout_ms) {
if (!is_connected()) {
last_error_ = "Simulated transport not connected";
return ESP_ERR_INVALID_STATE;
}
ESP_LOGV(SIM_TRANSPORT_TAG, "Simulating HID SET_REPORT: type=0x%02X, id=0x%02X, len=%zu",
report_type, report_id, data_len);
// Simulate beeper control
if (report_id == 0x1F || report_id == 0x18) {
if (data_len >= 2) {
uint8_t beeper_value = data[1];
switch (beeper_value) {
case 1:
beeper_status_ = "disabled";
ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper disabled");
break;
case 2:
beeper_status_ = "enabled";
ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper enabled");
break;
case 3:
beeper_status_ = "muted";
ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper muted");
break;
case 4:
beeper_status_ = "test";
ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated beeper test");
break;
default:
ESP_LOGW(SIM_TRANSPORT_TAG, "Unknown beeper command: %d", beeper_value);
break;
}
}
}
// Simulate test commands
if (report_id == 0x20 || report_id == 0x21) { // Battery test commands
if (data_len >= 2) {
uint8_t test_cmd = data[1];
if (test_cmd == 1) {
test_running_ = true;
test_result_ = "Battery test in progress";
ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated battery test started");
} else if (test_cmd == 0) {
test_running_ = false;
test_result_ = "Battery test completed - Good";
ESP_LOGI(SIM_TRANSPORT_TAG, "Simulated battery test stopped");
}
}
}
return ESP_OK;
}
esp_err_t SimulatedTransport::get_string_descriptor(uint8_t string_index,
std::string& result) {
if (!is_connected()) {
last_error_ = "Simulated transport not connected";
return ESP_ERR_INVALID_STATE;
}
// Simulate string descriptors
switch (string_index) {
case 1: // Manufacturer
result = "American Power Conversion";
break;
case 2: // Product
result = "Back-UPS ES 700 FW:866.L4.I USB FW:L4";
break;
case 3: // Serial number
result = "4B2037P30628";
break;
case 4: // Firmware (custom)
result = "866.L4.I";
break;
default:
result = "Unknown";
ESP_LOGW(SIM_TRANSPORT_TAG, "Unknown string index: %d", string_index);
return ESP_ERR_NOT_FOUND;
}
ESP_LOGV(SIM_TRANSPORT_TAG, "Simulated string descriptor %d: '%s'",
string_index, result.c_str());
return ESP_OK;
}
std::string SimulatedTransport::get_last_error() const {
return last_error_;
}
// Private methods
void SimulatedTransport::update_simulation_data() {
float elapsed = get_elapsed_seconds();
// Simulate battery level slowly decreasing when on battery
if (input_voltage_ < 100.0f) { // On battery
battery_level_ = std::max(10.0f, 95.0f - (elapsed * 0.5f)); // Decrease over time
runtime_minutes_ = static_cast<uint16_t>(battery_level_ * 0.6f); // Runtime based on battery
} else {
// On mains - slowly charge if below 100%
if (battery_level_ < 100.0f) {
battery_level_ = std::min(100.0f, battery_level_ + (elapsed * 0.1f));
}
runtime_minutes_ = static_cast<uint16_t>(battery_level_ * 0.8f);
}
// Simulate periodic power fluctuations
input_voltage_ = 120.0f + sin(elapsed * 0.1f) * 2.0f; // Slight voltage variation
output_voltage_ = 120.0f + sin(elapsed * 0.05f) * 1.0f;
// Simulate load variations
load_percent_ = 25.0f + sin(elapsed * 0.2f) * 5.0f; // 20-30% load
// Simulate brief battery switch every 5 minutes for testing
if (fmod(elapsed, 300.0f) < 30.0f) { // 30 seconds on battery every 5 minutes
input_voltage_ = 0.0f; // Simulate power outage
}
}
float SimulatedTransport::get_elapsed_seconds() const {
auto now = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - start_time_);
return static_cast<float>(duration.count());
}
void SimulatedTransport::generate_battery_report(uint8_t report_id, uint8_t* data, size_t* data_len) {
*data_len = 6;
if (report_id == 0x06) {
// Battery status report: [06 level runtime_low runtime_high 00 00]
data[1] = static_cast<uint8_t>(battery_level_);
data[2] = runtime_minutes_ & 0xFF;
data[3] = (runtime_minutes_ >> 8) & 0xFF;
data[4] = 0x00;
data[5] = 0x00;
} else if (report_id == 0x0C) {
// Power summary: [0C level runtime_low runtime_high]
data[1] = static_cast<uint8_t>(battery_level_);
data[2] = runtime_minutes_ & 0xFF;
data[3] = (runtime_minutes_ >> 8) & 0xFF;
}
ESP_LOGV(SIM_TRANSPORT_TAG, "Generated battery report 0x%02X: level=%.0f%%, runtime=%d min",
report_id, battery_level_, runtime_minutes_);
}
void SimulatedTransport::generate_power_report(uint8_t report_id, uint8_t* data, size_t* data_len) {
*data_len = 6;
if (report_id == 0x07) {
// Load report: [07 load 00 00 00 00]
data[1] = static_cast<uint8_t>(load_percent_);
data[2] = 0x00;
data[3] = 0x00;
data[4] = 0x00;
data[5] = 0x00;
} else if (report_id == 0x0E) {
// Voltage report: [0E voltage_low voltage_high 00 00 00]
uint16_t voltage = static_cast<uint16_t>(input_voltage_);
data[1] = voltage & 0xFF;
data[2] = (voltage >> 8) & 0xFF;
data[3] = 0x00;
data[4] = 0x00;
data[5] = 0x00;
}
ESP_LOGV(SIM_TRANSPORT_TAG, "Generated power report 0x%02X: load=%.0f%%, voltage=%.1fV",
report_id, load_percent_, input_voltage_);
}
void SimulatedTransport::generate_status_report(uint8_t report_id, uint8_t* data, size_t* data_len) {
*data_len = 6;
// Status bitmap: online, on_battery, low_battery, etc.
uint8_t status = 0x00;
if (input_voltage_ > 100.0f) {
status |= 0x01; // Online
} else {
status |= 0x02; // On battery
}
if (battery_level_ < 20.0f) {
status |= 0x04; // Low battery
}
if (load_percent_ > 80.0f) {
status |= 0x08; // Overload
}
data[1] = status;
data[2] = 0x00;
data[3] = 0x00;
data[4] = 0x00;
data[5] = 0x00;
ESP_LOGV(SIM_TRANSPORT_TAG, "Generated status report: 0x%02X", status);
}
void SimulatedTransport::generate_beeper_report(uint8_t report_id, uint8_t* data, size_t* data_len) {
*data_len = 2;
// Beeper status: 1=disabled, 2=enabled, 3=muted
if (beeper_status_ == "disabled") {
data[1] = 1;
} else if (beeper_status_ == "enabled") {
data[1] = 2;
} else if (beeper_status_ == "muted") {
data[1] = 3;
} else {
data[1] = 2; // Default enabled
}
ESP_LOGV(SIM_TRANSPORT_TAG, "Generated beeper report: status=%s (value=%d)",
beeper_status_.c_str(), data[1]);
}
void SimulatedTransport::generate_test_report(uint8_t report_id, uint8_t* data, size_t* data_len) {
*data_len = 6;
if (test_running_) {
data[1] = 0x01; // Test in progress
data[2] = 0x50; // 80% progress (example)
} else {
data[1] = 0x00; // No test
data[2] = 0x00;
}
data[3] = 0x00;
data[4] = 0x00;
data[5] = 0x00;
ESP_LOGV(SIM_TRANSPORT_TAG, "Generated test report: running=%s",
test_running_ ? "true" : "false");
}
void SimulatedTransport::generate_device_info_report(uint8_t report_id, uint8_t* data, size_t* data_len) {
*data_len = 6;
if (report_id == 0x03) {
// Device info - simulate some device characteristics
data[1] = 0x86; // Major version
data[2] = 0x6C; // Minor version
data[3] = 0x04; // Revision
data[4] = 0x00;
data[5] = 0x00;
} else if (report_id == 0x04) {
// Firmware version
data[1] = 0x08; // 866 (hex)
data[2] = 0x66;
data[3] = 0x4C; // L4 (hex)
data[4] = 0x34;
data[5] = 0x00;
}
ESP_LOGV(SIM_TRANSPORT_TAG, "Generated device info report 0x%02X", report_id);
}
} // namespace ups_hid
} // namespace esphome
+74
View File
@@ -0,0 +1,74 @@
#pragma once
#include "usb_transport_interface.h"
#include <map>
#include <chrono>
namespace esphome {
namespace ups_hid {
/**
* Simulated USB Transport Implementation
*
* Provides realistic UPS data simulation for testing and development
* without requiring physical hardware
*/
class SimulatedTransport : public IUsbTransport {
public:
SimulatedTransport();
~SimulatedTransport() override = default;
// IUsbTransport implementation
esp_err_t initialize() override;
esp_err_t deinitialize() override;
bool is_connected() const override;
uint16_t get_vendor_id() const override;
uint16_t get_product_id() const override;
esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id,
uint8_t* data, size_t* data_len,
uint32_t timeout_ms = 1000) override;
esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id,
const uint8_t* data, size_t data_len,
uint32_t timeout_ms = 1000) override;
esp_err_t get_string_descriptor(uint8_t string_index,
std::string& result) override;
std::string get_last_error() const override;
private:
bool connected_{false};
bool initialized_{false};
uint16_t vendor_id_{0x051D}; // Default to APC
uint16_t product_id_{0x0002}; // APC Back-UPS ES
std::string last_error_;
// Simulation state
std::chrono::steady_clock::time_point start_time_;
float battery_level_{85.0f};
float input_voltage_{120.0f};
float output_voltage_{120.0f};
float load_percent_{25.0f};
uint16_t runtime_minutes_{45};
std::string beeper_status_{"enabled"};
std::string test_result_{"No test initiated"};
bool test_running_{false};
// Simulated report generation
void generate_battery_report(uint8_t report_id, uint8_t* data, size_t* data_len);
void generate_power_report(uint8_t report_id, uint8_t* data, size_t* data_len);
void generate_status_report(uint8_t report_id, uint8_t* data, size_t* data_len);
void generate_beeper_report(uint8_t report_id, uint8_t* data, size_t* data_len);
void generate_test_report(uint8_t report_id, uint8_t* data, size_t* data_len);
void generate_device_info_report(uint8_t report_id, uint8_t* data, size_t* data_len);
// Dynamic data simulation
void update_simulation_data();
float get_elapsed_seconds() const;
};
} // namespace ups_hid
} // namespace esphome
+180
View File
@@ -0,0 +1,180 @@
#pragma once
#include <string>
#include <cstdint>
namespace esphome {
namespace ups_hid {
struct TestStatus {
// Test result information
std::string ups_test_result{}; // Current test result text
std::string last_test_result{}; // Last completed test result
// Test timing information
int16_t timer_reboot{-1}; // Reboot timer (seconds, -1 = not set)
int16_t timer_shutdown{-1}; // Shutdown timer (seconds, -1 = not set)
int16_t timer_start{-1}; // Start timer (seconds, -1 = not set)
// Test progress tracking
enum TestState {
TEST_STATE_IDLE = 0,
TEST_STATE_BATTERY_QUICK_RUNNING,
TEST_STATE_BATTERY_DEEP_RUNNING,
TEST_STATE_UPS_TEST_RUNNING,
TEST_STATE_PANEL_TEST_RUNNING,
TEST_STATE_COMPLETED,
TEST_STATE_FAILED,
TEST_STATE_ABORTED
};
TestState current_test_state{TEST_STATE_IDLE};
uint32_t test_start_time{0}; // Test start time (millis)
uint32_t test_duration_ms{0}; // Current test duration
// Test results enumeration (NUT compatible)
enum TestResult {
TEST_RESULT_UNKNOWN = 0,
TEST_RESULT_NO_TEST,
TEST_RESULT_PASSED,
TEST_RESULT_FAILED,
TEST_RESULT_IN_PROGRESS,
TEST_RESULT_NOT_SUPPORTED,
TEST_RESULT_ABORTED,
TEST_RESULT_BATTERY_GOOD,
TEST_RESULT_BATTERY_BAD,
TEST_RESULT_BATTERY_REPLACE
};
TestResult last_battery_test_result{TEST_RESULT_UNKNOWN};
TestResult last_ups_test_result{TEST_RESULT_UNKNOWN};
// Test type tracking
enum TestType {
TEST_TYPE_NONE = 0,
TEST_TYPE_BATTERY_QUICK,
TEST_TYPE_BATTERY_DEEP,
TEST_TYPE_UPS_SELF_TEST,
TEST_TYPE_PANEL_TEST
};
TestType current_test_type{TEST_TYPE_NONE};
// Validation and utility methods
bool is_test_running() const {
return current_test_state == TEST_STATE_BATTERY_QUICK_RUNNING ||
current_test_state == TEST_STATE_BATTERY_DEEP_RUNNING ||
current_test_state == TEST_STATE_UPS_TEST_RUNNING ||
current_test_state == TEST_STATE_PANEL_TEST_RUNNING;
}
bool is_battery_test_running() const {
return current_test_state == TEST_STATE_BATTERY_QUICK_RUNNING ||
current_test_state == TEST_STATE_BATTERY_DEEP_RUNNING;
}
bool has_test_results() const {
return !ups_test_result.empty() || !last_test_result.empty();
}
bool has_timers() const {
return timer_reboot != -1 || timer_shutdown != -1 || timer_start != -1;
}
std::string get_test_state_name() const {
switch (current_test_state) {
case TEST_STATE_IDLE: return "Idle";
case TEST_STATE_BATTERY_QUICK_RUNNING: return "Battery Quick Test";
case TEST_STATE_BATTERY_DEEP_RUNNING: return "Battery Deep Test";
case TEST_STATE_UPS_TEST_RUNNING: return "UPS Self Test";
case TEST_STATE_PANEL_TEST_RUNNING: return "Panel Test";
case TEST_STATE_COMPLETED: return "Test Completed";
case TEST_STATE_FAILED: return "Test Failed";
case TEST_STATE_ABORTED: return "Test Aborted";
default: return "Unknown";
}
}
std::string get_test_result_name(TestResult result) const {
switch (result) {
case TEST_RESULT_NO_TEST: return "No test";
case TEST_RESULT_PASSED: return "Passed";
case TEST_RESULT_FAILED: return "Failed";
case TEST_RESULT_IN_PROGRESS: return "In progress";
case TEST_RESULT_NOT_SUPPORTED: return "Not supported";
case TEST_RESULT_ABORTED: return "Aborted";
case TEST_RESULT_BATTERY_GOOD: return "Battery good";
case TEST_RESULT_BATTERY_BAD: return "Battery bad";
case TEST_RESULT_BATTERY_REPLACE: return "Replace battery";
default: return "Unknown";
}
}
void start_test(TestType type, uint32_t start_time) {
current_test_type = type;
test_start_time = start_time;
test_duration_ms = 0;
switch (type) {
case TEST_TYPE_BATTERY_QUICK:
current_test_state = TEST_STATE_BATTERY_QUICK_RUNNING;
break;
case TEST_TYPE_BATTERY_DEEP:
current_test_state = TEST_STATE_BATTERY_DEEP_RUNNING;
break;
case TEST_TYPE_UPS_SELF_TEST:
current_test_state = TEST_STATE_UPS_TEST_RUNNING;
break;
case TEST_TYPE_PANEL_TEST:
current_test_state = TEST_STATE_PANEL_TEST_RUNNING;
break;
default:
current_test_state = TEST_STATE_IDLE;
break;
}
}
void update_test_progress(uint32_t current_time) {
if (is_test_running() && test_start_time > 0) {
test_duration_ms = current_time - test_start_time;
}
}
void complete_test(TestResult result) {
current_test_state = TEST_STATE_COMPLETED;
if (current_test_type == TEST_TYPE_BATTERY_QUICK || current_test_type == TEST_TYPE_BATTERY_DEEP) {
last_battery_test_result = result;
} else {
last_ups_test_result = result;
}
// Move current result to last result
if (!ups_test_result.empty()) {
last_test_result = ups_test_result;
}
}
void abort_test() {
current_test_state = TEST_STATE_ABORTED;
ups_test_result = "Test aborted";
}
bool is_valid() const {
return has_test_results() || is_test_running() || has_timers();
}
void reset() {
*this = TestStatus{};
}
// Copy constructor and assignment for safe copying
TestStatus() = default;
TestStatus(const TestStatus&) = default;
TestStatus& operator=(const TestStatus&) = default;
TestStatus(TestStatus&&) = default;
TestStatus& operator=(TestStatus&&) = default;
};
} // namespace ups_hid
} // namespace esphome
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include "battery_data.h"
#include "power_data.h"
#include "device_info.h"
#include "test_status.h"
#include "config_data.h"
#include <cstdint>
#include <cstring> // For memcmp
namespace esphome {
namespace ups_hid {
/**
* Clean UPS Composite Data Structure
*
* Contains all UPS data organized into logical components following
* Single Responsibility Principle. No legacy compatibility code.
*/
struct UpsCompositeData {
// Specialized data components
BatteryData battery;
PowerData power;
DeviceInfo device;
TestStatus test;
ConfigData config;
// Validation and utility methods
bool is_valid() const {
return battery.is_valid() || power.is_valid() || device.is_valid() ||
test.is_valid() || config.is_valid();
}
bool has_core_data() const {
return battery.is_valid() && power.is_valid();
}
// Clean reset without legacy flags
void reset() {
battery.reset();
power.reset();
device.reset();
test.reset();
config.reset();
}
// Copy constructor and assignment for safe copying
UpsCompositeData() = default;
UpsCompositeData(const UpsCompositeData&) = default;
UpsCompositeData& operator=(const UpsCompositeData&) = default;
UpsCompositeData(UpsCompositeData&&) = default;
UpsCompositeData& operator=(UpsCompositeData&&) = default;
};
// Type alias for cleaner naming
using UpsData = UpsCompositeData;
} // namespace ups_hid
} // namespace esphome
File diff suppressed because it is too large. Load diff
+48 -288
View File
@@ -27,163 +27,32 @@
#include <map>
// USB HID Class defines
#ifndef USB_CLASS_HID
#define USB_CLASS_HID 0x03
#endif
// USB HID Class constant is now defined in hid_constants.h
#endif
// Include the clean refactored architecture
#include "ups_composite_data.h"
#include "usb_transport_interface.h"
#include "protocol_factory.h"
#include "hid_constants.h"
namespace esphome
{
namespace ups_hid
{
static const char *const TAG = "ups_hid";
// UPS status flags
enum UpsStatus
{
UPS_STATUS_UNKNOWN = 0,
UPS_STATUS_ONLINE = 1 << 0,
UPS_STATUS_ON_BATTERY = 1 << 1,
UPS_STATUS_LOW_BATTERY = 1 << 2,
UPS_STATUS_REPLACE_BATTERY = 1 << 3,
UPS_STATUS_CHARGING = 1 << 4,
UPS_STATUS_FAULT = 1 << 5,
UPS_STATUS_OVERLOAD = 1 << 6,
UPS_STATUS_CALIBRATING = 1 << 7,
UPS_STATUS_OFF = 1 << 8
};
// UPS protocols
enum UpsProtocol
{
PROTOCOL_UNKNOWN = 0,
PROTOCOL_APC_HID,
PROTOCOL_CYBERPOWER_HID,
PROTOCOL_GENERIC_HID
};
// UPS data structure with proper initialization
struct UpsData
{
float battery_level{NAN};
float input_voltage{NAN};
float output_voltage{NAN};
float load_percent{NAN};
float runtime_minutes{NAN};
float frequency{NAN};
uint32_t status_flags{UPS_STATUS_UNKNOWN};
std::string model{};
std::string manufacturer{};
std::string serial_number{};
std::string firmware_version{};
UpsProtocol detected_protocol{PROTOCOL_UNKNOWN};
// Additional sensor fields
float battery_voltage{NAN};
float battery_voltage_nominal{NAN};
float input_voltage_nominal{NAN};
float input_transfer_low{NAN};
float input_transfer_high{NAN};
float ups_realpower_nominal{NAN};
int16_t ups_delay_shutdown{-1};
int16_t ups_delay_start{-1};
std::string ups_beeper_status{};
std::string input_sensitivity{};
// Additional missing fields from NUT analysis
float battery_charge_low{NAN}; // Battery low threshold (%)
float battery_charge_warning{NAN}; // Battery warning threshold (%)
float battery_runtime_low{NAN}; // Runtime low threshold (minutes)
std::string battery_status{}; // Battery status text
std::string battery_type{}; // Battery chemistry
std::string battery_mfr_date{}; // Battery manufacture date
std::string ups_mfr_date{}; // UPS manufacture date
std::string ups_firmware_aux{}; // Auxiliary firmware info
std::string ups_test_result{}; // Test result
int16_t ups_timer_reboot{-1}; // Reboot timer
int16_t ups_timer_shutdown{-1}; // Shutdown timer
int16_t ups_timer_start{-1}; // Start timer
// Reset all data to default values
void reset() {
battery_level = NAN;
input_voltage = NAN;
output_voltage = NAN;
load_percent = NAN;
runtime_minutes = NAN;
frequency = NAN;
status_flags = UPS_STATUS_UNKNOWN;
model.clear();
manufacturer.clear();
serial_number.clear();
firmware_version.clear();
detected_protocol = PROTOCOL_UNKNOWN;
// Reset additional sensor fields
battery_voltage = NAN;
battery_voltage_nominal = NAN;
input_voltage_nominal = NAN;
input_transfer_low = NAN;
input_transfer_high = NAN;
ups_realpower_nominal = NAN;
ups_delay_shutdown = -1;
ups_delay_start = -1;
ups_beeper_status.clear();
input_sensitivity.clear();
// Reset additional missing fields
battery_charge_low = NAN;
battery_charge_warning = NAN;
battery_runtime_low = NAN;
battery_status.clear();
battery_type.clear();
battery_mfr_date.clear();
ups_mfr_date.clear();
ups_firmware_aux.clear();
ups_test_result.clear();
ups_timer_reboot = -1;
ups_timer_shutdown = -1;
ups_timer_start = -1;
}
// Check if core data is valid
bool is_valid() const {
return !std::isnan(battery_level) || !std::isnan(input_voltage) ||
!std::isnan(output_voltage) || status_flags != UPS_STATUS_UNKNOWN;
}
};
// Forward declarations
class UpsProtocolBase;
class ApcHidProtocol;
class CyberPowerProtocol;
class GenericHidProtocol;
class IUsbTransport;
class UpsHidComponent : public PollingComponent
{
public:
UpsHidComponent() {
#ifdef USE_ESP32
memset(&usb_device_, 0, sizeof(usb_device_));
usb_mutex_ = nullptr;
usb_lib_task_handle_ = nullptr;
usb_client_task_handle_ = nullptr;
usb_host_initialized_ = false;
device_connected_ = false;
usb_tasks_running_ = false;
#endif
}
~UpsHidComponent() {
#ifdef USE_ESP32
// Log any remaining suppressed errors before cleanup
log_suppressed_errors(usb_error_limiter_);
log_suppressed_errors(protocol_error_limiter_);
usb_deinit();
#endif
}
UpsHidComponent() = default;
~UpsHidComponent() = default;
void setup() override;
void update() override;
@@ -203,35 +72,17 @@ namespace esphome
protocol_timeout_ms_ = std::max(static_cast<uint32_t>(5000),
std::min(timeout_ms, static_cast<uint32_t>(300000)));
}
void set_auto_detect_protocol(bool auto_detect) { auto_detect_protocol_ = auto_detect; }
void set_protocol_selection(const std::string &protocol) { protocol_selection_ = protocol; }
void set_fallback_nominal_voltage(float voltage) { fallback_nominal_voltage_ = voltage; }
// Data getters for sensors (thread-safe)
UpsData get_ups_data() const {
std::lock_guard<std::mutex> lock(data_mutex_);
return ups_data_;
}
bool is_connected() const { return connected_; }
std::string get_protocol_name() const;
// USB device info getters
uint16_t get_usb_vendor_id() const { return usb_vendor_id_; }
uint16_t get_usb_product_id() const { return usb_product_id_; }
bool is_input_only_device() const {
#ifdef USE_ESP32
return usb_device_.is_input_only;
#else
return false;
#endif
}
// Connection status for protocols
bool is_device_connected() const {
#ifdef USE_ESP32
return device_connected_;
#else
return false;
#endif
}
uint32_t get_protocol_timeout() const { return protocol_timeout_ms_; }
float get_fallback_nominal_voltage() const { return fallback_nominal_voltage_; }
// Test control methods
bool start_battery_test_quick();
@@ -239,6 +90,12 @@ namespace esphome
bool stop_battery_test();
bool start_ups_test();
bool stop_ups_test();
// Beeper control methods
bool beeper_enable();
bool beeper_disable();
bool beeper_mute();
bool beeper_test();
// Sensor registration methods
void register_sensor(sensor::Sensor *sens, const std::string &type);
@@ -253,7 +110,8 @@ namespace esphome
uint16_t usb_vendor_id_{0}; // 0 means auto-detect
uint16_t usb_product_id_{0}; // 0 means auto-detect
uint32_t protocol_timeout_ms_{10000};
bool auto_detect_protocol_{true};
std::string protocol_selection_{"auto"};
float fallback_nominal_voltage_{230.0f}; // European standard (230V) for international compatibility
bool connected_{false};
uint32_t last_successful_read_{0};
@@ -273,104 +131,48 @@ namespace esphome
ErrorRateLimit usb_error_limiter_;
ErrorRateLimit protocol_error_limiter_;
// Clean architecture members
std::unique_ptr<IUsbTransport> transport_;
std::unique_ptr<UpsProtocolBase> active_protocol_;
std::unordered_map<std::string, sensor::Sensor *> sensors_;
std::unordered_map<std::string, binary_sensor::BinarySensor *> binary_sensors_;
std::unordered_map<std::string, text_sensor::TextSensor *> text_sensors_;
// Core methods
bool initialize_usb();
bool detect_ups_protocol();
bool initialize_transport();
bool detect_protocol();
bool read_ups_data();
void update_sensors();
void simulate_ups_data();
bool test_device_communication();
// Error rate limiting helpers
bool should_log_error(ErrorRateLimit& limiter);
void log_suppressed_errors(ErrorRateLimit& limiter);
public:
// USB communication methods (accessible by protocol classes)
bool usb_write(const std::vector<uint8_t> &data);
bool usb_read(std::vector<uint8_t> &data, uint32_t timeout_ms = 1000);
// Transport abstraction methods (accessible by protocol classes)
esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id,
uint8_t* data, size_t* data_len,
uint32_t timeout_ms = 1000);
esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id,
const uint8_t* data, size_t data_len,
uint32_t timeout_ms = 1000);
esp_err_t get_string_descriptor(uint8_t string_index, std::string& result);
#ifdef USE_ESP32
// HID class requests (UPS-specific communication)
esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id, uint8_t* data, size_t* data_len);
esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, const uint8_t* data, size_t data_len);
// Transport information
bool is_connected() const;
uint16_t get_vendor_id() const;
uint16_t get_product_id() const;
// USB string descriptor reading
esp_err_t usb_get_string_descriptor(uint8_t string_index, std::string& result, uint16_t language_id = 0x0409);
#endif
// Legacy compatibility for protocols
bool is_device_connected() const { return is_connected(); }
esp_err_t usb_get_string_descriptor(uint8_t string_index, std::string& result) {
return get_string_descriptor(string_index, result);
}
protected:
#ifdef USE_ESP32
// USB Host structures
struct UsbDevice {
usb_host_client_handle_t client_hdl;
usb_device_handle_t dev_hdl;
uint8_t dev_addr;
uint16_t vid;
uint16_t pid;
bool is_hid_device;
bool is_input_only; // True if device has no OUT endpoint (input-only HID device)
uint8_t interface_num;
uint8_t ep_in;
uint8_t ep_out;
uint16_t max_packet_size;
};
// USB Host member variables
UsbDevice usb_device_;
SemaphoreHandle_t usb_mutex_;
TaskHandle_t usb_lib_task_handle_;
TaskHandle_t usb_client_task_handle_;
bool usb_host_initialized_;
bool device_connected_;
volatile bool usb_tasks_running_;
// Asynchronous data cache for non-blocking access
struct UpsDataCache {
UpsData data;
std::mutex mutex;
uint32_t last_update_time{0};
bool data_valid{false};
} ups_data_cache_;
// ESP32-specific USB handling
esp_err_t usb_init();
void usb_deinit();
esp_err_t usb_host_lib_init();
esp_err_t usb_client_register();
esp_err_t usb_device_enumerate();
bool usb_is_ups_device(const usb_device_desc_t *desc);
esp_err_t usb_claim_interface();
esp_err_t usb_get_endpoints();
// USB communication
esp_err_t usb_transfer_sync(const std::vector<uint8_t> &data_out, std::vector<uint8_t> &data_in, uint32_t timeout_ms);
// Transfer completion tracking
struct TransferContext {
SemaphoreHandle_t done_sem;
esp_err_t result;
size_t actual_bytes;
uint8_t* buffer;
size_t buffer_size;
};
// USB Host event handling
static void usb_host_lib_task(void *arg);
static void usb_client_task(void *arg);
static void usb_client_event_callback(const usb_host_client_event_msg_t *event_msg, void *arg);
static void usb_transfer_callback(usb_transfer_t *transfer);
// Asynchronous USB operations
esp_err_t hid_get_report_async(uint8_t report_type, uint8_t report_id);
void process_cached_data();
#endif
private:
// Internal helper methods
void cleanup();
};
// Base class for UPS protocols
@@ -383,7 +185,7 @@ namespace esphome
virtual bool detect() = 0;
virtual bool initialize() = 0;
virtual bool read_data(UpsData &data) = 0;
virtual UpsProtocol get_protocol_type() const = 0;
virtual DeviceInfo::DetectedProtocol get_protocol_type() const = 0;
virtual std::string get_protocol_name() const = 0;
// Beeper control methods
@@ -407,47 +209,5 @@ namespace esphome
};
// Generic HID Protocol implementation
class GenericHidProtocol : public UpsProtocolBase
{
public:
explicit GenericHidProtocol(UpsHidComponent *parent) : UpsProtocolBase(parent) {}
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
UpsProtocol get_protocol_type() const override { return PROTOCOL_GENERIC_HID; }
std::string get_protocol_name() const override { return "Generic HID"; }
// Test method overrides
bool start_battery_test_quick() override;
bool start_battery_test_deep() override;
bool stop_battery_test() override;
bool start_ups_test() override;
bool stop_ups_test() override;
private:
// Report discovery and caching
std::set<uint8_t> available_input_reports_;
std::set<uint8_t> available_feature_reports_;
std::map<uint8_t, size_t> report_sizes_;
// Core methods
void enumerate_reports();
bool read_report(uint8_t report_id, uint8_t* buffer, size_t& buffer_len);
// Standard report parsers (based on NUT analysis)
void parse_power_summary(uint8_t* data, size_t len, UpsData& ups_data);
void parse_battery_status(uint8_t* data, size_t len, UpsData& ups_data);
void parse_present_status(uint8_t* data, size_t len, UpsData& ups_data);
void parse_general_status(uint8_t* data, size_t len, UpsData& ups_data);
void parse_voltage(uint8_t* data, size_t len, UpsData& ups_data, bool is_input);
void parse_load(uint8_t* data, size_t len, UpsData& ups_data);
void parse_input_sensitivity(uint8_t* data, size_t len, UpsData& ups_data, const char* style);
// Heuristic parsing for unknown reports
bool parse_unknown_report(uint8_t* data, size_t len, UpsData& ups_data);
};
} // namespace ups_hid
} // namespace esphome
@@ -0,0 +1,27 @@
#include "usb_transport_factory.h"
#include "usb_transport_interface.h"
#include "simulated_transport.h"
#ifdef USE_ESP32
#include "esp32_usb_transport.h"
#endif
namespace esphome {
namespace ups_hid {
std::unique_ptr<IUsbTransport> UsbTransportFactory::create(TransportType type, bool simulation_mode) {
if (simulation_mode || type == SIMULATION) {
return std::make_unique<SimulatedTransport>();
}
#ifdef USE_ESP32
if (type == ESP32_HARDWARE) {
return std::make_unique<Esp32UsbTransport>();
}
#endif
// Default fallback to simulation if ESP32 not available
return std::make_unique<SimulatedTransport>();
}
} // namespace ups_hid
} // namespace esphome
@@ -0,0 +1,23 @@
#pragma once
#include "usb_transport_interface.h"
namespace esphome {
namespace ups_hid {
/**
* Factory for creating USB transport instances
*/
class UsbTransportFactory {
public:
enum TransportType {
ESP32_HARDWARE,
SIMULATION
};
static std::unique_ptr<IUsbTransport> create(TransportType type,
bool simulation_mode = false);
};
} // namespace ups_hid
} // namespace esphome
@@ -0,0 +1,53 @@
#pragma once
#include "esp_err.h"
#include <vector>
#include <cstdint>
#include <memory>
namespace esphome {
namespace ups_hid {
/**
* Abstract USB Transport Interface
*
* Provides a clean abstraction over USB communication, allowing for
* different implementations (ESP32 hardware, simulation, etc.)
*
* Design Pattern: Strategy Pattern for transport selection
*/
class IUsbTransport {
public:
virtual ~IUsbTransport() = default;
// Transport lifecycle
virtual esp_err_t initialize() = 0;
virtual esp_err_t deinitialize() = 0;
// Device management
virtual bool is_connected() const = 0;
virtual uint16_t get_vendor_id() const = 0;
virtual uint16_t get_product_id() const = 0;
// HID communication
virtual esp_err_t hid_get_report(uint8_t report_type, uint8_t report_id,
uint8_t* data, size_t* data_len,
uint32_t timeout_ms = 1000) = 0;
virtual esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id,
const uint8_t* data, size_t data_len,
uint32_t timeout_ms = 1000) = 0;
// String descriptors
virtual esp_err_t get_string_descriptor(uint8_t string_index,
std::string& result) = 0;
// Error information
virtual std::string get_last_error() const = 0;
};
// Forward declaration - implementation in usb_transport_factory.h
class UsbTransportFactory;
} // namespace ups_hid
} // namespace esphome