Skip to content

Commit

Permalink
Update the home assistant discovery type interface (#12)
Browse files Browse the repository at this point in the history
update the home assistant discovery type interface
  • Loading branch information
miaucl authored Sep 14, 2024
1 parent 28afd58 commit 2d82816
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
2 changes: 2 additions & 0 deletions docker2mqtt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
Docker2MqttException,
Docker2MqttStatsException,
)
from .helpers import clean_for_discovery
from .type_definitions import (
ContainerDeviceEntry,
ContainerEntry,
Expand All @@ -48,6 +49,7 @@

__all__ = [
"Docker2Mqtt",
"clean_for_discovery",
"ContainerEvent",
"ContainerStats",
"ContainerStatsRef",
Expand Down
10 changes: 8 additions & 2 deletions docker2mqtt/docker2mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

import paho.mqtt.client

from docker2mqtt.helpers import clean_for_discovery

from . import __VERSION__
from .const import (
ANSI_ESCAPE,
Expand Down Expand Up @@ -606,7 +608,9 @@ def _register_container(self, container_entry: ContainerEvent) -> None:
}
)
self._mqtt_send(
registration_topic, json.dumps(registration_packet), retain=True
registration_topic,
json.dumps(clean_for_discovery(registration_packet)),
retain=True,
)
self._mqtt_send(
events_topic,
Expand Down Expand Up @@ -640,7 +644,9 @@ def _register_container(self, container_entry: ContainerEvent) -> None:
}
)
self._mqtt_send(
registration_topic, json.dumps(registration_packet), retain=True
registration_topic,
json.dumps(clean_for_discovery(registration_packet)),
retain=True,
)
self._mqtt_send(
stats_topic,
Expand Down
29 changes: 29 additions & 0 deletions docker2mqtt/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""docker2mqtt helpers."""

from typing import Dict, Union

from .type_definitions import ContainerEntry


def clean_for_discovery(
val: ContainerEntry,
) -> Dict[str, Union[str, int, float, object]]:
"""Cleanup a typed dict for home assistant discovery, which is quite picky and does not like empty of None values.
Parameters
----------
val
The TypedDict to cleanup
Returns
-------
dict
The cleaned dict
"""

return {
k: v
for k, v in dict(val).items()
if isinstance(v, (str, int, float, object)) and v not in (None, "")
}

0 comments on commit 2d82816

Please sign in to comment.