diff --git a/docker2mqtt/__init__.py b/docker2mqtt/__init__.py index 1d7eeec..0b422a9 100644 --- a/docker2mqtt/__init__.py +++ b/docker2mqtt/__init__.py @@ -35,6 +35,7 @@ Docker2MqttException, Docker2MqttStatsException, ) +from .helpers import clean_for_discovery from .type_definitions import ( ContainerDeviceEntry, ContainerEntry, @@ -48,6 +49,7 @@ __all__ = [ "Docker2Mqtt", + "clean_for_discovery", "ContainerEvent", "ContainerStats", "ContainerStatsRef", diff --git a/docker2mqtt/docker2mqtt.py b/docker2mqtt/docker2mqtt.py index 1bea216..1b57fd7 100755 --- a/docker2mqtt/docker2mqtt.py +++ b/docker2mqtt/docker2mqtt.py @@ -20,6 +20,8 @@ import paho.mqtt.client +from docker2mqtt.helpers import clean_for_discovery + from . import __VERSION__ from .const import ( ANSI_ESCAPE, @@ -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, @@ -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, diff --git a/docker2mqtt/helpers.py b/docker2mqtt/helpers.py new file mode 100644 index 0000000..d1e5a08 --- /dev/null +++ b/docker2mqtt/helpers.py @@ -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, "") + }