From fef699a3db81f8e260774dbcc80663a566c71813 Mon Sep 17 00:00:00 2001 From: Donald Clark Jackson Date: Wed, 11 Nov 2026 15:27:09 -0800 Subject: [PATCH] Warn on invalid ids, duplicate ids, homie_domain and broadcast subtopics (#92) Device, node and property ids outside the Homie ID format, a differing duplicate node or property, a device id repeated in one tree, an invalid homie_domain and invalid broadcast subtopic segments warn once per object and are still published (warn step of the #91 policy). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VUQ6apRySRNW8y3ppJMdJC --- CHANGELOG.md | 4 + src/ebus_sdk/homie.py | 71 +++++++++++ tests/test_homie_ids.py | 276 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 351 insertions(+) create mode 100644 tests/test_homie_ids.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 571ffaa..4450adf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to `ebus-sdk` are recorded here. Format follows [Keep a Chan ## [Unreleased] +### Changed + +- Invalid ids, topics and domains are warned about, once per object, and still published ([#92](https://github.com/electrification-bus/python-sdk/issues/92), part of [#91](https://github.com/electrification-bus/python-sdk/issues/91)): a device, node or property id that is empty, starts with `$` or has a character outside `a-z`, `0-9` and `-` (convention.md:39, :41); a second node with an existing id in `Device.add_node()` or property in `Node.add_property()` whose `$description` differs from the first, which it still replaces (:294, :326; an identical re-declaration is not warned about); a device id already used on another branch of the same tree (:194; an ancestor or sibling with the id still raises `ValueError`); a root `homie_domain` that is `""` (still published as `ebus`), starts with `$` or contains `/`, `+` or `#` (:157, :161); and a `Controller.broadcast()` subtopic with a segment that is not a valid id (:533). `sanitize_homie_id()` documents that distinct inputs can map to the same id. + ## [0.27.0] — 2026-10-21 A device built without nodes announces once, in its caller's first transition, instead of publishing `ready` before any value. Breaking for code that relied on a bare `Device(...)` being `ready`. diff --git a/src/ebus_sdk/homie.py b/src/ebus_sdk/homie.py index f7966c9..6a1b747 100644 --- a/src/ebus_sdk/homie.py +++ b/src/ebus_sdk/homie.py @@ -114,6 +114,29 @@ def _warn_invalid_once(owner: Any, problem: str, message: str) -> None: logger.warning(f"{message},hint=invalid Homie 5 input; this will raise in the next minor release") +# A topic level id: lowercase a-z, 0-9 and hyphen only (convention.md:39). `$` is +# reserved for attributes (:41), so it is outside the set. +_HOMIE_ID = re.compile(r"[a-z0-9-]+", re.ASCII) + + +def _homie_id_problem(value: Any) -> Optional[str]: + """Why ``value`` is not a valid Homie topic id, or None when it is.""" + if not isinstance(value, str) or not value: + return "empty" + if value.startswith("$"): + return "reservedDollar" + if not _HOMIE_ID.fullmatch(value): + return "invalidCharacter" + return None + + +def _warn_invalid_id(owner: Any, kind: str, value: Any) -> None: + """Warn once when a device, node or property id is not a Homie topic id (:39, :41).""" + problem = _homie_id_problem(value) + if problem is not None: + _warn_invalid_once(owner, "idInvalid", f"reason={kind}IdInvalid,{kind}ID={value},problem={problem}") + + # One-time warning when a `$format` JSONSchema is present but jsonschema is not. _jsonschema_warned = False @@ -792,6 +815,11 @@ def sanitize_homie_id(value: Optional[str]) -> str: on the resulting Homie-legal id. Composing first and sanitizing the composite is not equivalent — a hyphen-joiner can be collapsed if an adjacent segment ends/begins with characters that drop out. + + The mapping is many-to-one: distinct inputs can produce the same id + (``"Meter_1"``, ``"meter.1"`` and ``"meter--1"`` all become ``meter-1``). + Two such inputs collide where ids must be unique (devices in a tree, + nodes in a device, properties in a node). """ if not value: return "" @@ -910,6 +938,7 @@ def __init__( async_loop = from_dict.get("async_loop", None) # Regardless of how we got this info, construct it # AKA, the "business logic" of the constructor + _warn_invalid_id(self, "property", id) self._id = id self._round = round_to self._value = value @@ -1698,6 +1727,7 @@ def __init__( self._type = type self._properties = properties if properties is not None else {} self._device = device + _warn_invalid_id(self, "node", self._id) def as_dict(self) -> dict: returned_dict = {"id": self.id(), "name": self.name(), "type": self.type()} @@ -1772,6 +1802,16 @@ def add_property(self, property: Property) -> Property: # before the $description that names it and before ready (convention.md:279). # A node not yet attached to its device, or a re-declaration with identical # content, leaves the $description unchanged and publishes only the value. + # Property ids are unique per node (convention.md:326). A second property with + # an existing id and a different $description still replaces the first; an + # identical re-declaration is not a duplicate. + existing = self._properties.get(property.id()) + if existing is not None and existing is not property and existing.description() != property.description(): + _warn_invalid_once( + self, + f"duplicateProperty:{property.id()}", + f"reason=nodeDuplicatePropertyId,nodeID={self._id},propertyID={property.id()}", + ) self._properties.update({property.id(): property}) with self.device()._reconfiguration(): # force: announcing a property is a structural republish, so its value must @@ -2179,6 +2219,16 @@ def __init__( # homie_domain(). Defaults to the eBus domain, so a publisher that never # mentions it is unaffected. self._homie_domain = (homie_domain or EBUS_HOMIE_DOMAIN) if parent is None else None + _warn_invalid_id(self, "device", id) + # The domain is a single topic segment (convention.md:157) that the `+` + # discovery wildcard can match, so it may not start with '$' (:161). "" + # still falls back to the eBus domain; anything else is published as given. + if homie_domain is not None and ( + homie_domain == "" or homie_domain.startswith("$") or any(c in homie_domain for c in "/+#") + ): + _warn_invalid_once( + self, "homieDomainInvalid", f"reason=deviceHomieDomainInvalid,id={id},domain={homie_domain}" + ) self._name = name if name else id self._type = type self._parent: Optional[Device] = parent @@ -2230,6 +2280,14 @@ def __init__( if mqtt_cfg is not None: self.connect_broker() else: + # Device ids are unique across the tree (convention.md:194). An ancestor or + # sibling with this id was refused above; one on another branch publishes to + # the same topics too, so the root warns once per id. + root = parent.root() + if any(device._id == id for device in root._tree_pre_order()): + _warn_invalid_once( + root, f"duplicateDevice:{id}", f"reason=deviceDuplicateIdInTree,rootID={root._id},id={id}" + ) parent._children.append(self) # A device built inside an ancestor's open state_transition() and never # populated is announced, empty, when that ancestor's transition closes. @@ -2676,6 +2734,14 @@ def add_node(self, node: Node) -> Node: if self._async_loop is not None: prop.async_loop = self._async_loop node_id = node.id() + # Node ids are unique per device (convention.md:294). A second node with an + # existing id and a different $description still replaces the first; an + # identical re-declaration is not a duplicate. + existing = self._nodes.get(node_id) + if existing is not None and existing is not node and existing.description() != node.description(): + _warn_invalid_once( + self, f"duplicateNode:{node_id}", f"reason=deviceDuplicateNodeId,id={self._id},nodeID={node_id}" + ) # Outside a transition a ready device goes to init first, so the node's # values land before the $description that names them and before ready. self._nodes.update({node_id: node}) @@ -4940,6 +5006,11 @@ def broadcast(self, subtopic: str, message: str, qos: Optional[int] = None) -> b return False effective_qos = qos if qos is not None else self._qos + # Each subtopic segment follows the id format (convention.md:533). Still sent. + if any(_homie_id_problem(segment) is not None for segment in str(subtopic).split("/")): + _warn_invalid_once( + self, f"broadcastSubtopic:{subtopic}", f"reason=broadcastSubtopicInvalid,subtopic={subtopic}" + ) broadcast_topic = f"{self.homie_domain}/{EBUS_HOMIE_VERSION_MAJOR}/$broadcast/{subtopic}" logger.info(f"reason=broadcasting,topic={broadcast_topic}") diff --git a/tests/test_homie_ids.py b/tests/test_homie_ids.py new file mode 100644 index 0000000..74bc069 --- /dev/null +++ b/tests/test_homie_ids.py @@ -0,0 +1,276 @@ +"""Homie 5 id, topic and domain validation (issue #92): warn once, still publish. + +Line numbers in docstrings refer to homieiot/convention@7edc221 convention.md. +""" + +import json +import logging +from unittest.mock import MagicMock, patch + +import pytest + +from ebus_sdk.homie import ( + EBUS_HOMIE_DOMAIN, + EBUS_HOMIE_VERSION_MAJOR, + Controller, + Device, + Node, + Property, + PropertyDatatype, + sanitize_homie_id, +) + +BASE = f"{EBUS_HOMIE_DOMAIN}/{EBUS_HOMIE_VERSION_MAJOR}" + + +def _mock_mqtt_client(): + mock = MagicMock() + mock.is_running = True + mock.is_connected.return_value = True + mock.publish.return_value = MagicMock(rc=0) + mock.subscribe.return_value = (0, 1) + return mock + + +def _make_root(device_id="root", **kwargs): + with patch("ebus_sdk.homie.MqttClient.from_config") as from_config: + client = _mock_mqtt_client() + from_config.return_value = client + device = Device(id=device_id, mqtt_cfg={"host": "localhost", "port": 1883}, **kwargs) + with device.state_transition(): + pass + return device, client + + +def _topics(client): + return [c.args[0] for c in client.publish.call_args_list] + + +def _warnings(caplog, reason): + return [r for r in caplog.records if f"reason={reason}," in r.getMessage()] + + +def _int_property(property_id, value=1): + return Property(id=property_id, value=value, datatype=PropertyDatatype.INTEGER) + + +class TestIdFormat: + """:39: lowercase a-z, 0-9 and `-`; :41: `$` is reserved for attributes.""" + + @pytest.mark.parametrize("value", ["a", "panel-1", "000010024176", "-x-"]) + def test_valid_ids_do_not_warn(self, caplog, value): + with caplog.at_level(logging.WARNING, logger="homie"): + Device(id=value) + Node(id=value) + _int_property(value) + assert [r for r in caplog.records if "IdInvalid" in r.getMessage()] == [] + + @pytest.mark.parametrize( + "value, problem", + [ + ("Panel", "invalidCharacter"), + ("a_b", "invalidCharacter"), + ("a/b", "invalidCharacter"), + ("a+", "invalidCharacter"), + ("$state", "reservedDollar"), + ("", "empty"), + (None, "empty"), + ], + ) + def test_property_id_warns(self, caplog, value, problem): + with caplog.at_level(logging.WARNING, logger="homie"): + Property(id=value, datatype=PropertyDatatype.INTEGER) + records = _warnings(caplog, "propertyIdInvalid") + assert len(records) == 1 + assert f"problem={problem}" in records[0].getMessage() + + def test_node_id_warns_for_both_constructor_forms(self, caplog): + with caplog.at_level(logging.WARNING, logger="homie"): + Node(id="$target") + Node(from_dict={"id": "Meter_1"}) + assert len(_warnings(caplog, "nodeIdInvalid")) == 2 + + def test_device_id_warns(self, caplog): + with caplog.at_level(logging.WARNING, logger="homie"): + Device(id="Panel_1") + assert len(_warnings(caplog, "deviceIdInvalid")) == 1 + + def test_invalid_ids_still_publish(self, caplog): + with caplog.at_level(logging.WARNING, logger="homie"): + root, client = _make_root("Root") + node = Node(id="Node_1") + root.add_node(node) + node.add_property(_int_property("Prop", 7)) + assert f"{BASE}/Root/Node_1/Prop" in _topics(client) + description = json.loads( + [c.args[1] for c in client.publish.call_args_list if c.args[0] == f"{BASE}/Root/$description"][-1] + ) + assert "Prop" in description["nodes"]["Node_1"]["properties"] + + def test_an_invalid_property_id_warns_once_across_republishes(self, caplog): + root, client = _make_root() + node = root.new_node("n") + root.add_node(node) + with caplog.at_level(logging.WARNING, logger="homie"): + prop = node.add_property(_int_property("Bad")) + prop.set_value(2) + root.refresh_tree(force=True) + assert len(_warnings(caplog, "propertyIdInvalid")) == 1 + + +class TestDuplicateNodeAndPropertyIds: + """:294 node ids are unique per device, :326 property ids per node.""" + + def test_a_second_node_with_the_same_id_warns_and_still_replaces(self, caplog): + root, client = _make_root() + first = root.add_node(Node(id="n", name="first")) + second = Node(id="n", name="second") + with caplog.at_level(logging.WARNING, logger="homie"): + root.add_node(second) + assert len(_warnings(caplog, "deviceDuplicateNodeId")) == 1 + assert root.get_node("n") is second is not first + assert root.description()["nodes"]["n"]["name"] == "second" + + def test_a_duplicate_node_id_warns_once(self, caplog): + root, _ = _make_root() + root.add_node(Node(id="n", name="first")) + with caplog.at_level(logging.WARNING, logger="homie"): + root.add_node(Node(id="n", name="second")) + root.add_node(Node(id="n", name="third")) + assert len(_warnings(caplog, "deviceDuplicateNodeId")) == 1 + + def test_re_adding_a_node_or_an_identical_node_does_not_warn(self, caplog): + root, _ = _make_root() + node = root.add_node(Node(id="n", name="same")) + with caplog.at_level(logging.WARNING, logger="homie"): + root.add_node(node) + root.add_node(Node(id="n", name="same")) + assert _warnings(caplog, "deviceDuplicateNodeId") == [] + + def test_a_second_property_with_the_same_id_warns_and_still_publishes(self, caplog): + root, client = _make_root() + node = root.add_node(root.new_node("n")) + node.add_property(_int_property("p", 1)) + client.publish.reset_mock() + replacement = Property(id="p", value="x", datatype=PropertyDatatype.STRING) + with caplog.at_level(logging.WARNING, logger="homie"): + node.add_property(replacement) + node.add_property(Property(id="p", value=2.5, datatype=PropertyDatatype.FLOAT)) + assert len(_warnings(caplog, "nodeDuplicatePropertyId")) == 1 + assert (f"{BASE}/root/n/p", "x") in [(c.args[0], c.args[1]) for c in client.publish.call_args_list] + assert node.get_property("p").datatype() == PropertyDatatype.FLOAT + + def test_an_identical_property_re_declaration_does_not_warn(self, caplog): + root, _ = _make_root() + node = root.add_node(root.new_node("n")) + node.add_property(_int_property("p", 1)) + with caplog.at_level(logging.WARNING, logger="homie"): + node.add_property(_int_property("p", 2)) + assert _warnings(caplog, "nodeDuplicatePropertyId") == [] + + +class TestDuplicateDeviceIdsInTree: + """:194: device ids are unique; the ancestor and sibling cases already raise.""" + + def test_the_same_id_on_two_branches_warns_once_and_still_publishes(self, caplog): + root, client = _make_root() + a = Device(id="a", parent=root) + b = Device(id="b", parent=root) + Device(id="x", parent=a) + with caplog.at_level(logging.WARNING, logger="homie"): + dup = Device(id="x", parent=b) + Device(id="x", parent=Device(id="c", parent=root)) + records = _warnings(caplog, "deviceDuplicateIdInTree") + assert len(records) == 1 + assert "rootID=root" in records[0].getMessage() + assert dup in b.children() + client.publish.reset_mock() + with dup.state_transition(): + pass + assert f"{BASE}/x/$state" in _topics(client) + + def test_distinct_ids_do_not_warn(self, caplog): + root, _ = _make_root() + with caplog.at_level(logging.WARNING, logger="homie"): + a = Device(id="a", parent=root) + Device(id="a-1", parent=a) + Device(id="b", parent=root) + assert _warnings(caplog, "deviceDuplicateIdInTree") == [] + + def test_ancestor_and_sibling_collisions_still_raise(self): + root, _ = _make_root() + Device(id="a", parent=root) + with pytest.raises(ValueError): + Device(id="a", parent=root) + with pytest.raises(ValueError): + Device(id="root", parent=root.children()[0]) + + def test_a_deleted_device_id_can_be_reused_without_warning(self, caplog): + root, _ = _make_root() + a = Device(id="a", parent=root) + x = Device(id="x", parent=a) + with x.state_transition(): + pass + x.delete() + with caplog.at_level(logging.WARNING, logger="homie"): + Device(id="x", parent=Device(id="b", parent=root)) + assert _warnings(caplog, "deviceDuplicateIdInTree") == [] + + +class TestHomieDomain: + """:156: the homie-domain is a single segment.""" + + @pytest.mark.parametrize("domain", ["", "a/b", "a+", "#", "$sys"]) + def test_an_invalid_domain_warns(self, caplog, domain): + with caplog.at_level(logging.WARNING, logger="homie"): + Device(id="d", homie_domain=domain) + assert len(_warnings(caplog, "deviceHomieDomainInvalid")) == 1 + + @pytest.mark.parametrize("domain", [None, "ebus", "homie"]) + def test_a_valid_or_default_domain_does_not_warn(self, caplog, domain): + with caplog.at_level(logging.WARNING, logger="homie"): + Device(id="d", homie_domain=domain) + assert _warnings(caplog, "deviceHomieDomainInvalid") == [] + + def test_an_empty_domain_still_falls_back_to_ebus(self, caplog): + with caplog.at_level(logging.WARNING, logger="homie"): + device = Device(id="d", homie_domain="") + assert device.homie_domain() == EBUS_HOMIE_DOMAIN + + def test_a_multi_segment_domain_still_publishes(self, caplog): + with caplog.at_level(logging.WARNING, logger="homie"): + _, client = _make_root("d", homie_domain="a/b") + assert len(_warnings(caplog, "deviceHomieDomainInvalid")) == 1 + assert f"a/b/{EBUS_HOMIE_VERSION_MAJOR}/d/$state" in _topics(client) + + +class TestBroadcastSubtopic: + """:533: every subtopic segment follows the id format.""" + + def _controller(self): + client = MagicMock() + return Controller(mqttc=client), client + + @pytest.mark.parametrize("subtopic", ["alert", "security/alert", "a-1/b-2"]) + def test_valid_subtopics_do_not_warn(self, caplog, subtopic): + ctrl, _ = self._controller() + with caplog.at_level(logging.WARNING, logger="homie"): + assert ctrl.broadcast(subtopic, "m") is True + assert _warnings(caplog, "broadcastSubtopicInvalid") == [] + + @pytest.mark.parametrize("subtopic", ["Alert", "security//alert", "a/", "$x", "a/+", "#", ""]) + def test_an_invalid_subtopic_warns_once_and_is_still_sent(self, caplog, subtopic): + ctrl, client = self._controller() + with caplog.at_level(logging.WARNING, logger="homie"): + assert ctrl.broadcast(subtopic, "m") is True + assert ctrl.broadcast(subtopic, "m") is True + assert len(_warnings(caplog, "broadcastSubtopicInvalid")) == 1 + assert client.publish.call_count == 2 + assert client.publish.call_args.args[0] == f"{BASE}/$broadcast/{subtopic}" + + +class TestSanitizeHomieId: + def test_distinct_inputs_can_map_to_the_same_id(self): + assert ( + sanitize_homie_id("Meter_1") == sanitize_homie_id("meter.1") == sanitize_homie_id("meter--1") == "meter-1" + )