1 """UniFi Network services."""
3 from collections.abc
import Mapping
6 from aiounifi.models.client
import ClientReconnectRequest, ClientRemoveRequest
7 import voluptuous
as vol
15 from .const
import DOMAIN
as UNIFI_DOMAIN
17 SERVICE_RECONNECT_CLIENT =
"reconnect_client"
18 SERVICE_REMOVE_CLIENTS =
"remove_clients"
20 SERVICE_RECONNECT_CLIENT_SCHEMA = vol.All(
21 vol.Schema({vol.Required(ATTR_DEVICE_ID): str})
24 SUPPORTED_SERVICES = (SERVICE_RECONNECT_CLIENT, SERVICE_REMOVE_CLIENTS)
27 SERVICE_RECONNECT_CLIENT: SERVICE_RECONNECT_CLIENT_SCHEMA,
33 """Set up services for UniFi integration."""
36 SERVICE_RECONNECT_CLIENT: async_reconnect_client,
37 SERVICE_REMOVE_CLIENTS: async_remove_clients,
40 async
def async_call_unifi_service(service_call: ServiceCall) ->
None:
41 """Call correct UniFi service."""
42 await services[service_call.service](hass, service_call.data)
44 for service
in SUPPORTED_SERVICES:
45 hass.services.async_register(
48 async_call_unifi_service,
49 schema=SERVICE_TO_SCHEMA.get(service),
54 """Try to get wireless client to reconnect to Wi-Fi."""
55 device_registry = dr.async_get(hass)
56 device_entry = device_registry.async_get(data[ATTR_DEVICE_ID])
58 if device_entry
is None:
62 for connection
in device_entry.connections:
63 if connection[0] == CONNECTION_NETWORK_MAC:
70 for config_entry
in hass.config_entries.async_entries(UNIFI_DOMAIN):
71 if config_entry.state
is not ConfigEntryState.LOADED
or (
72 (hub := config_entry.runtime_data)
74 or (client := hub.api.clients.get(mac))
is None
79 await hub.api.request(ClientReconnectRequest.create(mac))
83 """Remove select clients from UniFi Network.
86 - Total time between first seen and last seen is less than 15 minutes.
87 - Neither IP, hostname nor name is configured.
89 for config_entry
in hass.config_entries.async_entries(UNIFI_DOMAIN):
91 config_entry.state
is not ConfigEntryState.LOADED
92 or (hub := config_entry.runtime_data)
97 clients_to_remove = []
99 for client
in hub.api.clients_all.values():
102 and client.first_seen
103 and client.last_seen - client.first_seen > 900
107 if any({client.fixed_ip, client.hostname, client.name}):
110 clients_to_remove.append(client.mac)
112 if clients_to_remove:
113 await hub.api.request(ClientRemoveRequest.create(clients_to_remove))
None async_remove_clients(HomeAssistant hass, Mapping[str, Any] data)
None async_reconnect_client(HomeAssistant hass, Mapping[str, Any] data)
None async_setup_services(HomeAssistant hass)