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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ All notable changes to `ebus-sdk` are recorded here. Format follows [Keep a Chan
- 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)).
- Breaking: invalid producer input that 0.25.0 warned about raises `ValueError`, before anything is published or attached, with the same `reason=` and id fields the warning carried ([#91](https://github.com/electrification-bus/python-sdk/issues/91)). A `homie.Property` raises from its constructor, so `Property(from_dict=...)`, `Node.add_property_from_dict()` and the declaration builders do too, for `propertyRetainedNull` (`retained=None`, which was published as `false`), `propertyDatatypeMissing`, `propertyDatatypeUnknown`, `propertyFormatMissing` (an `enum` or `color` with no `format`), `propertyEnumFormatEmptyValue`, `propertyEnumFormatDuplicate` and `propertyColorFormatInvalid`; `Property.set_format()` raises for the format checks and keeps the old format. `PropertySpec` raises the same reasons at declaration time, except for an `internal_only` spec, which never becomes a Homie property; `PropertySpec(retained=None)`, which the builder published as non-retained without a warning, also raises. `Device(description_extras=...)` with a Homie core `$description` key raises `deviceDescriptionExtrasCoreFieldDropped` (the key was dropped), and a child that raises is not attached to its parent. `Device.publish_alert()` raises `devicePublishAlertIdFormat` for an id outside `a-z`, `0-9`, `-` (it was published) and `devicePublishAlertEmptyMessage` for an empty or non-string message (it returned `False`); an id containing `/`, `+` or `#`, or an empty one, still returns `False`.

### Fixed

Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ temp.set_value(None) # retracts the retained topic (subscribers see nothing)
label.set_value("") # publishes an empty-string VALUE (0x00 on the wire)
```

#### Invalid declarations raise

A property or device declaration that Homie 5 rejects raises `ValueError` before anything is published, with a `reason=` naming the problem: a property with no `datatype` or an unknown one, `retained=None`, an `enum` or `color` with no `format`, an enum `format` with an empty or duplicate value, a `color` `format` listing anything but `rgb`, `hsv`, `xyz`, and `description_extras` that set a core `$description` field. This applies to `homie.Property(...)`, `add_property_from_dict()`, `Property.set_format()`, `PropertySpec` and `Device(description_extras=...)`.

#### Values the datatype cannot represent are refused

A value is encoded for its property's datatype before it is published (convention.md:74-150 at [homieiot/convention@7edc221](https://github.com/homieiot/convention/blob/7edc221336f1644a9f04445cbc50c5af695bb047/convention.md)). A value the datatype cannot represent is refused: nothing is published, the retained topic keeps the last good value, `set_value()` returns `False`, and a `reason=propertyValueRefused` warning names the problem. Refused: NaN and infinities on `float`, a `bool` on `integer` or `float`, an `integer` that is not whole or does not fit in 64 bits, an `enum` value not in its `format`, a `float` beyond the 64-bit float range, a `json` value that is not an array or object or contains NaN, and `""` on anything but `string`. Floats are written without `+` in the exponent (`1e20`, not `1e+20`).
Expand All @@ -146,7 +150,7 @@ A property with `retained=False` publishes non-retained at QoS 0, as Homie 5 req

#### Alerts

`device.publish_alert("battery", "Battery is low, at 8%")` raises a retained alert at `$alert/battery`; `device.clear_alert("battery")` deletes it. Alerts are republished on reconnect and cleared by `delete()`. `publish("$alert", ...)` without an alert id publishes nothing and logs a warning.
`device.publish_alert("battery", "Battery is low, at 8%")` raises a retained alert at `$alert/battery`; `device.clear_alert("battery")` deletes it. Alerts are republished on reconnect and cleared by `delete()`. `publish("$alert", ...)` without an alert id publishes nothing and logs a warning. An alert id outside `a-z`, `0-9`, `-`, or an empty message, raises `ValueError`.

#### Inbound `/set` is validated

Expand Down
6 changes: 5 additions & 1 deletion src/ebus_sdk/declaration.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from typing import Any, Callable, Iterable, Optional, Sequence, Union

from .adapter import bind_property_to_homie
from .homie import Device, PropertyDatatype, Unit
from .homie import Device, PropertyDatatype, Unit, _check_property_description
from .property import GroupedPropertyDict
from .property import Property as ObservableProperty

Expand Down Expand Up @@ -129,6 +129,10 @@ def __post_init__(self) -> None:
f"{self.capability}/{self.prop_id}: an internal_only property is never published, so it "
"has no /set topic and cannot be settable"
)
# The Homie property this spec builds would raise the same ValueError, but
# mid-materialization, after earlier nodes and model entries exist (#91).
if not self.internal_only:
_check_property_description(self.prop_id, self.datatype, self.format, self.retained)

@property
def model_key(self) -> str:
Expand Down
128 changes: 62 additions & 66 deletions src/ebus_sdk/homie.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,37 @@ def validate_json_format(value: Any, format_schema: Union[str, dict, None]) -> O
)


def _check_property_description(pid: Any, datatype: Any, fmt: Any, retained: Any = True) -> None:
"""Raise ``ValueError`` for property ``$description`` fields Homie 5 rejects (#91).

``retained`` is a non-null boolean (convention.md:343); ``datatype`` is
required (:340) and must be a Homie 5 datatype; ``enum`` and ``color`` require
a ``format``; an enum format lists at least one value, none empty and none
duplicated (:392); a color format lists only ``rgb``, ``hsv`` and ``xyz`` (:393).
"""
if retained is None:
raise ValueError(f"reason=propertyRetainedNull,propertyID={pid},hint=retained must be True or False")
if datatype is None:
raise ValueError(f"reason=propertyDatatypeMissing,propertyID={pid},hint=datatype is required")
if datatype not in PropertyDatatype._value2member_map_:
raise ValueError(f"reason=propertyDatatypeUnknown,propertyID={pid},datatype={datatype}")
if datatype in (PropertyDatatype.ENUM, PropertyDatatype.COLOR) and not fmt:
raise ValueError(
f"reason=propertyFormatMissing,propertyID={pid},datatype={datatype},hint={datatype} requires a format"
)
if datatype == PropertyDatatype.ENUM and isinstance(fmt, str):
values = fmt.split(",")
if "" in values:
raise ValueError(f"reason=propertyEnumFormatEmptyValue,propertyID={pid},format={fmt}")
if len(set(values)) != len(values):
raise ValueError(f"reason=propertyEnumFormatDuplicate,propertyID={pid},format={fmt}")
if datatype == PropertyDatatype.COLOR and isinstance(fmt, str):
if not set(fmt.split(",")) <= _COLOR_FORMATS:
raise ValueError(
f"reason=propertyColorFormatInvalid,propertyID={pid},format={fmt},hint=allowed: rgb, hsv, xyz"
)


@dataclass(frozen=True)
class JsonFieldConstraint:
"""The control-surface constraint on one field of a ``json`` ``$format`` schema.
Expand Down Expand Up @@ -753,7 +784,7 @@ def _encode_property_value(value: Any, datatype: Any, format_: Any = None) -> tu
return _encode_duration(value)
if datatype == PropertyDatatype.JSON:
return _encode_json(value)
# string, and a missing or unknown datatype (already warned about).
# string, and a missing or unknown datatype.
return (str(value.value) if isinstance(value, Enum) else str(value)), None


Expand Down Expand Up @@ -895,7 +926,7 @@ def _parse_set_payload(text: str, datatype: Any, format_: Any, current: Any) ->
return _encode_duration(text)
if datatype == PropertyDatatype.DATETIME:
return _encode_datetime(text)
# string, and a missing or unknown datatype (already warned about).
# string, and a missing or unknown datatype.
return decode_empty_string(text), None


Expand Down Expand Up @@ -1061,6 +1092,8 @@ def __init__(
device = from_dict.get("device", None)
set_callback = from_dict.get("set_callback", None)
async_loop = from_dict.get("async_loop", None)
# Invalid Homie 5 input raises before anything is assigned or published (#91).
_check_property_description(id, datatype, format, retained)
# Regardless of how we got this info, construct it
# AKA, the "business logic" of the constructor
_warn_invalid_id(self, "property", id)
Expand All @@ -1079,10 +1112,6 @@ def __init__(
self._set_callback = set_callback
else:
self._set_callback = None
if retained is None:
# `retained` is a non-nullable boolean in $description (convention.md:343).
# The publish path always treated None as non-retained, so keep that.
_warn_invalid_once(self, "retainedNull", f"reason=propertyRetainedNull,propertyID={id},treatedAs=false")
self._retained = bool(retained)
self._unit = unit
self._supports_target = supports_target
Expand Down Expand Up @@ -1141,43 +1170,6 @@ def __init__(
self._initial_value_was_none = value is None
# Check for skip_initial_publish flag from dict
self._skip_initial_publish = from_dict.get("skip_initial_publish", False) if from_dict else False
self._check_description_fields()

def _check_description_fields(self) -> None:
"""Warn (once per problem) about $description fields Homie 5 rejects.

``datatype`` is required (convention.md:340); ``enum`` and ``color`` require
a ``format``; an enum format lists at least one value, none empty and none
duplicated (:392); a color format lists only ``rgb``, ``hsv`` and ``xyz``
(:393).
"""
pid = self._id
datatype = self._datatype
if datatype is None:
_warn_invalid_once(self, "datatypeMissing", f"reason=propertyDatatypeMissing,propertyID={pid}")
return
if datatype not in PropertyDatatype._value2member_map_:
_warn_invalid_once(
self, "datatypeUnknown", f"reason=propertyDatatypeUnknown,propertyID={pid},datatype={datatype}"
)
return
fmt = self._format
if datatype in (PropertyDatatype.ENUM, PropertyDatatype.COLOR) and not fmt:
_warn_invalid_once(
self, "formatMissing", f"reason=propertyFormatMissing,propertyID={pid},datatype={datatype}"
)
return
if datatype == PropertyDatatype.ENUM and isinstance(fmt, str):
values = fmt.split(",")
if "" in values:
_warn_invalid_once(self, "enumEmptyValue", f"reason=propertyEnumFormatEmptyValue,propertyID={pid}")
if len(set(values)) != len(values):
_warn_invalid_once(self, "enumDuplicate", f"reason=propertyEnumFormatDuplicate,propertyID={pid}")
if datatype == PropertyDatatype.COLOR and isinstance(fmt, str):
if not set(fmt.split(",")) <= _COLOR_FORMATS:
_warn_invalid_once(
self, "colorFormatInvalid", f"reason=propertyColorFormatInvalid,propertyID={pid},format={fmt}"
)

def as_dict(self) -> dict:
return {
Expand Down Expand Up @@ -1315,9 +1307,12 @@ def set_format(self, new_format: Optional[str]) -> None:
it; the SDK does not republish a single property attribute on its own. This
is the public replacement for adapters that previously assigned the private
``_format`` because no setter existed (SDK-6do.2).

A format Homie 5 rejects for this datatype raises ``ValueError`` and the
format is left unchanged.
"""
_check_property_description(self._id, self._datatype, new_format)
self._format = new_format
self._check_description_fields()

def coerced_value(self) -> Optional[str]:
"""
Expand Down Expand Up @@ -1524,8 +1519,7 @@ def publish_value(self, *, force: bool = False) -> bool:
# Encode an empty-string value as a single 0x00 byte so the broker
# does not mistake it for a zero-length "clear retained" payload. Only
# for string (convention.md:65-67); another datatype never encodes to
# "" because its encoder refuses an empty value. A missing datatype was
# warned about at construction and keeps the string behavior.
# "" because its encoder refuses an empty value.
payload = encode_empty_string(value)
# GH #50: skip a republish whose final wire payload is byte-identical to
# the one already sitting on this topic. Compared AFTER coercion and
Expand Down Expand Up @@ -1667,8 +1661,7 @@ def description(self) -> dict:
property = dict()
property["name"] = self._name
if self._datatype is not None:
# Required (convention.md:340); a missing datatype was warned about at
# construction, and null is not a valid value for it.
# Required (convention.md:340); the constructor refuses a missing one.
property["datatype"] = self.datatype()
if self._format:
fmt = self.format()
Expand Down Expand Up @@ -2311,6 +2304,15 @@ def __init__(
f"Device id={id}: cannot pass both mqtt_cfg= and mqttc=; pass mqtt_cfg to have the SDK "
"build and own a client, or mqttc to inject one whose lifecycle you own"
)
# A core field is the SDK's to compute: an extra could otherwise add
# `root`/`parent` to a root device (convention.md:220) or a `type` the SDK
# omits (#91).
core_extras = sorted((description_extras or {}).keys() & _DESCRIPTION_CORE_FIELDS)
if core_extras:
raise ValueError(
f"reason=deviceDescriptionExtrasCoreFieldDropped,id={id},field={','.join(core_extras)},"
"hint=description_extras cannot set a Homie core $description field"
)
# The `_mqtt_cfg` term separates "root never started" (an error) from "root built
# transport-free" (mqtt_cfg=None), which must still take children. Drop it and the
# transport-free tree can only ever be a single node.
Expand Down Expand Up @@ -2384,16 +2386,8 @@ def __init__(
# `imported-from` attribute of the `energy.ebus.imported` extension).
# Homie 5 forward-compat requires controllers to ignore unknown
# description fields (convention §Forward compatibility), so these are
# safe; core fields always take precedence over an extra of the same key.
# safe; an extra naming a core field was refused above.
self._description_extras = dict(description_extras) if description_extras else {}
for key in sorted(self._description_extras.keys() & _DESCRIPTION_CORE_FIELDS):
# A core field is the SDK's to compute: an extra could otherwise add
# `root`/`parent` to a root device (convention.md:220) or a `type` the
# SDK omits. Dropped, with a warning per the invalid-input policy.
del self._description_extras[key]
_warn_invalid_once(
self, f"extrasCoreField:{key}", f"reason=deviceDescriptionExtrasCoreFieldDropped,id={id},field={key}"
)
# Counter of how many state_transition() / delete() scopes are currently active
# on this device. >0 means "a transition is in progress" — suppresses child-induced
# parent flaps and makes nested state_transition()s reentrant (only the outermost
Expand Down Expand Up @@ -2832,8 +2826,8 @@ def description(self) -> dict:
# Required if the parent is NOT the root device. Defaults to the value of the root property.
description["parent"] = self._parent.id()
description["extensions"] = self._extensions
# Merge extension-defined device attributes (core fields were dropped from
# the extras at construction).
# Merge extension-defined device attributes (an extra naming a core field
# was refused at construction).
for key, value in self._description_extras.items():
description.setdefault(key, value)
# A new version whenever the document changes (convention.md:215), and the
Expand Down Expand Up @@ -3412,20 +3406,22 @@ def publish_alert(self, alert_id: str, message: str) -> bool:

``alert_id`` must be a single topic level; one containing ``/``, ``+`` or
``#``, or an empty one, is refused. An id outside the Homie ID format
(``a-z``, ``0-9``, ``-``) is warned about and still published. ``message``
must be a non-empty string: an empty payload deletes the topic, so clear an
alert with ``clear_alert()``. Returns True if published.
(``a-z``, ``0-9``, ``-``) raises ``ValueError``, and so does a ``message``
that is not a non-empty string: an empty payload deletes the topic, so clear
an alert with ``clear_alert()``. Returns True if published.
"""
if not alert_id or not isinstance(alert_id, str) or any(c in alert_id for c in "/+#"):
logger.warning(f"reason=devicePublishAlertInvalidId,id={self._id},alertId={alert_id!r}")
return False
if not re.fullmatch(r"[a-z0-9-]+", alert_id):
_warn_invalid_once(
self, f"alertId:{alert_id}", f"reason=devicePublishAlertIdFormat,id={self._id},alertId={alert_id}"
raise ValueError(
f"reason=devicePublishAlertIdFormat,id={self._id},alertId={alert_id},hint=use a-z, 0-9 and -"
)
if not isinstance(message, str) or message == "":
logger.warning(f"reason=devicePublishAlertEmptyMessage,id={self._id},alertId={alert_id}")
return False
raise ValueError(
f"reason=devicePublishAlertEmptyMessage,id={self._id},alertId={alert_id},"
"hint=message must be a non-empty string; use clear_alert() to remove an alert"
)
self._alerts[alert_id] = message
return self._publish_alert_topic(alert_id, message)

Expand Down
Loading
Loading