Bugfix 2026.7.0.

This commit is contained in:
Roy Walker committed 2026-07-17 13:36:06 -05:00
1 parent c69b2e0754
commit 74cdb3d56f
4 files changed
+101 -167

No files matched your search

+62 -116
View File
@@ -3,101 +3,43 @@
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "esphome/components/logger/logger.h" #include "esphome/components/logger/logger.h"
#include <algorithm> #include <algorithm>
#include <cctype>
namespace esphome { namespace esphome {
namespace ups_hid { namespace ups_hid {
static const char *const FACTORY_TAG = "ups_hid.factory"; static const char *const FACTORY_TAG = "ups_hid.factory";
// Forward declarations for protocol creator functions
// These are defined in their respective protocol implementation files
extern std::unique_ptr<UpsProtocolBase> create_apc_protocol(UpsHidComponent* parent);
extern std::unique_ptr<UpsProtocolBase> create_cyberpower_protocol(UpsHidComponent* parent);
extern std::unique_ptr<UpsProtocolBase> create_goldenmate_protocol(UpsHidComponent* parent);
extern std::unique_ptr<UpsProtocolBase> create_generic_protocol(UpsHidComponent* parent);
// Static registry implementations // Static registry implementations
std::unordered_map<uint16_t, std::vector<ProtocolFactory::ProtocolInfo>>& std::unordered_map<uint16_t, std::vector<ProtocolFactory::ProtocolInfo>>&
ProtocolFactory::get_vendor_registry() { ProtocolFactory::get_vendor_registry() {
static std::unordered_map<uint16_t, std::vector<ProtocolInfo>> vendor_registry; static std::unordered_map<uint16_t, std::vector<ProtocolInfo>> vendor_registry;
return vendor_registry; return vendor_registry;
} }
std::vector<ProtocolFactory::ProtocolInfo>& std::vector<ProtocolFactory::ProtocolInfo>&
ProtocolFactory::get_fallback_registry() { ProtocolFactory::get_fallback_registry() {
static std::vector<ProtocolInfo> fallback_registry; static std::vector<ProtocolInfo> fallback_registry;
return fallback_registry; return fallback_registry;
} }
void ProtocolFactory::ensure_initialized() { void ProtocolFactory::ensure_initialized() {
// Initialize built-in protocols on first access // With the Open/Closed refactor, protocol self-registration using macros handles everything.
// This ensures all protocols are registered regardless of static initializer order // This function is kept for backwards compatibility or future core initializations.
static bool initialized = false; static bool initialized = false;
if (initialized) return; if (initialized) return;
initialized = true; initialized = true;
ESP_LOGI(FACTORY_TAG, "Initializing built-in UPS protocol support"); ESP_LOGI(FACTORY_TAG, "Protocol registries initialized.");
// Register APC protocol for vendor 0x051D
{
ProtocolInfo info;
info.creator = create_apc_protocol;
info.name = "APC";
info.description = "APC HID Protocol";
info.supported_vendors = {0x051D};
info.priority = 200;
auto& registry = get_vendor_registry();
registry[0x051D].push_back(info);
ESP_LOGI(FACTORY_TAG, "Registered APC protocol for vendor 0x051D");
}
// Register CyberPower protocol for vendor 0x0764
{
ProtocolInfo info;
info.creator = create_cyberpower_protocol;
info.name = "CyberPower";
info.description = "CyberPower HID Protocol";
info.supported_vendors = {0x0764};
info.priority = 200;
auto& registry = get_vendor_registry();
registry[0x0764].push_back(info);
ESP_LOGI(FACTORY_TAG, "Registered CyberPower protocol for vendor 0x0764");
}
// Register GoldenMate protocol for vendor 0x075D
{
ProtocolInfo info;
info.creator = create_goldenmate_protocol;
info.name = "GoldenMate";
info.description = "GoldenMate HID Protocol";
info.supported_vendors = {0x075D};
info.priority = 200;
auto& registry = get_vendor_registry();
registry[0x075D].push_back(info);
ESP_LOGI(FACTORY_TAG, "Registered GoldenMate protocol for vendor 0x075D");
}
// Register Generic protocol as fallback (always last)
{
ProtocolInfo info;
info.creator = create_generic_protocol;
info.name = "Generic HID Protocol";
info.description = "Universal HID protocol fallback for unknown UPS vendors";
info.supported_vendors = {};
info.priority = 10;
auto& registry = get_fallback_registry();
registry.push_back(info);
ESP_LOGI(FACTORY_TAG, "Registered Generic HID protocol as fallback");
}
} }
void ProtocolFactory::register_protocol_for_vendor(uint16_t vendor_id, void ProtocolFactory::register_protocol_for_vendor(uint16_t vendor_id,
const ProtocolInfo& info) { const ProtocolInfo& info) {
ensure_initialized(); ensure_initialized();
auto& registry = get_vendor_registry(); auto& registry = get_vendor_registry();
registry[vendor_id].push_back(info); registry[vendor_id].push_back(info);
// Sort by priority (higher first) // Sort by priority (higher first)
std::sort(registry[vendor_id].begin(), registry[vendor_id].end(), std::sort(registry[vendor_id].begin(), registry[vendor_id].end(),
[](const ProtocolInfo& a, const ProtocolInfo& b) { [](const ProtocolInfo& a, const ProtocolInfo& b) {
@@ -107,10 +49,10 @@ void ProtocolFactory::register_protocol_for_vendor(uint16_t vendor_id,
void ProtocolFactory::register_fallback_protocol(const ProtocolInfo& info) { void ProtocolFactory::register_fallback_protocol(const ProtocolInfo& info) {
ensure_initialized(); ensure_initialized();
auto& registry = get_fallback_registry(); auto& registry = get_fallback_registry();
registry.push_back(info); registry.push_back(info);
// Sort by priority (higher first) // Sort by priority (higher first)
std::sort(registry.begin(), registry.end(), std::sort(registry.begin(), registry.end(),
[](const ProtocolInfo& a, const ProtocolInfo& b) { [](const ProtocolInfo& a, const ProtocolInfo& b) {
@@ -118,88 +60,88 @@ void ProtocolFactory::register_fallback_protocol(const ProtocolInfo& info) {
}); });
} }
std::unique_ptr<UpsProtocolBase> std::unique_ptr<UpsProtocolBase>
ProtocolFactory::create_for_vendor(uint16_t vendor_id, UpsHidComponent* parent) { ProtocolFactory::create_for_vendor(uint16_t vendor_id, UpsHidComponent* parent) {
ensure_initialized(); ensure_initialized();
if (!parent) { if (!parent) {
ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component"); ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component");
return nullptr; return nullptr;
} }
// Try vendor-specific protocols first // Try vendor-specific protocols first
auto& vendor_registry = get_vendor_registry(); auto& vendor_registry = get_vendor_registry();
auto vendor_it = vendor_registry.find(vendor_id); auto vendor_it = vendor_registry.find(vendor_id);
if (vendor_it != vendor_registry.end()) { if (vendor_it != vendor_registry.end()) {
ESP_LOGD(FACTORY_TAG, "Found %zu vendor-specific protocols for 0x%04X", ESP_LOGD(FACTORY_TAG, "Found %zu vendor-specific protocols for 0x%04X",
vendor_it->second.size(), vendor_id); vendor_it->second.size(), vendor_id);
for (const auto& info : vendor_it->second) { for (const auto& info : vendor_it->second) {
ESP_LOGD(FACTORY_TAG, "Trying vendor protocol '%s' for 0x%04X", ESP_LOGD(FACTORY_TAG, "Trying vendor protocol '%s' for 0x%04X",
info.name.c_str(), vendor_id); info.name.c_str(), vendor_id);
auto protocol = info.creator(parent); auto protocol = info.creator(parent);
if (protocol && protocol->detect()) { if (protocol && protocol->detect()) {
ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' for vendor 0x%04X", ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' for vendor 0x%04X",
info.name.c_str(), vendor_id); info.name.c_str(), vendor_id);
return protocol; return protocol;
} }
} }
} }
// Try fallback protocols // Try fallback protocols
auto& fallback_registry = get_fallback_registry(); auto& fallback_registry = get_fallback_registry();
ESP_LOGD(FACTORY_TAG, "Trying %zu fallback protocols for vendor 0x%04X", ESP_LOGD(FACTORY_TAG, "Trying %zu fallback protocols for vendor 0x%04X",
fallback_registry.size(), vendor_id); fallback_registry.size(), vendor_id);
for (const auto& info : fallback_registry) { for (const auto& info : fallback_registry) {
ESP_LOGD(FACTORY_TAG, "Trying fallback protocol '%s' for 0x%04X", ESP_LOGD(FACTORY_TAG, "Trying fallback protocol '%s' for 0x%04X",
info.name.c_str(), vendor_id); info.name.c_str(), vendor_id);
auto protocol = info.creator(parent); auto protocol = info.creator(parent);
if (protocol && protocol->detect()) { if (protocol && protocol->detect()) {
ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' for vendor 0x%04X", ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' for vendor 0x%04X",
info.name.c_str(), vendor_id); info.name.c_str(), vendor_id);
return protocol; return protocol;
} }
} }
ESP_LOGW(FACTORY_TAG, "No suitable protocol found for vendor 0x%04X", vendor_id); ESP_LOGW(FACTORY_TAG, "No suitable protocol found for vendor 0x%04X", vendor_id);
return nullptr; return nullptr;
} }
std::vector<ProtocolFactory::ProtocolInfo> std::vector<ProtocolFactory::ProtocolInfo>
ProtocolFactory::get_protocols_for_vendor(uint16_t vendor_id) { ProtocolFactory::get_protocols_for_vendor(uint16_t vendor_id) {
ensure_initialized(); ensure_initialized();
std::vector<ProtocolInfo> protocols; std::vector<ProtocolInfo> protocols;
// Add vendor-specific protocols first // Add vendor-specific protocols first
auto& vendor_registry = get_vendor_registry(); auto& vendor_registry = get_vendor_registry();
auto vendor_it = vendor_registry.find(vendor_id); auto vendor_it = vendor_registry.find(vendor_id);
if (vendor_it != vendor_registry.end()) { if (vendor_it != vendor_registry.end()) {
for (const auto& info : vendor_it->second) { for (const auto& info : vendor_it->second) {
protocols.push_back(info); protocols.push_back(info);
} }
} }
// Add fallback protocols // Add fallback protocols
auto& fallback_registry = get_fallback_registry(); auto& fallback_registry = get_fallback_registry();
for (const auto& info : fallback_registry) { for (const auto& info : fallback_registry) {
protocols.push_back(info); protocols.push_back(info);
} }
return protocols; return protocols;
} }
std::vector<std::pair<uint16_t, ProtocolFactory::ProtocolInfo>> std::vector<std::pair<uint16_t, ProtocolFactory::ProtocolInfo>>
ProtocolFactory::get_all_protocols() { ProtocolFactory::get_all_protocols() {
ensure_initialized(); ensure_initialized();
std::vector<std::pair<uint16_t, ProtocolInfo>> all_protocols; std::vector<std::pair<uint16_t, ProtocolInfo>> all_protocols;
// Add vendor-specific protocols // Add vendor-specific protocols
auto& vendor_registry = get_vendor_registry(); auto& vendor_registry = get_vendor_registry();
for (const auto& vendor_pair : vendor_registry) { for (const auto& vendor_pair : vendor_registry) {
@@ -208,40 +150,40 @@ ProtocolFactory::get_all_protocols() {
all_protocols.emplace_back(vendor_id, info); all_protocols.emplace_back(vendor_id, info);
} }
} }
// Add fallback protocols (use 0x0000 as special vendor ID for fallbacks) // Add fallback protocols (use 0x0000 as special vendor ID for fallbacks)
auto& fallback_registry = get_fallback_registry(); auto& fallback_registry = get_fallback_registry();
for (const auto& info : fallback_registry) { for (const auto& info : fallback_registry) {
all_protocols.emplace_back(0x0000, info); all_protocols.emplace_back(0x0000, info);
} }
return all_protocols; return all_protocols;
} }
bool ProtocolFactory::has_vendor_support(uint16_t vendor_id) { bool ProtocolFactory::has_vendor_support(uint16_t vendor_id) {
ensure_initialized(); ensure_initialized();
auto& vendor_registry = get_vendor_registry(); auto& vendor_registry = get_vendor_registry();
auto it = vendor_registry.find(vendor_id); auto it = vendor_registry.find(vendor_id);
// Has support if vendor-specific protocols exist OR fallback protocols exist // Has support if vendor-specific protocols exist OR fallback protocols exist
bool has_vendor_specific = (it != vendor_registry.end() && !it->second.empty()); bool has_vendor_specific = (it != vendor_registry.end() && !it->second.empty());
bool has_fallback = !get_fallback_registry().empty(); bool has_fallback = !get_fallback_registry().empty();
return has_vendor_specific || has_fallback; return has_vendor_specific || has_fallback;
} }
std::unique_ptr<UpsProtocolBase> std::unique_ptr<UpsProtocolBase>
ProtocolFactory::create_by_name(const std::string& protocol_name, UpsHidComponent* parent) { ProtocolFactory::create_by_name(const std::string& protocol_name, UpsHidComponent* parent) {
ensure_initialized(); ensure_initialized();
if (!parent) { if (!parent) {
ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component"); ESP_LOGE(FACTORY_TAG, "Cannot create protocol with null parent component");
return nullptr; return nullptr;
} }
ESP_LOGD(FACTORY_TAG, "Creating protocol by name: %s", protocol_name.c_str()); ESP_LOGD(FACTORY_TAG, "Creating protocol by name: %s", protocol_name.c_str());
// Search through all registered protocols to find one with matching name // Search through all registered protocols to find one with matching name
auto& vendor_registry = get_vendor_registry(); auto& vendor_registry = get_vendor_registry();
for (const auto& vendor_pair : vendor_registry) { for (const auto& vendor_pair : vendor_registry) {
@@ -249,42 +191,46 @@ ProtocolFactory::create_by_name(const std::string& protocol_name, UpsHidComponen
// Match protocol name (case-insensitive) // Match protocol name (case-insensitive)
std::string info_name_lower = info.name; std::string info_name_lower = info.name;
std::string protocol_name_lower = protocol_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(info_name_lower.begin(), info_name_lower.end(), info_name_lower.begin(),
std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(), ::tolower); [](unsigned char c) { return std::tolower(c); });
std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(),
[](unsigned char c) { return std::tolower(c); });
if (info_name_lower.find(protocol_name_lower) != std::string::npos) { if (info_name_lower.find(protocol_name_lower) != std::string::npos) {
ESP_LOGD(FACTORY_TAG, "Found matching protocol '%s' for name '%s'", ESP_LOGD(FACTORY_TAG, "Found matching protocol '%s' for name '%s'",
info.name.c_str(), protocol_name.c_str()); info.name.c_str(), protocol_name.c_str());
auto protocol = info.creator(parent); auto protocol = info.creator(parent);
if (protocol) { if (protocol) {
ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' by name", ESP_LOGI(FACTORY_TAG, "Successfully created protocol '%s' by name",
protocol->get_protocol_name().c_str()); protocol->get_protocol_name().c_str());
return protocol; return protocol;
} }
} }
} }
} }
// Search through fallback protocols // Search through fallback protocols
auto& fallback_registry = get_fallback_registry(); auto& fallback_registry = get_fallback_registry();
for (const auto& info : fallback_registry) { for (const auto& info : fallback_registry) {
std::string info_name_lower = info.name; std::string info_name_lower = info.name;
std::string protocol_name_lower = protocol_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(info_name_lower.begin(), info_name_lower.end(), info_name_lower.begin(),
std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(), ::tolower); [](unsigned char c) { return std::tolower(c); });
std::transform(protocol_name_lower.begin(), protocol_name_lower.end(), protocol_name_lower.begin(),
[](unsigned char c) { return std::tolower(c); });
if (info_name_lower.find(protocol_name_lower) != std::string::npos) { if (info_name_lower.find(protocol_name_lower) != std::string::npos) {
ESP_LOGD(FACTORY_TAG, "Found matching fallback protocol '%s' for name '%s'", ESP_LOGD(FACTORY_TAG, "Found matching fallback protocol '%s' for name '%s'",
info.name.c_str(), protocol_name.c_str()); info.name.c_str(), protocol_name.c_str());
auto protocol = info.creator(parent); auto protocol = info.creator(parent);
if (protocol) { if (protocol) {
ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' by name", ESP_LOGI(FACTORY_TAG, "Successfully created fallback protocol '%s' by name",
protocol->get_protocol_name().c_str()); protocol->get_protocol_name().c_str());
return protocol; return protocol;
} }
} }
} }
ESP_LOGE(FACTORY_TAG, "No protocol found with name containing '%s'", protocol_name.c_str()); ESP_LOGE(FACTORY_TAG, "No protocol found with name containing '%s'", protocol_name.c_str());
return nullptr; return nullptr;
} }
+15 -21
View File
@@ -13,26 +13,20 @@ namespace ups_hid {
class UpsProtocolBase; class UpsProtocolBase;
class UpsHidComponent; class UpsHidComponent;
// Forward declarations for built-in protocol creator functions
std::unique_ptr<UpsProtocolBase> create_apc_protocol(UpsHidComponent* parent);
std::unique_ptr<UpsProtocolBase> create_cyberpower_protocol(UpsHidComponent* parent);
std::unique_ptr<UpsProtocolBase> create_goldenmate_protocol(UpsHidComponent* parent);
std::unique_ptr<UpsProtocolBase> create_generic_protocol(UpsHidComponent* parent);
/** /**
* Protocol Factory with Self-Registration Support * Protocol Factory with Self-Registration Support
* *
* Enables protocols to register themselves automatically, following the * Enables protocols to register themselves automatically, following the
* Open/Closed Principle - new protocols can be added without modifying * Open/Closed Principle - new protocols can be added without modifying
* existing code. * existing code.
* *
* Design Pattern: Factory Method + Registry Pattern * Design Pattern: Factory Method + Registry Pattern
*/ */
class ProtocolFactory { class ProtocolFactory {
public: public:
// Protocol creator function type // Protocol creator function type
using CreatorFunc = std::function<std::unique_ptr<UpsProtocolBase>(UpsHidComponent*)>; using CreatorFunc = std::function<std::unique_ptr<UpsProtocolBase>(UpsHidComponent*)>;
// Protocol metadata for better selection // Protocol metadata for better selection
struct ProtocolInfo { struct ProtocolInfo {
CreatorFunc creator; CreatorFunc creator;
@@ -41,41 +35,41 @@ public:
std::vector<uint16_t> supported_vendors; std::vector<uint16_t> supported_vendors;
int priority; // Higher priority = tried first int priority; // Higher priority = tried first
}; };
/** /**
* Register a protocol with specific vendor IDs * Register a protocol with specific vendor IDs
*/ */
static void register_protocol_for_vendor(uint16_t vendor_id, static void register_protocol_for_vendor(uint16_t vendor_id,
const ProtocolInfo& info); const ProtocolInfo& info);
/** /**
* Register a fallback protocol (tried when vendor-specific fails) * Register a fallback protocol (tried when vendor-specific fails)
*/ */
static void register_fallback_protocol(const ProtocolInfo& info); static void register_fallback_protocol(const ProtocolInfo& info);
/** /**
* Create protocol instance for specific vendor * Create protocol instance for specific vendor
*/ */
static std::unique_ptr<UpsProtocolBase> create_for_vendor(uint16_t vendor_id, static std::unique_ptr<UpsProtocolBase> create_for_vendor(uint16_t vendor_id,
UpsHidComponent* parent); UpsHidComponent* parent);
/** /**
* Create protocol instance by name (manual selection) * Create protocol instance by name (manual selection)
*/ */
static std::unique_ptr<UpsProtocolBase> create_by_name(const std::string& protocol_name, static std::unique_ptr<UpsProtocolBase> create_by_name(const std::string& protocol_name,
UpsHidComponent* parent); UpsHidComponent* parent);
/** /**
* Get ordered list of protocols to try for a vendor * Get ordered list of protocols to try for a vendor
* Returns vendor-specific first, then fallbacks by priority * Returns vendor-specific first, then fallbacks by priority
*/ */
static std::vector<ProtocolInfo> get_protocols_for_vendor(uint16_t vendor_id); static std::vector<ProtocolInfo> get_protocols_for_vendor(uint16_t vendor_id);
/** /**
* Get list of all registered protocols * Get list of all registered protocols
*/ */
static std::vector<std::pair<uint16_t, ProtocolInfo>> get_all_protocols(); static std::vector<std::pair<uint16_t, ProtocolInfo>> get_all_protocols();
/** /**
* Check if vendor has registered protocols * Check if vendor has registered protocols
*/ */
@@ -84,17 +78,17 @@ public:
private: private:
// Vendor-specific protocol registry // Vendor-specific protocol registry
static std::unordered_map<uint16_t, std::vector<ProtocolInfo>>& get_vendor_registry(); static std::unordered_map<uint16_t, std::vector<ProtocolInfo>>& get_vendor_registry();
// Fallback protocol registry (sorted by priority) // Fallback protocol registry (sorted by priority)
static std::vector<ProtocolInfo>& get_fallback_registry(); static std::vector<ProtocolInfo>& get_fallback_registry();
// Ensure registries are initialized with built-in protocols // Ensure registries are initialized with built-in protocols
static void ensure_initialized(); static void ensure_initialized();
}; };
/** /**
* Protocol Registration Helper Macros * Protocol Registration Helper Macros
* *
* These macros enable automatic protocol registration at startup * These macros enable automatic protocol registration at startup
*/ */
+20 -29
View File
@@ -11,7 +11,7 @@ static const char *const GM_TAG = "ups_hid.goldenmate";
// Register for vendor 0x075D with a UNIQUE macro name identifier // Register for vendor 0x075D with a UNIQUE macro name identifier
REGISTER_UPS_PROTOCOL_FOR_VENDOR( REGISTER_UPS_PROTOCOL_FOR_VENDOR(
0x075D, GoldenMateProtocol_075D, 0x075D, GoldenMateProtocol_075D,
[](UpsHidComponent *p) { return std::make_unique<GoldenMateProtocol>(p); }, [](UpsHidComponent *p) { return std::make_unique<GoldenMateProtocol>(p); },
"GoldenMate", "UPS Pro", 200); "GoldenMate", "UPS Pro", 200);
@@ -74,11 +74,11 @@ bool GoldenMateProtocol::initialize() {
data.device.manufacturer.c_str(), data.device.manufacturer.c_str(),
data.device.model.c_str(), data.device.model.c_str(),
data.device.serial_number.c_str()); data.device.serial_number.c_str());
return true; return true;
} }
bool GoldenMateProtocol::parse_binary_status(const HidReport &report, UpsData &data) { bool GoldenMateProtocol::parse_binary_status(const HidReport &/*report*/, UpsData &/*data*/) {
// We ignore the binary runtime here to prevent the 16-bit overflow bug // We ignore the binary runtime here to prevent the 16-bit overflow bug
// The true runtime will be grabbed from the ASCII string instead. // The true runtime will be grabbed from the ASCII string instead.
return true; return true;
@@ -89,7 +89,7 @@ bool GoldenMateProtocol::parse_megatec_string(const HidReport &report, UpsData &
const uint8_t *d = report.data.data(); const uint8_t *d = report.data.data();
std::string packed; std::string packed;
// Extract exactly bytes 30 to 61 without shifting // Extract exactly bytes 30 to 61 without shifting
for (int i = 30; i < 62; i++) { for (int i = 30; i < 62; i++) {
char c = static_cast<char>(d[i]); char c = static_cast<char>(d[i]);
@@ -110,9 +110,10 @@ bool GoldenMateProtocol::parse_megatec_string(const HidReport &report, UpsData &
} }
// Extract the live values safely // Extract the live values safely
// NOTE: Verify if substr(0,4) is actually runtime or current as per the header comments
float runtime_mins = std::atof(packed.substr(0, 4).c_str()); float runtime_mins = std::atof(packed.substr(0, 4).c_str());
float battery_pct = std::atof(packed.substr(12, 3).c_str()); float battery_pct = std::atof(packed.substr(12, 3).c_str());
// --- SANITY CHECK FILTER --- // --- SANITY CHECK FILTER ---
// Catch perfectly formatted transient zeroes from wiped buffers // Catch perfectly formatted transient zeroes from wiped buffers
if (battery_pct == 0.0f || runtime_mins == 0.0f) { if (battery_pct == 0.0f || runtime_mins == 0.0f) {
@@ -122,33 +123,30 @@ bool GoldenMateProtocol::parse_megatec_string(const HidReport &report, UpsData &
data.battery.runtime_minutes = runtime_mins; data.battery.runtime_minutes = runtime_mins;
data.battery.level = battery_pct; data.battery.level = battery_pct;
// Parse Status // Parse Status
std::string status_str = packed.substr(24, 8); std::string status_str = packed.substr(24, 8);
bool on_battery = (status_str.length() > 0 && status_str[0] == '1'); bool on_battery = (status_str.length() > 0 && status_str[0] == '1');
// --- TIME-BASED DEBOUNCE LOGIC --- // --- TIME-BASED DEBOUNCE LOGIC ---
static bool is_full = true;
static int below_100_count = 0;
if (battery_pct >= 100.0f) { if (battery_pct >= 100.0f) {
is_full = true; this->is_full_ = true;
below_100_count = 0; // Reset counter immediately on a 100% read this->below_100_count_ = 0; // Reset counter immediately on a 100% read
} else { } else {
below_100_count++; this->below_100_count_++;
// Require 2 consecutive reads (~20 seconds) below 100% to drop the 'Full' status // Require 2 consecutive reads (~20 seconds) below 100% to drop the 'Full' status
if (below_100_count >= 2) { if (this->below_100_count_ >= 2) {
is_full = false; this->is_full_ = false;
} }
} }
if (on_battery) { if (on_battery) {
data.power.status = "OB DISCHRG"; data.power.status = "OB DISCHRG";
data.battery.status = "Discharging"; data.battery.status = "Discharging";
is_full = false; // Force reset if we lose AC power this->is_full_ = false; // Force reset if we lose AC power
below_100_count = 2; // Keep counter aligned with state this->below_100_count_ = 2; // Keep counter aligned with state
} else { } else {
if (is_full) { if (this->is_full_) {
data.power.status = "OL"; data.power.status = "OL";
data.battery.status = "Full"; data.battery.status = "Full";
} else { } else {
@@ -166,9 +164,11 @@ bool GoldenMateProtocol::parse_megatec_string(const HidReport &report, UpsData &
bool GoldenMateProtocol::read_data(UpsData &data) { bool GoldenMateProtocol::read_data(UpsData &data) {
bool success = false; bool success = false;
// CRITICAL HARDWARE TRIGGER: // CRITICAL HARDWARE TRIGGER:
// We MUST poll Report 0x01 first to force the firmware to refresh Report 0x0C // We MUST poll Report 0x01 first to force the firmware to refresh Report 0x0C
HidReport status_report; HidReport status_report;
// If this read times out, we still attempt the Megatec read below,
// but it may return stale data if the hardware trigger failed.
read_feature_report(REPORT_ID_STATUS, status_report); read_feature_report(REPORT_ID_STATUS, status_report);
// Now read the freshly updated ASCII data from Report 0x0C // Now read the freshly updated ASCII data from Report 0x0C
@@ -179,17 +179,8 @@ bool GoldenMateProtocol::read_data(UpsData &data) {
} }
} }
// Set actual names on every read cycle
data.device.manufacturer = "GoldenMate";
data.device.model = "UPS Pro";
std::string str;
if (parent_->get_string_descriptor(3, str) == ESP_OK && !str.empty()) {
data.device.serial_number = str;
}
return success; return success;
} }
} // namespace ups_hid } // namespace ups_hid
} // namespace esphome } // namespace esphome
+4 -1
View File
@@ -40,6 +40,9 @@ class GoldenMateProtocol : public UpsProtocolBase {
static const uint8_t REPORT_ID_STATUS = 0x01; static const uint8_t REPORT_ID_STATUS = 0x01;
static const uint8_t REPORT_ID_MEGATEC = 0x0C; static const uint8_t REPORT_ID_MEGATEC = 0x0C;
bool is_full_ = true;
int below_100_count_ = 0;
struct HidReport { struct HidReport {
uint8_t report_id; uint8_t report_id;
std::vector<uint8_t> data; std::vector<uint8_t> data;
@@ -52,4 +55,4 @@ class GoldenMateProtocol : public UpsProtocolBase {
}; };
} // namespace ups_hid } // namespace ups_hid
} // namespace esphome } // namespace esphome