From 1f8ba681fb6bc1d4dd862ed9ba753e92d7c9a655 Mon Sep 17 00:00:00 2001 From: Donald Clark Jackson Date: Wed, 11 Nov 2026 15:27:08 -0800 Subject: [PATCH 1/2] Let a /set callback refuse a value with SetRefused (#102) Raising ebus_sdk.SetRefused from a set callback (sync, or the awaited coroutine) logs reason=propertySetRefused at info instead of a callback exception. ObservableProperty.set_entity re-raises it, so declaration- built properties refuse the same way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VUQ6apRySRNW8y3ppJMdJC --- CHANGELOG.md | 4 +++ README.md | 2 ++ doc/building-a-proxy.md | 2 ++ src/ebus_sdk/__init__.py | 2 ++ src/ebus_sdk/homie.py | 23 +++++++++++++--- src/ebus_sdk/property.py | 16 ++++++++++- tests/test_declaration.py | 24 +++++++++++++++++ tests/test_homie_device.py | 54 ++++++++++++++++++++++++++++++++++++++ tests/test_property.py | 20 ++++++++++++++ 9 files changed, 143 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 571ffaa..eb84173 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] +### Added + +- `SetRefused`, exported from `ebus_sdk`: a `/set` callback (or the coroutine an async one returns) raises it to refuse a well-formed value it will not apply, and the property logs `reason=propertySetRefused,propertyID=...` at info level instead of `propertySetCallbackException`. `ObservableProperty.set_entity()` re-raises it from its `entity_setter` and still logs and swallows any other exception, so a refusal in an `entity_setter` wired by `build_from_declarations` reaches the Homie layer. Return values keep their meaning ([#102](https://github.com/electrification-bus/python-sdk/issues/102)). + ## [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/README.md b/README.md index 58ee3ce..8943cf0 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,8 @@ A property with `retained=False` publishes non-retained at QoS 0, as Homie 5 req A `/set` payload is checked against the property's datatype before its `set_callback` runs, and an invalid one is dropped with a `reason=propertySetRejected` warning: `json` must be an array or object (and match a `$format` JSONschema when one can be checked), `integer` and `float` must follow the payload grammar, `boolean` must be `true` or `false`, an `enum` value must be in its `format`, and a `datetime` must be ISO 8601. A number is rounded to its format's step and then checked against min/max (convention.md:397-413): the callback receives the payload as sent, or its rounded form if rounding changed it (`5` on `0:10:2` arrives as `6`). +A `set_callback` refuses a valid value by raising `ebus_sdk.SetRefused` (from the callback, or from the coroutine an async callback returns); it is logged as `reason=propertySetRefused` at info level, not as a callback exception. Its return value is not a refusal. + A `/set` the broker delivers with the retain flag set is a stale command replayed at subscribe time, since controllers publish `/set` non-retained only; it is ignored with a `reason=propertySetRetainedIgnored` warning. That needs ebus-mqtt-client 0.7.0 or later, whose `subscribe(..., with_retain=True)` delivers the flag. With an older client, or an injected transport whose `subscribe` has no `with_retain` parameter, the check is skipped and a debug line says so. `supports_target=True` is inert: `$target` is not implemented, so the property logs one warning at construction and never publishes `$target`. diff --git a/doc/building-a-proxy.md b/doc/building-a-proxy.md index 657b78e..aac63e7 100644 --- a/doc/building-a-proxy.md +++ b/doc/building-a-proxy.md @@ -220,6 +220,8 @@ For each settable spec that has an `entity_setter`, `build_from_declarations` re Inbound flow: MQTT `/set` -> Homie property `set_callback` -> `model.set_entity(capability, prop_id, value)` -> your `entity_setter` -> device command. Your `entity_setter` actuates the device and, once the real state changes, writes it back with `model.set_value(...)`, which mirrors onto Homie via the outbound (report) path. +To refuse a command the device cannot apply now (interlocked, busy, out of range for its current mode), raise `ebus_sdk.SetRefused` from the `entity_setter`. `model.set_entity` re-raises it (any other exception it logs and swallows), and the Homie property logs `reason=propertySetRefused,propertyID=...` at info level rather than a callback exception. A `set_callback` you wire yourself, or the coroutine an async one returns, refuses the same way. Return values carry no meaning here: `set_entity` returns the value it was given. + If you build the tree by hand instead of via `build_from_declarations`, wire the same two seams yourself: `model.set_entity_setter(capability, prop_id, fn)` and `homie_property.set_set_callback(partial(model.set_entity, capability, prop_id))`. ### Settable `json` properties and `$format` validation diff --git a/src/ebus_sdk/__init__.py b/src/ebus_sdk/__init__.py index 9352d8a..d0e3f85 100644 --- a/src/ebus_sdk/__init__.py +++ b/src/ebus_sdk/__init__.py @@ -48,6 +48,7 @@ PropertyDict, ChangeEvent, BulkUpdateContext, + SetRefused, ) # Proxy / adapter helpers (see doc/building-a-proxy.md) @@ -117,6 +118,7 @@ "PropertyDict", "ChangeEvent", "BulkUpdateContext", + "SetRefused", # Proxy / adapter helpers "set_homie_property_from_python_property", "bind_property_to_homie", diff --git a/src/ebus_sdk/homie.py b/src/ebus_sdk/homie.py index f7966c9..3df5ac1 100644 --- a/src/ebus_sdk/homie.py +++ b/src/ebus_sdk/homie.py @@ -74,6 +74,7 @@ class StrEnum(str, Enum): from ebus_mqtt_client import MqttClient from ebus_sdk.transport import MqttControllerTransport, MqttDeviceTransport +from ebus_sdk.property import SetRefused # Optional: JSONSchema validation of a `json` property's `$format`. Kept optional # (see `ebus-sdk[validation]`) so a constrained build can omit it; absent it, @@ -1278,7 +1279,15 @@ def get_set_callback(self) -> Callable: return self._set_callback def set_set_callback(self, callback: Callable) -> None: - """Set the callback function for handling /set topic messages.""" + """Set the callback function for handling /set topic messages. + + The callback receives the validated value. To refuse it (well-formed, but not + applicable now: interlocked, busy, out of range for the current mode), raise + ``SetRefused``, from the callback or from the coroutine it returns; the refusal + is logged as ``reason=propertySetRefused`` at info level. Any other exception is + logged as a callback exception. The return value is used only to detect a + coroutine. + """ self._set_callback = callback def supports_target(self) -> bool: @@ -1542,6 +1551,9 @@ def _settable_callback(self, topic: str, payload: Union[bytes, bytearray], retai (convention.md:399), an enum must be in ``$format``, a boolean must be ``true`` or ``false``. The ``0x00`` empty-string decoding applies to string properties only. + + A callback refuses a valid value by raising ``SetRefused``, logged as + ``reason=propertySetRefused`` at info level. """ logger.debug(f"reason=propertySetCallback,topic={topic}") try: @@ -1608,6 +1620,8 @@ def _settable_callback(self, topic: str, payload: Union[bytes, bytearray], retai # coroutine would vanish silently (the inline path is caught below by the # surrounding try/except). Surface it, matching the sync path's logging. future.add_done_callback(partial(self._log_async_set_result, property_id=property_id)) + except SetRefused as e: + logger.info(f"reason=propertySetRefused,propertyID={property_id},e={e}") except Exception as e: logger.exception(f"reason=propertySetCallbackException,e={e}") @@ -1616,12 +1630,15 @@ def _log_async_set_result(self, future, property_id) -> None: The scheduling Future is otherwise discarded, and a discarded concurrent.futures Future swallows a stored exception silently (unlike an asyncio.Task). Surface it, - matching the synchronous path's ``propertySetCallbackException`` logging. + matching the synchronous path's ``propertySetCallbackException`` logging, and + its ``propertySetRefused`` logging for a ``SetRefused``. """ if future.cancelled(): return exc = future.exception() - if exc is not None: + if isinstance(exc, SetRefused): + logger.info(f"reason=propertySetRefused,propertyID={property_id},e={exc}") + elif exc is not None: logger.error(f"reason=propertySetAsyncCallbackException,propertyID={property_id},exc={exc!r}") def set_subscribe(self) -> None: diff --git a/src/ebus_sdk/property.py b/src/ebus_sdk/property.py index fab65ea..b74eed3 100644 --- a/src/ebus_sdk/property.py +++ b/src/ebus_sdk/property.py @@ -21,6 +21,17 @@ from typing import List, Callable, Union, Optional, Any, Type +class SetRefused(Exception): + """Raised by a ``/set`` callback (or an ``entity_setter``) to refuse a value. + + The value was well-formed but the application will not apply it: out of range + for the hardware's current mode, interlocked, busy. The Homie layer logs + ``reason=propertySetRefused`` at info level instead of a callback exception. + ``Property.set_entity()`` re-raises it, so a refusal in an ``entity_setter`` + reaches the Homie layer through ``GroupedPropertyDict.set_entity()``. + """ + + class ChangeEvent(Enum): """Events fired by GroupedPropertyDict""" @@ -183,12 +194,15 @@ def set_entity(self, new_value: Any) -> Any: which is done by the property invoking a registered set_entity_callback function Presumably changing the entity state will eventually result in the property's state being set/changed, which will then invoke any on_set and/or in_change callbacks - Returns the new value + Returns the new value. A ``SetRefused`` raised by the entity_setter propagates; + any other exception is logged and swallowed. """ if self._entity_setter: logging.info(f"reason=setEntity,propertyId={self._id},new_value={new_value}") try: self._entity_setter(new_value) + except SetRefused: + raise except Exception as e: logging.warning(f"reason=setEntityException,propertyId={self._id},new_value={new_value},e={e}") else: diff --git a/tests/test_declaration.py b/tests/test_declaration.py index 98d0475..4e9a18a 100644 --- a/tests/test_declaration.py +++ b/tests/test_declaration.py @@ -1,5 +1,7 @@ """Tests for the declarative PropertySpec + build_from_declarations builder.""" +from unittest.mock import patch + import pytest from ebus_sdk import ( @@ -10,6 +12,7 @@ ObservableProperty, PropertyDatatype, PropertySpec, + SetRefused, Unit, build_from_declarations, python_type_for, @@ -123,6 +126,27 @@ def test_build_from_declarations_wires_settable_entity_setter(mock_paho): assert received[-1] == "OTHER" +def test_entity_setter_refusal_reaches_the_homie_layer(mock_paho): + """A SetRefused from an entity_setter crosses model.set_entity to the /set handler (#102).""" + device = Device("dev-refuse", mqtt_cfg={"host": "localhost", "port": 1883}) + device.start_mqtt_client() + model = GroupedPropertyDict() + + def refuse(value): + raise SetRefused("interlocked") + + specs = [PropertySpec("relay", "state", PropertyDatatype.BOOLEAN, settable=True, entity_setter=refuse)] + hp = build_from_declarations(device, model, specs)[("relay", "state")] + + with pytest.raises(SetRefused): + hp.get_set_callback()(True) + + with patch("ebus_sdk.homie.logger") as mock_logger: + hp._settable_callback("ebus/5/dev-refuse/relay/state/set", b"true") + assert any("reason=propertySetRefused,propertyID=state" in str(c) for c in mock_logger.info.call_args_list) + mock_logger.exception.assert_not_called() + + def test_build_from_declarations_settable_without_entity_setter_not_auto_wired(mock_paho): device = Device("dev-set2", mqtt_cfg={"host": "localhost", "port": 1883}) device.start_mqtt_client() diff --git a/tests/test_homie_device.py b/tests/test_homie_device.py index a626e92..7fdfeca 100644 --- a/tests/test_homie_device.py +++ b/tests/test_homie_device.py @@ -1,5 +1,6 @@ """Tests for ebus_sdk.homie device-role classes: Property, Node, Device, and helpers.""" +import asyncio import json import logging import threading @@ -8,6 +9,7 @@ import pytest +from ebus_sdk import SetRefused from ebus_sdk.homie import ( Property, PropertyDatatype, @@ -860,6 +862,34 @@ def test_settable_callback_invalid_topic_noop(self): prop._settable_callback(topic, b"manual") cb.assert_not_called() + def test_set_refused_logs_info_not_exception(self): + """A callback raising SetRefused is a refusal, not a callback failure (#102).""" + cb = MagicMock(side_effect=SetRefused("interlocked")) + mock_client = _mock_mqtt_client() + prop = _make_wired_property( + mock_client, id="mode", settable=True, set_callback=cb, datatype=PropertyDatatype.STRING + ) + + topic = f"{EBUS_HOMIE_DOMAIN}/{EBUS_HOMIE_VERSION_MAJOR}/dev1/node1/mode/set" + with patch("ebus_sdk.homie.logger") as mock_logger: + prop._settable_callback(topic, b"manual") + cb.assert_called_once_with("manual") + assert any("reason=propertySetRefused,propertyID=mode" in str(c) for c in mock_logger.info.call_args_list) + assert not any("propertySetCallbackException" in str(c) for c in mock_logger.exception.call_args_list) + + def test_other_exception_still_logged_as_callback_exception(self): + cb = MagicMock(side_effect=ValueError("boom")) + mock_client = _mock_mqtt_client() + prop = _make_wired_property( + mock_client, id="mode", settable=True, set_callback=cb, datatype=PropertyDatatype.STRING + ) + + topic = f"{EBUS_HOMIE_DOMAIN}/{EBUS_HOMIE_VERSION_MAJOR}/dev1/node1/mode/set" + with patch("ebus_sdk.homie.logger") as mock_logger: + prop._settable_callback(topic, b"manual") + assert any("propertySetCallbackException" in str(c) for c in mock_logger.exception.call_args_list) + assert not any("propertySetRefused" in str(c) for c in mock_logger.info.call_args_list) + class TestEmptyStringEncoding: # Homie 5: an empty-string *value* is carried as a single 0x00 byte, to @@ -2877,6 +2907,30 @@ def test_async_set_callback_exception_is_surfaced(self): prop._log_async_set_result(future, "mode") assert any("propertySetAsyncCallbackException" in str(c) for c in mock_logger.error.call_args_list) + def test_async_set_refused_logs_info(self): + """A SetRefused from an awaited /set coroutine is a refusal, as on the sync path (#102).""" + + async def cb(payload): + raise SetRefused("busy") + + loop = asyncio.new_event_loop() + thread = threading.Thread(target=loop.run_forever, daemon=True) + thread.start() + try: + prop = Property(id="mode", settable=True, set_callback=cb) + prop.async_loop = loop + logged = threading.Event() + with patch("ebus_sdk.homie.logger") as mock_logger: + mock_logger.info.side_effect = lambda *a, **k: logged.set() + prop._settable_callback("ebus/5/dev/node/mode/set", b"LOAD_UP") + assert logged.wait(timeout=5) + assert any("reason=propertySetRefused,propertyID=mode" in str(c) for c in mock_logger.info.call_args_list) + mock_logger.error.assert_not_called() + finally: + loop.call_soon_threadsafe(loop.stop) + thread.join(timeout=5) + loop.close() + class TestDeviceWithoutTransport: """`mqtt_cfg=None` — the declared default — builds a device tree with no transport.""" diff --git a/tests/test_property.py b/tests/test_property.py index 7512a3c..200dcb2 100644 --- a/tests/test_property.py +++ b/tests/test_property.py @@ -3,12 +3,14 @@ import threading from unittest.mock import MagicMock +import pytest from ebus_sdk.property import ( Property, PropertyDict, GroupedPropertyDict, ChangeEvent, + SetRefused, ) @@ -87,6 +89,16 @@ def test_entity_setter_not_set(self): # Should not raise p.set_entity("manual") + def test_set_entity_reraises_set_refused(self): + """A refusal reaches the caller (the Homie /set layer); other errors do not (#102).""" + p = Property(id="mode", value="auto", entity_setter=MagicMock(side_effect=SetRefused("busy"))) + with pytest.raises(SetRefused): + p.set_entity("manual") + + def test_set_entity_swallows_other_exceptions(self): + p = Property(id="mode", value="auto", entity_setter=MagicMock(side_effect=ValueError("boom"))) + assert p.set_entity("manual") == "manual" + def test_set_entity_setter(self): p = Property(id="mode", value="auto") setter = MagicMock() @@ -362,6 +374,14 @@ def test_set_entity(self): gpd.set_entity("ctrl", "mode", "manual") setter.assert_called_once_with("manual") + def test_set_entity_propagates_set_refused(self): + setter = MagicMock(side_effect=SetRefused("interlocked")) + gpd = GroupedPropertyDict() + gpd.add_property("ctrl", Property(id="mode", value="auto", entity_setter=setter)) + + with pytest.raises(SetRefused): + gpd.set_entity("ctrl", "mode", "manual") + def test_as_dict(self): gpd = GroupedPropertyDict() gpd.add_property("sensors", Property(id="temp", value=72)) From d091e00d249d184a57047ed02dc5de83f0bed38a Mon Sep 17 00:00:00 2001 From: Donald Clark Jackson Date: Wed, 11 Nov 2026 15:29:17 -0800 Subject: [PATCH 2/2] Give the async refusal test's property a datatype Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VUQ6apRySRNW8y3ppJMdJC --- tests/test_homie_device.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_homie_device.py b/tests/test_homie_device.py index 7fdfeca..91cda7f 100644 --- a/tests/test_homie_device.py +++ b/tests/test_homie_device.py @@ -2917,7 +2917,7 @@ async def cb(payload): thread = threading.Thread(target=loop.run_forever, daemon=True) thread.start() try: - prop = Property(id="mode", settable=True, set_callback=cb) + prop = Property(id="mode", datatype=PropertyDatatype.STRING, settable=True, set_callback=cb) prop.async_loop = loop logged = threading.Event() with patch("ebus_sdk.homie.logger") as mock_logger: