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 @@ -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/<id>` and `$log/<level>` 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

Expand Down
112 changes: 98 additions & 14 deletions src/ebus_sdk/homie.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand Down Expand Up @@ -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/<id> and $log/<level>.
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)

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

Expand All @@ -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
Expand All @@ -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}")
Expand All @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading