From b86ab2bb2f5cf69ff76dabed28d36b4e4305a580 Mon Sep 17 00:00:00 2001 From: bullshit Date: Thu, 7 Aug 2025 00:39:09 +0200 Subject: [PATCH] feat: keep known vendor in sync across tooling and framework Signed-off-by: bullshit --- .devcontainer/setup.sh | 15 ++- components/nut_ups/__init__.py | 70 +++++++++++-- components/nut_ups/nut_ups.cpp | 130 +++++++++++++++++-------- components/nut_ups/nut_ups.h | 63 ++++++++---- components/nut_ups/sensor.py | 1 - components/nut_ups/text_sensor.py | 3 +- components/nut_ups/ups_vendors.h | 64 ++++++++++++ tools/README.md | 71 ++++++++++++++ tools/generate_vendor_list.py | 157 ++++++++++++++++++++++++++++++ tools/scan-usb.sh | 6 +- 10 files changed, 505 insertions(+), 75 deletions(-) create mode 100644 components/nut_ups/ups_vendors.h create mode 100644 tools/README.md create mode 100644 tools/generate_vendor_list.py diff --git a/.devcontainer/setup.sh b/.devcontainer/setup.sh index af1f345..da5d9cd 100755 --- a/.devcontainer/setup.sh +++ b/.devcontainer/setup.sh @@ -20,9 +20,14 @@ cat > /etc/udev/rules.d/99-esphome-usb.rules << 'UDEV_EOF' SUBSYSTEM=="usb", ATTR{idVendor}=="303a", MODE="0666" SUBSYSTEM=="usb", ATTR{idVendor}=="10c4", MODE="0666" SUBSYSTEM=="usb", ATTR{idVendor}=="1a86", MODE="0666" -SUBSYSTEM=="usb", ATTR{idVendor}=="051d", MODE="0666" -SUBSYSTEM=="usb", ATTR{idVendor}=="0764", MODE="0666" SUBSYSTEM=="usb", ATTR{idVendor}=="0403", MODE="0666" +SUBSYSTEM=="usb", ATTR{idVendor}=="0001", MODE="0666" +SUBSYSTEM=="usb", ATTR{idVendor}=="0463", MODE="0666" +SUBSYSTEM=="usb", ATTR{idVendor}=="051d", MODE="0666" +SUBSYSTEM=="usb", ATTR{idVendor}=="0665", MODE="0666" +SUBSYSTEM=="usb", ATTR{idVendor}=="06da", MODE="0666" +SUBSYSTEM=="usb", ATTR{idVendor}=="0764", MODE="0666" +SUBSYSTEM=="usb", ATTR{idVendor}=="09ae", MODE="0666" UDEV_EOF # Create aliases @@ -34,9 +39,9 @@ alias esphome-logs='esphome logs' alias esphome-dashboard='esphome dashboard /workspace' alias lsusb='lsusb -v' alias serialports='ls -la /dev/tty{USB,ACM}* 2>/dev/null || echo "No serial ports found"' -alias build-component='cd /workspace && esphome compile configs/test-config.yaml' -alias flash-test='cd /workspace && esphome upload configs/test-config.yaml' -alias monitor='cd /workspace && esphome logs configs/test-config.yaml' +alias build-component='cd /workspace && esphome compile full-test.yaml' +alias flash-test='cd /workspace && esphome upload full-test.yaml' +alias monitor='cd /workspace && esphome logs full-test.yaml' BASH_EOF # Welcome message diff --git a/components/nut_ups/__init__.py b/components/nut_ups/__init__.py index 05e44db..3c051a4 100644 --- a/components/nut_ups/__init__.py +++ b/components/nut_ups/__init__.py @@ -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): diff --git a/components/nut_ups/nut_ups.cpp b/components/nut_ups/nut_ups.cpp index 5332fb1..c9949f9 100644 --- a/components/nut_ups/nut_ups.cpp +++ b/components/nut_ups/nut_ups.cpp @@ -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 &data_ou std::vector &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(100), static_cast(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 &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(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 &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(64), static_cast(usb_device_.max_packet_size)); + buffer_size = std::min(buffer_size, static_cast(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 &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); diff --git a/components/nut_ups/nut_ups.h b/components/nut_ups/nut_ups.h index 2a36988..2077fa9 100644 --- a/components/nut_ups/nut_ups.h +++ b/components/nut_ups/nut_ups.h @@ -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(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(); diff --git a/components/nut_ups/sensor.py b/components/nut_ups/sensor.py index a4b0ca8..563a807 100644 --- a/components/nut_ups/sensor.py +++ b/components/nut_ups/sensor.py @@ -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, diff --git a/components/nut_ups/text_sensor.py b/components/nut_ups/text_sensor.py index 3168d16..0e0bd21 100644 --- a/components/nut_ups/text_sensor.py +++ b/components/nut_ups/text_sensor.py @@ -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", diff --git a/components/nut_ups/ups_vendors.h b/components/nut_ups/ups_vendors.h new file mode 100644 index 0000000..cc8f037 --- /dev/null +++ b/components/nut_ups/ups_vendors.h @@ -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 \ No newline at end of file diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000..dc5a65e --- /dev/null +++ b/tools/README.md @@ -0,0 +1,71 @@ +# Development Tools + +This folder contains development tools for the NUT UPS ESPHome component. + +## scan-usb.sh + +This script lists esp and ups releated usb devices. + +## generate_vendor_list.py + +This script keeps the UPS vendor ID lists synchronized between C++, scripts and Python code. + +### Purpose + +The NUT UPS component maintains a list of known UPS vendor IDs in two places: +- `components/nut_ups/ups_vendors.h` (C++ runtime code) +- `components/nut_ups/__init__.py` (Python configuration validation) + +This script extracts the vendor list from the C++ header file and updates the Python file to ensure they stay in sync. + +### Usage + +#### Command Line +```bash +cd /workspace +python3 tools/generate_vendor_list.py +``` + +#### VSCode Task +1. Open the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`) +2. Type "Tasks: Run Task" +3. Select "Generate UPS Vendor List" + +Or use the keyboard shortcut `Ctrl+Shift+P` -> "Tasks: Run Build Task" and select the vendor list generator. + +### When to Run + +Run this script whenever you: +1. Add new UPS vendor IDs to `components/nut_ups/ups_vendors.h` +2. Modify existing vendor information +3. Want to ensure the C++ and Python lists are synchronized + +### Output + +The script will: +- Parse the C++ header file for vendor definitions +- Extract vendor IDs, names, and descriptions +- Update the `KNOWN_VENDOR_IDS` dictionary in `__init__.py` +- Display the number of vendors processed + +### Example Output + +``` +Parsing vendors from /workspace/components/nut_ups/ups_vendors.h... +Found 7 vendors +Updated /workspace/components/nut_ups/__init__.py +``` + +## Adding New Vendors + +To add a new UPS vendor: + +1. Edit `components/nut_ups/ups_vendors.h` +2. Add a new entry to the `KNOWN_UPS_VENDORS` array: + ```cpp + {0x1234, "New Vendor", "New Vendor Description"}, + ``` +3. Run the generate_vendor_list.py script to update the Python file +4. Compile and test the component + +The script automatically maintains alphabetical ordering by vendor ID. \ No newline at end of file diff --git a/tools/generate_vendor_list.py b/tools/generate_vendor_list.py new file mode 100644 index 0000000..1f4f25c --- /dev/null +++ b/tools/generate_vendor_list.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +""" +Script to extract UPS vendor IDs from ups_vendors.h and generate Python dict. +This ensures the Python configuration validation uses the same vendor list as C++. +""" + +import re +import os +from pathlib import Path + + +def parse_vendor_header(header_path): + """Parse ups_vendors.h and extract vendor information.""" + vendors = {} + + with open(header_path, 'r') as f: + content = f.read() + + # Find the KNOWN_UPS_VENDORS array + pattern = r'\{0x([0-9A-Fa-f]+),\s*"([^"]+)",\s*"([^"]+)"\}' + matches = re.findall(pattern, content) + + for match in matches: + vendor_id_str, name, description = match + vendor_id = int(vendor_id_str, 16) + vendors[vendor_id] = { + 'name': name, + 'description': description + } + + return vendors + + +def generate_python_dict(vendors): + """Generate Python dictionary code.""" + lines = ["# Known UPS vendor IDs for validation", "# Auto-generated from ups_vendors.h", "KNOWN_VENDOR_IDS = {"] + + for vendor_id, info in sorted(vendors.items()): + lines.append(f' 0x{vendor_id:04X}: "{info["name"]}",') + + lines.append("}") + return '\n'.join(lines) + + +def generate_udev_rules(vendors): + """Generate udev rules for UPS vendors.""" + lines = [] + + # Standard ESP development boards (keep existing ones) + standard_vendors = [ + ("303a", "Espressif ESP32-S2/S3"), + ("10c4", "Silicon Labs CP210x"), + ("1a86", "QinHeng Electronics CH340"), + ("0403", "FTDI USB Serial"), + ] + + for vid, desc in standard_vendors: + lines.append(f'SUBSYSTEM=="usb", ATTR{{idVendor}}=="{vid}", MODE="0666"') + + # UPS vendors from header file + for vendor_id, info in sorted(vendors.items()): + vid_hex = f"{vendor_id:04x}" # lowercase for udev + lines.append(f'SUBSYSTEM=="usb", ATTR{{idVendor}}=="{vid_hex}", MODE="0666"') + + return lines + + +def update_udev_rules_in_setup_sh(setup_path, udev_rules): + """Update udev rules in setup.sh file.""" + if not setup_path.exists(): + print(f"Warning: {setup_path} not found!") + return False + + with open(setup_path, 'r') as f: + content = f.read() + + # Find the udev rules section + udev_start = "cat > /etc/udev/rules.d/99-esphome-usb.rules << 'UDEV_EOF'" + udev_end = "UDEV_EOF" + + start_pos = content.find(udev_start) + if start_pos == -1: + print(f"Warning: Could not find udev rules section in {setup_path}") + return False + + end_pos = content.find(udev_end, start_pos + len(udev_start)) + if end_pos == -1: + print(f"Warning: Could not find end of udev rules section in {setup_path}") + return False + + # Build the new udev section + new_udev_section = udev_start + "\n" + for rule in udev_rules: + new_udev_section += rule + "\n" + new_udev_section += udev_end + + # Replace the section + new_content = content[:start_pos] + new_udev_section + content[end_pos + len(udev_end):] + + with open(setup_path, 'w') as f: + f.write(new_content) + + return True + + +def main(): + """Main function to update __init__.py and setup.sh with current vendor list.""" + script_dir = Path(__file__).parent + component_dir = script_dir.parent / "components" / "nut_ups" + header_path = component_dir / "ups_vendors.h" + init_path = component_dir / "__init__.py" + setup_path = script_dir.parent / ".devcontainer" / "setup.sh" + + if not header_path.exists(): + print(f"Error: {header_path} not found!") + return 1 + + print(f"Parsing vendors from {header_path}...") + vendors = parse_vendor_header(header_path) + print(f"Found {len(vendors)} UPS vendors") + + # Generate the Python code + python_code = generate_python_dict(vendors) + + # Update Python __init__.py + if init_path.exists(): + # Read current __init__.py + with open(init_path, 'r') as f: + content = f.read() + + # Replace the KNOWN_VENDOR_IDS section + pattern = r'KNOWN_VENDOR_IDS = \{[^}]*\}' + if re.search(pattern, content, re.DOTALL): + new_content = re.sub(pattern, python_code.split('\n', 2)[2], content, flags=re.DOTALL) + + with open(init_path, 'w') as f: + f.write(new_content) + print(f"✅ Updated {init_path}") + else: + print(f"Warning: Could not find KNOWN_VENDOR_IDS in {init_path}") + print("Generated Python code:") + print(python_code) + else: + print("Generated Python code:") + print(python_code) + + # Generate and update udev rules + udev_rules = generate_udev_rules(vendors) + if update_udev_rules_in_setup_sh(setup_path, udev_rules): + print(f"✅ Updated udev rules in {setup_path}") + print(f" Added {len([r for r in udev_rules if 'UPS' not in r])} standard + {len(vendors)} UPS vendor rules") + + return 0 + + +if __name__ == "__main__": + exit(main()) \ No newline at end of file diff --git a/tools/scan-usb.sh b/tools/scan-usb.sh index 6a2f4d0..b620ce1 100755 --- a/tools/scan-usb.sh +++ b/tools/scan-usb.sh @@ -7,8 +7,12 @@ echo "" echo "ESP32 boards:" lsusb | grep -E "(303a|10c4|1a86)" || echo "No ESP32 boards found" echo "" +# @TODO: update this with generate_vendor_list.py echo "UPS devices:" -lsusb | grep -E "(051d|0764)" || echo "No UPS devices found" +lsusb | grep -E "(051D|0764|09AE|06DA|0665|0463|06da|0001)" || echo "No UPS devices found" echo "" echo "Serial ports:" ls -la /dev/tty{USB,ACM}* 2>/dev/null || echo "No serial ports found" + + + \ No newline at end of file