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
@@ -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.
|
||||
@@ -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())
|
||||
+5
-1
@@ -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"
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user