|
| 1 | +"""The Format BLE Tracker integration.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import asyncio |
| 5 | +from curses import has_key |
| 6 | +import json |
| 7 | +import logging |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +import voluptuous as vol |
| 11 | + |
| 12 | +from homeassistant.components import mqtt |
| 13 | +from homeassistant.config_entries import ConfigEntry |
| 14 | +from homeassistant.const import Platform |
| 15 | +from homeassistant.core import HomeAssistant, callback |
| 16 | +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator |
| 17 | + |
| 18 | +from .const import ( |
| 19 | + ALIVE_NODES_TOPIC, |
| 20 | + DOMAIN, |
| 21 | + MAC, |
| 22 | + NAME, |
| 23 | + ROOM, |
| 24 | + ROOT_TOPIC, |
| 25 | + RSSI, |
| 26 | +) |
| 27 | + |
| 28 | +PLATFORMS: list[Platform] = [ |
| 29 | + Platform.DEVICE_TRACKER, |
| 30 | + Platform.SENSOR, |
| 31 | + Platform.NUMBER |
| 32 | +] |
| 33 | +_LOGGER = logging.getLogger(__name__) |
| 34 | + |
| 35 | +MQTT_PAYLOAD = vol.Schema( |
| 36 | + vol.All( |
| 37 | + json.loads, |
| 38 | + vol.Schema( |
| 39 | + { |
| 40 | + vol.Required(RSSI): vol.Coerce(int), |
| 41 | + }, |
| 42 | + extra=vol.ALLOW_EXTRA, |
| 43 | + ), |
| 44 | + ) |
| 45 | +) |
| 46 | + |
| 47 | + |
| 48 | +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: |
| 49 | + """Set up Format BLE Tracker from a config entry.""" |
| 50 | + |
| 51 | + hass.data.setdefault(DOMAIN, {}) |
| 52 | + |
| 53 | + coordinator = BeaconCoordinator(hass, entry.data) |
| 54 | + |
| 55 | + mac = entry.data[MAC] |
| 56 | + state_topic = ROOT_TOPIC + "/" + mac + "/+" |
| 57 | + _LOGGER.info("Subscribing to %s", state_topic) |
| 58 | + await mqtt.async_subscribe(hass, state_topic, coordinator.message_received, 1) |
| 59 | + alive_topic = ALIVE_NODES_TOPIC + "/" + mac |
| 60 | + _LOGGER.info("Notifying alive to %s", alive_topic) |
| 61 | + await mqtt.async_publish(hass, alive_topic, True, 1, retain=True) |
| 62 | + |
| 63 | + hass.data[DOMAIN][entry.entry_id] = coordinator |
| 64 | + hass.config_entries.async_setup_platforms(entry, PLATFORMS) |
| 65 | + |
| 66 | + return True |
| 67 | + |
| 68 | + |
| 69 | +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: |
| 70 | + """Unload a config entry.""" |
| 71 | + if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): |
| 72 | + hass.data[DOMAIN].pop(entry.entry_id) |
| 73 | + |
| 74 | + mac = entry.data[MAC] |
| 75 | + alive_topic = ALIVE_NODES_TOPIC + "/" + mac |
| 76 | + _LOGGER.info("Notifying alive to %s", alive_topic) |
| 77 | + await mqtt.async_publish(hass, alive_topic, "", 1, retain=True) |
| 78 | + |
| 79 | + return unload_ok |
| 80 | + |
| 81 | + |
| 82 | +class BeaconCoordinator(DataUpdateCoordinator[dict[str, Any]]): |
| 83 | + """Class to arrange interaction with MQTT""" |
| 84 | + |
| 85 | + def __init__(self, hass: HomeAssistant, data) -> None: |
| 86 | + self.mac = data[MAC] |
| 87 | + self.expiration_time : int |
| 88 | + self.default_expiration_time : int = 2 |
| 89 | + given_name = data[NAME] if data.__contains__(NAME) else self.mac |
| 90 | + self.room_data = dict[str, int]() |
| 91 | + self.room_expiration_timers = dict[str, asyncio.TimerHandle]() |
| 92 | + self.room = None |
| 93 | + |
| 94 | + super().__init__(hass, _LOGGER, name=given_name) |
| 95 | + |
| 96 | + async def _async_update_data(self) -> dict[str, Any]: |
| 97 | + """Update data via library.""" |
| 98 | + _LOGGER.error("Room data: %s", str(self.room_data)) |
| 99 | + if len(self.room_data) == 0: |
| 100 | + self.room = None |
| 101 | + else: |
| 102 | + self.room = next( |
| 103 | + iter( |
| 104 | + dict( |
| 105 | + sorted( |
| 106 | + self.room_data.items(), |
| 107 | + key=lambda item: item[1], |
| 108 | + reverse=True, |
| 109 | + ) |
| 110 | + ) |
| 111 | + ) |
| 112 | + ) |
| 113 | + return {**{ROOM: self.room}} |
| 114 | + |
| 115 | + async def subscribe_to_mqtt(self) -> None: |
| 116 | + """Subscribe coordinator to MQTT messages""" |
| 117 | + |
| 118 | + @callback |
| 119 | + async def message_received(self, msg): |
| 120 | + """Handle new MQTT messages.""" |
| 121 | + try: |
| 122 | + data = MQTT_PAYLOAD(msg.payload) |
| 123 | + except vol.MultipleInvalid as error: |
| 124 | + _LOGGER.debug("Skipping update because of malformatted data: %s", error) |
| 125 | + return |
| 126 | + room_topic = msg.topic.split("/")[2] |
| 127 | + |
| 128 | + await self.schedule_data_expiration(room_topic) |
| 129 | + self.room_data[room_topic] = data.get(RSSI) |
| 130 | + await self.async_refresh() |
| 131 | + |
| 132 | + async def schedule_data_expiration(self, room): |
| 133 | + """Start timer for data expiration for certain room""" |
| 134 | + if room in self.room_expiration_timers: |
| 135 | + self.room_expiration_timers[room].cancel() |
| 136 | + loop = asyncio.get_event_loop() |
| 137 | + timer = loop.call_later( |
| 138 | + (self.expiration_time if self.expiration_time else self.default_expiration_time) * 60, |
| 139 | + lambda: asyncio.ensure_future(self.expire_data(room)), |
| 140 | + ) |
| 141 | + self.room_expiration_timers[room] = timer |
| 142 | + |
| 143 | + async def expire_data(self, room): |
| 144 | + """Set data for certain room expired""" |
| 145 | + del self.room_data[room] |
| 146 | + del self.room_expiration_timers[room] |
| 147 | + await self.async_refresh() |
| 148 | + |
| 149 | + async def on_expiration_time_changed(self, new_time : int): |
| 150 | + """Respond to expiration time changed by user""" |
| 151 | + if new_time is None: |
| 152 | + return |
| 153 | + self.expiration_time = new_time |
| 154 | + for room in self.room_expiration_timers.keys(): |
| 155 | + await self.schedule_data_expiration(room) |
0 commit comments