Public Access
feat: keep known vendor in sync across tooling and framework
Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
10 files changed
+505
-75
No files matched your search
@@ -1,3 +1,5 @@
|
||||
"""NUT UPS Component for ESPHome - Enhanced validation and configuration."""
|
||||
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
@@ -15,20 +17,76 @@ CONF_PROTOCOL_TIMEOUT = "protocol_timeout"
|
||||
CONF_AUTO_DETECT_PROTOCOL = "auto_detect_protocol"
|
||||
CONF_NUT_UPS_ID = "nut_ups_id"
|
||||
|
||||
# Known UPS vendor IDs for validation
|
||||
KNOWN_VENDOR_IDS = {
|
||||
0x0001: "Fiskars",
|
||||
0x0463: "MGE Office Protection Systems",
|
||||
0x051D: "APC",
|
||||
0x0665: "Cypress/Other",
|
||||
0x06DA: "Phoenixtec Power",
|
||||
0x0764: "CyberPower",
|
||||
0x09AE: "Tripp Lite",
|
||||
}
|
||||
|
||||
nut_ups_ns = cg.esphome_ns.namespace("nut_ups")
|
||||
NutUpsComponent = nut_ups_ns.class_("NutUpsComponent", cg.PollingComponent)
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
|
||||
def validate_usb_config(config):
|
||||
"""Validate USB configuration with helpful warnings."""
|
||||
vendor_id = config.get(CONF_USB_VENDOR_ID, 0x051D)
|
||||
product_id = config.get(CONF_USB_PRODUCT_ID, 0x0002)
|
||||
|
||||
# Validate non-zero IDs
|
||||
if vendor_id == 0 or product_id == 0:
|
||||
raise cv.Invalid("USB vendor and product IDs must be non-zero")
|
||||
|
||||
# Warn about unknown vendor IDs
|
||||
if vendor_id not in KNOWN_VENDOR_IDS:
|
||||
raise cv.Invalid("Unknown vendor id")
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def validate_protocol_timeout(value):
|
||||
"""Validate protocol timeout with reasonable bounds."""
|
||||
value = cv.positive_time_period_milliseconds(value)
|
||||
ms = value.total_milliseconds
|
||||
|
||||
if ms < 5000:
|
||||
raise cv.Invalid("Protocol timeout must be at least 5 seconds for reliable communication")
|
||||
if ms > 60000:
|
||||
raise cv.Invalid("Protocol timeout must be at most 60 seconds to avoid blocking")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def validate_update_interval(value):
|
||||
"""Validate update interval for UPS monitoring."""
|
||||
value = cv.update_interval(value)
|
||||
ms = value.total_milliseconds
|
||||
|
||||
if ms < 5000:
|
||||
cg.global_ns.logger.LOGGER.warning(
|
||||
"Update interval less than 5 seconds may cause excessive USB traffic. "
|
||||
"Consider using 10s or higher for production."
|
||||
)
|
||||
|
||||
return value
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema({
|
||||
cv.GenerateID(): cv.declare_id(NutUpsComponent),
|
||||
cv.Optional(CONF_UPDATE_INTERVAL, default="30s"): cv.update_interval,
|
||||
cv.Optional(CONF_UPDATE_INTERVAL, default="30s"): validate_update_interval,
|
||||
cv.Optional(CONF_SIMULATION_MODE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_USB_VENDOR_ID, default=0x051D): cv.hex_uint16_t,
|
||||
cv.Optional(CONF_USB_PRODUCT_ID, default=0x0002): cv.hex_uint16_t,
|
||||
cv.Optional(CONF_PROTOCOL_TIMEOUT, default="10s"): cv.positive_time_period_milliseconds,
|
||||
cv.Optional(CONF_PROTOCOL_TIMEOUT, default="15s"): validate_protocol_timeout,
|
||||
cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean,
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA)
|
||||
}).extend(cv.COMPONENT_SCHEMA),
|
||||
validate_usb_config
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "nut_ups.h"
|
||||
#include "ups_vendors.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/application.h"
|
||||
|
||||
@@ -193,30 +194,62 @@ bool NutUpsComponent::detect_ups_protocol() {
|
||||
|
||||
bool NutUpsComponent::read_ups_data() {
|
||||
if (!active_protocol_) {
|
||||
ESP_LOGW(TAG, "No active protocol available for reading data");
|
||||
return false;
|
||||
}
|
||||
|
||||
return active_protocol_->read_data(ups_data_);
|
||||
// Create temporary data structure to avoid corrupting existing data on failure
|
||||
UpsData temp_data = ups_data_;
|
||||
|
||||
if (active_protocol_->read_data(temp_data)) {
|
||||
// Only update if we got valid data
|
||||
if (temp_data.is_valid()) {
|
||||
ups_data_ = temp_data;
|
||||
return true;
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Protocol returned invalid data");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "Failed to read data from protocol: %s", active_protocol_->get_protocol_name().c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
void NutUpsComponent::update_sensors() {
|
||||
// Update numeric sensors
|
||||
for (auto &pair : sensors_) {
|
||||
const std::string &type = pair.first;
|
||||
auto *sensor = pair.second;
|
||||
// Update numeric sensors with validation
|
||||
for (const auto &[type, sensor] : sensors_) {
|
||||
if (!sensor) continue; // Safety check
|
||||
|
||||
if (type == "battery_level" && !std::isnan(ups_data_.battery_level)) {
|
||||
sensor->publish_state(ups_data_.battery_level);
|
||||
} else if (type == "input_voltage" && !std::isnan(ups_data_.input_voltage)) {
|
||||
sensor->publish_state(ups_data_.input_voltage);
|
||||
} else if (type == "output_voltage" && !std::isnan(ups_data_.output_voltage)) {
|
||||
sensor->publish_state(ups_data_.output_voltage);
|
||||
} else if (type == "load_percent" && !std::isnan(ups_data_.load_percent)) {
|
||||
sensor->publish_state(ups_data_.load_percent);
|
||||
} else if (type == "runtime" && !std::isnan(ups_data_.runtime_minutes)) {
|
||||
sensor->publish_state(ups_data_.runtime_minutes);
|
||||
} else if (type == "frequency" && !std::isnan(ups_data_.frequency)) {
|
||||
sensor->publish_state(ups_data_.frequency);
|
||||
float value = NAN;
|
||||
|
||||
if (type == "battery_level") {
|
||||
value = ups_data_.battery_level;
|
||||
} else if (type == "input_voltage") {
|
||||
value = ups_data_.input_voltage;
|
||||
} else if (type == "output_voltage") {
|
||||
value = ups_data_.output_voltage;
|
||||
} else if (type == "load_percent") {
|
||||
value = ups_data_.load_percent;
|
||||
} else if (type == "runtime") {
|
||||
value = ups_data_.runtime_minutes;
|
||||
} else if (type == "frequency") {
|
||||
value = ups_data_.frequency;
|
||||
}
|
||||
|
||||
// Only publish if value is valid and within reasonable bounds
|
||||
if (!std::isnan(value)) {
|
||||
// Add bounds checking for safety
|
||||
if (type == "battery_level" && (value < 0.0f || value > 100.0f)) {
|
||||
ESP_LOGW(TAG, "Battery level out of bounds: %.1f%%", value);
|
||||
continue;
|
||||
}
|
||||
if (type == "load_percent" && (value < 0.0f || value > 100.0f)) {
|
||||
ESP_LOGW(TAG, "Load percentage out of bounds: %.1f%%", value);
|
||||
continue;
|
||||
}
|
||||
|
||||
sensor->publish_state(value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -523,37 +556,29 @@ esp_err_t NutUpsComponent::usb_device_enumerate() {
|
||||
}
|
||||
|
||||
bool NutUpsComponent::usb_is_ups_device(const usb_device_desc_t *desc) {
|
||||
// Check if this is a known UPS device
|
||||
// Common UPS vendors: APC (0x051D), CyberPower (0x0764), Tripp Lite (0x09AE)
|
||||
uint16_t vid = desc->idVendor;
|
||||
uint16_t pid = desc->idProduct;
|
||||
|
||||
ESP_LOGV(TAG, "Checking device: VID=0x%04X, PID=0x%04X", vid, pid);
|
||||
|
||||
// Check configured VID/PID first
|
||||
// Check configured VID/PID first (highest priority)
|
||||
if (vid == usb_vendor_id_ && pid == usb_product_id_) {
|
||||
ESP_LOGD(TAG, "Device matches configured VID/PID");
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check known UPS vendor IDs
|
||||
switch (vid) {
|
||||
case 0x051D: // APC
|
||||
case 0x0764: // CyberPower
|
||||
case 0x09AE: // Tripp Lite
|
||||
case 0x06DA: // MGE UPS Systems
|
||||
case 0x0665: // Cypress (some UPS devices)
|
||||
ESP_LOGD(TAG, "Recognized UPS vendor: 0x%04X", vid);
|
||||
return true;
|
||||
default:
|
||||
break;
|
||||
// Check against known UPS vendor list
|
||||
if (is_known_ups_vendor(vid)) {
|
||||
const char* vendor_name = get_ups_vendor_name(vid);
|
||||
ESP_LOGD(TAG, "Recognized UPS vendor: %s (0x%04X)", vendor_name, vid);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check device class (some UPS devices use HID class)
|
||||
if (desc->bDeviceClass == USB_CLASS_HID ||
|
||||
(desc->bDeviceClass == 0 && desc->bDeviceSubClass == 0)) {
|
||||
ESP_LOGV(TAG, "Device might be HID-compatible UPS");
|
||||
return true; // Could be a HID UPS
|
||||
ESP_LOGV(TAG, "Device might be HID-compatible UPS (unknown vendor)");
|
||||
return true; // Could be a HID UPS from unknown vendor
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -651,16 +676,26 @@ esp_err_t NutUpsComponent::usb_transfer_sync(const std::vector<uint8_t> &data_ou
|
||||
std::vector<uint8_t> &data_in,
|
||||
uint32_t timeout_ms) {
|
||||
if (!device_connected_ || !usb_device_.dev_hdl) {
|
||||
ESP_LOGW(TAG, "USB device not connected for transfer");
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
// Validate timeout
|
||||
timeout_ms = std::clamp(timeout_ms, static_cast<uint32_t>(100), static_cast<uint32_t>(30000)); // 100ms to 30s
|
||||
|
||||
esp_err_t ret = ESP_OK;
|
||||
|
||||
// Send data if provided
|
||||
if (!data_out.empty() && usb_device_.ep_out != 0) {
|
||||
usb_transfer_t *transfer_out;
|
||||
if (data_out.size() > usb_device_.max_packet_size * 4) { // Reasonable size check
|
||||
ESP_LOGW(TAG, "Output data too large: %zu bytes", data_out.size());
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
|
||||
usb_transfer_t *transfer_out = nullptr;
|
||||
ret = usb_host_transfer_alloc(data_out.size(), 0, &transfer_out);
|
||||
if (ret != ESP_OK) {
|
||||
if (ret != ESP_OK || !transfer_out) {
|
||||
ESP_LOGE(TAG, "Failed to allocate OUT transfer: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -673,8 +708,9 @@ esp_err_t NutUpsComponent::usb_transfer_sync(const std::vector<uint8_t> &data_ou
|
||||
|
||||
ret = usb_host_transfer_submit(transfer_out);
|
||||
if (ret == ESP_OK) {
|
||||
// Wait for completion
|
||||
vTaskDelay(pdMS_TO_TICKS(timeout_ms));
|
||||
vTaskDelay(pdMS_TO_TICKS(std::min(timeout_ms, static_cast<uint32_t>(1000)))); // Max 1s for OUT
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Failed to submit OUT transfer: %s", esp_err_to_name(ret));
|
||||
}
|
||||
|
||||
usb_host_transfer_free(transfer_out);
|
||||
@@ -685,10 +721,13 @@ esp_err_t NutUpsComponent::usb_transfer_sync(const std::vector<uint8_t> &data_ou
|
||||
|
||||
// Read data if IN endpoint exists
|
||||
if (usb_device_.ep_in != 0) {
|
||||
usb_transfer_t *transfer_in;
|
||||
size_t buffer_size = std::max(static_cast<size_t>(64), static_cast<size_t>(usb_device_.max_packet_size));
|
||||
buffer_size = std::min(buffer_size, static_cast<size_t>(1024)); // Cap at 1KB
|
||||
|
||||
usb_transfer_t *transfer_in = nullptr;
|
||||
ret = usb_host_transfer_alloc(buffer_size, 0, &transfer_in);
|
||||
if (ret != ESP_OK) {
|
||||
if (ret != ESP_OK || !transfer_in) {
|
||||
ESP_LOGE(TAG, "Failed to allocate IN transfer: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -700,14 +739,21 @@ esp_err_t NutUpsComponent::usb_transfer_sync(const std::vector<uint8_t> &data_ou
|
||||
|
||||
ret = usb_host_transfer_submit(transfer_in);
|
||||
if (ret == ESP_OK) {
|
||||
// Wait for completion
|
||||
vTaskDelay(pdMS_TO_TICKS(timeout_ms));
|
||||
|
||||
// Copy received data
|
||||
if (transfer_in->actual_num_bytes > 0) {
|
||||
// Copy received data with bounds checking
|
||||
if (transfer_in->actual_num_bytes > 0 &&
|
||||
transfer_in->actual_num_bytes <= buffer_size) {
|
||||
data_in.resize(transfer_in->actual_num_bytes);
|
||||
std::memcpy(data_in.data(), transfer_in->data_buffer, transfer_in->actual_num_bytes);
|
||||
ESP_LOGV(TAG, "USB IN transfer received %d bytes", transfer_in->actual_num_bytes);
|
||||
} else if (transfer_in->actual_num_bytes > buffer_size) {
|
||||
ESP_LOGW(TAG, "USB IN transfer size mismatch: %d > %zu",
|
||||
transfer_in->actual_num_bytes, buffer_size);
|
||||
ret = ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Failed to submit IN transfer: %s", esp_err_to_name(ret));
|
||||
}
|
||||
|
||||
usb_host_transfer_free(transfer_in);
|
||||
|
||||
@@ -60,21 +60,43 @@ namespace esphome
|
||||
PROTOCOL_GENERIC_HID
|
||||
};
|
||||
|
||||
// UPS data structure
|
||||
// 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;
|
||||
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};
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -104,11 +126,17 @@ namespace esphome
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override { return setup_priority::DATA; }
|
||||
|
||||
// Configuration setters
|
||||
// Configuration setters with validation
|
||||
void set_simulation_mode(bool simulation_mode) { simulation_mode_ = simulation_mode; }
|
||||
void set_usb_vendor_id(uint16_t vendor_id) { usb_vendor_id_ = vendor_id; }
|
||||
void set_usb_product_id(uint16_t product_id) { usb_product_id_ = product_id; }
|
||||
void set_protocol_timeout(uint32_t timeout_ms) { protocol_timeout_ms_ = timeout_ms; }
|
||||
void set_usb_vendor_id(uint16_t vendor_id) {
|
||||
if (vendor_id != 0) usb_vendor_id_ = vendor_id;
|
||||
}
|
||||
void set_usb_product_id(uint16_t product_id) {
|
||||
if (product_id != 0) usb_product_id_ = product_id;
|
||||
}
|
||||
void set_protocol_timeout(uint32_t timeout_ms) {
|
||||
protocol_timeout_ms_ = std::max(timeout_ms, static_cast<uint32_t>(5000)); // Min 5 seconds
|
||||
}
|
||||
void set_auto_detect_protocol(bool auto_detect) { auto_detect_protocol_ = auto_detect; }
|
||||
|
||||
// Data getters for sensors
|
||||
@@ -178,7 +206,6 @@ namespace esphome
|
||||
void usb_deinit();
|
||||
esp_err_t usb_host_lib_init();
|
||||
esp_err_t usb_client_register();
|
||||
esp_err_t usb_device_open();
|
||||
esp_err_t usb_device_enumerate();
|
||||
bool usb_is_ups_device(const usb_device_desc_t *desc);
|
||||
esp_err_t usb_claim_interface();
|
||||
|
||||
@@ -2,7 +2,6 @@ import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.components import sensor
|
||||
from esphome.const import (
|
||||
CONF_ID,
|
||||
CONF_TYPE,
|
||||
DEVICE_CLASS_BATTERY,
|
||||
DEVICE_CLASS_VOLTAGE,
|
||||
|
||||
@@ -2,7 +2,6 @@ import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.components import text_sensor
|
||||
from esphome.const import (
|
||||
CONF_ID,
|
||||
CONF_TYPE,
|
||||
)
|
||||
|
||||
@@ -14,7 +13,7 @@ NutUpsTextSensor = nut_ups_ns.class_("NutUpsTextSensor", text_sensor.TextSensor,
|
||||
|
||||
TEXT_SENSOR_TYPES = [
|
||||
"model",
|
||||
"manufacturer",
|
||||
"manufacturer",
|
||||
"status",
|
||||
"protocol",
|
||||
"serial_number",
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* @file ups_vendors.h
|
||||
* @brief Known UPS vendor IDs for device identification and validation
|
||||
*
|
||||
* This file contains the definitive list of known UPS vendor IDs
|
||||
* shared between C++ runtime code and Python configuration validation.
|
||||
*/
|
||||
|
||||
namespace esphome {
|
||||
namespace nut_ups {
|
||||
|
||||
// Known UPS vendor IDs with their names
|
||||
struct UpsVendor {
|
||||
uint16_t vendor_id;
|
||||
const char* name;
|
||||
const char* description;
|
||||
};
|
||||
|
||||
// Definitive list of known UPS vendors
|
||||
static constexpr UpsVendor KNOWN_UPS_VENDORS[] = {
|
||||
{0x051D, "APC", "American Power Conversion"},
|
||||
{0x0764, "CyberPower", "CyberPower Systems"},
|
||||
{0x09AE, "Tripp Lite", "Tripp Lite"},
|
||||
{0x06DA, "MGE UPS Systems", "MGE UPS Systems (now Eaton)"},
|
||||
{0x0665, "Cypress/Other", "Cypress or other UPS devices"},
|
||||
{0x0463, "MGE Office Protection Systems", "MGE Office Protection Systems"},
|
||||
{0x06da, "Phoenixtec Power", "Phoenixtec Power Co., Ltd."},
|
||||
{0x0001, "Fiskars", "Fiskars Corporation (some UPS models)"},
|
||||
};
|
||||
|
||||
static constexpr size_t KNOWN_UPS_VENDORS_COUNT = sizeof(KNOWN_UPS_VENDORS) / sizeof(KNOWN_UPS_VENDORS[0]);
|
||||
|
||||
/**
|
||||
* Check if a vendor ID is in the known UPS vendors list
|
||||
* @param vendor_id The USB vendor ID to check
|
||||
* @return True if vendor ID is known, false otherwise
|
||||
*/
|
||||
inline bool is_known_ups_vendor(uint16_t vendor_id) {
|
||||
for (size_t i = 0; i < KNOWN_UPS_VENDORS_COUNT; i++) {
|
||||
if (KNOWN_UPS_VENDORS[i].vendor_id == vendor_id) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get vendor name for a given vendor ID
|
||||
* @param vendor_id The USB vendor ID
|
||||
* @return Vendor name or nullptr if unknown
|
||||
*/
|
||||
inline const char* get_ups_vendor_name(uint16_t vendor_id) {
|
||||
for (size_t i = 0; i < KNOWN_UPS_VENDORS_COUNT; i++) {
|
||||
if (KNOWN_UPS_VENDORS[i].vendor_id == vendor_id) {
|
||||
return KNOWN_UPS_VENDORS[i].name;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace nut_ups
|
||||
} // namespace esphome
|
||||
Reference in new issue
Block a user