-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscan_device.py
282 lines (245 loc) · 9.4 KB
/
scan_device.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
import asyncio
import logging
import os
from zigpy.exceptions import DeliveryError
from zigpy.util import retryable
from homeassistant.util.json import save_json
LOGGER = logging.getLogger(__name__)
@retryable((DeliveryError, asyncio.TimeoutError), tries=3)
async def read_attr(cluster, attrs):
return await cluster.read_attributes(attrs, allow_cache=False)
@retryable((DeliveryError, asyncio.TimeoutError), tries=3)
def wrapper(cmd, *args, **kwargs):
return cmd(*args, **kwargs)
async def scan_results(device):
result = {"ieee": str(device.ieee), "nwk": "0x{:04x}".format(device.nwk)}
LOGGER.debug("Scanning device 0x{:04x}".format(device.nwk))
endpoints = []
for epid, ep in device.endpoints.items():
if epid == 0:
continue
LOGGER.debug("scanning endpoint #%i", epid)
result["model"] = ep.model
result["manufacturer"] = ep.manufacturer
endpoint = {
"id": epid,
"device_type": "0x{:04x}".format(ep.device_type),
"profile": "0x{:04x}".format(ep.profile_id),
}
if epid != 242:
endpoint.update(await scan_endpoint(ep))
endpoints.append(endpoint)
result["endpoints"] = endpoints
return result
async def scan_endpoint(ep):
result = {}
clusters = {}
for cluster in ep.in_clusters.values():
LOGGER.debug(
"Scanning cluster_id 0x{:04x}/'{}' input cluster".format(
cluster.cluster_id, cluster.ep_attribute
)
)
key = "0x{:04x}".format(cluster.cluster_id)
clusters[key] = await scan_cluster(cluster, is_server=True)
result["in_clusters"] = dict(sorted(clusters.items(), key=lambda k: k[0]))
clusters = {}
for cluster in ep.out_clusters.values():
LOGGER.debug(
"Scanning cluster_id 0x{:04x}/'{}' output cluster".format(
cluster.cluster_id, cluster.ep_attribute
)
)
key = "0x{:04x}".format(cluster.cluster_id)
clusters[key] = await scan_cluster(cluster, is_server=True)
result["out_clusters"] = dict(sorted(clusters.items(), key=lambda k: k[0]))
return result
async def scan_cluster(cluster, is_server=True):
if is_server:
cmds_gen = "commands_generated"
cmds_rec = "commands_received"
else:
cmds_rec = "commands_generated"
cmds_gen = "commands_received"
return {
"cluster_id": "0x{:04x}".format(cluster.cluster_id),
"name": cluster.ep_attribute,
"attributes": await discover_attributes_extended(cluster),
cmds_rec: await discover_commands_received(cluster, is_server),
cmds_gen: await discover_commands_generated(cluster, is_server),
}
async def discover_attributes_extended(cluster, manufacturer=None):
from zigpy.zcl import foundation
LOGGER.debug("Discovering attributes extended")
result = {}
attr_id = 0
done = False
while not done:
try:
done, rsp = await wrapper(
cluster.discover_attributes_extended,
attr_id,
16,
manufacturer=manufacturer,
)
await asyncio.sleep(0.4)
except (DeliveryError, asyncio.TimeoutError) as ex:
LOGGER.error(
"Failed to discover attributes extended starting %s. Error: {}".format(
attr_id, ex
)
)
break
if isinstance(rsp, foundation.Status):
LOGGER.error(
"got %s status for discover_attribute starting %s", rsp, attr_id
)
break
for attr_rec in rsp:
attr_id = attr_rec.attrid
attr_name = cluster.attributes.get(
attr_rec.attrid, (str(attr_rec.attrid), None)
)[0]
attr_type = foundation.DATA_TYPES.get(attr_rec.datatype)
if attr_type:
attr_type = [attr_type[1].__name__, attr_type[2].__name__]
else:
attr_type = "0x{:02x}".format(attr_rec.datatype)
try:
access = foundation.AttributeAccessControl(attr_rec.acl).name
except ValueError:
access = "undefined"
result[attr_id] = {
"attribute_id": "0x{:04x}".format(attr_id),
"attribute_name": attr_name,
"value_type": attr_type,
"access": access,
}
attr_id += 1
await asyncio.sleep(0.2)
to_read = list(result.keys())
LOGGER.debug("Reading attrs: %s", to_read)
chunk, to_read = to_read[:4], to_read[4:]
while chunk:
try:
success, failed = await read_attr(cluster, chunk)
LOGGER.debug("Reading attr success: %s, failed %s", success, failed)
for attr_id, value in success.items():
if isinstance(value, bytes):
try:
value = value.split(b"\x00")[0].decode().strip()
except UnicodeDecodeError:
value = value.hex()
result[attr_id]["attribute_value"] = value
except (DeliveryError, asyncio.TimeoutError) as ex:
LOGGER.error("Couldn't read attr_id %i: %s", attr_id, ex)
chunk, to_read = to_read[:4], to_read[4:]
await asyncio.sleep(0.3)
return {
"0x{:04x}".format(a_id): result[a_id] for a_id in sorted(result)
}
async def discover_commands_received(cluster, is_server, manufacturer=None):
from zigpy.zcl.foundation import Status
LOGGER.debug("Discovering commands received")
direction = "received" if is_server else "generated"
result = {}
cmd_id = 0
done = False
while not done:
try:
done, rsp = await wrapper(
cluster.discover_commands_received,
cmd_id,
16,
manufacturer=manufacturer,
)
await asyncio.sleep(0.3)
except (DeliveryError, asyncio.TimeoutError) as ex:
LOGGER.error(
"Failed to discover commands starting %s. Error: {}".format(cmd_id, ex)
)
break
if isinstance(rsp, Status):
LOGGER.error(
"got %s status for discover_attribute starting %s", rsp, cmd_id
)
break
for cmd_id in rsp:
cmd_data = cluster.server_commands.get(
cmd_id, (str(cmd_id), "not_in_zcl", None)
)
cmd_name, cmd_args, _ = cmd_data
if not isinstance(cmd_args, str):
cmd_args = [arg.__name__ for arg in cmd_args]
key = "0x{:02x}".format(cmd_id)
result[key] = {
"command_id": "0x{:02x}".format(cmd_id),
"command_name": cmd_name,
"command_arguments": cmd_args,
}
cmd_id += 1
await asyncio.sleep(0.2)
return dict(sorted(result.items(), key=lambda k: k[0]))
async def discover_commands_generated(cluster, is_server, manufacturer=None):
from zigpy.zcl.foundation import Status
direction = "generated" if is_server else "received"
result = {}
cmd_id = 0
done = False
while not done:
try:
done, rsp = await wrapper(
cluster.discover_commands_generated,
cmd_id,
16,
manufacturer=manufacturer,
)
await asyncio.sleep(0.3)
except (DeliveryError, asyncio.TimeoutError) as ex:
LOGGER.error(
"Failed to discover commands starting %s. Error: {}".format(cmd_id, ex)
)
break
if isinstance(rsp, Status):
LOGGER.error(
"got %s status for discover_attribute starting %s", rsp, cmd_id
)
break
for cmd_id in rsp:
cmd_data = cluster.client_commands.get(
cmd_id, (str(cmd_id), "not_in_zcl", None)
)
cmd_name, cmd_args, _ = cmd_data
if not isinstance(cmd_args, str):
cmd_args = [arg.__name__ for arg in cmd_args]
key = "0x{:02x}".format(cmd_id)
result[key] = {
"command_id": "0x{:02x}".format(cmd_id),
"command_Name": cmd_name,
"command_args": cmd_args,
}
cmd_id += 1
await asyncio.sleep(0.2)
return dict(sorted(result.items(), key=lambda k: k[0]))
async def scan_device(app, listener, ieee, cmd, data, service):
if ieee is None:
LOGGER.error("missing ieee")
return
LOGGER.debug("running 'scan_device' command: %s", service)
device = app.get_device(ieee=ieee)
scan = await scan_results(device)
model = scan.get("model")
manufacturer = scan.get("manufacturer")
if model is not None and manufacturer is not None:
ieee_tail = "".join(["%02x" % (o,) for o in ieee[-4:]])
file_name = "{}_{}_{}_scan_results.txt".format(model, manufacturer, ieee_tail)
else:
ieee_tail = "".join(["%02x" % (o,) for o in ieee])
file_name = "{}_scan_results.txt".format(ieee_tail)
conf_dir = listener._hass.config.config_dir
scan_dir = os.path.join(conf_dir, "scans")
if not os.path.isdir(scan_dir):
os.mkdir(scan_dir)
file_name = os.path.join(scan_dir, file_name)
save_json(file_name, scan)
LOGGER.debug("Finished writing scan results int '%s'", file_name)