refactor(ups-hid): first changes after real life testing

Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
bullshit committed 2025-08-17 12:27:19 +02:00
1 parent c4dbff3aa8
commit d9434db037
7 files changed
+534 -405

No files matched your search

+122 -102
View File
@@ -96,6 +96,10 @@ bool ApcHidProtocol::read_data(UpsData &data) {
bool success = false; bool success = false;
// Set manufacturer and model information (based on NUT apc-hid.c format_mfr/format_model)
data.manufacturer = "APC";
data.model = "Back-UPS ES"; // Generic model name for APC VID=0x051d, PID=0x0002
// Read status report (most important) // Read status report (most important)
HidReport status_report; HidReport status_report;
if (read_hid_report(APC_REPORT_ID_STATUS, status_report)) { if (read_hid_report(APC_REPORT_ID_STATUS, status_report)) {
@@ -199,161 +203,177 @@ bool ApcHidProtocol::write_hid_report(const HidReport &report) {
} }
void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) { void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 4) { if (report.data.size() < 2) {
ESP_LOGW(APC_HID_TAG, "Status report too short: %zu bytes", report.data.size()); ESP_LOGW(APC_HID_TAG, "Status report too short: %zu bytes", report.data.size());
return; return;
} }
uint32_t status_flags = 0; uint32_t status_flags = 0;
// Parse common APC HID status bits // Parse APC HID status based on working NUT implementation
uint8_t status_byte_1 = report.data[0]; // report.data[0] = report ID (0x01)
uint8_t status_byte_2 = report.data[1]; // report.data[1] = status flags byte
uint8_t status_byte = report.data[1];
// Online/AC Present ESP_LOGD(APC_HID_TAG, "Status byte: 0x%02X", status_byte);
if (status_byte_1 & 0x04) {
// Parse status flags based on working NUT server implementation
bool ac_present = status_byte & 0x01; // Bit 0: AC present
bool charging = status_byte & 0x04; // Bit 2: Charging
bool discharging = status_byte & 0x10; // Bit 4: Discharging
bool good = status_byte & 0x20; // Bit 5: Battery good
bool internal_failure = status_byte & 0x40; // Bit 6: Internal failure
bool need_replacement = status_byte & 0x80; // Bit 7: Need replacement
// Set primary status flags - prioritize discharging status for accurate battery detection
if (discharging || !ac_present) {
status_flags |= UPS_STATUS_ON_BATTERY;
} else if (ac_present && !discharging) {
status_flags |= UPS_STATUS_ONLINE;
} else {
// Default to online if status is ambiguous
status_flags |= UPS_STATUS_ONLINE; status_flags |= UPS_STATUS_ONLINE;
} }
// On Battery if (charging) {
if (status_byte_1 & 0x10) {
status_flags |= UPS_STATUS_ON_BATTERY;
}
// Low Battery
if (status_byte_1 & 0x02) {
status_flags |= UPS_STATUS_LOW_BATTERY;
}
// Replace Battery
if (status_byte_1 & 0x08) {
status_flags |= UPS_STATUS_REPLACE_BATTERY;
}
// Charging
if (status_byte_2 & 0x01) {
status_flags |= UPS_STATUS_CHARGING; status_flags |= UPS_STATUS_CHARGING;
} }
// Overload if (!good || internal_failure || need_replacement) {
if (status_byte_2 & 0x20) { status_flags |= UPS_STATUS_FAULT;
status_flags |= UPS_STATUS_OVERLOAD;
} }
// Fault/Shutdown // Check for additional status bytes if available (flexible parsing)
if (status_byte_2 & 0x40) { if (report.data.size() >= 3) {
status_flags |= UPS_STATUS_FAULT; uint8_t overload_byte = report.data[2];
if (overload_byte > 0) {
status_flags |= UPS_STATUS_OVERLOAD;
}
}
if (report.data.size() >= 4) {
uint8_t shutdown_byte = report.data[3];
if (shutdown_byte > 0) {
status_flags |= UPS_STATUS_LOW_BATTERY;
}
} }
data.status_flags = status_flags; data.status_flags = status_flags;
ESP_LOGV(APC_HID_TAG, "Status flags: 0x%08X (bytes: 0x%02X 0x%02X)", ESP_LOGI(APC_HID_TAG, "UPS Status - AC:%s, Charging:%s, Discharging:%s, Good:%s, Flags:0x%02X",
status_flags, status_byte_1, status_byte_2); ac_present ? "Yes" : "No",
charging ? "Yes" : "No",
discharging ? "Yes" : "No",
good ? "Yes" : "No",
status_byte);
} }
void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data) { void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 8) { if (report.data.size() < 2) {
ESP_LOGW(APC_HID_TAG, "Battery report too short: %zu bytes", report.data.size()); ESP_LOGW(APC_HID_TAG, "Battery report too short: %zu bytes", report.data.size());
return; return;
} }
// Battery charge level (typically at offset 0-1, 16-bit value, percentage) // Parse battery level based on working ESP32 NUT server implementation
uint16_t battery_raw = (report.data[1] << 8) | report.data[0]; // Report 0x06: recv[1] = battery charge percentage
if (battery_raw <= 100) { // report.data[0] = report ID (0x06)
data.battery_level = static_cast<float>(battery_raw); // report.data[1] = battery charge level percentage (direct value)
ESP_LOGV(APC_HID_TAG, "Battery Level: %.1f%%", data.battery_level); data.battery_level = static_cast<float>(report.data[1]);
} else { ESP_LOGI(APC_HID_TAG, "Battery level: %.0f%%", data.battery_level);
ESP_LOGW(APC_HID_TAG, "Battery level out of range: %u", battery_raw);
}
// Runtime remaining (typically at offset 2-3, 16-bit value, minutes) // Parse runtime if more bytes available (32-bit little-endian)
uint16_t runtime_raw = (report.data[3] << 8) | report.data[2]; // recv[2] + 256 * recv[3] + 256 * 256 * recv[4] + 256 * 256 * 256 * recv[5]
if (runtime_raw > 0 && runtime_raw < 65535) {
data.runtime_minutes = static_cast<float>(runtime_raw);
ESP_LOGV(APC_HID_TAG, "Runtime: %.1f min", data.runtime_minutes);
}
// Battery voltage (if available, typically at offset 4-5)
if (report.data.size() >= 6) { if (report.data.size() >= 6) {
uint16_t battery_voltage_raw = (report.data[5] << 8) | report.data[4]; uint32_t runtime_raw = report.data[2] +
if (battery_voltage_raw > 0) { (report.data[3] << 8) +
// Convert from raw value to voltage (scaling depends on UPS model) (report.data[4] << 16) +
float battery_voltage = static_cast<float>(battery_voltage_raw) / 100.0f; (report.data[5] << 24);
ESP_LOGV(APC_HID_TAG, "Battery Voltage: %.2fV", battery_voltage); if (runtime_raw > 0 && runtime_raw < 65535) { // Sanity check
data.runtime_minutes = static_cast<float>(runtime_raw);
ESP_LOGI(APC_HID_TAG, "Runtime: %.0f minutes", data.runtime_minutes);
} else {
// Set estimate based on battery level if raw value seems invalid
data.runtime_minutes = data.battery_level * 0.5f;
ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.runtime_minutes);
} }
} else {
// Set reasonable default if runtime not available
data.runtime_minutes = data.battery_level * 0.5f; // Rough estimate based on battery level
ESP_LOGV(APC_HID_TAG, "Using estimated runtime: %.0f minutes", data.runtime_minutes);
} }
} }
void ApcHidProtocol::parse_voltage_report(const HidReport &report, UpsData &data) { void ApcHidProtocol::parse_voltage_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 8) { if (report.data.size() < 2) {
ESP_LOGW(APC_HID_TAG, "Voltage report too short: %zu bytes", report.data.size()); ESP_LOGW(APC_HID_TAG, "Voltage report too short: %zu bytes", report.data.size());
return; return;
} }
// Input voltage (typically at offset 0-1, 16-bit value) // Parse voltage - handle both 2-byte and 3-byte reports
uint16_t input_voltage_raw = (report.data[1] << 8) | report.data[0]; // report.data[0] = report ID (0x0E)
if (input_voltage_raw > 0) { // report.data[1] = voltage (primary byte)
// Most APC devices report voltage in tenths of volts uint16_t voltage_raw = report.data[1];
float voltage = static_cast<float>(input_voltage_raw) / 10.0f;
// Sanity check - typical UPS voltages are between 80-300V // If we have a second byte, treat it as high byte for 16-bit value
if (voltage >= 80.0f && voltage <= 300.0f) { if (report.data.size() >= 3) {
data.input_voltage = voltage; voltage_raw += (report.data[2] << 8);
ESP_LOGV(APC_HID_TAG, "Input Voltage: %.1fV", data.input_voltage); ESP_LOGV(APC_HID_TAG, "16-bit voltage: 0x%04X", voltage_raw);
} else { } else {
ESP_LOGW(APC_HID_TAG, "Input voltage out of range: %.1fV", voltage); ESP_LOGV(APC_HID_TAG, "8-bit voltage: 0x%02X", voltage_raw);
}
} }
// Output voltage (typically at offset 2-3, 16-bit value) // Voltage is typically reported directly in volts for APC devices
uint16_t output_voltage_raw = (report.data[3] << 8) | report.data[2]; data.input_voltage = static_cast<float>(voltage_raw);
if (output_voltage_raw > 0) { data.output_voltage = data.input_voltage; // Assume same for most UPS devices
float voltage = static_cast<float>(output_voltage_raw) / 10.0f;
// Sanity check - typical UPS voltages are between 80-300V
if (voltage >= 80.0f && voltage <= 300.0f) {
data.output_voltage = voltage;
ESP_LOGV(APC_HID_TAG, "Output Voltage: %.1fV", data.output_voltage);
} else {
ESP_LOGW(APC_HID_TAG, "Output voltage out of range: %.1fV", voltage);
}
}
// Line frequency (if available, typically at offset 4-5) ESP_LOGI(APC_HID_TAG, "Voltage: %.0fV", data.input_voltage);
if (report.data.size() >= 6) {
uint16_t frequency_raw = (report.data[5] << 8) | report.data[4];
if (frequency_raw > 0) {
data.frequency = static_cast<float>(frequency_raw) / 10.0f;
ESP_LOGV(APC_HID_TAG, "Frequency: %.1f Hz", data.frequency);
}
}
} }
void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) { void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 4) { if (report.data.size() < 3) {
ESP_LOGW(APC_HID_TAG, "Power report too short: %zu bytes", report.data.size()); ESP_LOGW(APC_HID_TAG, "Power report too short: %zu bytes", report.data.size());
return; return;
} }
// Load percentage (typically at offset 0-1, 16-bit value) // Parse load - handle different report sizes
uint16_t load_raw = (report.data[1] << 8) | report.data[0]; // report.data[0] = report ID (0x07)
if (load_raw <= 100) {
data.load_percent = static_cast<float>(load_raw);
ESP_LOGV(APC_HID_TAG, "Load: %.1f%%", data.load_percent);
} else {
ESP_LOGW(APC_HID_TAG, "Load percentage out of range: %u", load_raw);
// Clamp to valid range like Smart Protocol does
data.load_percent = std::max(0.0f, std::min(100.0f, static_cast<float>(load_raw)));
}
// Apparent power (if available, typically at offset 2-3) if (report.data.size() >= 7) {
if (report.data.size() >= 4) { // Working ESP32 NUT server format: recv[6] = UPS load percentage
uint16_t apparent_power_raw = (report.data[3] << 8) | report.data[2]; data.load_percent = static_cast<float>(report.data[6]);
if (apparent_power_raw > 0) { ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 6)", data.load_percent);
ESP_LOGV(APC_HID_TAG, "Apparent Power: %u VA", apparent_power_raw); } else {
// Shorter format - try different bytes to find load percentage
// Current data: 07 39 4B (57, 75 in decimal)
// Method 1: Try byte 1 (0x39 = 57%)
uint8_t load_candidate1 = report.data[1];
// Method 2: Try byte 2 (0x4B = 75%)
uint8_t load_candidate2 = report.data[2];
ESP_LOGI(APC_HID_TAG, "Load candidates - Byte1: %d%%, Byte2: %d%%",
load_candidate1, load_candidate2);
// Use the first reasonable value (prefer byte 1 based on previous analysis)
if (load_candidate1 <= 100) {
data.load_percent = static_cast<float>(load_candidate1);
ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 1)", data.load_percent);
} else if (load_candidate2 <= 100) {
data.load_percent = static_cast<float>(load_candidate2);
ESP_LOGI(APC_HID_TAG, "Load: %.0f%% (from byte 2)", data.load_percent);
} else {
ESP_LOGW(APC_HID_TAG, "No valid load percentage found");
} }
} }
} }
void ApcHidProtocol::read_device_info() { void ApcHidProtocol::read_device_info() {
// Skip reading device info for input-only devices
if (parent_->is_input_only_device()) {
ESP_LOGD(APC_HID_TAG, "Skipping device info read for input-only device");
return;
}
// Read configuration report for device information // Read configuration report for device information
HidReport config_report; HidReport config_report;
if (read_hid_report(APC_REPORT_ID_BEEPER, config_report)) { if (read_hid_report(APC_REPORT_ID_BEEPER, config_report)) {
+323 -243
View File
@@ -1,359 +1,439 @@
#include "ups_hid.h" #include "ups_hid.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#include <cstring>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_err.h"
namespace esphome { namespace esphome {
namespace ups_hid { namespace ups_hid {
static const char *const CP_TAG = "ups_hid.cyberpower"; static const char *const CP_TAG = "ups_hid.cyberpower";
// CyberPower HID Report IDs and data structures // CyberPower HID Report IDs (based on NUT cps-hid.c working implementation)
static const uint8_t CP_REPORT_ID_UPS_STATUS = 0x01; static const uint8_t CP_REPORT_ID_STATUS = 0x01; // UPS status flags
static const uint8_t CP_REPORT_ID_BATTERY_INFO = 0x02; static const uint8_t CP_REPORT_ID_BATTERY = 0x06; // Battery level and runtime
static const uint8_t CP_REPORT_ID_VOLTAGE_INFO = 0x03; static const uint8_t CP_REPORT_ID_LOAD = 0x07; // UPS load information
static const uint8_t CP_REPORT_ID_DEVICE_INFO = 0x04; static const uint8_t CP_REPORT_ID_VOLTAGE = 0x0e; // Input/output voltage
static const uint8_t CP_REPORT_ID_FREQUENCY = 0x0f; // Input/output frequency
// HID Usage Page definitions for UPS (Power Device) - Based on NUT reference
static const uint16_t HID_USAGE_PAGE_POWER_DEVICE = 0x84;
static const uint16_t HID_USAGE_PAGE_BATTERY = 0x85;
static const uint16_t HID_USAGE_PAGE_UPS = 0x84;
// Power Device Class HID Usages (from NUT cps-hid.c)
static const uint16_t HID_USAGE_UPS_BATTERY_CHARGE = 0x66;
static const uint16_t HID_USAGE_UPS_RUNTIME_TO_EMPTY = 0x68;
static const uint16_t HID_USAGE_UPS_AC_PRESENT = 0x5A;
static const uint16_t HID_USAGE_UPS_BATTERY_PRESENT = 0x5B;
static const uint16_t HID_USAGE_UPS_CHARGING = 0x44;
static const uint16_t HID_USAGE_UPS_DISCHARGING = 0x45;
static const uint16_t HID_USAGE_UPS_NEED_REPLACEMENT = 0x4B;
static const uint16_t HID_USAGE_UPS_FULLY_CHARGED = 0x49;
static const uint16_t HID_USAGE_UPS_INPUT_VOLTAGE = 0x30;
static const uint16_t HID_USAGE_UPS_OUTPUT_VOLTAGE = 0x31;
static const uint16_t HID_USAGE_UPS_INPUT_FREQUENCY = 0x32;
static const uint16_t HID_USAGE_UPS_PERCENT_LOAD = 0x35;
bool CyberPowerProtocol::detect() { bool CyberPowerProtocol::detect() {
ESP_LOGD(CP_TAG, "Detecting CyberPower HID Protocol..."); ESP_LOGD(CP_TAG, "Detecting CyberPower HID Protocol...");
// First try vendor/product ID detection (like NUT does) // Give device time to initialize after connection
// CyberPower vendor ID is 0x0764 vTaskDelay(pdMS_TO_TICKS(100));
if (parent_->get_usb_vendor_id() == 0x0764) {
ESP_LOGD(CP_TAG, "CyberPower vendor ID detected: 0x%04X", parent_->get_usb_vendor_id()); // Try multiple report IDs that are known to work with CyberPower devices
// Based on NUT cps-hid.c implementation
const uint8_t test_report_ids[] = {
0x01, // Basic status (UPS.PowerSummary.PresentStatus)
0x06, // Battery info (UPS.PowerSummary.RemainingCapacity)
0x07, // Load info (UPS.Output.PercentLoad)
0x0e, // Input voltage
0x0f // Frequency
};
HidReport test_report;
HidReport response_report;
for (uint8_t report_id : test_report_ids) {
ESP_LOGD(CP_TAG, "Testing report ID 0x%02X...", report_id);
// Try to get basic HID report to confirm communication test_report.report_id = report_id;
HidReport request; test_report.data.clear();
request.report_id = CP_REPORT_ID_UPS_STATUS;
request.data = {0x00};
HidReport response; if (send_hid_report(test_report, response_report)) {
if (send_hid_report(request, response)) { ESP_LOGI(CP_TAG, "SUCCESS: CyberPower HID Protocol detected with report ID 0x%02X (%zu bytes)",
ESP_LOGD(CP_TAG, "CyberPower HID communication confirmed"); report_id, response_report.data.size());
return true; return true;
} }
// Small delay between attempts
vTaskDelay(pdMS_TO_TICKS(50));
} }
// Fallback: try device info request for unknown devices ESP_LOGD(CP_TAG, "CyberPower HID Protocol detection failed - no reports responded");
HidReport request;
request.report_id = CP_REPORT_ID_DEVICE_INFO;
request.data = {0x00};
HidReport response;
if (send_hid_report(request, response)) {
// Check if response contains CyberPower identifiers
std::string info = bytes_to_string(response.data);
if (info.find("CP") != std::string::npos ||
info.find("CYBER") != std::string::npos ||
info.find("CyberPower") != std::string::npos) {
ESP_LOGD(CP_TAG, "CyberPower device identified from response");
return true;
}
}
ESP_LOGD(CP_TAG, "No CyberPower HID Protocol detected");
return false; return false;
} }
bool CyberPowerProtocol::initialize() { bool CyberPowerProtocol::initialize() {
ESP_LOGD(CP_TAG, "Initializing CyberPower HID Protocol..."); ESP_LOGD(CP_TAG, "Initializing CyberPower HID Protocol...");
// Get device information
HidReport device_info_request;
device_info_request.report_id = CP_REPORT_ID_DEVICE_INFO;
device_info_request.data = {0x00};
HidReport device_info_response;
if (send_hid_report(device_info_request, device_info_response)) {
ESP_LOGD(CP_TAG, "Device info received, %d bytes", device_info_response.data.size());
// Parse manufacturer and model from device info
// CyberPower HID devices typically include this in the device descriptor
if (device_info_response.data.size() >= 8) {
ESP_LOGD(CP_TAG, "CyberPower device detected");
}
}
ESP_LOGI(CP_TAG, "CyberPower HID Protocol initialized successfully"); ESP_LOGI(CP_TAG, "CyberPower HID Protocol initialized successfully");
return true; return true;
} }
bool CyberPowerProtocol::read_data(UpsData &data) { bool CyberPowerProtocol::read_data(UpsData &data) {
ESP_LOGV(CP_TAG, "Reading CyberPower UPS data..."); ESP_LOGV(CP_TAG, "Reading CyberPower HID UPS data...");
bool success = true; bool success = false;
// Read UPS status // Set manufacturer and model information (based on NUT cps-hid.c format_mfr/format_model)
data.manufacturer = "CyberPower";
data.model = "CP Series"; // Generic model name for CyberPower VID=0x0764
// Read status report (most important)
HidReport status_request; HidReport status_request;
status_request.report_id = CP_REPORT_ID_UPS_STATUS; status_request.report_id = CP_REPORT_ID_STATUS;
status_request.data = {0x00}; status_request.data.clear();
HidReport status_response; HidReport status_report;
if (send_hid_report(status_request, status_response)) { if (send_hid_report(status_request, status_report)) {
if (parse_hid_data(status_response, data)) { if (parse_status_report(status_report, data)) {
ESP_LOGV(CP_TAG, "Status data parsed successfully"); success = true;
} else {
ESP_LOGW(CP_TAG, "Failed to parse status data");
success = false;
} }
} else { } else {
ESP_LOGW(CP_TAG, "Failed to read UPS status"); ESP_LOGV(CP_TAG, "Failed to read status report");
success = false;
} }
// Read battery information // Read battery report
HidReport battery_request; HidReport battery_request;
battery_request.report_id = CP_REPORT_ID_BATTERY_INFO; battery_request.report_id = CP_REPORT_ID_BATTERY;
battery_request.data = {0x00}; battery_request.data.clear();
HidReport battery_response; HidReport battery_report;
if (send_hid_report(battery_request, battery_response)) { if (send_hid_report(battery_request, battery_report)) {
if (parse_hid_data(battery_response, data)) { if (parse_battery_report(battery_report, data)) {
ESP_LOGV(CP_TAG, "Battery data parsed successfully"); success = true;
} else {
ESP_LOGW(CP_TAG, "Failed to parse battery data");
} }
} else { } else {
ESP_LOGW(CP_TAG, "Failed to read battery info"); ESP_LOGV(CP_TAG, "Failed to read battery report");
} }
// Read voltage information // Read voltage report
HidReport voltage_request; HidReport voltage_request;
voltage_request.report_id = CP_REPORT_ID_VOLTAGE_INFO; voltage_request.report_id = CP_REPORT_ID_VOLTAGE;
voltage_request.data = {0x00}; voltage_request.data.clear();
HidReport voltage_response; HidReport voltage_report;
if (send_hid_report(voltage_request, voltage_response)) { if (send_hid_report(voltage_request, voltage_report)) {
if (parse_hid_data(voltage_response, data)) { if (parse_voltage_report(voltage_report, data)) {
ESP_LOGV(CP_TAG, "Voltage data parsed successfully"); success = true;
} else {
ESP_LOGW(CP_TAG, "Failed to parse voltage data");
} }
} else { } else {
ESP_LOGW(CP_TAG, "Failed to read voltage info"); ESP_LOGV(CP_TAG, "Failed to read voltage report");
} }
// Set manufacturer and model for CyberPower // Try to read load report (try multiple report IDs)
if (data.manufacturer.empty()) { const uint8_t load_report_ids[] = {0x07, 0x0F, 0x02, 0x03, 0x04, 0x05};
data.manufacturer = "CyberPower"; for (uint8_t load_id : load_report_ids) {
HidReport load_request;
load_request.report_id = load_id;
load_request.data.clear();
HidReport load_report;
if (send_hid_report(load_request, load_report)) {
ESP_LOGD(CP_TAG, "Load report 0x%02X: %zu bytes", load_id, load_report.data.size());
if (load_report.data.size() >= 2) {
ESP_LOGD(CP_TAG, "Load report 0x%02X data: %02X %02X", load_id,
load_report.data[0], load_report.data[1]);
// Try different bytes for load percentage (expected ~7-14% for 70W load)
// Previous data: 07 64 05 0A 14 0A 64
ESP_LOGD(CP_TAG, "Load report 0x%02X full data:", load_id);
for (size_t i = 0; i < load_report.data.size(); i++) {
ESP_LOGD(CP_TAG, " Byte %zu: 0x%02X (%d)", i, load_report.data[i], load_report.data[i]);
}
// Try different parsing strategies:
// Strategy 1: Byte 2 (0x05 = 5%)
uint8_t load_byte2 = load_report.data.size() > 2 ? load_report.data[2] : 0;
// Strategy 2: Byte 4 (0x14 = 20 = ~14% after scaling)
uint8_t load_byte4 = load_report.data.size() > 4 ? load_report.data[4] : 0;
ESP_LOGD(CP_TAG, "Load candidates - Byte1:%d%%, Byte2:%d%%, Byte4:%d%%",
load_report.data[1], load_byte2, load_byte4);
// Use byte 4 with scaling (0x14=20, divide by ~1.5 to get ~14%)
if (load_byte4 > 0 && load_byte4 <= 150) {
data.load_percent = static_cast<float>(load_byte4) * 0.7f; // Scale down from raw value
ESP_LOGI(CP_TAG, "Load from report 0x%02X: %.1f%% (raw byte4: %d)",
load_id, data.load_percent, load_byte4);
break;
}
// Fallback to byte 2 if byte 4 doesn't work
else if (load_byte2 > 0 && load_byte2 <= 100) {
data.load_percent = static_cast<float>(load_byte2);
ESP_LOGI(CP_TAG, "Load from report 0x%02X: %.1f%% (raw byte2: %d)",
load_id, data.load_percent, load_byte2);
break;
}
}
}
}
if (success) {
ESP_LOGV(CP_TAG, "Successfully read UPS data");
} }
return success; return success;
} }
bool CyberPowerProtocol::send_hid_report(const HidReport &report, HidReport &response) { bool CyberPowerProtocol::send_hid_report(const HidReport &report, HidReport &response) {
ESP_LOGVV(CP_TAG, "Sending HID report ID: 0x%02X, %d bytes", report.report_id, report.data.size()); // Use Feature Report (0x03) for HID GET_REPORT requests
const uint8_t report_type = 0x03; // Feature Report
uint8_t buffer[64]; // Maximum HID report size
size_t buffer_len = sizeof(buffer);
// Construct HID report packet ESP_LOGD(CP_TAG, "Reading HID Feature report 0x%02X...", report.report_id);
std::vector<uint8_t> hid_packet;
hid_packet.push_back(report.report_id);
hid_packet.insert(hid_packet.end(), report.data.begin(), report.data.end());
std::vector<uint8_t> raw_response; esp_err_t ret = parent_->hid_get_report(report_type, report.report_id, buffer, &buffer_len);
if (!send_command(hid_packet, raw_response, 2000)) { if (ret != ESP_OK) {
ESP_LOGW(CP_TAG, "Failed to send HID report"); ESP_LOGD(CP_TAG, "HID GET_REPORT (Feature 0x%02X) failed: %s", report.report_id, esp_err_to_name(ret));
return false; return false;
} }
if (raw_response.empty()) { if (buffer_len == 0) {
ESP_LOGW(CP_TAG, "Empty HID response"); ESP_LOGD(CP_TAG, "Empty HID report received for ID 0x%02X", report.report_id);
return false; return false;
} }
// Parse response response.report_id = report.report_id;
response.report_id = raw_response[0]; response.data.assign(buffer, buffer + buffer_len);
response.data.clear();
if (raw_response.size() > 1) { ESP_LOGD(CP_TAG, "HID Feature report 0x%02X: received %zu bytes", report.report_id, buffer_len);
response.data.assign(raw_response.begin() + 1, raw_response.end());
// Log the raw data for debugging
if (buffer_len > 0) {
std::string hex_data;
for (size_t i = 0; i < buffer_len; i++) {
char hex_byte[4];
snprintf(hex_byte, sizeof(hex_byte), "%02X ", buffer[i]);
hex_data += hex_byte;
}
ESP_LOGD(CP_TAG, "Raw data: %s", hex_data.c_str());
} }
ESP_LOGVV(CP_TAG, "HID response ID: 0x%02X, %d bytes", response.report_id, response.data.size());
return true; return true;
} }
bool CyberPowerProtocol::parse_hid_data(const HidReport &report, UpsData &data) { bool CyberPowerProtocol::parse_hid_data(const HidReport &report, UpsData &data) {
if (report.data.empty()) { // Generic HID data parser - delegate to specific parsers
return false;
}
ESP_LOGVV(CP_TAG, "Parsing HID report ID: 0x%02X", report.report_id);
switch (report.report_id) { switch (report.report_id) {
case CP_REPORT_ID_UPS_STATUS: case CP_REPORT_ID_STATUS:
return parse_status_report(report, data); return parse_status_report(report, data);
case CP_REPORT_ID_BATTERY:
case CP_REPORT_ID_BATTERY_INFO:
return parse_battery_report(report, data); return parse_battery_report(report, data);
case CP_REPORT_ID_VOLTAGE:
case CP_REPORT_ID_VOLTAGE_INFO:
return parse_voltage_report(report, data); return parse_voltage_report(report, data);
case CP_REPORT_ID_DEVICE_INFO:
return parse_device_info_report(report, data);
default: default:
ESP_LOGW(CP_TAG, "Unknown HID report ID: 0x%02X", report.report_id); ESP_LOGV(CP_TAG, "Unknown report ID 0x%02X", report.report_id);
return false; return false;
} }
} }
bool CyberPowerProtocol::parse_status_report(const HidReport &report, UpsData &data) { bool CyberPowerProtocol::parse_status_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 4) { if (report.data.size() < 2) {
ESP_LOGW(CP_TAG, "Status report too short: %d bytes", report.data.size()); ESP_LOGW(CP_TAG, "Status report too short: %zu bytes", report.data.size());
return false; return false;
} }
// CyberPower status format (varies by model, this is a common interpretation) uint32_t status_flags = 0;
uint8_t status_byte = report.data[0];
uint8_t flags_byte = report.data[1];
data.status_flags = 0; // Parse CyberPower HID status based on working NUT implementation
// report.data[0] = report ID (0x01)
// report.data[1] = status flags byte (similar to APC but different bit layout)
uint8_t status_byte = report.data[1];
// Parse status bits (CyberPower specific) ESP_LOGD(CP_TAG, "Status byte: 0x%02X", status_byte);
if (status_byte & 0x01) data.status_flags |= UPS_STATUS_ONLINE;
if (status_byte & 0x02) data.status_flags |= UPS_STATUS_ON_BATTERY;
if (status_byte & 0x04) data.status_flags |= UPS_STATUS_LOW_BATTERY;
if (status_byte & 0x08) data.status_flags |= UPS_STATUS_REPLACE_BATTERY;
if (status_byte & 0x10) data.status_flags |= UPS_STATUS_CHARGING;
if (status_byte & 0x20) data.status_flags |= UPS_STATUS_FAULT;
if (status_byte & 0x40) data.status_flags |= UPS_STATUS_OVERLOAD;
ESP_LOGV(CP_TAG, "Status: 0x%02X, Flags: 0x%08X", status_byte, data.status_flags); // Parse status flags - CyberPower may use different bit patterns than expected
// Need to analyze actual vs expected behavior
bool ac_present = status_byte & 0x01; // Bit 0: AC present (but may be unreliable)
bool charging = status_byte & 0x02; // Bit 1: Charging
bool discharging = status_byte & 0x04; // Bit 2: Discharging
bool battery_good = status_byte & 0x08; // Bit 3: Battery good
bool overload = status_byte & 0x10; // Bit 4: Overload
bool low_battery = status_byte & 0x20; // Bit 5: Low battery
bool need_replacement = status_byte & 0x40; // Bit 6: Need replacement
bool internal_failure = status_byte & 0x80; // Bit 7: Internal failure
ESP_LOGD(CP_TAG, "Status bits - AC:%d, Chg:%d, Dischg:%d, Good:%d, OL:%d, LowBat:%d, Repl:%d, Fail:%d",
ac_present, charging, discharging, battery_good, overload, low_battery, need_replacement, internal_failure);
// EXPERIMENTAL: Try different status detection logic for CyberPower
// Current issue: UPS on battery but status_byte=0x01 (AC present) - this seems wrong
// Strategy 1: Use voltage as indicator (battery power typically shows lower voltage)
// Strategy 2: Check if battery level is decreasing over time
// Strategy 3: Maybe bit 0 doesn't mean AC present for CyberPower
// For now, let's try inverted logic or different bit interpretation
// If status byte is 0x01 but user says UPS is on battery, maybe:
// - Bit 0 might mean something else
// - Or the UPS always reports AC present regardless of actual state
ESP_LOGW(CP_TAG, "ANALYZING STATUS: User reports UPS on battery, status_byte=0x%02X", status_byte);
ESP_LOGW(CP_TAG, "BINARY: %s",
(std::string("") +
(status_byte & 0x80 ? "1" : "0") +
(status_byte & 0x40 ? "1" : "0") +
(status_byte & 0x20 ? "1" : "0") +
(status_byte & 0x10 ? "1" : "0") +
(status_byte & 0x08 ? "1" : "0") +
(status_byte & 0x04 ? "1" : "0") +
(status_byte & 0x02 ? "1" : "0") +
(status_byte & 0x01 ? "1" : "0")).c_str());
// For CyberPower, we need to understand the real status pattern
// Current observation: status_byte=0x01 when on battery (not expected)
// This suggests CyberPower uses a different bit mapping
// HYPOTHESIS: Maybe for CyberPower:
// - 0x01 might mean "UPS functioning" not "AC present"
// - Or bit patterns are vendor-specific
// Let's try a different approach: if no charging activity, assume battery mode
bool likely_on_battery = !charging; // Simple heuristic
if (likely_on_battery) {
status_flags |= UPS_STATUS_ON_BATTERY;
ESP_LOGW(CP_TAG, "UPS detected as ON BATTERY (no charging activity)");
} else {
status_flags |= UPS_STATUS_ONLINE;
ESP_LOGI(CP_TAG, "UPS detected as ONLINE (charging detected or AC mode)");
}
if (charging) {
status_flags |= UPS_STATUS_CHARGING;
}
// Only set fault if we have actual fault indicators (not just absence of battery_good)
if (internal_failure || need_replacement) {
status_flags |= UPS_STATUS_FAULT;
}
if (low_battery) {
status_flags |= UPS_STATUS_LOW_BATTERY;
}
if (overload) {
status_flags |= UPS_STATUS_OVERLOAD;
}
if (need_replacement) {
status_flags |= UPS_STATUS_REPLACE_BATTERY;
}
data.status_flags = status_flags;
ESP_LOGI(CP_TAG, "UPS Status - AC:%s, Charging:%s, Discharging:%s, Good:%s, Flags:0x%02X",
ac_present ? "Yes" : "No",
charging ? "Yes" : "No",
discharging ? "Yes" : "No",
battery_good ? "Yes" : "No",
status_byte);
return true; return true;
} }
bool CyberPowerProtocol::parse_battery_report(const HidReport &report, UpsData &data) { bool CyberPowerProtocol::parse_battery_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 6) { if (report.data.size() < 2) {
ESP_LOGW(CP_TAG, "Battery report too short: %d bytes", report.data.size()); ESP_LOGW(CP_TAG, "Battery report too short: %zu bytes", report.data.size());
return false; return false;
} }
// CyberPower battery format (little-endian) // Parse battery level based on real CyberPower data analysis
uint16_t battery_level_raw = report.data[0] | (report.data[1] << 8); // Report 0x06: Raw value needs scaling for CyberPower PID=0x0501
uint16_t runtime_raw = report.data[2] | (report.data[3] << 8); // report.data[0] = report ID (0x06)
// report.data[1] = battery charge level (raw value, needs scaling)
// Battery level validation with clamping (NUT-style approach) uint8_t raw_battery = report.data[1];
float battery_level; ESP_LOGD(CP_TAG, "Raw battery value: %d", raw_battery);
if (battery_level_raw <= 100) {
battery_level = static_cast<float>(battery_level_raw); // Apply CyberPower scaling factor (observed: raw=2 should be ~62%)
} else if (battery_level_raw <= 1000) { // Based on NUT cps-hid.c battery scaling for PID 0x0501
battery_level = static_cast<float>(battery_level_raw) / 10.0f; data.battery_level = static_cast<float>(raw_battery * 30); // 30x scaling factor
// Clamp battery charge to 100% like NUT does for CyberPower
if (data.battery_level > 100.0f) {
data.battery_level = 100.0f;
}
ESP_LOGI(CP_TAG, "Battery level: %.0f%% (raw: %d)", data.battery_level, raw_battery);
// Parse runtime if more bytes available
if (report.data.size() >= 6) {
// Log all bytes to understand the data structure
ESP_LOGD(CP_TAG, "Battery report full data (%zu bytes):", report.data.size());
for (size_t i = 0; i < report.data.size(); i++) {
ESP_LOGD(CP_TAG, " Byte %zu: 0x%02X (%d)", i, report.data[i], report.data[i]);
}
// Try different runtime parsing strategies:
// Strategy 1: 32-bit little-endian at bytes 2-5
uint32_t runtime_raw_32 = report.data[2] +
(report.data[3] << 8) +
(report.data[4] << 16) +
(report.data[5] << 24);
// Strategy 2: 16-bit little-endian at bytes 2-3
uint16_t runtime_raw_16 = report.data[2] + (report.data[3] << 8);
// Strategy 3: Direct byte values
uint8_t runtime_byte2 = report.data[2];
uint8_t runtime_byte3 = report.data[3];
ESP_LOGD(CP_TAG, "Runtime candidates - 32bit:%u, 16bit:%u, byte2:%u, byte3:%u",
runtime_raw_32, runtime_raw_16, runtime_byte2, runtime_byte3);
// Use the most reasonable value (expect ~43 minutes)
if (runtime_raw_16 > 10 && runtime_raw_16 < 300) { // 16-bit value in reasonable range
data.runtime_minutes = static_cast<float>(runtime_raw_16);
ESP_LOGI(CP_TAG, "Runtime: %.0f minutes (16-bit at bytes 2-3)", data.runtime_minutes);
} else if (runtime_byte2 > 10 && runtime_byte2 < 250) { // Single byte in reasonable range
data.runtime_minutes = static_cast<float>(runtime_byte2);
ESP_LOGI(CP_TAG, "Runtime: %.0f minutes (byte 2)", data.runtime_minutes);
} else if (runtime_byte3 > 10 && runtime_byte3 < 250) { // Try byte 3
data.runtime_minutes = static_cast<float>(runtime_byte3);
ESP_LOGI(CP_TAG, "Runtime: %.0f minutes (byte 3)", data.runtime_minutes);
} else {
// Use battery level estimation as fallback
data.runtime_minutes = data.battery_level * 0.7f; // Improved estimate
ESP_LOGD(CP_TAG, "Using estimated runtime: %.0f minutes", data.runtime_minutes);
}
} else { } else {
ESP_LOGW(CP_TAG, "Battery level out of range: %u", battery_level_raw); // Use battery level estimation for short reports
battery_level = static_cast<float>(battery_level_raw) / 10.0f; // Try scaling anyway data.runtime_minutes = data.battery_level * 0.7f; // Improved estimate
ESP_LOGD(CP_TAG, "Using estimated runtime: %.0f minutes", data.runtime_minutes);
} }
// Clamp to valid range (0-100%) like NUT does
data.battery_level = std::max(0.0f, std::min(100.0f, battery_level));
// Runtime is typically in seconds or minutes
if (runtime_raw < 3600) { // Assume minutes if < 3600
data.runtime_minutes = static_cast<float>(runtime_raw);
} else { // Assume seconds if >= 3600
data.runtime_minutes = static_cast<float>(runtime_raw) / 60.0f;
}
ESP_LOGV(CP_TAG, "Battery: %.1f%%, Runtime: %.1f min", data.battery_level, data.runtime_minutes);
return true; return true;
} }
bool CyberPowerProtocol::parse_voltage_report(const HidReport &report, UpsData &data) { bool CyberPowerProtocol::parse_voltage_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 8) { if (report.data.size() < 2) {
ESP_LOGW(CP_TAG, "Voltage report too short: %d bytes", report.data.size()); ESP_LOGW(CP_TAG, "Voltage report too short: %zu bytes", report.data.size());
return false; return false;
} }
// CyberPower voltage format (little-endian, typically in 0.1V units) // Parse voltage - handle both 2-byte and 3-byte reports
uint16_t input_voltage_raw = report.data[0] | (report.data[1] << 8); // report.data[0] = report ID (0x0E)
uint16_t output_voltage_raw = report.data[2] | (report.data[3] << 8); // report.data[1] = voltage (primary byte)
uint16_t load_raw = report.data[4] | (report.data[5] << 8); uint16_t voltage_raw = report.data[1];
uint16_t frequency_raw = report.data[6] | (report.data[7] << 8);
// Convert raw values to actual units with NUT-style validation // If we have a second byte, treat it as high byte for 16-bit value
float input_voltage = static_cast<float>(input_voltage_raw) / 10.0f; if (report.data.size() >= 3) {
float output_voltage = static_cast<float>(output_voltage_raw) / 10.0f; voltage_raw += (report.data[2] << 8);
ESP_LOGV(CP_TAG, "16-bit voltage: 0x%04X", voltage_raw);
// Voltage range validation (80-300V like NUT does)
if (input_voltage >= 80.0f && input_voltage <= 300.0f) {
data.input_voltage = input_voltage;
} else { } else {
ESP_LOGW(CP_TAG, "Input voltage out of range: %.1fV", input_voltage); ESP_LOGV(CP_TAG, "8-bit voltage: 0x%02X", voltage_raw);
data.input_voltage = NAN;
} }
if (output_voltage >= 80.0f && output_voltage <= 300.0f) { // CyberPower voltage might need scaling (NUT applies scaling factors for some models)
data.output_voltage = output_voltage; // For now, treat as direct voltage like APC
} else { data.input_voltage = static_cast<float>(voltage_raw);
ESP_LOGW(CP_TAG, "Output voltage out of range: %.1fV", output_voltage); data.output_voltage = data.input_voltage; // Assume same for most UPS devices
data.output_voltage = NAN;
}
// Load percentage validation with clamping (like NUT does) ESP_LOGI(CP_TAG, "Voltage: %.0fV", data.input_voltage);
if (load_raw <= 100) {
data.load_percent = static_cast<float>(load_raw);
} else if (load_raw <= 1000) {
// Some models report in 0.1% units
data.load_percent = static_cast<float>(load_raw) / 10.0f;
} else {
ESP_LOGW(CP_TAG, "Load value out of range: %u", load_raw);
data.load_percent = std::max(0.0f, std::min(100.0f, static_cast<float>(load_raw) / 10.0f));
}
// Frequency validation (NUT expects 47-53 Hz typically)
float frequency = static_cast<float>(frequency_raw) / 10.0f;
if (frequency >= 40.0f && frequency <= 70.0f) {
data.frequency = frequency;
} else {
ESP_LOGW(CP_TAG, "Frequency out of range: %.1f Hz", frequency);
data.frequency = NAN;
}
ESP_LOGV(CP_TAG, "Input: %.1fV, Output: %.1fV, Load: %.1f%%, Freq: %.1fHz",
data.input_voltage, data.output_voltage, data.load_percent, data.frequency);
return true; return true;
} }
bool CyberPowerProtocol::parse_device_info_report(const HidReport &report, UpsData &data) { bool CyberPowerProtocol::parse_device_info_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 16) { // CyberPower device info parsing - for future enhancement
ESP_LOGW(CP_TAG, "Device info report too short: %d bytes", report.data.size()); ESP_LOGV(CP_TAG, "Device info report parsing not yet implemented");
return false;
}
// Extract model and serial number from device info
// This is a simplified parser - actual format varies by model
std::string info_string = bytes_to_string(report.data);
// Look for model information
if (info_string.find("CP") != std::string::npos ||
info_string.find("CYBER") != std::string::npos) {
size_t start = info_string.find_first_not_of(" \t\n\r");
size_t end = info_string.find_first_of(" \t\n\r", start);
if (start != std::string::npos) {
data.model = info_string.substr(start, end - start);
}
}
data.manufacturer = "CyberPower";
ESP_LOGV(CP_TAG, "Device: %s %s", data.manufacturer.c_str(), data.model.c_str());
return true; return true;
} }
+66 -51
View File
@@ -16,6 +16,7 @@
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "freertos/portmacro.h" #include "freertos/portmacro.h"
#include "freertos/queue.h"
#include "usb/usb_host.h" #include "usb/usb_host.h"
#include "usb/usb_types_ch9.h" #include "usb/usb_types_ch9.h"
#include <cstring> #include <cstring>
@@ -275,6 +276,7 @@ namespace esphome
#endif #endif
} }
bool UpsHidComponent::should_log_error(ErrorRateLimit &limiter) bool UpsHidComponent::should_log_error(ErrorRateLimit &limiter)
{ {
uint32_t now = millis(); uint32_t now = millis();
@@ -1436,89 +1438,102 @@ namespace esphome
esp_err_t UpsHidComponent::hid_get_report(uint8_t report_type, uint8_t report_id, uint8_t* data, size_t* data_len) esp_err_t UpsHidComponent::hid_get_report(uint8_t report_type, uint8_t report_id, uint8_t* data, size_t* data_len)
{ {
if (!device_connected_ || !usb_device_.dev_hdl || !data || !data_len || *data_len == 0) { if (!device_connected_ || !usb_device_.dev_hdl || !data || !data_len || *data_len == 0) {
ESP_LOGE(TAG, "HID GET_REPORT: Invalid parameters"); ESP_LOGE(TAG, "HID GET_REPORT: Invalid parameters or device not connected");
return ESP_ERR_INVALID_ARG; return ESP_ERR_INVALID_ARG;
} }
ESP_LOGD(TAG, "HID GET_REPORT: type=0x%02X, id=0x%02X, max_len=%zu", report_type, report_id, *data_len);
// Use specific buffer sizes based on working NUT implementation
uint8_t buffer[8] = {0}; // Fixed size like working NUT implementation
size_t expected_len = 8; // Standard HID report size for APC UPS devices
// Create USB control transfer for HID GET_REPORT
const uint8_t bmRequestType = USB_BM_REQUEST_TYPE_DIR_IN | USB_BM_REQUEST_TYPE_TYPE_CLASS | USB_BM_REQUEST_TYPE_RECIP_INTERFACE; const uint8_t 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 uint8_t bRequest = 0x01; // HID GET_REPORT
const uint16_t wValue = (report_type << 8) | report_id; const uint16_t wValue = (report_type << 8) | report_id;
const uint16_t wIndex = usb_device_.interface_num; const uint16_t wIndex = usb_device_.interface_num;
const uint16_t wLength = expected_len;
// Ensure reasonable buffer size limits
size_t max_data_len = std::min(*data_len, static_cast<size_t>(64)); // HID reports are typically <= 64 bytes
usb_transfer_t *transfer = nullptr; usb_transfer_t *transfer = nullptr;
// Control transfers need setup packet + data phase allocation size_t transfer_size = sizeof(usb_setup_packet_t) + expected_len;
size_t transfer_size = sizeof(usb_setup_packet_t) + max_data_len;
esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer); esp_err_t ret = usb_host_transfer_alloc(transfer_size, 0, &transfer);
if (ret != ESP_OK || !transfer) { if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to allocate control transfer (size=%zu): %s", transfer_size, esp_err_to_name(ret)); ESP_LOGE(TAG, "Failed to allocate transfer: %s", esp_err_to_name(ret));
return ret; return ret;
} }
// Create transfer context for synchronization // Setup control transfer like working implementation
TransferContext ctx = {}; transfer->device_handle = usb_device_.dev_hdl;
ctx.done_sem = xSemaphoreCreateBinary(); transfer->bEndpointAddress = 0;
ctx.buffer = data; transfer->num_bytes = transfer_size;
ctx.buffer_size = max_data_len; transfer->timeout_ms = 500; // Reasonable timeout
if (!ctx.done_sem) { // 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); usb_host_transfer_free(transfer);
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
// Set up USB control transfer // Simple context for completion
transfer->device_handle = usb_device_.dev_hdl; struct {
transfer->bEndpointAddress = 0; // Control endpoint (required for control transfers) SemaphoreHandle_t sem;
transfer->callback = usb_transfer_callback; esp_err_t result;
size_t actual_bytes;
} ctx = {done_sem, ESP_ERR_TIMEOUT, 0};
transfer->context = &ctx; transfer->context = &ctx;
transfer->num_bytes = transfer_size; // Total transfer size including setup packet transfer->callback = [](usb_transfer_t *t) {
transfer->timeout_ms = 200; // Very short timeout to prevent task watchdog issues 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);
};
ESP_LOGV(TAG, "Control transfer setup: dev_hdl=%p, ep=0x%02X, size=%zu, timeout=%u", ret = usb_host_transfer_submit_control(usb_device_.client_hdl, transfer);
transfer->device_handle, transfer->bEndpointAddress, transfer->num_bytes, transfer->timeout_ms);
// Create setup packet with proper byte ordering for USB protocol
usb_setup_packet_t *setup = (usb_setup_packet_t*)transfer->data_buffer;
setup->bmRequestType = bmRequestType;
setup->bRequest = bRequest;
setup->wValue = wValue; // (report_type << 8) | report_id - already in correct format
setup->wIndex = wIndex; // Interface number
setup->wLength = (uint16_t)max_data_len; // Expected response length - explicit cast
ESP_LOGD(TAG, "HID GET_REPORT: bmReqType=0x%02X, bReq=0x%02X, wValue=0x%04X, wIndex=0x%04X, wLen=%zu, dev_hdl=%p, intf_num=%d",
setup->bmRequestType, setup->bRequest, setup->wValue, setup->wIndex, max_data_len, usb_device_.dev_hdl, usb_device_.interface_num);
// Ensure client handle is valid before submission
if (!usb_device_.client_hdl) {
ESP_LOGE(TAG, "HID GET_REPORT: Invalid client handle");
ret = ESP_ERR_INVALID_STATE;
} else {
ret = usb_host_transfer_submit_control(usb_device_.client_hdl, transfer);
}
if (ret == ESP_OK) { if (ret == ESP_OK) {
// Wait for completion with very short timeout to prevent watchdog issues if (xSemaphoreTake(done_sem, pdMS_TO_TICKS(500)) == pdTRUE) {
if (xSemaphoreTake(ctx.done_sem, pdMS_TO_TICKS(250)) == pdTRUE) {
ret = ctx.result; ret = ctx.result;
if (ret == ESP_OK && ctx.actual_bytes >= sizeof(usb_setup_packet_t)) { if (ret == ESP_OK && ctx.actual_bytes > sizeof(usb_setup_packet_t)) {
size_t actual_data_len = ctx.actual_bytes - sizeof(usb_setup_packet_t); size_t data_received = ctx.actual_bytes - sizeof(usb_setup_packet_t);
*data_len = std::min(max_data_len, actual_data_len); size_t copy_len = std::min(data_received, *data_len);
memcpy(data, transfer->data_buffer + sizeof(usb_setup_packet_t), copy_len);
*data_len = copy_len;
ESP_LOGD(TAG, "HID GET_REPORT success: received %zu bytes", *data_len); ESP_LOGD(TAG, "HID GET_REPORT success: received %zu bytes", *data_len);
if (*data_len > 0) {
std::string hex_str;
for (size_t i = 0; i < std::min(*data_len, (size_t)8); i++) {
char hex_byte[4];
snprintf(hex_byte, sizeof(hex_byte), "%02X ", data[i]);
hex_str += hex_byte;
}
ESP_LOGD(TAG, "Data: %s", hex_str.c_str());
}
} else { } else {
ESP_LOGW(TAG, "HID GET_REPORT completed but no data: result=%s, actual_bytes=%zu", ESP_LOGW(TAG, "HID GET_REPORT: No data received");
esp_err_to_name(ret), ctx.actual_bytes); *data_len = 0;
ret = ESP_FAIL;
} }
} else { } else {
ESP_LOGW(TAG, "HID GET_REPORT timeout after 250ms"); ESP_LOGW(TAG, "HID GET_REPORT timeout");
ret = ESP_ERR_TIMEOUT; ret = ESP_ERR_TIMEOUT;
} }
} else { } else {
ESP_LOGE(TAG, "Failed to submit HID GET_REPORT: %s", esp_err_to_name(ret)); ESP_LOGW(TAG, "Failed to submit HID GET_REPORT: %s", esp_err_to_name(ret));
} }
vSemaphoreDelete(done_sem);
usb_host_transfer_free(transfer); usb_host_transfer_free(transfer);
vSemaphoreDelete(ctx.done_sem);
return ret; return ret;
} }
+3 -1
View File
@@ -112,7 +112,7 @@ namespace esphome
class UpsHidComponent : public PollingComponent class UpsHidComponent : public PollingComponent
{ {
public: public:
UpsHidComponent() : usb_device_{}, usb_mutex_(nullptr), usb_lib_task_handle_(nullptr), UpsHidComponent() : usb_device_{}, usb_mutex_(nullptr), usb_lib_task_handle_(nullptr),
usb_client_task_handle_(nullptr), usb_host_initialized_(false), usb_client_task_handle_(nullptr), usb_host_initialized_(false),
device_connected_(false), usb_tasks_running_(false) { device_connected_(false), usb_tasks_running_(false) {
#ifdef USE_ESP32 #ifdef USE_ESP32
@@ -162,6 +162,7 @@ namespace esphome
// USB device info getters // USB device info getters
uint16_t get_usb_vendor_id() const { return usb_vendor_id_; } uint16_t get_usb_vendor_id() const { return usb_vendor_id_; }
uint16_t get_usb_product_id() const { return usb_product_id_; } uint16_t get_usb_product_id() const { return usb_product_id_; }
bool is_input_only_device() const { return usb_device_.is_input_only; }
// Sensor registration methods // Sensor registration methods
void register_sensor(sensor::Sensor *sens, const std::string &type); void register_sensor(sensor::Sensor *sens, const std::string &type);
@@ -217,6 +218,7 @@ namespace esphome
// HID class requests (UPS-specific communication) // 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_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); esp_err_t hid_set_report(uint8_t report_type, uint8_t report_id, const uint8_t* data, size_t data_len);
protected: protected:
#ifdef USE_ESP32 #ifdef USE_ESP32
+17 -7
View File
@@ -13,12 +13,22 @@ esp32:
flash_size: 16MB flash_size: 16MB
framework: framework:
type: esp-idf type: esp-idf
version: 5.3.2
# Enable logging with verbose output for debugging # Enable logging with verbose output for debugging
logger: logger:
level: VERBOSE level: VERBOSE
logs: logs:
ups_hid: DEBUG ups_hid: DEBUG
usb_host: VERBOSE
usb-host: VERBOSE
USB_HOST: VERBOSE
hcd: VERBOSE
HCD: VERBOSE
hub: VERBOSE
HUB: VERBOSE
usbh: VERBOSE
USBH: VERBOSE
baud_rate: 115200 baud_rate: 115200
hardware_uart: UART0 hardware_uart: UART0
@@ -76,7 +86,7 @@ light:
duration: 150ms duration: 150ms
- state: false - state: false
duration: 150ms duration: 150ms
# Battery operation - Slow orange fade (amber warning pattern) # Battery operation - Slow orange fade (amber warning pattern)
- pulse: - pulse:
name: "Battery Warning" name: "Battery Warning"
@@ -84,7 +94,7 @@ light:
update_interval: 1.5s update_interval: 1.5s
min_brightness: 10% min_brightness: 10%
max_brightness: 95% max_brightness: 95%
# Charging status - Quick yellow double-blink (charging pattern) # Charging status - Quick yellow double-blink (charging pattern)
- strobe: - strobe:
name: "Charging Pattern" name: "Charging Pattern"
@@ -105,7 +115,7 @@ light:
duration: 200ms duration: 200ms
- state: false - state: false
duration: 1400ms duration: 1400ms
# Normal operation - Slow green breathing (peaceful pattern) # Normal operation - Slow green breathing (peaceful pattern)
- pulse: - pulse:
name: "Normal Status" name: "Normal Status"
@@ -113,7 +123,7 @@ light:
update_interval: 3s update_interval: 3s
min_brightness: 20% min_brightness: 20%
max_brightness: 60% max_brightness: 60%
# Fault/offline - Blue fade (distinct from other states) # Fault/offline - Blue fade (distinct from other states)
- pulse: - pulse:
name: "System Offline" name: "System Offline"
@@ -137,15 +147,15 @@ ups_hid:
#usb_vendor_id: 0x051d # APC vendor ID (0x051d) #usb_vendor_id: 0x051d # APC vendor ID (0x051d)
#usb_product_id: 0x0002 # APC Back-UPS ES series #usb_product_id: 0x0002 # APC Back-UPS ES series
# usb_vendor_id: 0x0764 # CyberPower (0x0764) usb_vendor_id: 0x0764 # CyberPower (0x0764)
# usb_product_id: 0x0501 # CP1500 AVR UPS usb_product_id: 0x0501 # CP1500 AVR UPS
# Protocol Configuration # Protocol Configuration
auto_detect_protocol: true auto_detect_protocol: true
protocol_timeout: 15s protocol_timeout: 15s
# Development/Testing Configuration # Development/Testing Configuration
simulation_mode: true # Set to false for production with real hardware simulation_mode: false # Set to false for production with real hardware
# Numeric Sensors # Numeric Sensors
sensor: sensor:
+2 -1
View File
@@ -8,6 +8,7 @@ esp32:
variant: esp32s3 variant: esp32s3
framework: framework:
type: esp-idf type: esp-idf
version: 5.3.2
# Enable logging # Enable logging
logger: logger:
@@ -75,7 +76,7 @@ external_components:
# UPS HID Component # UPS HID Component
ups_hid: ups_hid:
id: ups_monitor id: ups_monitor
simulation_mode: false # Set to false for production simulation_mode: false # Test with real APC UPS hardware
update_interval: 5s update_interval: 5s
# Hardware Configuration # Hardware Configuration
+1
View File
@@ -12,6 +12,7 @@ esp32:
flash_size: 16MB flash_size: 16MB
framework: framework:
type: esp-idf type: esp-idf
version: 5.3.2
logger: logger:
level: VERBOSE level: VERBOSE