-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
651 lines (588 loc) · 29.6 KB
/
Copy pathmain.py
File metadata and controls
651 lines (588 loc) · 29.6 KB
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
import sys
import json
import socket
import re
from typing import List, Dict, Any
last_topology_data = {}
config = json.load(open('config.json'))
test_file_index = 0
TEST_COUNT = 6
def get_topology_data():
SEND_COMMAND = "networkdiagnostic get ff02::1 "
TLV_NUMBER = "0 01 02 04 05 06 07 08 09 16 17"
COMMAND_SUFFIX = "\r\n"
START_MARKER = "DIAG_GET.rsp/ans from"
END_MARKER = "Done"
RECEIVE_TIMEOUT = 5.0
# ソケットの作成
unix_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server_address = config['socket_path']
print(f"Connecting to {server_address}")
# サーバに接続
try:
unix_socket.connect(server_address)
except OSError as err:
print(err)
# コマンドの送信
try:
message_str = SEND_COMMAND + TLV_NUMBER + COMMAND_SUFFIX
message_bytes = message_str.encode('utf-8')
all_data = ""
with unix_socket:
print(f"Sending command: {message_str.strip()}")
unix_socket.sendall(message_bytes)
# タイムアウト設定
unix_socket.settimeout(RECEIVE_TIMEOUT)
try:
print(f"Received:")
while END_MARKER not in all_data:
data = unix_socket.recv(16384)
all_data += data.decode('utf-8')
if not data:
break
except TimeoutError:
print("Socket timeout")
response = all_data.strip()
print(response)
except OSError as err:
print(err)
print("Close socket")
# 解析したデータを格納するリスト
parsed_data: List[Dict[str, Any]] = []
blocks = response.split(START_MARKER)
blocks = [block.strip() for block in blocks if block.strip()]
# 抽出したい正規表現パターン
NODE_PATTERN = re.compile(
r"Ext\s*Address:\s*(?P<ext_addr>[0-9a-f]+)\s*.*?"
r"Rloc16:\s*(?P<rloc_16>0x[0-9a-f]+)\s*.*?"
r"Mode:.*?"
r"RxOnWhenIdle:\s*(?P<rx_on>\d+).*?"
r"DeviceType:\s*(?P<dev_type>\d+).*?"
r"NetworkData:\s*(?P<net_data>\d+).*?"
r"Connectivity:.*?"
r"ParentPriority:\s*(?P<parent_priority>-?\d+).*?"
r"LinkQuality3:\s*(?P<link_quality3>\d+).*?"
r"LinkQuality2:\s*(?P<link_quality2>\d+).*?"
r"LinkQuality1:\s*(?P<link_quality1>\d+).*?"
r"LeaderCost:\s*(?P<leader_cost>\d+).*?"
r"IdSequence:\s*(?P<id_sequence>\d+).*?"
r"ActiveRouters:\s*(?P<active_routers>\d+).*?"
r"SedBufferSize:\s*(?P<sed_buffer_size>\d+).*?"
r"SedDatagramCount:\s*(?P<sed_datagram_count>\d+).*?"
r"(?:Route:\s*IdSequence:\s*(?P<route_id_sequence>\d+).*?RouteData:\s*(?P<route_data>.*?(?=Leader\s*Data:)))?"
r"Leader\s*Data:.*?"
r"PartitionId:\s*(?P<partition_id>0x[0-9a-f]+).*?"
r"Weighting:\s*(?P<weighting>\d+).*?"
r"DataVersion:\s*(?P<data_version>\d+).*?"
r"StableDataVersion:\s*(?P<stable_data_version>\d+).*?"
r"LeaderRouterId:\s*(?P<leader_router_id>0x[0-9a-f]+).*?"
r"Network\s*Data:\s*(?P<network_data>[0-9a-f]+).*?"
r"IP6\s*Address\s*List:\s*(?P<ip6_address_list>(?:\s*-\s*[0-9a-f:]+\s*)+).*?"
r"MAC\s*Counters:.*?"
r"IfInUnknownProtos:\s*(?P<if_in_unknown_protos>\d+).*?"
r"IfInErrors:\s*(?P<if_in_errors>\d+).*?"
r"IfOutErrors:\s*(?P<if_out_errors>\d+).*?"
r"IfInUcastPkts:\s*(?P<if_in_ucastpkts>\d+).*?"
r"IfInBroadcastPkts:\s*(?P<if_in_broadcast_pkts>\d+).*?"
r"IfInDiscards:\s*(?P<if_in_discards>\d+).*?"
r"IfOutUcastPkts:\s*(?P<if_out_ucastpkts>\d+).*?"
r"IfOutBroadcastPkts:\s*(?P<if_out_broadcast_pkts>\d+).*?"
r"IfOutDiscards:\s*(?P<if_out_discards>\d+).*?"
r"(?:Child\s*Table:\s*-\s*(?P<child_table>.*?(?=Channel\s*Pages:)))?"
r"Channel\s*Pages:\s*'(?P<channel_pages>\d\d)'",
re.IGNORECASE | re.DOTALL
)
ROUTE_PATTERN = re.compile(
r"-\s*RouteId:\s*(?P<route_id>0x[0-9a-f]+)\s*"
r"LinkQualityOut:\s*(?P<link_quality_out>\d+)\s*"
r"LinkQualityIn:\s*(?P<link_quality_in>\d+)\s*"
r"RouteCost:\s*(?P<route_cost>\d+)",
re.IGNORECASE
)
CHILD_PATTERN = re.compile(
r"ChildId:\s*(?P<child_id>0x[0-9a-f]+).*?"
r"Timeout:\s*(?P<timeout>\d+).*?"
r"Link\s*Quality:\s*(?P<link_quality>\d+).*?"
r"Mode:.*?"
r"RxOnWhenIdle:\s*(?P<rx_on>\d+).*?"
r"DeviceType:\s*(?P<dev_type>\d+).*?"
r"NetworkData:\s*(?P<net_data>\d+).*?",
re.IGNORECASE | re.DOTALL
)
for block in blocks:
match = NODE_PATTERN.search(block)
if match:
try:
node_info = {
'ExtAddress': match.group('ext_addr').strip(),
'Rloc16': int(match.group('rloc_16').strip(), 16),
'Mode': {
'RxOnWhenIdle': int(match.group('rx_on').strip()),
'DeviceType': int(match.group('dev_type').strip()),
'NetworkData': int(match.group('net_data').strip())
},
'Connectivity': {
'ParentPriority': int(match.group('parent_priority').strip()),
'LinkQuality3': int(match.group('link_quality3').strip()),
'LinkQuality2': int(match.group('link_quality2').strip()),
'LinkQuality1': int(match.group('link_quality1').strip()),
'LeaderCost': int(match.group('leader_cost').strip()),
'IdSequence': int(match.group('id_sequence').strip()),
'ActiveRouters': int(match.group('active_routers').strip()),
'SedBufferSize': int(match.group('sed_buffer_size').strip()),
'SedDatagramCount': int(match.group('sed_datagram_count').strip())
},
'LeaderData': {
'PartitionId': int(match.group('partition_id'), 16),
'Weighting': int(match.group('weighting').strip()),
'DataVersion': int(match.group('data_version').strip()),
'StableDataVersion': int(match.group('stable_data_version').strip()),
'LeaderRouterId': int(match.group('leader_router_id'), 16)
},
'NetworkData': match.group('network_data').strip(),
'MACCounters': {
'IfInUnknownProtos': int(match.group('if_in_unknown_protos').strip()),
'IfInErrors': int(match.group('if_in_errors').strip()),
'IfOutErrors': int(match.group('if_out_errors').strip()),
'IfInUcastPkts': int(match.group('if_in_ucastpkts').strip()),
'IfInBroadcastPkts': int(match.group('if_in_broadcast_pkts').strip()),
'IfInDiscards': int(match.group('if_in_discards').strip()),
'IfOutUcastPkts': int(match.group('if_out_ucastpkts').strip()),
'IfOutBroadcastPkts': int(match.group('if_out_broadcast_pkts').strip()),
'IfOutDiscards': int(match.group('if_out_discards').strip())
},
'ChannelPages': match.group('channel_pages').strip().zfill(2)
}
ip6_list = match.group('ip6_address_list')
if ip6_list:
# ハイフン (-) で始まる行の IPv6 アドレスを抽出
addresses = re.findall(r'-\s*([0-9a-f:]+)', ip6_list, re.IGNORECASE)
node_info['IP6AddressList'] = addresses
route_id_seq = match.group('route_id_sequence')
route_data_list = match.group('route_data')
node_info['Route'] = {}
route_info = node_info['Route']
if route_id_seq and route_data_list:
route_info['RouteIdSequence'] = int(route_id_seq.strip())
routes = []
for route_match in ROUTE_PATTERN.finditer(route_data_list):
route = {
'RouteId': int(route_match.group('route_id'), 16),
'LinkQualityOut': int(route_match.group('link_quality_out').strip()),
'LinkQualityIn': int(route_match.group('link_quality_in').strip()),
'RouteCost': int(route_match.group('route_cost').strip())
}
routes.append(route)
if routes:
route_info['RouteData'] = routes
child_data = match.group('child_table')
has_child_table_section = "Child Table:" in block
children = []
if child_data:
for child_match in CHILD_PATTERN.finditer(child_data):
child = {
'ChildId': int(child_match.group('child_id'), 16),
'Timeout': int(child_match.group('timeout').strip()),
'LinkQuality': int(child_match.group('link_quality').strip()),
'Mode': {
'RxOnWhenIdle': int(child_match.group('rx_on').strip()),
'DeviceType': int(child_match.group('dev_type').strip()),
'NetworkData': int(child_match.group('net_data').strip())
}
}
children.append(child)
if has_child_table_section:
node_info['ChildTable'] = children
parsed_data.append(node_info)
except Exception as e:
print(f"Warning: Failed to parse node data completely: {e}")
if parsed_data:
# D3.js用の構造化データを作成
nodes = []
links = []
node_map = {} # Rloc16 -> node_index のマッピング
# 1. ルーターおよびリーダーノードを登録
for node in parsed_data:
# RLOC16の下位10ビットが0でないものはChildなので、ここではスキップする
# Child は後ほど親ルータから登録される
if (node['Rloc16'] & 0x3FF) != 0:
continue
node['Rloc16_str'] = f"0x{node['Rloc16']:04x}"
# 役割判定
leader_id = node['LeaderData']['LeaderRouterId']
router_id = node['Rloc16'] >> 10
node['Role'] = 'Leader' if router_id == leader_id else 'Router'
# まだ登録されていない場合のみ追加
if node['Rloc16'] not in node_map:
nodes.append(node)
node_map[node['Rloc16']] = len(nodes) - 1
# for i, node in enumerate(parsed_data):
# # 数値を 0x 付きの 16進数文字列に変換
# node['Rloc16_str'] = f"0x{node['Rloc16']:04x}"
# # 役割判定
# leader_id = node['LeaderData']['LeaderRouterId']
# router_id = node['Rloc16'] >> 10
# node['Role'] = 'Leader' if router_id == leader_id else 'Router'
# nodes.append(node)
# node_map[node['Rloc16']] = i
# 2. リンクと子ノードを登録
router_count = len(nodes)
for i in range(router_count):
source_node = nodes[i]
# Router-Router リンク
if 'Route' in source_node and 'RouteData' in source_node['Route']:
for route in source_node['Route']['RouteData']:
target_rloc = route['RouteId'] << 10
if target_rloc in node_map:
target_idx = node_map[target_rloc]
if i < target_idx: # 重複リンクを避ける
links.append({
'source': i,
'target': target_idx,
'type': 0, # Router-Router
'linkInfo': {
'inQuality': route['LinkQualityIn'],
'outQuality': route['LinkQualityOut']
}
})
# Router-Child リンクと子ノードの追加
if 'ChildTable' in source_node:
for child in source_node['ChildTable']:
child_rloc = source_node['Rloc16'] + child['ChildId']
child_node = {
'Rloc16_str': f"0x{child_rloc:04x}",
'Role': 'Child',
'ParentRloc16': source_node['Rloc16_str']
}
nodes.append(child_node)
child_idx = len(nodes) - 1
links.append({
'source': i,
'target': child_idx,
'type': 1, # Router-Child
'linkInfo': {
'Timeout': child['Timeout'],
'Mode': child['Mode']
}
})
child_count = len(nodes) - router_count
current_data = {
'nodes': nodes,
'links': links,
'router_number': router_count,
'child_number': child_count
}
global last_topology_data
new_nodes = {node['Rloc16_str']: node for node in current_data['nodes']}
logs = []
# 1. 離脱とRole変化のチェック
if last_topology_data:
for rloc, old_node in last_topology_data.items():
if rloc not in new_nodes:
logs.append(f"Device {rloc} left the network.")
else:
if old_node.get('Role') != new_nodes[rloc].get('Role'):
logs.append(f"Device {rloc} changed role: {old_node['Role']} -> {new_nodes[rloc]['Role']}")
# 2. 新規接続のチェック
for rloc, new_node in new_nodes.items():
if rloc not in last_topology_data:
logs.append(f"Device {rloc} joined as {new_node['Role']}.")
last_topology_data = new_nodes
current_data['logs'] = logs
return current_data
else:
return False
def get_test_data():
START_MARKER = "DIAG_GET.rsp/ans from"
END_MARKER = "Done"
pattern = re.compile(r'^test._path')
global test_file_index
test_path = config[f"test{test_file_index + 1}_path"]
if test_file_index < TEST_COUNT - 1:
test_file_index += 1
try:
all_data = ""
print(f"test data:")
while END_MARKER not in all_data:
with open(test_path, 'r', encoding='utf-8') as f:
all_data = f.read()
except FileNotFoundError as e:
print(f"No test file found: {e}")
response = all_data.strip()
print(response)
# 解析したデータを格納するリスト
parsed_data: List[Dict[str, Any]] = []
blocks = response.split(START_MARKER)
blocks = [block.strip() for block in blocks if block.strip()]
# 抽出したい正規表現パターン
NODE_PATTERN = re.compile(
r"Ext\s*Address:\s*(?P<ext_addr>[0-9a-f]+)\s*.*?"
r"Rloc16:\s*(?P<rloc_16>0x[0-9a-f]+)\s*.*?"
r"Mode:.*?"
r"RxOnWhenIdle:\s*(?P<rx_on>\d+).*?"
r"DeviceType:\s*(?P<dev_type>\d+).*?"
r"NetworkData:\s*(?P<net_data>\d+).*?"
r"Connectivity:.*?"
r"ParentPriority:\s*(?P<parent_priority>-?\d+).*?"
r"LinkQuality3:\s*(?P<link_quality3>\d+).*?"
r"LinkQuality2:\s*(?P<link_quality2>\d+).*?"
r"LinkQuality1:\s*(?P<link_quality1>\d+).*?"
r"LeaderCost:\s*(?P<leader_cost>\d+).*?"
r"IdSequence:\s*(?P<id_sequence>\d+).*?"
r"ActiveRouters:\s*(?P<active_routers>\d+).*?"
r"SedBufferSize:\s*(?P<sed_buffer_size>\d+).*?"
r"SedDatagramCount:\s*(?P<sed_datagram_count>\d+).*?"
r"(?:Route:\s*IdSequence:\s*(?P<route_id_sequence>\d+).*?RouteData:\s*(?P<route_data>.*?(?=Leader\s*Data:)))?"
r"Leader\s*Data:.*?"
r"PartitionId:\s*(?P<partition_id>0x[0-9a-f]+).*?"
r"Weighting:\s*(?P<weighting>\d+).*?"
r"DataVersion:\s*(?P<data_version>\d+).*?"
r"StableDataVersion:\s*(?P<stable_data_version>\d+).*?"
r"LeaderRouterId:\s*(?P<leader_router_id>0x[0-9a-f]+).*?"
r"Network\s*Data:\s*(?P<network_data>[0-9a-f]+).*?"
r"IP6\s*Address\s*List:\s*(?P<ip6_address_list>(?:\s*-\s*[0-9a-f:]+\s*)+).*?"
r"MAC\s*Counters:.*?"
r"IfInUnknownProtos:\s*(?P<if_in_unknown_protos>\d+).*?"
r"IfInErrors:\s*(?P<if_in_errors>\d+).*?"
r"IfOutErrors:\s*(?P<if_out_errors>\d+).*?"
r"IfInUcastPkts:\s*(?P<if_in_ucastpkts>\d+).*?"
r"IfInBroadcastPkts:\s*(?P<if_in_broadcast_pkts>\d+).*?"
r"IfInDiscards:\s*(?P<if_in_discards>\d+).*?"
r"IfOutUcastPkts:\s*(?P<if_out_ucastpkts>\d+).*?"
r"IfOutBroadcastPkts:\s*(?P<if_out_broadcast_pkts>\d+).*?"
r"IfOutDiscards:\s*(?P<if_out_discards>\d+).*?"
r"(?:Child\s*Table:\s*-\s*(?P<child_table>.*?(?=Channel\s*Pages:)))?"
r"Channel\s*Pages:\s*'(?P<channel_pages>\d\d)'",
re.IGNORECASE | re.DOTALL
)
ROUTE_PATTERN = re.compile(
r"-\s*RouteId:\s*(?P<route_id>0x[0-9a-f]+)\s*"
r"LinkQualityOut:\s*(?P<link_quality_out>\d+)\s*"
r"LinkQualityIn:\s*(?P<link_quality_in>\d+)\s*"
r"RouteCost:\s*(?P<route_cost>\d+)",
re.IGNORECASE
)
CHILD_PATTERN = re.compile(
r"ChildId:\s*(?P<child_id>0x[0-9a-f]+).*?"
r"Timeout:\s*(?P<timeout>\d+).*?"
r"Link\s*Quality:\s*(?P<link_quality>\d+).*?"
r"Mode:.*?"
r"RxOnWhenIdle:\s*(?P<rx_on>\d+).*?"
r"DeviceType:\s*(?P<dev_type>\d+).*?"
r"NetworkData:\s*(?P<net_data>\d+).*?",
re.IGNORECASE | re.DOTALL
)
for block in blocks:
match = NODE_PATTERN.search(block)
if match:
try:
node_info = {
'ExtAddress': match.group('ext_addr').strip(),
'Rloc16': int(match.group('rloc_16').strip(), 16),
'Mode': {
'RxOnWhenIdle': int(match.group('rx_on').strip()),
'DeviceType': int(match.group('dev_type').strip()),
'NetworkData': int(match.group('net_data').strip())
},
'Connectivity': {
'ParentPriority': int(match.group('parent_priority').strip()),
'LinkQuality3': int(match.group('link_quality3').strip()),
'LinkQuality2': int(match.group('link_quality2').strip()),
'LinkQuality1': int(match.group('link_quality1').strip()),
'LeaderCost': int(match.group('leader_cost').strip()),
'IdSequence': int(match.group('id_sequence').strip()),
'ActiveRouters': int(match.group('active_routers').strip()),
'SedBufferSize': int(match.group('sed_buffer_size').strip()),
'SedDatagramCount': int(match.group('sed_datagram_count').strip())
},
'LeaderData': {
'PartitionId': int(match.group('partition_id'), 16),
'Weighting': int(match.group('weighting').strip()),
'DataVersion': int(match.group('data_version').strip()),
'StableDataVersion': int(match.group('stable_data_version').strip()),
'LeaderRouterId': int(match.group('leader_router_id'), 16)
},
'NetworkData': match.group('network_data').strip(),
'MACCounters': {
'IfInUnknownProtos': int(match.group('if_in_unknown_protos').strip()),
'IfInErrors': int(match.group('if_in_errors').strip()),
'IfOutErrors': int(match.group('if_out_errors').strip()),
'IfInUcastPkts': int(match.group('if_in_ucastpkts').strip()),
'IfInBroadcastPkts': int(match.group('if_in_broadcast_pkts').strip()),
'IfInDiscards': int(match.group('if_in_discards').strip()),
'IfOutUcastPkts': int(match.group('if_out_ucastpkts').strip()),
'IfOutBroadcastPkts': int(match.group('if_out_broadcast_pkts').strip()),
'IfOutDiscards': int(match.group('if_out_discards').strip())
},
'ChannelPages': match.group('channel_pages').strip().zfill(2)
}
ip6_list = match.group('ip6_address_list')
if ip6_list:
# ハイフン (-) で始まる行の IPv6 アドレスを抽出
addresses = re.findall(r'-\s*([0-9a-f:]+)', ip6_list, re.IGNORECASE)
node_info['IP6AddressList'] = addresses
route_id_seq = match.group('route_id_sequence')
route_data_list = match.group('route_data')
node_info['Route'] = {}
route_info = node_info['Route']
if route_id_seq and route_data_list:
route_info['RouteIdSequence'] = int(route_id_seq.strip())
routes = []
for route_match in ROUTE_PATTERN.finditer(route_data_list):
route = {
'RouteId': int(route_match.group('route_id'), 16),
'LinkQualityOut': int(route_match.group('link_quality_out').strip()),
'LinkQualityIn': int(route_match.group('link_quality_in').strip()),
'RouteCost': int(route_match.group('route_cost').strip())
}
routes.append(route)
if routes:
route_info['RouteData'] = routes
child_data = match.group('child_table')
has_child_table_section = "Child Table:" in block
children = []
if child_data:
for child_match in CHILD_PATTERN.finditer(child_data):
child = {
'ChildId': int(child_match.group('child_id'), 16),
'Timeout': int(child_match.group('timeout').strip()),
'LinkQuality': int(child_match.group('link_quality').strip()),
'Mode': {
'RxOnWhenIdle': int(child_match.group('rx_on').strip()),
'DeviceType': int(child_match.group('dev_type').strip()),
'NetworkData': int(child_match.group('net_data').strip())
}
}
children.append(child)
if has_child_table_section:
node_info['ChildTable'] = children
parsed_data.append(node_info)
except Exception as e:
print(f"Warning: Failed to parse node data completely: {e}")
if parsed_data:
# D3.js用の構造化データを作成
nodes = []
links = []
node_map = {} # Rloc16 -> node_index のマッピング
# 1. ルーターおよびリーダーノードを登録
for node in parsed_data:
# RLOC16の下位10ビットが0でないものはChildなので、ここではスキップする
# Child は後ほど親ルータから登録される
if (node['Rloc16'] & 0x3FF) != 0:
continue
node['Rloc16_str'] = f"0x{node['Rloc16']:04x}"
# 役割判定
leader_id = node['LeaderData']['LeaderRouterId']
router_id = node['Rloc16'] >> 10
node['Role'] = 'Leader' if router_id == leader_id else 'Router'
# まだ登録されていない場合のみ追加
if node['Rloc16'] not in node_map:
nodes.append(node)
node_map[node['Rloc16']] = len(nodes) - 1
# for i, node in enumerate(parsed_data):
# # 数値を 0x 付きの 16進数文字列に変換
# node['Rloc16_str'] = f"0x{node['Rloc16']:04x}"
# # 役割判定
# leader_id = node['LeaderData']['LeaderRouterId']
# router_id = node['Rloc16'] >> 10
# node['Role'] = 'Leader' if router_id == leader_id else 'Router'
# nodes.append(node)
# node_map[node['Rloc16']] = i
# 2. リンクと子ノードを登録
router_count = len(nodes)
for i in range(router_count):
source_node = nodes[i]
# Router-Router リンク
if 'Route' in source_node and 'RouteData' in source_node['Route']:
for route in source_node['Route']['RouteData']:
target_rloc = route['RouteId'] << 10
if target_rloc in node_map:
target_idx = node_map[target_rloc]
if i < target_idx: # 重複リンクを避ける
links.append({
'source': i,
'target': target_idx,
'type': 0, # Router-Router
'linkInfo': {
'inQuality': route['LinkQualityIn'],
'outQuality': route['LinkQualityOut']
}
})
# Router-Child リンクと子ノードの追加
if 'ChildTable' in source_node:
for child in source_node['ChildTable']:
child_rloc = source_node['Rloc16'] + child['ChildId']
child_node = {
'Rloc16_str': f"0x{child_rloc:04x}",
'Role': 'Child',
'ParentRloc16': source_node['Rloc16_str']
}
nodes.append(child_node)
child_idx = len(nodes) - 1
links.append({
'source': i,
'target': child_idx,
'type': 1, # Router-Child
'linkInfo': {
'Timeout': child['Timeout'],
'Mode': child['Mode']
}
})
child_count = len(nodes) - router_count
current_data = {
'nodes': nodes,
'links': links,
'router_number': router_count,
'child_number': child_count
}
global last_topology_data
new_nodes = {node['Rloc16_str']: node for node in current_data['nodes']}
logs = []
# 1. 離脱とRole変化のチェック
if last_topology_data:
for rloc, old_node in last_topology_data.items():
if rloc not in new_nodes:
logs.append(f"Device {rloc} left the network.")
else:
if old_node.get('Role') != new_nodes[rloc].get('Role'):
logs.append(f"Device {rloc} changed role: {old_node['Role']} -> {new_nodes[rloc]['Role']}")
# 2. 新規接続のチェック
for rloc, new_node in new_nodes.items():
if rloc not in last_topology_data:
logs.append(f"Device {rloc} joined as {new_node['Role']}.")
last_topology_data = new_nodes
current_data['logs'] = logs
return current_data
else:
return False
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="templates")
# 静的ファイル (.js,.css など) 用
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
global last_topology_data
global test_file_index
last_topology_data = {}
test_file_index = 0
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/topology")
async def topology():
try:
topology_data = get_topology_data()
return topology_data
except Exception as e:
print(f"Error in /topology: {e}")
return {"error": "Failed to get topology data"}
@app.get("/test_topology")
async def test_topology():
try:
test_data = get_test_data()
return test_data
except Exception as e:
print(f"Error in /test_topology: {e}")
return {"error": "Failed to get test topology data"}