diff --git a/custom_components/xiaomi_gateway3/__init__.py b/custom_components/xiaomi_gateway3/__init__.py index f9cd6e34..25777f9d 100644 --- a/custom_components/xiaomi_gateway3/__init__.py +++ b/custom_components/xiaomi_gateway3/__init__.py @@ -2,7 +2,7 @@ import voluptuous as vol from homeassistant.const import STATE_UNKNOWN -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, Event from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity import Entity @@ -37,6 +37,8 @@ async def async_setup(hass: HomeAssistant, hass_config: dict): hass.data[DOMAIN] = {'config': config} + await _handle_device_remove(hass) + return True @@ -58,6 +60,43 @@ async def async_setup_entry(hass: HomeAssistant, config_entry): return True +# async def async_unload_entry(hass: HomeAssistant, config_entry): +# return True + + +async def _handle_device_remove(hass: HomeAssistant): + """Remove device from Hass and Mi Home if the device is renamed to + `delete`. + """ + + async def device_registry_updated(event: Event): + if event.data['action'] != 'update': + return + + registry = hass.data['device_registry'] + hass_device = registry.async_get(event.data['device_id']) + + domain, mac = next(iter(hass_device.identifiers)) + # handle only our devices + if domain != DOMAIN or hass_device.name_by_user != 'delete': + return + + # remove from Mi Home + for gw in hass.data[DOMAIN].values(): + if not isinstance(gw, Gateway3): + continue + gw_device = gw.get_device(mac) + if not gw_device: + continue + gw.miio.send('remove_device', [gw_device['did']]) + break + + # remove from Hass + registry.async_remove_device(hass_device.id) + + hass.bus.async_listen('device_registry_updated', device_registry_updated) + + class Gateway3Device(Entity): _state = STATE_UNKNOWN diff --git a/custom_components/xiaomi_gateway3/gateway3.py b/custom_components/xiaomi_gateway3/gateway3.py index b8a02b48..24a45acb 100644 --- a/custom_components/xiaomi_gateway3/gateway3.py +++ b/custom_components/xiaomi_gateway3/gateway3.py @@ -500,6 +500,12 @@ def send(self, device: dict, data: dict): payload = json.dumps(payload, separators=(',', ':')).encode() self.mqtt.publish('zigbee/recv', payload) + def get_device(self, mac: str) -> Optional[dict]: + for device in self.devices.values(): + if device.get('mac') == mac: + return device + return None + class GatewayBLE(Thread): def __init__(self, gw: Gateway3):