diff --git a/CHANGELOG.md b/CHANGELOG.md index 5739a13..ae45bfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,14 @@ All notable changes to `ebus-sdk` are recorded here. Format follows [Keep a Chan - `jsonschema` is imported on the first `$format` validation instead of when `ebus_sdk.homie` loads, so a process that never validates a `json` property's `$format` does not load it ([#113](https://github.com/electrification-bus/python-sdk/issues/113)). Validation, and the one-time warning when `jsonschema` is not installed, are unchanged. - `Controller.get_effective_state()` and `HOMIE_EFFECTIVE_STATE_TABLE` follow the convention's rule (convention.md:262-267): a child's effective state is its own `$state` unless its root is `lost`. A root in `init`, `disconnected` or `sleeping` no longer overrides its descendants, so a child of a `disconnected` root that reports `ready` now reads `ready`. ([#110](https://github.com/electrification-bus/python-sdk/issues/110)) - 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. +- `Controller`: a zero-length property value removes the stored value from `DiscoveredDevice.properties` and fires the property-changed callback with `new_value=None`; it was stored as `""`. A zero-length `$target` removes the entry from `property_targets`. A single `0x00` byte still decodes to `""` (convention.md:62-63, :613; [#93](https://github.com/electrification-bus/python-sdk/issues/93)). +- `Controller.set_property()` publishes at QoS 0 when the device's discovered `$description` marks the property `retained: false` (convention.md:49, :695); an explicit `qos=` still wins ([#93](https://github.com/electrification-bus/python-sdk/issues/93)). ### Fixed - Payload validation applies Homie 5 rules it missed. On `/set`, an integer that step rounding carries past the int64 range is rejected as `integerOutOf64Bit` (`9223372036854775807` with `$format` `0::2` was accepted as `9223372036854775808`), and a float carried past the float range as `floatOutOfRange`. On `/set` and on publish, a datetime accepts hour 24 only as `24:00[:00[.0]]`, ordinal day 366 only in a leap year and ISO week 53 only in a year that has one (`2024-01-01T24:30`, `2023-366` and `2021-W53` were accepted), and a json payload holding a number outside the float range (`[1e400]` decoded to `inf`), a string or key with a lone surrogate (`["\ud800"]`) or nesting too deep to parse is rejected as `jsonInvalid`. A number over Python's 4,300-digit int conversion limit no longer raises `ValueError`: an integer or float `/set` is a grammar rejection (`propertySetRejected`, where it was logged as `propertySetCallbackException`), an integer published with `set_value()` is refused as out of int64, and a numeric `$format` bound is ignored, like any other bound that does not parse. A float `/set` or `$format` bound with a huge exponent (`1e-100000000`) no longer computes the power exactly, which took seconds. ([#110](https://github.com/electrification-bus/python-sdk/issues/110)) +- `Controller`: only the five `$state` values create or update a device; any other value is logged and dropped (convention.md:272-274). A `$state`, property value or `$target` payload that is not UTF-8 is logged and dropped instead of raising in the handler ([#93](https://github.com/electrification-bus/python-sdk/issues/93)). +- `Controller`: `$alert/` and `$log/` messages are no longer stored as properties of a node named `$alert` or `$log` (convention.md:41; [#93](https://github.com/electrification-bus/python-sdk/issues/93)). ## [0.27.0] — 2026-10-21 diff --git a/src/ebus_sdk/homie.py b/src/ebus_sdk/homie.py index fdc9336..ad7a6f0 100644 --- a/src/ebus_sdk/homie.py +++ b/src/ebus_sdk/homie.py @@ -3665,6 +3665,17 @@ def ebus_cfg_add_auth(cfg, username, password): return cfg +def _pop_nested(table: dict, node_id: str, property_id: str) -> Optional[str]: + """Pop table[node_id][property_id], dropping the node's dict once it is empty.""" + values = table.get(node_id) + if values is None: + return None + value = values.pop(property_id, None) + if not values: + del table[node_id] + return value + + class DiscoveredDevice: """ Represents a device discovered by a Controller. @@ -3707,6 +3718,16 @@ def update_property_target(self, node_id: str, property_id: str, target: str) -> self.property_targets[node_id][property_id] = target self.last_seen = time.time() + def remove_property(self, node_id: str, property_id: str) -> Optional[str]: + """Forget a property value whose retained topic was removed; return the value it had.""" + self.last_seen = time.time() + return _pop_nested(self.properties, node_id, property_id) + + def remove_property_target(self, node_id: str, property_id: str) -> Optional[str]: + """Forget a property $target whose retained topic was removed; return the target it had.""" + self.last_seen = time.time() + return _pop_nested(self.property_targets, node_id, property_id) + def get_property(self, node_id: str, property_id: str) -> Optional[str]: """Get current value of a property (raw string as received)""" return self.properties.get(node_id, {}).get(property_id) @@ -3842,6 +3863,19 @@ def get_node_properties(self, node_id: str) -> dict: _PROPERTY_FILTERS = ("+/+", "+/+/$target") # Controller._property_coverage value for a device whose whole-device property filters are subscribed. _ALL_NODES = "*" +# The only $state values that create or update a discovered device (convention.md:272-274). +_DEVICE_STATES = frozenset(state.value for state in DeviceState) + + +def _decode_payload(topic: str, payload: Union[bytes, str]) -> Optional[str]: + """Decode an inbound payload as UTF-8 (convention.md:76), or log and return None.""" + if not isinstance(payload, bytes): + return payload + try: + return payload.decode("utf-8") + except UnicodeDecodeError: + logger.warning(f"reason=payloadNotUtf8,topic={topic}") + return None class _DefaultBatchSize: @@ -4709,8 +4743,9 @@ def _on_state_message(self, topic: str, payload: bytes) -> None: homie_domain = parts[0] device_id = parts[2] - # Decode payload - payload_str = payload.decode("utf-8") if isinstance(payload, bytes) else payload + payload_str = _decode_payload(topic, payload) + if payload_str is None: + return # Empty payload indicates device removal if not payload_str or len(payload_str) == 0: @@ -4728,6 +4763,11 @@ def _on_state_message(self, topic: str, payload: bytes) -> None: self._on_device_removed(removed_device) return + # Any other value neither creates nor updates a device (convention.md:272-274). + if payload_str not in _DEVICE_STATES: + logger.warning(f"reason=invalidStateValue,deviceID={device_id},state={payload_str!r}") + return + # Tree-rooted mode tracks only what the tree declares. A device that cleared its # $state and is still declared comes back; a $state for anything else arrives on # filters left over from a dropped device: remove them. @@ -4976,18 +5016,31 @@ def _on_property_message(self, device_id: str, topic: str, payload: bytes) -> No node_id = parts[3] property_id = parts[4] - # Skip attribute topics (starting with $) - if property_id.startswith("$"): + # Skip attribute topics (starting with $): a property's own attributes, and + # device attributes two levels deep such as $alert/ and $log/. + if node_id.startswith("$") or property_id.startswith("$"): return if device_id not in self.devices: return - payload_str = payload.decode("utf-8") if isinstance(payload, bytes) else payload - # Homie 5: a single 0x00 byte denotes an empty-string value (a truly - # zero-length payload would instead be a retained-topic clear). - payload_str = decode_empty_string(payload_str) + payload_str = _decode_payload(topic, payload) + if payload_str is None: + return device = self.devices[device_id] + + # A zero-length payload removes the retained value (convention.md:62-63, :613). + if not payload_str: + old_value = device.remove_property(node_id, property_id) + if old_value is None: + return + logger.debug(f"reason=propertyRemoved,deviceID={device_id},node={node_id},property={property_id}") + if self._on_property_changed: + self._on_property_changed(device_id, node_id, property_id, None, old_value) + return + + # Homie 5: a single 0x00 byte denotes an empty-string value. + payload_str = decode_empty_string(payload_str) old_value = device.get_property(node_id, property_id) device.update_property(node_id, property_id, payload_str) @@ -5035,9 +5088,18 @@ def _on_target_message(self, device_id: str, topic: str, payload: bytes) -> None if device_id not in self.devices: return - payload_str = payload.decode("utf-8") if isinstance(payload, bytes) else payload - payload_str = decode_empty_string(payload_str) + payload_str = _decode_payload(topic, payload) + if payload_str is None: + return device = self.devices[device_id] + + # A zero-length payload removes the retained $target. + if not payload_str: + device.remove_property_target(node_id, property_id) + logger.debug(f"reason=targetRemoved,deviceID={device_id},node={node_id},property={property_id}") + return + + payload_str = decode_empty_string(payload_str) device.update_property_target(node_id, property_id, payload_str) self._note_burst_message(device_id, (node_id, property_id, "$target")) @@ -5064,7 +5126,8 @@ def set_property( node_id: Target node ID property_id: Target property ID value: Value to set (as string) - qos: MQTT QoS level (default: controller's QoS) + qos: MQTT QoS level (default: 0 when the discovered $description marks + the property non-retained, else the controller's QoS) Returns: True if message was sent successfully, False otherwise @@ -5073,7 +5136,13 @@ def set_property( logger.error("reason=setPropertyFailedNoConnection") return False - effective_qos = qos if qos is not None else self._qos + if qos is not None: + effective_qos = qos + elif self._is_non_retained(device_id, node_id, property_id): + # A /set to a non-retained property goes at QoS 0 (convention.md:49, :695). + effective_qos = 0 + else: + effective_qos = self._qos set_topic = f"{self.homie_domain}/{EBUS_HOMIE_VERSION_MAJOR}/{device_id}/{node_id}/{property_id}/set" logger.info(f"reason=settingProperty,topic={set_topic},value={value}") @@ -5088,6 +5157,16 @@ def set_property( logger.error(f"reason=setPropertyException,error={e}") return False + def _is_non_retained(self, device_id: str, node_id: str, property_id: str) -> bool: + """True when the device's discovered $description marks the property retained=false.""" + device = self.devices.get(device_id) + node: Any = device.description if device is not None else None + for key in ("nodes", node_id, "properties", property_id): + if not isinstance(node, dict): + return False + node = node.get(key) + return isinstance(node, dict) and node.get("retained") is False + def set_property_json( self, device_id: str, @@ -5372,8 +5451,13 @@ def set_on_device_removed_callback(self, callback: Callable[[DiscoveredDevice], """Set callback for when a device is removed""" self._on_device_removed = callback - def set_on_property_changed_callback(self, callback: Callable[[str, str, str, str, Optional[str]], None]) -> None: - """Set callback for property changes (device_id, node_id, property_id, new_value, old_value)""" + def set_on_property_changed_callback( + self, callback: Callable[[str, str, str, Optional[str], Optional[str]], None] + ) -> None: + """Set callback for property changes (device_id, node_id, property_id, new_value, old_value). + + new_value is None when the property's retained value was removed (a zero-length payload). + """ self._on_property_changed = callback def set_on_tree_ready_callback(self, callback: Callable[[DiscoveredDevice], None]) -> None: diff --git a/tests/test_controller.py b/tests/test_controller.py index f46c277..2ef4620 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -2496,3 +2496,188 @@ def test_injected_wildcard_resync_leaves_subscribed_devices_alone(self): client.reset_mock() ctrl.resync() client.subscribe.assert_not_called() + + +class TestControllerInboundRobustness: + """GH #93: $state values, non-UTF-8 payloads, $alert/$log, zero-length values.""" + + def _discovered(self, mock_paho): + ctrl, client = _make_controller(mock_paho) + ctrl.start_discovery() + ctrl._on_state_message(_topic("panel-1", "$state"), b"ready") + return ctrl, client + + @pytest.mark.parametrize("state", [s.value for s in DeviceState]) + def test_each_valid_state_creates_device(self, mock_paho, state): + ctrl, _ = _make_controller(mock_paho) + ctrl.start_discovery() + ctrl._on_state_message(_topic("panel-1", "$state"), state.encode()) + assert ctrl.devices["panel-1"].state == state + + def test_invalid_state_does_not_create_device(self, mock_paho): + ctrl, _ = _make_controller(mock_paho) + discovered = [] + ctrl.set_on_device_discovered_callback(discovered.append) + ctrl.start_discovery() + + ctrl._on_state_message(_topic("panel-1", "$state"), b"banana") + + assert "panel-1" not in ctrl.devices + assert discovered == [] + + def test_invalid_state_does_not_update_device(self, mock_paho): + ctrl, _ = self._discovered(mock_paho) + changes = [] + ctrl.set_on_device_state_changed_callback(lambda dev, old, new: changes.append((old, new))) + + ctrl._on_state_message(_topic("panel-1", "$state"), b"READY") + + assert ctrl.devices["panel-1"].state == "ready" + assert changes == [] + + def test_invalid_state_does_not_complete_pre_created_device(self, mock_paho): + ctrl, _ = _make_controller(mock_paho, device_id="panel-1") + ctrl.start_discovery() + + ctrl._on_state_message(_topic("panel-1", "$state"), b"banana") + + assert ctrl.devices["panel-1"].state is None + + def test_non_utf8_state_is_dropped(self, mock_paho): + ctrl, _ = _make_controller(mock_paho) + ctrl.start_discovery() + + ctrl._on_state_message(_topic("panel-1", "$state"), b"\xff\xfe") + + assert "panel-1" not in ctrl.devices + + def test_non_utf8_property_is_dropped(self, mock_paho): + ctrl, _ = self._discovered(mock_paho) + changes = [] + ctrl.set_on_property_changed_callback(lambda *args: changes.append(args)) + ctrl._on_property_message("panel-1", _topic("panel-1", "core/p"), b"1") + + ctrl._on_property_message("panel-1", _topic("panel-1", "core/p"), b"\xff") + + assert ctrl.devices["panel-1"].get_property("core", "p") == "1" + assert len(changes) == 1 + + def test_non_utf8_target_is_dropped(self, mock_paho): + ctrl, _ = self._discovered(mock_paho) + ctrl._on_target_message("panel-1", _topic("panel-1", "core/p/$target"), b"1") + + ctrl._on_target_message("panel-1", _topic("panel-1", "core/p/$target"), b"\xff") + + assert ctrl.devices["panel-1"].get_property_target("core", "p") == "1" + + @pytest.mark.parametrize("suffix", ["$alert/battery-low", "$log/warn"]) + def test_alert_and_log_are_not_properties(self, mock_paho, suffix): + ctrl, _ = self._discovered(mock_paho) + changes = [] + ctrl.set_on_property_changed_callback(lambda *args: changes.append(args)) + + ctrl._on_property_message("panel-1", _topic("panel-1", suffix), b"Battery is low") + + assert ctrl.devices["panel-1"].properties == {} + assert changes == [] + + def test_zero_length_value_removes_property(self, mock_paho): + ctrl, _ = self._discovered(mock_paho) + changes = [] + ctrl.set_on_property_changed_callback(lambda *args: changes.append(args)) + ctrl._on_property_message("panel-1", _topic("panel-1", "core/p"), b"42") + + ctrl._on_property_message("panel-1", _topic("panel-1", "core/p"), b"") + + dev = ctrl.devices["panel-1"] + assert dev.get_property("core", "p") is None + assert dev.properties == {} + assert changes[-1] == ("panel-1", "core", "p", None, "42") + + def test_zero_length_value_for_unknown_property_is_silent(self, mock_paho): + ctrl, _ = self._discovered(mock_paho) + changes = [] + ctrl.set_on_property_changed_callback(lambda *args: changes.append(args)) + + ctrl._on_property_message("panel-1", _topic("panel-1", "core/p"), b"") + + assert ctrl.devices["panel-1"].properties == {} + assert changes == [] + + def test_null_byte_value_is_still_empty_string(self, mock_paho): + ctrl, _ = self._discovered(mock_paho) + ctrl._on_property_message("panel-1", _topic("panel-1", "core/p"), b"\x00") + assert ctrl.devices["panel-1"].get_property("core", "p") == "" + + def test_zero_length_target_removes_target(self, mock_paho): + ctrl, _ = self._discovered(mock_paho) + ctrl._on_target_message("panel-1", _topic("panel-1", "core/p/$target"), b"on") + ctrl._on_target_message("panel-1", _topic("panel-1", "core/q/$target"), b"off") + + ctrl._on_target_message("panel-1", _topic("panel-1", "core/p/$target"), b"") + + dev = ctrl.devices["panel-1"] + assert dev.get_property_target("core", "p") is None + assert dev.property_targets == {"core": {"q": "off"}} + + +class TestControllerSetPropertyNonRetained: + """GH #93: a /set to a non-retained property goes at QoS 0 (convention.md:49).""" + + def _described(self, mock_paho, retained): + ctrl, client = _make_controller_with_qos(mock_paho, qos=2) + ctrl.start_discovery() + ctrl._on_state_message(_topic("panel-1", "$state"), b"ready") + spec = {"datatype": "string", "settable": True} + if retained is not None: + spec["retained"] = retained + desc = {"homie": "5.0", "version": 1, "nodes": {"core": {"properties": {"cmd": spec}}}} + ctrl._on_description_message("panel-1", _topic("panel-1", "$description"), json.dumps(desc).encode()) + return ctrl, client + + @pytest.mark.parametrize("retained, expected_qos", [(False, 0), (True, 2), (None, 2)]) + def test_qos_follows_retained(self, mock_paho, retained, expected_qos): + ctrl, client = self._described(mock_paho, retained) + + assert ctrl.set_property("panel-1", "core", "cmd", "go") is True + + _, kwargs = client.publish.call_args + assert kwargs["qos"] == expected_qos + assert kwargs["retain"] is False + + def test_explicit_qos_wins(self, mock_paho): + ctrl, client = self._described(mock_paho, retained=False) + + ctrl.set_property("panel-1", "core", "cmd", "go", qos=1) + + _, kwargs = client.publish.call_args + assert kwargs["qos"] == 1 + + @pytest.mark.parametrize( + "desc", + [ + {"homie": "5.0", "nodes": {"core": "x"}}, + {"homie": "5.0", "nodes": {"core": {"properties": "x"}}}, + {"homie": "5.0", "nodes": {"core": {"properties": {"cmd": "x"}}}}, + {"homie": "5.0", "nodes": "core"}, + ["not", "a", "dict"], + ], + ) + def test_malformed_description_uses_controller_qos(self, mock_paho, desc): + ctrl, client = _make_controller_with_qos(mock_paho, qos=2) + ctrl.start_discovery() + ctrl._on_state_message(_topic("panel-1", "$state"), b"ready") + ctrl._on_description_message("panel-1", _topic("panel-1", "$description"), json.dumps(desc).encode()) + + assert ctrl.set_property("panel-1", "core", "cmd", "go") is True + + _, kwargs = client.publish.call_args + assert kwargs["qos"] == 2 + + def test_undiscovered_device_uses_controller_qos(self, mock_paho): + ctrl, client = _make_controller_with_qos(mock_paho, qos=2) + + ctrl.set_property("other", "core", "cmd", "go") + + _, kwargs = client.publish.call_args + assert kwargs["qos"] == 2