Skip to content

Commit

Permalink
Add remove device feature
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed Sep 27, 2020
1 parent 7bd679e commit 8592d2a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
41 changes: 40 additions & 1 deletion custom_components/xiaomi_gateway3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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


Expand All @@ -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

Expand Down
6 changes: 6 additions & 0 deletions custom_components/xiaomi_gateway3/gateway3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit 8592d2a

Please sign in to comment.