Public Access
chore: linting and formating python files
Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
5 files changed
+86
-69
No files matched your search
@@ -36,15 +36,15 @@ def validate_usb_config(config):
|
|||||||
"""Validate USB configuration with helpful warnings."""
|
"""Validate USB configuration with helpful warnings."""
|
||||||
vendor_id = config.get(CONF_USB_VENDOR_ID, 0x051D)
|
vendor_id = config.get(CONF_USB_VENDOR_ID, 0x051D)
|
||||||
product_id = config.get(CONF_USB_PRODUCT_ID, 0x0002)
|
product_id = config.get(CONF_USB_PRODUCT_ID, 0x0002)
|
||||||
|
|
||||||
# Validate non-zero IDs
|
# Validate non-zero IDs
|
||||||
if vendor_id == 0 or product_id == 0:
|
if vendor_id == 0 or product_id == 0:
|
||||||
raise cv.Invalid("USB vendor and product IDs must be non-zero")
|
raise cv.Invalid("USB vendor and product IDs must be non-zero")
|
||||||
|
|
||||||
# Warn about unknown vendor IDs
|
# Warn about unknown vendor IDs
|
||||||
if vendor_id not in KNOWN_VENDOR_IDS:
|
if vendor_id not in KNOWN_VENDOR_IDS:
|
||||||
raise cv.Invalid("Unknown vendor id")
|
raise cv.Invalid("Unknown vendor id")
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
@@ -52,12 +52,16 @@ def validate_protocol_timeout(value):
|
|||||||
"""Validate protocol timeout with reasonable bounds."""
|
"""Validate protocol timeout with reasonable bounds."""
|
||||||
value = cv.positive_time_period_milliseconds(value)
|
value = cv.positive_time_period_milliseconds(value)
|
||||||
ms = value.total_milliseconds
|
ms = value.total_milliseconds
|
||||||
|
|
||||||
if ms < 5000:
|
if ms < 5000:
|
||||||
raise cv.Invalid("Protocol timeout must be at least 5 seconds for reliable communication")
|
raise cv.Invalid(
|
||||||
|
"Protocol timeout must be at least 5 seconds for reliable communication"
|
||||||
|
)
|
||||||
if ms > 60000:
|
if ms > 60000:
|
||||||
raise cv.Invalid("Protocol timeout must be at most 60 seconds to avoid blocking")
|
raise cv.Invalid(
|
||||||
|
"Protocol timeout must be at most 60 seconds to avoid blocking"
|
||||||
|
)
|
||||||
|
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
@@ -65,27 +69,31 @@ def validate_update_interval(value):
|
|||||||
"""Validate update interval for UPS monitoring."""
|
"""Validate update interval for UPS monitoring."""
|
||||||
value = cv.update_interval(value)
|
value = cv.update_interval(value)
|
||||||
ms = value.total_milliseconds
|
ms = value.total_milliseconds
|
||||||
|
|
||||||
if ms < 5000:
|
if ms < 5000:
|
||||||
cg.global_ns.logger.LOGGER.warning(
|
cg.global_ns.logger.LOGGER.warning(
|
||||||
"Update interval less than 5 seconds may cause excessive USB traffic. "
|
"Update interval less than 5 seconds may cause excessive USB traffic. "
|
||||||
"Consider using 10s or higher for production."
|
"Consider using 10s or higher for production."
|
||||||
)
|
)
|
||||||
|
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
CONFIG_SCHEMA = cv.All(
|
CONFIG_SCHEMA = cv.All(
|
||||||
cv.Schema({
|
cv.Schema(
|
||||||
cv.GenerateID(): cv.declare_id(NutUpsComponent),
|
{
|
||||||
cv.Optional(CONF_UPDATE_INTERVAL, default="30s"): validate_update_interval,
|
cv.GenerateID(): cv.declare_id(NutUpsComponent),
|
||||||
cv.Optional(CONF_SIMULATION_MODE, default=False): cv.boolean,
|
cv.Optional(CONF_UPDATE_INTERVAL, default="30s"): validate_update_interval,
|
||||||
cv.Optional(CONF_USB_VENDOR_ID, default=0x051D): cv.hex_uint16_t,
|
cv.Optional(CONF_SIMULATION_MODE, default=False): cv.boolean,
|
||||||
cv.Optional(CONF_USB_PRODUCT_ID, default=0x0002): cv.hex_uint16_t,
|
cv.Optional(CONF_USB_VENDOR_ID, default=0x051D): cv.hex_uint16_t,
|
||||||
cv.Optional(CONF_PROTOCOL_TIMEOUT, default="15s"): validate_protocol_timeout,
|
cv.Optional(CONF_USB_PRODUCT_ID, default=0x0002): cv.hex_uint16_t,
|
||||||
cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean,
|
cv.Optional(
|
||||||
}).extend(cv.COMPONENT_SCHEMA),
|
CONF_PROTOCOL_TIMEOUT, default="15s"
|
||||||
validate_usb_config
|
): validate_protocol_timeout,
|
||||||
|
cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean,
|
||||||
|
}
|
||||||
|
).extend(cv.COMPONENT_SCHEMA),
|
||||||
|
validate_usb_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -97,4 +105,4 @@ async def to_code(config):
|
|||||||
cg.add(var.set_usb_vendor_id(config[CONF_USB_VENDOR_ID]))
|
cg.add(var.set_usb_vendor_id(config[CONF_USB_VENDOR_ID]))
|
||||||
cg.add(var.set_usb_product_id(config[CONF_USB_PRODUCT_ID]))
|
cg.add(var.set_usb_product_id(config[CONF_USB_PRODUCT_ID]))
|
||||||
cg.add(var.set_protocol_timeout(config[CONF_PROTOCOL_TIMEOUT]))
|
cg.add(var.set_protocol_timeout(config[CONF_PROTOCOL_TIMEOUT]))
|
||||||
cg.add(var.set_auto_detect_protocol(config[CONF_AUTO_DETECT_PROTOCOL]))
|
cg.add(var.set_auto_detect_protocol(config[CONF_AUTO_DETECT_PROTOCOL]))
|
||||||
@@ -2,7 +2,6 @@ import esphome.codegen as cg
|
|||||||
import esphome.config_validation as cv
|
import esphome.config_validation as cv
|
||||||
from esphome.components import binary_sensor
|
from esphome.components import binary_sensor
|
||||||
from esphome.const import (
|
from esphome.const import (
|
||||||
CONF_ID,
|
|
||||||
CONF_TYPE,
|
CONF_TYPE,
|
||||||
DEVICE_CLASS_CONNECTIVITY,
|
DEVICE_CLASS_CONNECTIVITY,
|
||||||
DEVICE_CLASS_BATTERY,
|
DEVICE_CLASS_BATTERY,
|
||||||
@@ -14,7 +13,9 @@ from . import nut_ups_ns, NutUpsComponent, CONF_NUT_UPS_ID
|
|||||||
|
|
||||||
DEPENDENCIES = ["nut_ups"]
|
DEPENDENCIES = ["nut_ups"]
|
||||||
|
|
||||||
NutUpsBinarySensor = nut_ups_ns.class_("NutUpsBinarySensor", binary_sensor.BinarySensor, cg.Component)
|
NutUpsBinarySensor = nut_ups_ns.class_(
|
||||||
|
"NutUpsBinarySensor", binary_sensor.BinarySensor, cg.Component
|
||||||
|
)
|
||||||
|
|
||||||
BINARY_SENSOR_TYPES = {
|
BINARY_SENSOR_TYPES = {
|
||||||
"online": {
|
"online": {
|
||||||
@@ -61,4 +62,4 @@ async def to_code(config):
|
|||||||
|
|
||||||
# Override config with sensor type defaults if not specified
|
# Override config with sensor type defaults if not specified
|
||||||
if "device_class" not in config and "device_class" in sensor_config:
|
if "device_class" not in config and "device_class" in sensor_config:
|
||||||
cg.add(var.set_device_class(sensor_config["device_class"]))
|
cg.add(var.set_device_class(sensor_config["device_class"]))
|
||||||
@@ -94,4 +94,4 @@ async def to_code(config):
|
|||||||
cg.add(var.set_state_class(sensor_config["state_class"]))
|
cg.add(var.set_state_class(sensor_config["state_class"]))
|
||||||
|
|
||||||
if "accuracy_decimals" not in config and "accuracy_decimals" in sensor_config:
|
if "accuracy_decimals" not in config and "accuracy_decimals" in sensor_config:
|
||||||
cg.add(var.set_accuracy_decimals(sensor_config["accuracy_decimals"]))
|
cg.add(var.set_accuracy_decimals(sensor_config["accuracy_decimals"]))
|
||||||
@@ -9,7 +9,9 @@ from . import nut_ups_ns, NutUpsComponent, CONF_NUT_UPS_ID
|
|||||||
|
|
||||||
DEPENDENCIES = ["nut_ups"]
|
DEPENDENCIES = ["nut_ups"]
|
||||||
|
|
||||||
NutUpsTextSensor = nut_ups_ns.class_("NutUpsTextSensor", text_sensor.TextSensor, cg.Component)
|
NutUpsTextSensor = nut_ups_ns.class_(
|
||||||
|
"NutUpsTextSensor", text_sensor.TextSensor, cg.Component
|
||||||
|
)
|
||||||
|
|
||||||
TEXT_SENSOR_TYPES = [
|
TEXT_SENSOR_TYPES = [
|
||||||
"model",
|
"model",
|
||||||
@@ -36,4 +38,4 @@ async def to_code(config):
|
|||||||
|
|
||||||
sensor_type = config[CONF_TYPE]
|
sensor_type = config[CONF_TYPE]
|
||||||
cg.add(var.set_sensor_type(sensor_type))
|
cg.add(var.set_sensor_type(sensor_type))
|
||||||
cg.add(parent.register_text_sensor(var, sensor_type))
|
cg.add(parent.register_text_sensor(var, sensor_type))
|
||||||
@@ -5,47 +5,47 @@ This ensures the Python configuration validation uses the same vendor list as C+
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import os
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
def parse_vendor_header(header_path):
|
def parse_vendor_header(header_path):
|
||||||
"""Parse ups_vendors.h and extract vendor information."""
|
"""Parse ups_vendors.h and extract vendor information."""
|
||||||
vendors = {}
|
vendors = {}
|
||||||
|
|
||||||
with open(header_path, 'r') as f:
|
with open(header_path, "r") as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
|
|
||||||
# Find the KNOWN_UPS_VENDORS array
|
# Find the KNOWN_UPS_VENDORS array
|
||||||
pattern = r'\{0x([0-9A-Fa-f]+),\s*"([^"]+)",\s*"([^"]+)"\}'
|
pattern = r'\{0x([0-9A-Fa-f]+),\s*"([^"]+)",\s*"([^"]+)"\}'
|
||||||
matches = re.findall(pattern, content)
|
matches = re.findall(pattern, content)
|
||||||
|
|
||||||
for match in matches:
|
for match in matches:
|
||||||
vendor_id_str, name, description = match
|
vendor_id_str, name, description = match
|
||||||
vendor_id = int(vendor_id_str, 16)
|
vendor_id = int(vendor_id_str, 16)
|
||||||
vendors[vendor_id] = {
|
vendors[vendor_id] = {"name": name, "description": description}
|
||||||
'name': name,
|
|
||||||
'description': description
|
|
||||||
}
|
|
||||||
|
|
||||||
return vendors
|
return vendors
|
||||||
|
|
||||||
|
|
||||||
def generate_python_dict(vendors):
|
def generate_python_dict(vendors):
|
||||||
"""Generate Python dictionary code."""
|
"""Generate Python dictionary code."""
|
||||||
lines = ["# Known UPS vendor IDs for validation", "# Auto-generated from ups_vendors.h", "KNOWN_VENDOR_IDS = {"]
|
lines = [
|
||||||
|
"# Known UPS vendor IDs for validation",
|
||||||
|
"# Auto-generated from ups_vendors.h",
|
||||||
|
"KNOWN_VENDOR_IDS = {",
|
||||||
|
]
|
||||||
|
|
||||||
for vendor_id, info in sorted(vendors.items()):
|
for vendor_id, info in sorted(vendors.items()):
|
||||||
lines.append(f' 0x{vendor_id:04X}: "{info["name"]}",')
|
lines.append(f' 0x{vendor_id:04X}: "{info["name"]}",')
|
||||||
|
|
||||||
lines.append("}")
|
lines.append("}")
|
||||||
return '\n'.join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def generate_udev_rules(vendors):
|
def generate_udev_rules(vendors):
|
||||||
"""Generate udev rules for UPS vendors."""
|
"""Generate udev rules for UPS vendors."""
|
||||||
lines = []
|
lines = []
|
||||||
|
|
||||||
# Standard ESP development boards (keep existing ones)
|
# Standard ESP development boards (keep existing ones)
|
||||||
standard_vendors = [
|
standard_vendors = [
|
||||||
("303a", "Espressif ESP32-S2/S3"),
|
("303a", "Espressif ESP32-S2/S3"),
|
||||||
@@ -53,15 +53,15 @@ def generate_udev_rules(vendors):
|
|||||||
("1a86", "QinHeng Electronics CH340"),
|
("1a86", "QinHeng Electronics CH340"),
|
||||||
("0403", "FTDI USB Serial"),
|
("0403", "FTDI USB Serial"),
|
||||||
]
|
]
|
||||||
|
|
||||||
for vid, desc in standard_vendors:
|
for vid, desc in standard_vendors:
|
||||||
lines.append(f'SUBSYSTEM=="usb", ATTR{{idVendor}}=="{vid}", MODE="0666"')
|
lines.append(f'SUBSYSTEM=="usb", ATTR{{idVendor}}=="{vid}", MODE="0666"')
|
||||||
|
|
||||||
# UPS vendors from header file
|
# UPS vendors from header file
|
||||||
for vendor_id, info in sorted(vendors.items()):
|
for vendor_id, info in sorted(vendors.items()):
|
||||||
vid_hex = f"{vendor_id:04x}" # lowercase for udev
|
vid_hex = f"{vendor_id:04x}" # lowercase for udev
|
||||||
lines.append(f'SUBSYSTEM=="usb", ATTR{{idVendor}}=="{vid_hex}", MODE="0666"')
|
lines.append(f'SUBSYSTEM=="usb", ATTR{{idVendor}}=="{vid_hex}", MODE="0666"')
|
||||||
|
|
||||||
return lines
|
return lines
|
||||||
|
|
||||||
|
|
||||||
@@ -70,36 +70,38 @@ def update_udev_rules_in_setup_sh(setup_path, udev_rules):
|
|||||||
if not setup_path.exists():
|
if not setup_path.exists():
|
||||||
print(f"Warning: {setup_path} not found!")
|
print(f"Warning: {setup_path} not found!")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
with open(setup_path, 'r') as f:
|
with open(setup_path, "r") as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
|
|
||||||
# Find the udev rules section
|
# Find the udev rules section
|
||||||
udev_start = "cat > /etc/udev/rules.d/99-esphome-usb.rules << 'UDEV_EOF'"
|
udev_start = "cat > /etc/udev/rules.d/99-esphome-usb.rules << 'UDEV_EOF'"
|
||||||
udev_end = "UDEV_EOF"
|
udev_end = "UDEV_EOF"
|
||||||
|
|
||||||
start_pos = content.find(udev_start)
|
start_pos = content.find(udev_start)
|
||||||
if start_pos == -1:
|
if start_pos == -1:
|
||||||
print(f"Warning: Could not find udev rules section in {setup_path}")
|
print(f"Warning: Could not find udev rules section in {setup_path}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
end_pos = content.find(udev_end, start_pos + len(udev_start))
|
end_pos = content.find(udev_end, start_pos + len(udev_start))
|
||||||
if end_pos == -1:
|
if end_pos == -1:
|
||||||
print(f"Warning: Could not find end of udev rules section in {setup_path}")
|
print(f"Warning: Could not find end of udev rules section in {setup_path}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Build the new udev section
|
# Build the new udev section
|
||||||
new_udev_section = udev_start + "\n"
|
new_udev_section = udev_start + "\n"
|
||||||
for rule in udev_rules:
|
for rule in udev_rules:
|
||||||
new_udev_section += rule + "\n"
|
new_udev_section += rule + "\n"
|
||||||
new_udev_section += udev_end
|
new_udev_section += udev_end
|
||||||
|
|
||||||
# Replace the section
|
# Replace the section
|
||||||
new_content = content[:start_pos] + new_udev_section + content[end_pos + len(udev_end):]
|
new_content = (
|
||||||
|
content[:start_pos] + new_udev_section + content[end_pos + len(udev_end) :]
|
||||||
with open(setup_path, 'w') as f:
|
)
|
||||||
|
|
||||||
|
with open(setup_path, "w") as f:
|
||||||
f.write(new_content)
|
f.write(new_content)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -110,30 +112,32 @@ def main():
|
|||||||
header_path = component_dir / "ups_vendors.h"
|
header_path = component_dir / "ups_vendors.h"
|
||||||
init_path = component_dir / "__init__.py"
|
init_path = component_dir / "__init__.py"
|
||||||
setup_path = script_dir.parent / ".devcontainer" / "setup.sh"
|
setup_path = script_dir.parent / ".devcontainer" / "setup.sh"
|
||||||
|
|
||||||
if not header_path.exists():
|
if not header_path.exists():
|
||||||
print(f"Error: {header_path} not found!")
|
print(f"Error: {header_path} not found!")
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
print(f"Parsing vendors from {header_path}...")
|
print(f"Parsing vendors from {header_path}...")
|
||||||
vendors = parse_vendor_header(header_path)
|
vendors = parse_vendor_header(header_path)
|
||||||
print(f"Found {len(vendors)} UPS vendors")
|
print(f"Found {len(vendors)} UPS vendors")
|
||||||
|
|
||||||
# Generate the Python code
|
# Generate the Python code
|
||||||
python_code = generate_python_dict(vendors)
|
python_code = generate_python_dict(vendors)
|
||||||
|
|
||||||
# Update Python __init__.py
|
# Update Python __init__.py
|
||||||
if init_path.exists():
|
if init_path.exists():
|
||||||
# Read current __init__.py
|
# Read current __init__.py
|
||||||
with open(init_path, 'r') as f:
|
with open(init_path, "r") as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
|
|
||||||
# Replace the KNOWN_VENDOR_IDS section
|
# Replace the KNOWN_VENDOR_IDS section
|
||||||
pattern = r'KNOWN_VENDOR_IDS = \{[^}]*\}'
|
pattern = r"KNOWN_VENDOR_IDS = \{[^}]*\}"
|
||||||
if re.search(pattern, content, re.DOTALL):
|
if re.search(pattern, content, re.DOTALL):
|
||||||
new_content = re.sub(pattern, python_code.split('\n', 2)[2], content, flags=re.DOTALL)
|
new_content = re.sub(
|
||||||
|
pattern, python_code.split("\n", 2)[2], content, flags=re.DOTALL
|
||||||
with open(init_path, 'w') as f:
|
)
|
||||||
|
|
||||||
|
with open(init_path, "w") as f:
|
||||||
f.write(new_content)
|
f.write(new_content)
|
||||||
print(f"✅ Updated {init_path}")
|
print(f"✅ Updated {init_path}")
|
||||||
else:
|
else:
|
||||||
@@ -143,15 +147,17 @@ def main():
|
|||||||
else:
|
else:
|
||||||
print("Generated Python code:")
|
print("Generated Python code:")
|
||||||
print(python_code)
|
print(python_code)
|
||||||
|
|
||||||
# Generate and update udev rules
|
# Generate and update udev rules
|
||||||
udev_rules = generate_udev_rules(vendors)
|
udev_rules = generate_udev_rules(vendors)
|
||||||
if update_udev_rules_in_setup_sh(setup_path, udev_rules):
|
if update_udev_rules_in_setup_sh(setup_path, udev_rules):
|
||||||
print(f"✅ Updated udev rules in {setup_path}")
|
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")
|
print(
|
||||||
|
f" Added {len([r for r in udev_rules if 'UPS' not in r])} standard + {len(vendors)} UPS vendor rules"
|
||||||
|
)
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
exit(main())
|
exit(main())
|
||||||
Reference in new issue
Block a user