Public Access
refactor(ups-hid): remove unused UpsVendor class
Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
7 files changed
+101
-368
No files matched your search
@@ -1181,8 +1181,7 @@ A: Yes, beeper settings are stored in the UPS device's NVRAM and persist across
|
||||
|
||||
1. Inherit from `UpsProtocolBase`
|
||||
2. Implement required methods: `detect()`, `initialize()`, `read_data()`
|
||||
3. Add to protocol detection in `detect_ups_protocol()`
|
||||
4. Update vendor ID mapping in `ups_vendors.h`
|
||||
3. Register protocol using `REGISTER_UPS_PROTOCOL_FOR_VENDOR()` macro
|
||||
|
||||
### Testing
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#include "ups_hid.h"
|
||||
#include "ups_constants.h"
|
||||
#include "ups_vendors.h"
|
||||
#include "usb_transport_factory.h"
|
||||
#include "simulated_transport.h"
|
||||
#ifdef USE_ESP32
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
#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 ups_hid
|
||||
{
|
||||
|
||||
// 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 (based on NUT project HID driver support)
|
||||
static constexpr UpsVendor KNOWN_UPS_VENDORS[] = {
|
||||
// Vendors with dedicated HID drivers and ESPHome implementations
|
||||
{0x051D, "APC", "American Power Conversion (dedicated ESPHome protocol)"},
|
||||
{0x0764, "CyberPower", "CyberPower Systems (dedicated ESPHome protocol)"},
|
||||
|
||||
// Vendors with dedicated NUT HID drivers (Generic HID protocol support)
|
||||
{0x0463, "MGE Office Protection Systems", "MGE Office Protection Systems (Eaton)"},
|
||||
{0x047C, "Dell", "Dell UPS devices (via MGE HID driver)"},
|
||||
{0x04B3, "IBM", "IBM UPS devices (via MGE HID driver)"},
|
||||
{0x04D8, "OpenUPS", "OpenUPS HID devices"},
|
||||
{0x050D, "Belkin", "Belkin USB UPS models"},
|
||||
{0x0592, "Powerware", "Powerware UPS devices (via MGE HID driver)"},
|
||||
{0x05DD, "Delta Electronics", "Delta UPS devices (Tripp Lite OEM)"},
|
||||
{0x06DA, "MGE UPS Systems", "MGE UPS Systems / Liebert / Phoenixtec (now Eaton)"},
|
||||
{0x075D, "Idowell", "Idowell HID UPS devices"},
|
||||
{0x09AE, "Tripp Lite", "Tripp Lite UPS devices"},
|
||||
{0x09D6, "KSTAR", "KSTAR/Micropower UPS devices"},
|
||||
|
||||
// STMicroelectronics OEM vendor (used by multiple UPS manufacturers)
|
||||
{0x0483, "STMicroelectronics", "STMicro OEM UPS devices (CPS, Ever, others)"},
|
||||
};
|
||||
|
||||
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 ups_hid
|
||||
} // namespace esphome
|
||||
+15
-63
@@ -1,6 +1,6 @@
|
||||
# Development Tools
|
||||
|
||||
This folder contains development tools for ESP32 ESPHome component development, including debugging utilities and vendor management tools.
|
||||
This folder contains development tools for ESP32 ESPHome component development and debugging utilities.
|
||||
|
||||
## USB Device Management
|
||||
|
||||
@@ -8,73 +8,25 @@ This folder contains development tools for ESP32 ESPHome component development,
|
||||
|
||||
Lists ESP32, UPS, and related USB devices connected to the system. Useful for identifying device paths and vendor/product IDs during development.
|
||||
|
||||
## generate_vendor_list.py
|
||||
## Protocol Development
|
||||
|
||||
This script keeps the UPS vendor ID lists synchronized between C++, scripts and Python code.
|
||||
The UPS HID component uses a modern self-registering protocol system. New protocols automatically register themselves using macros:
|
||||
|
||||
### Purpose
|
||||
### Adding New Vendor-Specific Protocols
|
||||
|
||||
The UPS HID component maintains a list of known UPS vendor IDs in two places:
|
||||
|
||||
- `components/ups_hid/ups_vendors.h` (C++ runtime code)
|
||||
- `components/ups_hid/__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/ups_hid/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/ups_hid/ups_vendors.h...
|
||||
Found 7 vendors
|
||||
Updated /workspace/components/ups_hid/__init__.py
|
||||
```
|
||||
|
||||
## Adding New Vendors
|
||||
|
||||
To add a new UPS vendor:
|
||||
|
||||
1. Edit `components/ups_hid/ups_vendors.h`
|
||||
2. Add a new entry to the `KNOWN_UPS_VENDORS` array:
|
||||
1. Create a new protocol class inheriting from `UpsProtocolBase`
|
||||
2. Implement required methods: `detect()`, `initialize()`, `read_data()`
|
||||
3. Register the protocol using the registration macro:
|
||||
|
||||
```cpp
|
||||
{0x1234, "New Vendor", "New Vendor Description"},
|
||||
// At the end of your protocol .cpp file
|
||||
REGISTER_UPS_PROTOCOL_FOR_VENDOR(0x1234, my_protocol,
|
||||
esphome::ups_hid::create_my_protocol,
|
||||
"My Protocol Name",
|
||||
"Description of my protocol",
|
||||
100); // Priority
|
||||
```
|
||||
|
||||
3. Run the generate_vendor_list.py script to update the Python file
|
||||
4. Compile and test the component
|
||||
### Universal Compatibility
|
||||
|
||||
The script automatically maintains alphabetical ordering by vendor ID.
|
||||
All unknown UPS vendors automatically use the Generic HID protocol as a fallback, providing basic monitoring capabilities without requiring vendor-specific code. This ensures broad compatibility with minimal maintenance.
|
||||
@@ -1,217 +0,0 @@
|
||||
#!/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
|
||||
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:
|
||||
lines = f.readlines()
|
||||
|
||||
# Find and parse only uncommented entries in KNOWN_UPS_VENDORS array
|
||||
pattern = r'\{0x([0-9A-Fa-f]+),\s*"([^"]+)",\s*"([^"]+)"\}'
|
||||
|
||||
for line in lines:
|
||||
# Skip commented lines (starting with // or /* or whitespace + //)
|
||||
stripped_line = line.strip()
|
||||
if stripped_line.startswith('//') or stripped_line.startswith('/*'):
|
||||
continue
|
||||
|
||||
# Look for vendor entries in uncommented lines only
|
||||
match = re.search(pattern, line)
|
||||
if match:
|
||||
vendor_id_str, name, description = match.groups()
|
||||
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)
|
||||
|
||||
# @TODO: reload udev if possible
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def update_scan_usb_vendors(scan_usb_path, vendors):
|
||||
"""Update vendor list in scan-usb.sh file."""
|
||||
if not scan_usb_path.exists():
|
||||
print(f"Warning: {scan_usb_path} not found!")
|
||||
return False
|
||||
|
||||
with open(scan_usb_path, "r") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
# Generate the vendor ID pattern for grep
|
||||
vendor_ids = [f"{vid:04x}" for vid in sorted(vendors.keys())]
|
||||
vendor_pattern = "|".join(vendor_ids)
|
||||
|
||||
# Find and replace the UPS devices grep line
|
||||
new_line = f'lsusb | grep -iE "({vendor_pattern})" || echo "No UPS devices found"\n'
|
||||
|
||||
# Find the line that contains the UPS vendor grep pattern
|
||||
found_line = False
|
||||
for i, line in enumerate(lines):
|
||||
# Look for the line after "UPS devices:" that contains lsusb | grep -iE
|
||||
if (i > 0 and
|
||||
"UPS devices:" in lines[i-1] and
|
||||
line.strip().startswith("lsusb | grep -iE") and
|
||||
"UPS devices found" in line):
|
||||
lines[i] = new_line
|
||||
found_line = True
|
||||
break
|
||||
|
||||
if found_line:
|
||||
with open(scan_usb_path, "w") as f:
|
||||
f.writelines(lines)
|
||||
return True
|
||||
else:
|
||||
print(f"Warning: Could not find UPS devices grep line in {scan_usb_path}")
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
"""Update __init__.py, setup.sh, and scan-usb.sh with vendor list."""
|
||||
script_dir = Path(__file__).parent
|
||||
component_dir = script_dir.parent / "components" / "ups_hid"
|
||||
header_path = component_dir / "ups_vendors.h"
|
||||
init_path = component_dir / "__init__.py"
|
||||
setup_path = script_dir.parent / ".devcontainer" / "setup.sh"
|
||||
scan_usb_path = script_dir / "scan-usb.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}")
|
||||
esp_rules = len([r for r in udev_rules if 'UPS' not in r])
|
||||
print(f" Added {esp_rules} standard + {len(vendors)} UPS vendor rules")
|
||||
|
||||
# Update scan-usb.sh vendor list
|
||||
if update_scan_usb_vendors(scan_usb_path, vendors):
|
||||
print(f"✅ Updated vendor list in {scan_usb_path}")
|
||||
print(f" UPS vendor pattern: ({len(vendors)} vendors)")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit(main())
|
||||
+1
-1
@@ -7,7 +7,7 @@ echo ""
|
||||
echo "ESP32 boards:"
|
||||
lsusb | grep -iE "(303a|10c4|1a86)" || echo "No ESP32 boards found"
|
||||
echo ""
|
||||
# Auto-generated from ups_vendors.h
|
||||
# Known UPS vendor IDs for debugging
|
||||
echo "UPS devices:"
|
||||
lsusb | grep -iE "(0463|047c|0483|04b3|04d8|050d|051d|0592|05dd|06da|075d|0764|09ae|09d6)" || echo "No UPS devices found"
|
||||
echo ""
|
||||
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script to generate version string with git hash
|
||||
# Usage: ./version.sh
|
||||
|
||||
set -euo pipefail # Exit on error, undefined vars, pipe failures
|
||||
|
||||
# Configuration
|
||||
readonly VERSION_BASE="0.0.0"
|
||||
readonly SCRIPT_NAME="$(basename "$0")"
|
||||
|
||||
# Function to get git hash
|
||||
get_git_hash() {
|
||||
local git_hash
|
||||
|
||||
# Check if we're in a git repository
|
||||
if ! git rev-parse --git-dir >/dev/null 2>&1; then
|
||||
echo "Error: Not in a git repository" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Get short git hash (7 characters)
|
||||
if ! git_hash=$(git rev-parse --short HEAD 2>/dev/null); then
|
||||
echo "Error: Failed to get git hash" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "$git_hash"
|
||||
}
|
||||
|
||||
# Function to generate version string
|
||||
generate_version() {
|
||||
local git_hash
|
||||
|
||||
if git_hash=$(get_git_hash); then
|
||||
echo "${VERSION_BASE}-${git_hash}"
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to display usage
|
||||
usage() {
|
||||
cat << EOF
|
||||
Usage: $SCRIPT_NAME [OPTIONS]
|
||||
|
||||
Generate a version string in format: $VERSION_BASE-<git_hash>
|
||||
|
||||
OPTIONS:
|
||||
-h, --help Show this help message
|
||||
|
||||
EXAMPLES:
|
||||
$SCRIPT_NAME # Output: 0.0.0-a1b2c3d
|
||||
EOF
|
||||
}
|
||||
|
||||
# Main function
|
||||
main() {
|
||||
# Parse command line arguments
|
||||
case "${1:-}" in
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
"")
|
||||
# No arguments - proceed with version generation
|
||||
;;
|
||||
*)
|
||||
echo "Error: Unknown option '$1'" >&2
|
||||
usage >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# Generate and output version string
|
||||
if ! generate_version; then
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Only run main if script is executed directly (not sourced)
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
||||
Reference in new issue
Block a user