Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).

### Changed

- `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.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 2 additions & 0 deletions doc/building-a-proxy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/ebus_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
PropertyDict,
ChangeEvent,
BulkUpdateContext,
SetRefused,
)

# Proxy / adapter helpers (see doc/building-a-proxy.md)
Expand Down Expand Up @@ -117,6 +118,7 @@
"PropertyDict",
"ChangeEvent",
"BulkUpdateContext",
"SetRefused",
# Proxy / adapter helpers
"set_homie_property_from_python_property",
"bind_property_to_homie",
Expand Down
23 changes: 20 additions & 3 deletions src/ebus_sdk/homie.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,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,
Expand Down Expand Up @@ -1402,7 +1403,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:
Expand Down Expand Up @@ -1666,6 +1675,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:
Expand Down Expand Up @@ -1732,6 +1744,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}")

Expand All @@ -1740,12 +1754,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:
Expand Down
16 changes: 15 additions & 1 deletion src/ebus_sdk/property.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""

Expand Down Expand Up @@ -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:
Expand Down
24 changes: 24 additions & 0 deletions tests/test_declaration.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Tests for the declarative PropertySpec + build_from_declarations builder."""

from unittest.mock import patch

import pytest

from ebus_sdk import (
Expand All @@ -10,6 +12,7 @@
ObservableProperty,
PropertyDatatype,
PropertySpec,
SetRefused,
Unit,
build_from_declarations,
python_type_for,
Expand Down Expand Up @@ -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()
Expand Down
54 changes: 54 additions & 0 deletions tests/test_homie_device.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -8,6 +9,7 @@

import pytest

from ebus_sdk import SetRefused
from ebus_sdk.homie import (
Property,
PropertyDatatype,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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", datatype=PropertyDatatype.STRING, 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."""
Expand Down
20 changes: 20 additions & 0 deletions tests/test_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
import threading
from unittest.mock import MagicMock

import pytest

from ebus_sdk.property import (
Property,
PropertyDict,
GroupedPropertyDict,
ChangeEvent,
SetRefused,
)


Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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))
Expand Down
Loading