lwzbus/genlwz.py
Michael Hope 9625ad6498
Some checks failed
/ build (push) Failing after 5m48s
lwz: add version data
2026-10-14 08:50:02 +13:00

135 lines
4.1 KiB
Python

# Copyright (c) 2025 Michael Hope <michaelh@juju.nz>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# SPDX-License-Identifier: MIT
"""Generates ESPHome sensors and buttons from the https://github.com/kdarnok/lwz180 README."""
import fileinput
import re
import yaml
_DEVICE_CLASS = {
"°C": "temperature",
"m³/h": "volume_flow_rate",
"d": "duration",
"h": "duration",
"Pa": "atmospheric_pressure",
}
def _ucfirst(value: str) -> str:
return value[0].upper() + value[1:]
def _cname(value: str) -> str:
return "lwz_" + re.sub(r"[^\w]+", "_", value.lower()).removesuffix("_")
def _parse():
sensors = []
buttons = []
for line in fileinput.input():
parts = [x.strip() for x in line.strip().split("|")]
if len(parts) < 4 or parts[0] or parts[-1]:
continue
if len(parts) == 6 and parts[1].startswith("0x"):
type, scale, name, unit = parts[1:-1]
type = int(type, 16)
scale = float(scale)
match = re.match(r"(\w+)\s+\((.+)\)", name)
if match:
id, name = match.groups()
name = f"{_ucfirst(name)} ({id})"
sensor = {
"id": _cname(name),
"platform": "modbus_controller",
"name": name,
"address": type,
"unit_of_measurement": unit,
"register_type": "read",
"value_type": "S_WORD",
"state_class": "measurement",
}
if unit in _DEVICE_CLASS:
sensor["device_class"] = _DEVICE_CLASS[unit]
if scale != 1:
sensor["filters"] = [{"multiply": scale}]
sensors.append(sensor)
elif len(parts) == 4 and re.match(r"^\d+$", parts[1]):
code, name = parts[1:-1]
button = {
"id": _cname(name),
"platform": "modbus_controller",
"register_type": "coil",
"address": int(code),
"name": _ucfirst(name),
"assumed_state": False,
}
buttons.append(button)
return sensors, buttons
def _emit_esphome():
sensors, buttons = _parse()
doc = {"sensor": sensors, "switch": buttons}
print(yaml.dump(doc))
def _emit_register_map():
sensors, buttons = _parse()
for mod in range(len(sensors), len(sensors) * 2):
for mul in range(1, 100):
for offset in range(0, 10):
slots = [None] * mod
bad = False
for sensor in sensors:
idx = sensor["address"]
idx = (idx * mul + offset) % mod
if slots[idx]:
bad = True
break
slots[idx] = sensor
if not bad:
print(
mul,
mod,
", ".join("%d" % (x["address"] if x else -1) for x in slots),
)
def main():
_emit_register_map()
if __name__ == "__main__":
main()