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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ All notable changes to `ebus-sdk` are recorded here. Format follows [Keep a Chan
### 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.
- `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))

### 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))

## [0.27.0] — 2026-10-21

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ Device(id='mid-1', type='...metering', parent=bess)
panel.children()[0].delete()
```

Children may have children of their own. A single Last Will registered on the root marks the entire tree `lost` if the publisher process dies, and `root.declare_lost()` publishes the same thing deliberately when the publisher knows it is dying — controllers compute effective state per the Homie 5 precedence table (see [`HOMIE_EFFECTIVE_STATE_TABLE`](src/ebus_sdk/homie.py)).
Children may have children of their own. A single Last Will registered on the root marks the entire tree `lost` if the publisher process dies, and `root.declare_lost()` publishes the same thing deliberately when the publisher knows it is dying — controllers compute effective state per the Homie 5 rule that a lost root makes every descendant lost (see [`HOMIE_EFFECTIVE_STATE_TABLE`](src/ebus_sdk/homie.py)).

`$description` republishes are minimized: structural changes made inside one `state_transition()` collapse to a single consolidated publish at exit (not one per `add_node`), and `publish_description()` is a no-op when the description content is unchanged — so a `state_transition()` that changes nothing structural does not re-emit the (potentially multi-KB) `$description`. A reconnect always republishes regardless, to restore retained state. Note this suppresses the redundant `$description` payload, not the `$state` `init`→`ready` edge of an empty transition. Property *values* are minimized the same way and with the same reconnect carve-out (see [Unchanged values are not republished](#unchanged-values-are-not-republished)). The document's `version` is derived from its content (the top 52 bits of a SHA-256 of the document without `version`), so an unchanged document keeps its version across reconnects and restarts, and any change gets a new one. Homie 5 lets `$description` change only while the device is `init`, `disconnected` or `lost`: a structural change made outside a `state_transition()` on a `ready` or `sleeping` device is published as `init`, the changed values, the new `$description`, then the state the device was in. A change that leaves the document as last published (a property added to a node not yet attached to its device, or an identical re-declaration) publishes only its values.

Expand Down Expand Up @@ -274,8 +274,8 @@ Controllers can also navigate device hierarchies and compute effective state:
roots = controller.get_root_devices()
for root in roots:
for descendant in controller.get_descendants(root.device_id):
# When the root is lost/disconnected/sleeping/init, every descendant
# is effectively the same regardless of its own reported $state.
# When the root is lost, every descendant is effectively lost
# regardless of its own reported $state.
print(f'{descendant.device_id}: {controller.get_effective_state(descendant.device_id)}')
```

Expand Down
2 changes: 1 addition & 1 deletion doc/consuming-a-homie-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ It is specifically **not**:

The rollup reading is the common one and it cannot be made true by any producer. Children are commissioned and decommissioned out of band, so at any instant a new child may be mid-publish. **There is no moment at which a producer knows it has published "all" its children.** The strongest guarantee any producer can offer is per-transaction: *within this cascade, my announcement follows the content it announces.* That is a statement about a transaction, not about the world.

The one thing a root's state **is** authoritative for is **effective state**. Homie 5 propagates a non-ready root down the tree: when the root is `init`, `disconnected`, `sleeping`, or `lost`, its descendants are effectively that too, because the root is the gateway. Only when the root is `ready` do a child's own reported states stand. `Controller.get_effective_state(device_id)` implements this. Note it keys on the **root**, not on the immediate parent, so a mid-tree device entering a `state_transition()` does not mask its own children.
The one thing a root's state **is** authoritative for is **effective state**, and only when it is `lost` (convention.md:262-267). The root's Last Will sets the root `lost` but cannot update its descendants, so a lost root makes every descendant effectively `lost`. In every other root state (`init`, `ready`, `disconnected`, `sleeping`) a child's own reported `$state` stands. `Controller.get_effective_state(device_id)` implements this. Note it keys on the **root**, not on the immediate parent, so a mid-tree device entering a `state_transition()` does not mask its own children.

## What a consumer MUST do

Expand Down
2 changes: 1 addition & 1 deletion examples/simple-controller
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def _print_device(controller: Controller, device: DiscoveredDevice, depth: int)
pad = " " * depth
effective = controller.get_effective_state(device.device_id)
own = device.state
# Show the effective state; call out when a non-ready root has suppressed a
# Show the effective state; call out when a lost root has overridden a
# descendant's own state (the whole point of a tree-aware view).
state = str(effective) if effective == own else f"{effective} (own: {own})"
dtype = (device.description or {}).get("type", "?")
Expand Down
168 changes: 139 additions & 29 deletions src/ebus_sdk/homie.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"""

import asyncio
import calendar
import contextlib
import datetime
import decimal
Expand Down Expand Up @@ -423,7 +424,7 @@ class PropertyDatatype(StrEnum):
| -?W(?P<week>\d{2})(?:-?(?P<weekday>\d))?
)?
(?:
T(?P<hour>\d{2})(?::?(?P<minute>\d{2})(?::?(?P<second>\d{2}))?)?(?:[.,]\d+)?
T(?P<hour>\d{2})(?::?(?P<minute>\d{2})(?::?(?P<second>\d{2}))?)?(?:[.,](?P<fraction>\d+))?
(?:Z|[+-](?P<zhour>\d{2})(?::?(?P<zminute>\d{2}))?)?
)?
""",
Expand All @@ -437,6 +438,36 @@ def _reject_json_constant(name: str) -> Any:
raise ValueError(f"{name} is not JSON")


def _finite_json_float(text: str) -> float:
# A number outside the float range (`1e400`) would otherwise decode to inf.
number = float(text)
if not math.isfinite(number):
raise ValueError(f"{text} is not a finite number")
return number


def _json_has_lone_surrogate(value: Any) -> bool:
"""Whether any string or key in a decoded JSON value holds a lone surrogate.

A `\\ud800` escape decodes to a code point that is not a Unicode scalar value
and cannot be encoded as UTF-8. Iterative, so nesting depth costs no stack.
"""
pending = [value]
while pending:
item = pending.pop()
if isinstance(item, dict):
pending.extend(item.keys())
pending.extend(item.values())
elif isinstance(item, list):
pending.extend(item)
elif isinstance(item, str):
try:
item.encode("utf-8")
except UnicodeEncodeError:
return True
return False


def _format_float(number: float) -> Optional[str]:
"""A finite float in the convention's grammar: no `+` in the exponent (:97)."""
if not math.isfinite(number):
Expand All @@ -450,7 +481,10 @@ def _encode_integer(value: Any) -> tuple:
if isinstance(value, str):
if not _INTEGER_PAYLOAD.fullmatch(value):
return None, "integerGrammar"
number = int(value)
try:
number = int(value)
except ValueError: # over Python's 4,300-digit int conversion limit
return None, "integerOutOf64Bit"
elif isinstance(value, numbers.Integral):
number = int(value)
elif isinstance(value, numbers.Real):
Expand Down Expand Up @@ -564,7 +598,8 @@ def _check_datetime_payload(text: str) -> Optional[str]:
match = _DATETIME_PAYLOAD.fullmatch(text)
if not match:
return "datetimeGrammar"
fields = {k: int(v) for k, v in match.groupdict().items() if v is not None}
fraction = match.group("fraction")
fields = {k: int(v) for k, v in match.groupdict().items() if v is not None and k != "fraction"}
if "hour" in fields and not fields.keys() & {"day", "bday", "ordinal", "weekday"}:
return "datetimeGrammar" # a time of day needs a complete date
try:
Expand All @@ -579,9 +614,29 @@ def _check_datetime_payload(text: str) -> Optional[str]:
for name, (low, high) in limits.items():
if name in fields and not low <= fields[name] <= high:
return "datetimeRange"
# 24 is only the end-of-day instant 24:00[:00[.0]].
if fields.get("hour") == 24 and (fields.get("minute") or fields.get("second") or (fraction or "").strip("0")):
return "datetimeRange"
if fields.get("ordinal") == 366 and not calendar.isleap(fields["year"]):
return "datetimeRange"
if fields.get("week") == 53 and not _has_iso_week_53(fields["year"]):
return "datetimeRange"
return None


def _has_iso_week_53(year: int) -> bool:
"""Whether ISO ``year`` has a week 53 (it ends on a Thursday, or its predecessor on a Wednesday).

Arithmetic rather than ``date(year, 12, 28).isocalendar()``, which cannot
represent year 0000.
"""

def dec31_weekday(y: int) -> int: # 0 = Sunday ... 4 = Thursday
return (y + y // 4 - y // 100 + y // 400) % 7

return dec31_weekday(year) == 4 or dec31_weekday(year - 1) == 3


def _encode_datetime(value: Any) -> tuple:
if isinstance(value, (datetime.datetime, datetime.date)):
# ISO 8601 extended form, `T` separator (convention.md:132).
Expand Down Expand Up @@ -618,13 +673,19 @@ def _encode_duration(value: Any) -> tuple:


def _decode_json_container(text: str) -> tuple:
"""Parse a json payload: an array or object, never NaN/Infinity (convention.md:150)."""
"""Parse a json payload: an array or object (convention.md:150).

Rejected as ``jsonInvalid``: NaN/Infinity, a number outside the float range,
and a string or key holding a lone surrogate.
"""
try:
decoded = json.loads(text, parse_constant=_reject_json_constant)
except (ValueError, TypeError):
decoded = json.loads(text, parse_constant=_reject_json_constant, parse_float=_finite_json_float)
except (ValueError, TypeError, RecursionError):
return None, "jsonInvalid"
if not isinstance(decoded, (list, dict)):
return None, "jsonNotArrayOrObject"
if _json_has_lone_surrogate(decoded):
return None, "jsonInvalid"
return decoded, None


Expand All @@ -636,9 +697,12 @@ def _encode_json(value: Any) -> tuple:
if not isinstance(value, (list, tuple, dict)):
return None, "jsonNotArrayOrObject"
try:
return json.dumps(value, allow_nan=False), None
except (TypeError, ValueError):
payload = json.dumps(value, allow_nan=False)
except (TypeError, ValueError, RecursionError):
return None, "jsonInvalid"
# The same grammar the /set path applies: no lone surrogates.
_, problem = _decode_json_container(payload)
return (None, problem) if problem else (payload, None)


def _encode_property_value(value: Any, datatype: Any, format_: Any = None) -> tuple:
Expand Down Expand Up @@ -669,6 +733,41 @@ def _encode_property_value(value: Any, datatype: Any, format_: Any = None) -> tu
return (str(value.value) if isinstance(value, Enum) else str(value)), None


# Past float's range both ways (about 1.8e308 down to 4.9e-324).
_EXACT_MAGNITUDE_LIMIT = 1000


def _exact_number(text: str) -> Optional[Fraction]:
"""The exact value of a ``_FLOAT_PAYLOAD`` text, or None over 4,300 digits.

A nonzero magnitude past ``10**±_EXACT_MAGNITUDE_LIMIT`` is clamped to it,
sign kept, so ``1e-100000000`` costs no ``10**100000000``. Clamping keeps
its order against every float-range number.
"""
mantissa, _, exponent = text.lower().partition("e")
negative = mantissa.startswith("-")
whole, _, fraction = mantissa.lstrip("-").partition(".")
try:
significand = int(whole + fraction)
except ValueError: # over Python's 4,300-digit int conversion limit
return None
if significand == 0:
return Fraction(0)
exponent_digits = exponent.lstrip("-").lstrip("0")
if len(exponent_digits) > 6:
scale = (-1 if exponent.startswith("-") else 1) * (10 * _EXACT_MAGNITUDE_LIMIT)
else:
scale = int(exponent or "0") - len(fraction)
magnitude = scale + len(str(significand))
if magnitude > _EXACT_MAGNITUDE_LIMIT:
number = Fraction(10**_EXACT_MAGNITUDE_LIMIT)
elif magnitude < -_EXACT_MAGNITUDE_LIMIT:
number = Fraction(1, 10**_EXACT_MAGNITUDE_LIMIT)
else:
number = significand * Fraction(10) ** scale
return -number if negative else number


def _numeric_format(format_: Any) -> tuple:
"""``(min, max, step)`` as Fractions (each may be None) from ``[min]:[max][:step]``.

Expand All @@ -682,9 +781,7 @@ def _numeric_format(format_: Any) -> tuple:
return None, None, None

def bound(text: str) -> Optional[Fraction]:
if not _FLOAT_PAYLOAD.fullmatch(text):
return None
return Fraction(text)
return _exact_number(text) if _FLOAT_PAYLOAD.fullmatch(text) else None

low, high = bound(parts[0]), bound(parts[1])
step = bound(parts[2]) if len(parts) == 3 else None
Expand Down Expand Up @@ -728,22 +825,38 @@ def _parse_set_payload(text: str, datatype: Any, format_: Any, current: Any) ->
if datatype == PropertyDatatype.JSON:
return _decode_json_container(text)
if datatype == PropertyDatatype.INTEGER:
if not _INTEGER_PAYLOAD.fullmatch(text) or not _INT64_MIN <= int(text) <= _INT64_MAX:
if not _INTEGER_PAYLOAD.fullmatch(text):
return None, "integerGrammar"
try:
number = int(text)
except ValueError: # over Python's 4,300-digit int conversion limit
return None, "integerGrammar"
if not _INT64_MIN <= number <= _INT64_MAX:
return None, "integerGrammar"
rounded, problem = _round_and_range_check(Fraction(int(text)), format_, current)
rounded, problem = _round_and_range_check(Fraction(number), format_, current)
if problem:
return None, problem
if rounded.denominator != 1:
return None, "integerStepNotWhole"
return (text if rounded == int(text) else str(int(rounded))), None
# Step rounding can carry an in-range payload past int64 (convention.md:87-88).
if not _INT64_MIN <= rounded <= _INT64_MAX:
return None, "integerOutOf64Bit"
return (text if rounded == number else str(int(rounded))), None
if datatype == PropertyDatatype.FLOAT:
if not _FLOAT_PAYLOAD.fullmatch(text) or not math.isfinite(float(text)):
return None, "floatGrammar"
number = Fraction(text)
number = _exact_number(text)
if number is None:
return None, "floatGrammar"
rounded, problem = _round_and_range_check(number, format_, current)
if problem:
return None, problem
return (text if rounded == number else _format_float(float(rounded))), None
if rounded == number:
return text, None
try:
return _format_float(float(rounded)), None
except OverflowError: # step rounding carried it past the float range
return None, "floatOutOfRange"
if datatype == PropertyDatatype.BOOLEAN:
return (text, None) if text in ("true", "false") else (None, "booleanGrammar")
if datatype == PropertyDatatype.ENUM:
Expand Down Expand Up @@ -858,20 +971,18 @@ class DeviceState(StrEnum):
LOST = "lost"


# Homie 5 effective-state precedence table (SDK-zt2).
# Homie 5 effective-state precedence table (convention.md:262-267).
#
# A non-root device's effective state is determined by its root's reported state:
# whenever the root is in a non-ready state, that state propagates down the tree
# (the root is the gateway to the children, so if it's lost/disconnected/sleeping/
# init the children are effectively the same). Only when the root is `ready` do
# the children's own reported states stand.
# A non-root device's effective state is its own reported `$state`, unless its
# root is `lost`: the root's Last Will does not update the children, so a lost
# root makes every descendant lost. A root in any other state overrides nothing.
#
# Mapping: root_state -> override_for_children. A None value means "no override,
# use the child's own state".
HOMIE_EFFECTIVE_STATE_TABLE: dict = {
DeviceState.INIT: DeviceState.INIT,
DeviceState.DISCONNECTED: DeviceState.DISCONNECTED,
DeviceState.SLEEPING: DeviceState.SLEEPING,
DeviceState.INIT: None,
DeviceState.DISCONNECTED: None,
DeviceState.SLEEPING: None,
DeviceState.LOST: DeviceState.LOST,
DeviceState.READY: None,
}
Expand Down Expand Up @@ -5098,13 +5209,12 @@ def _reevaluate_tree_completeness(self) -> None:

def get_effective_state(self, device_id: str) -> Optional[str]:
"""
Return the device's effective state per the Homie 5 spec (SDK-zt2).
Return the device's effective state per the Homie 5 spec (convention.md:262-267).

For a root device: returns its own reported state.

For a child: applies HOMIE_EFFECTIVE_STATE_TABLE — when the root is in a
non-ready state (init/disconnected/sleeping/lost), that state propagates
down the tree. Only when the root is ready do children's own states stand.
For a child: applies HOMIE_EFFECTIVE_STATE_TABLE: a child is ``lost`` when
its root is ``lost``, and otherwise its own reported state stands.

Returns None when the device isn't discovered. Returns the device's own
state (best-effort) when the device's named root isn't yet discovered —
Expand Down
Loading
Loading