Skip to content
This repository has been archived by the owner on Aug 29, 2024. It is now read-only.

Add device to Home Assistant auto-discovery #39

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
23 changes: 18 additions & 5 deletions plantgw/plantgw.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def process_mac(self, sensor_config: SensorConfig):
"""Get data from one Sensor."""
logging.info('Getting data from sensor %s', sensor_config.get_topic())
poller = MiFloraPoller(sensor_config.mac, BluepyBackend)
self.announce_sensor(sensor_config)
self.announce_sensor(sensor_config, poller)
self._publish(sensor_config, poller)

def process_all(self):
Expand Down Expand Up @@ -276,24 +276,37 @@ def process_all(self):
# return sensors that could not be processed after max_retry
return next_list

def announce_sensor(self, sensor_config: SensorConfig):
def announce_sensor(self, sensor_config: SensorConfig, poller: MiFloraPoller):
"""Announce the sensor via Home Assistant MQTT Discovery.

see https://www.home-assistant.io/docs/mqtt/discovery/
"""
if self.config.mqtt_discovery_prefix is None:
return
self.start_client()
device_name = 'plant_{}'.format(sensor_config.short_mac)

device_id = 'plant_{}'.format(sensor_config.short_mac)
device_name = sensor_config.alias or 'Plant {}'.format(sensor_config.short_mac)
device_model = poller.name()
device_firmware = poller.firmware_version()

for attribute in MQTTAttributes:
topic = '{}/sensor/{}_{}/config'.format(self.config.mqtt_discovery_prefix, device_name, attribute.value)
topic = '{}/sensor/{}_{}/config'.format(self.config.mqtt_discovery_prefix, device_id, attribute.value)
payload = {
'unique_id': '{}_{}'.format(device_id, attribute.value),
'state_topic': self._get_state_topic(sensor_config),
'unit_of_measurement': UNIT_OF_MEASUREMENT[attribute],
'value_template': '{{value_json.'+attribute.value+'}}',
'device': {
'identifiers': '[ {} ]'.format(device_id),
'name': device_name,
'model': device_model,
'manufacturer': 'Xiaomi',
'sw_version': device_firmware,
}
}
if sensor_config.alias is not None:
payload['name'] = '{}_{}'.format(sensor_config.alias, attribute.value)
payload['name'] = '{} {}'.format(sensor_config.alias, attribute.value.capitalize())

if DEVICE_CLASS[attribute] is not None:
payload['device_class'] = DEVICE_CLASS[attribute]
Expand Down