/
device_tracker.py
389 lines (305 loc) · 11.9 KB
/
device_tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""Track devices using UniFi controllers."""
from datetime import timedelta
from aiounifi.api import SOURCE_DATA, SOURCE_EVENT
from aiounifi.events import (
ACCESS_POINT_UPGRADED,
GATEWAY_UPGRADED,
SWITCH_UPGRADED,
WIRED_CLIENT_CONNECTED,
WIRELESS_CLIENT_CONNECTED,
WIRELESS_CLIENT_ROAM,
WIRELESS_CLIENT_ROAMRADIO,
WIRELESS_GUEST_CONNECTED,
WIRELESS_GUEST_ROAM,
WIRELESS_GUEST_ROAMRADIO,
)
from homeassistant.components.device_tracker import DOMAIN
from homeassistant.components.device_tracker.config_entry import ScannerEntity
from homeassistant.components.device_tracker.const import SOURCE_TYPE_ROUTER
from homeassistant.core import callback
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.event import async_track_point_in_utc_time
import homeassistant.util.dt as dt_util
from .const import ATTR_MANUFACTURER, DOMAIN as UNIFI_DOMAIN
from .unifi_client import UniFiClient
from .unifi_entity_base import UniFiBase
CLIENT_TRACKER = "client"
DEVICE_TRACKER = "device"
CLIENT_CONNECTED_ATTRIBUTES = [
"_is_guest_by_uap",
"ap_mac",
"authorized",
"essid",
"ip",
"is_11r",
"is_guest",
"noted",
"qos_policy_applied",
"radio",
"radio_proto",
"vlan",
]
CLIENT_STATIC_ATTRIBUTES = [
"hostname",
"mac",
"name",
"oui",
]
DEVICE_UPGRADED = (ACCESS_POINT_UPGRADED, GATEWAY_UPGRADED, SWITCH_UPGRADED)
WIRED_CONNECTION = (WIRED_CLIENT_CONNECTED,)
WIRELESS_CONNECTION = (
WIRELESS_CLIENT_CONNECTED,
WIRELESS_CLIENT_ROAM,
WIRELESS_CLIENT_ROAMRADIO,
WIRELESS_GUEST_CONNECTED,
WIRELESS_GUEST_ROAM,
WIRELESS_GUEST_ROAMRADIO,
)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up device tracker for UniFi component."""
controller = hass.data[UNIFI_DOMAIN][config_entry.entry_id]
controller.entities[DOMAIN] = {CLIENT_TRACKER: set(), DEVICE_TRACKER: set()}
@callback
def items_added(
clients: set = controller.api.clients, devices: set = controller.api.devices
) -> None:
"""Update the values of the controller."""
if controller.option_track_clients:
add_client_entities(controller, async_add_entities, clients)
if controller.option_track_devices:
add_device_entities(controller, async_add_entities, devices)
for signal in (controller.signal_update, controller.signal_options_update):
controller.listeners.append(async_dispatcher_connect(hass, signal, items_added))
items_added()
@callback
def add_client_entities(controller, async_add_entities, clients):
"""Add new client tracker entities from the controller."""
trackers = []
for mac in clients:
if mac in controller.entities[DOMAIN][UniFiClientTracker.TYPE]:
continue
client = controller.api.clients[mac]
if mac not in controller.wireless_clients:
if not controller.option_track_wired_clients:
continue
elif (
client.essid
and controller.option_ssid_filter
and client.essid not in controller.option_ssid_filter
):
continue
trackers.append(UniFiClientTracker(client, controller))
if trackers:
async_add_entities(trackers)
@callback
def add_device_entities(controller, async_add_entities, devices):
"""Add new device tracker entities from the controller."""
trackers = []
for mac in devices:
if mac in controller.entities[DOMAIN][UniFiDeviceTracker.TYPE]:
continue
device = controller.api.devices[mac]
trackers.append(UniFiDeviceTracker(device, controller))
if trackers:
async_add_entities(trackers)
class UniFiClientTracker(UniFiClient, ScannerEntity):
"""Representation of a network client."""
DOMAIN = DOMAIN
TYPE = CLIENT_TRACKER
def __init__(self, client, controller):
"""Set up tracked client."""
super().__init__(client, controller)
self.schedule_update = False
self.cancel_scheduled_update = None
self._is_connected = False
if client.last_seen:
self._is_connected = (
self.is_wired == client.is_wired
and dt_util.utcnow()
- dt_util.utc_from_timestamp(float(client.last_seen))
< controller.option_detection_time
)
if self._is_connected:
self.schedule_update = True
async def async_will_remove_from_hass(self) -> None:
"""Disconnect object when removed."""
if self.cancel_scheduled_update:
self.cancel_scheduled_update()
await super().async_will_remove_from_hass()
@callback
def async_update_callback(self) -> None:
"""Update the clients state."""
if self.client.last_updated == SOURCE_EVENT:
if (self.is_wired and self.client.event.event in WIRED_CONNECTION) or (
not self.is_wired and self.client.event.event in WIRELESS_CONNECTION
):
self._is_connected = True
self.schedule_update = False
if self.cancel_scheduled_update:
self.cancel_scheduled_update()
self.cancel_scheduled_update = None
# Ignore extra scheduled update from wired bug
elif not self.cancel_scheduled_update:
self.schedule_update = True
elif not self.client.event and self.client.last_updated == SOURCE_DATA:
if self.is_wired == self.client.is_wired:
self._is_connected = True
self.schedule_update = True
if self.schedule_update:
self.schedule_update = False
if self.cancel_scheduled_update:
self.cancel_scheduled_update()
self.cancel_scheduled_update = async_track_point_in_utc_time(
self.hass,
self._make_disconnected,
dt_util.utcnow() + self.controller.option_detection_time,
)
super().async_update_callback()
@callback
def _make_disconnected(self, _):
"""Mark client as disconnected."""
self._is_connected = False
self.cancel_scheduled_update = None
self.async_write_ha_state()
@property
def is_connected(self):
"""Return true if the client is connected to the network."""
if (
not self.is_wired
and self.client.essid
and self.controller.option_ssid_filter
and self.client.essid not in self.controller.option_ssid_filter
):
return False
return self._is_connected
@property
def source_type(self):
"""Return the source type of the client."""
return SOURCE_TYPE_ROUTER
@property
def unique_id(self) -> str:
"""Return a unique identifier for this client."""
return f"{self.client.mac}-{self.controller.site}"
@property
def device_state_attributes(self):
"""Return the client state attributes."""
attributes = {"is_wired": self.is_wired}
if self.is_connected:
for variable in CLIENT_CONNECTED_ATTRIBUTES:
if variable in self.client.raw:
attributes[variable] = self.client.raw[variable]
for variable in CLIENT_STATIC_ATTRIBUTES:
if variable in self.client.raw:
attributes[variable] = self.client.raw[variable]
return attributes
async def options_updated(self) -> None:
"""Config entry options are updated, remove entity if option is disabled."""
if not self.controller.option_track_clients:
await self.remove_item({self.client.mac})
elif self.is_wired:
if not self.controller.option_track_wired_clients:
await self.remove_item({self.client.mac})
elif (
self.controller.option_ssid_filter
and self.client.essid not in self.controller.option_ssid_filter
):
await self.remove_item({self.client.mac})
class UniFiDeviceTracker(UniFiBase, ScannerEntity):
"""Representation of a network infrastructure device."""
DOMAIN = DOMAIN
TYPE = DEVICE_TRACKER
def __init__(self, device, controller):
"""Set up tracked device."""
super().__init__(device, controller)
self._is_connected = device.state == 1
self.cancel_scheduled_update = None
@property
def device(self):
"""Wrap item."""
return self._item
async def async_will_remove_from_hass(self) -> None:
"""Disconnect device object when removed."""
if self.cancel_scheduled_update:
self.cancel_scheduled_update()
await super().async_will_remove_from_hass()
@callback
def async_update_callback(self):
"""Update the devices' state."""
if self.device.last_updated == SOURCE_DATA:
self._is_connected = True
if self.cancel_scheduled_update:
self.cancel_scheduled_update()
self.cancel_scheduled_update = async_track_point_in_utc_time(
self.hass,
self._no_heartbeat,
dt_util.utcnow() + timedelta(seconds=self.device.next_interval + 60),
)
elif (
self.device.last_updated == SOURCE_EVENT
and self.device.event.event in DEVICE_UPGRADED
):
self.hass.async_create_task(self.async_update_device_registry())
return
super().async_update_callback()
@callback
def _no_heartbeat(self, _):
"""No heart beat by device."""
self._is_connected = False
self.cancel_scheduled_update = None
self.async_write_ha_state()
@property
def is_connected(self):
"""Return true if the device is connected to the network."""
return self._is_connected
@property
def source_type(self):
"""Return the source type of the device."""
return SOURCE_TYPE_ROUTER
@property
def name(self) -> str:
"""Return the name of the device."""
return self.device.name or self.device.model
@property
def unique_id(self) -> str:
"""Return a unique identifier for this device."""
return self.device.mac
@property
def available(self) -> bool:
"""Return if controller is available."""
return not self.device.disabled and self.controller.available
@property
def device_info(self):
"""Return a device description for device registry."""
info = {
"connections": {(CONNECTION_NETWORK_MAC, self.device.mac)},
"manufacturer": ATTR_MANUFACTURER,
"model": self.device.model,
"sw_version": self.device.version,
}
if self.device.name:
info["name"] = self.device.name
return info
async def async_update_device_registry(self) -> None:
"""Update device registry."""
device_registry = await self.hass.helpers.device_registry.async_get_registry()
device_registry.async_get_or_create(
config_entry_id=self.controller.config_entry.entry_id, **self.device_info
)
@property
def device_state_attributes(self):
"""Return the device state attributes."""
if self.device.state == 0:
return {}
attributes = {}
if self.device.has_fan:
attributes["fan_level"] = self.device.fan_level
if self.device.overheating:
attributes["overheating"] = self.device.overheating
if self.device.upgradable:
attributes["upgradable"] = self.device.upgradable
return attributes
async def options_updated(self) -> None:
"""Config entry options are updated, remove entity if option is disabled."""
if not self.controller.option_track_devices:
await self.remove_item({self.device.mac})