|
| 1 | +"""The HASS.Agent integration.""" |
| 2 | +from __future__ import annotations |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import requests |
| 6 | +from homeassistant.helpers import device_registry as dr |
| 7 | +from homeassistant.components.mqtt.models import ReceiveMessage |
| 8 | +from homeassistant.components.mqtt.subscription import ( |
| 9 | + async_prepare_subscribe_topics, |
| 10 | + async_subscribe_topics, |
| 11 | + async_unsubscribe_topics, |
| 12 | +) |
| 13 | + |
| 14 | +from homeassistant.config_entries import ConfigEntry |
| 15 | +from homeassistant.const import CONF_ID, CONF_NAME, CONF_URL, Platform |
| 16 | +from homeassistant.core import HomeAssistant |
| 17 | +from homeassistant.helpers import discovery |
| 18 | + |
| 19 | +from .const import DOMAIN |
| 20 | + |
| 21 | +PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER] |
| 22 | + |
| 23 | +_logger = logging.getLogger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +def update_device_info(hass: HomeAssistant, entry: ConfigEntry, new_device_info): |
| 27 | + device_registry = dr.async_get(hass) |
| 28 | + device_registry.async_get_or_create( |
| 29 | + config_entry_id=entry.entry_id, |
| 30 | + identifiers={(DOMAIN, entry.unique_id)}, |
| 31 | + name=new_device_info["device"]["name"], |
| 32 | + manufacturer=new_device_info["device"]["manufacturer"], |
| 33 | + model=new_device_info["device"]["model"], |
| 34 | + sw_version=new_device_info["device"]["sw_version"], |
| 35 | + ) |
| 36 | + |
| 37 | + |
| 38 | +async def handle_apis_changed(hass: HomeAssistant, entry: ConfigEntry, apis): |
| 39 | + if apis is not None: |
| 40 | + |
| 41 | + device_registry = dr.async_get(hass) |
| 42 | + device = device_registry.async_get_device( |
| 43 | + identifiers={(DOMAIN, entry.unique_id)} |
| 44 | + ) |
| 45 | + |
| 46 | + media_player = apis.get("media_player", False) |
| 47 | + is_media_player_loaded = hass.data[DOMAIN][entry.entry_id]["loaded"][ |
| 48 | + "media_player" |
| 49 | + ] |
| 50 | + |
| 51 | + notifications = apis.get("notifications", False) |
| 52 | + |
| 53 | + is_notifications_loaded = hass.data[DOMAIN][entry.entry_id]["loaded"][ |
| 54 | + "notifications" |
| 55 | + ] |
| 56 | + |
| 57 | + if media_player and is_media_player_loaded is False: |
| 58 | + _logger.debug("loading media_player for device: %s", device.name) |
| 59 | + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) |
| 60 | + |
| 61 | + hass.data[DOMAIN][entry.entry_id]["loaded"]["media_player"] = True |
| 62 | + else: |
| 63 | + if is_media_player_loaded: |
| 64 | + _logger.debug( |
| 65 | + "unloading media_player for device: %s", |
| 66 | + device.name, |
| 67 | + ) |
| 68 | + await hass.config_entries.async_forward_entry_unload( |
| 69 | + entry, Platform.MEDIA_PLAYER |
| 70 | + ) |
| 71 | + |
| 72 | + hass.data[DOMAIN][entry.entry_id]["loaded"]["media_player"] = False |
| 73 | + |
| 74 | + if notifications and is_notifications_loaded is False: |
| 75 | + _logger.debug("loading notify for device: %s", device.name) |
| 76 | + |
| 77 | + hass.async_create_task( |
| 78 | + discovery.async_load_platform( |
| 79 | + hass, |
| 80 | + Platform.NOTIFY, |
| 81 | + DOMAIN, |
| 82 | + {CONF_ID: entry.entry_id, CONF_NAME: device.name}, |
| 83 | + {}, |
| 84 | + ) |
| 85 | + ) |
| 86 | + hass.data[DOMAIN][entry.entry_id]["loaded"]["notifications"] = True |
| 87 | + else: |
| 88 | + if is_notifications_loaded: |
| 89 | + _logger.debug("unloading notify for device: %s", device.name) |
| 90 | + await hass.config_entries.async_unload_platforms( |
| 91 | + entry, [Platform.NOTIFY] |
| 92 | + ) |
| 93 | + |
| 94 | + hass.data[DOMAIN][entry.entry_id]["loaded"]["notifications"] = False |
| 95 | + |
| 96 | + |
| 97 | +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: |
| 98 | + """Set up HASS.Agent from a config entry.""" |
| 99 | + |
| 100 | + hass.data.setdefault(DOMAIN, {}) |
| 101 | + |
| 102 | + hass.data[DOMAIN].setdefault( |
| 103 | + entry.entry_id, |
| 104 | + { |
| 105 | + "internal_mqtt": {}, |
| 106 | + "apis": {}, |
| 107 | + "mqtt": {}, |
| 108 | + "loaded": {"media_player": False, "notifications": False}, |
| 109 | + }, |
| 110 | + ) |
| 111 | + |
| 112 | + print(entry.options) |
| 113 | + |
| 114 | + url = entry.data.get(CONF_URL, None) |
| 115 | + |
| 116 | + if url is not None: |
| 117 | + def get_device_info(): |
| 118 | + return requests.get(f"{url}/info", timeout=10) |
| 119 | + |
| 120 | + response = await hass.async_add_executor_job(get_device_info) |
| 121 | + |
| 122 | + response_json = response.json() |
| 123 | + |
| 124 | + update_device_info(hass, entry, response_json) |
| 125 | + |
| 126 | + apis = { |
| 127 | + "notifications": True, |
| 128 | + "media_player": False, # unsupported for the moment |
| 129 | + } |
| 130 | + |
| 131 | + hass.async_create_task(handle_apis_changed(hass, entry, apis)) |
| 132 | + hass.data[DOMAIN][entry.entry_id]["apis"] = apis |
| 133 | + |
| 134 | + else: |
| 135 | + device_name = entry.data["device"]["name"] |
| 136 | + |
| 137 | + sub_state = hass.data[DOMAIN][entry.entry_id]["internal_mqtt"] |
| 138 | + |
| 139 | + def updated(message: ReceiveMessage): |
| 140 | + payload = json.loads(message.payload) |
| 141 | + cached = hass.data[DOMAIN][entry.entry_id]["apis"] |
| 142 | + apis = payload["apis"] |
| 143 | + |
| 144 | + update_device_info(hass, entry, payload) |
| 145 | + |
| 146 | + if cached != apis: |
| 147 | + hass.async_create_task(handle_apis_changed(hass, entry, apis)) |
| 148 | + hass.data[DOMAIN][entry.entry_id]["apis"] = apis |
| 149 | + |
| 150 | + sub_state = async_prepare_subscribe_topics( |
| 151 | + hass, |
| 152 | + sub_state, |
| 153 | + { |
| 154 | + f"{entry.unique_id}-apis": { |
| 155 | + "topic": f"hass.agent/devices/{device_name}", |
| 156 | + "msg_callback": updated, |
| 157 | + "qos": 0, |
| 158 | + } |
| 159 | + }, |
| 160 | + ) |
| 161 | + |
| 162 | + await async_subscribe_topics(hass, sub_state) |
| 163 | + |
| 164 | + hass.data[DOMAIN][entry.entry_id]["internal_mqtt"] = sub_state |
| 165 | + |
| 166 | + return True |
| 167 | + |
| 168 | + |
| 169 | +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: |
| 170 | + """Unload a config entry.""" |
| 171 | + |
| 172 | + # known issue: notify does not always unload |
| 173 | + |
| 174 | + loaded = hass.data[DOMAIN][entry.entry_id].get("loaded", None) |
| 175 | + |
| 176 | + if loaded is not None: |
| 177 | + notifications = loaded.get("notifications", False) |
| 178 | + |
| 179 | + media_player = loaded.get("media_player", False) |
| 180 | + |
| 181 | + if notifications: |
| 182 | + if unload_ok := await hass.config_entries.async_unload_platforms( |
| 183 | + entry, [Platform.NOTIFY] |
| 184 | + ): |
| 185 | + _logger.debug("unloaded %s for %s", "notify", entry.unique_id) |
| 186 | + |
| 187 | + if media_player: |
| 188 | + if unload_ok := await hass.config_entries.async_unload_platforms( |
| 189 | + entry, [Platform.MEDIA_PLAYER] |
| 190 | + ): |
| 191 | + _logger.debug("unloaded %s for %s", "media_player", entry.unique_id) |
| 192 | + else: |
| 193 | + _logger.warning("config entry (%s) with has no apis loaded?", entry.entry_id) |
| 194 | + |
| 195 | + url = entry.data.get(CONF_URL, None) |
| 196 | + if url is None: |
| 197 | + async_unsubscribe_topics( |
| 198 | + hass, hass.data[DOMAIN][entry.entry_id]["internal_mqtt"] |
| 199 | + ) |
| 200 | + |
| 201 | + hass.data[DOMAIN].pop(entry.entry_id) |
| 202 | + |
| 203 | + return unload_ok |
0 commit comments