forked from openthread/pyspinel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spinel-cli.py
executable file
·2481 lines (1983 loc) · 71.6 KB
/
spinel-cli.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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright (c) 2016-2019, The OpenThread Authors.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Shell tool for controlling OpenThread NCP instances.
"""
import os
import sys
import time
import traceback
import random
import importlib
import optparse
import binascii
import socket
import struct
import string
import textwrap
import logging
import logging.config
import logging.handlers
from cmd import Cmd
from spinel.const import SPINEL
from spinel.const import kThread
from spinel.codec import WpanApi
from spinel.codec import SpinelCodec
from spinel.stream import StreamOpen
from spinel.tun import TunInterface
import spinel.config as CONFIG
import spinel.util as util
import ipaddress
__copyright__ = "Copyright (c) 2016 The OpenThread Authors."
__version__ = "0.1.0"
NETWORK_PROMPT = "spinel-cli"
import io
import spinel.ipv6 as ipv6
import spinel.common as common
DEFAULT_BAUDRATE = 115200
class IcmpV6Factory(object):
ipv6_factory = ipv6.IPv6PacketFactory(
ehf={
0:
ipv6.HopByHopFactory(
hop_by_hop_options_factory=ipv6.HopByHopOptionsFactory(
options_factories={109: ipv6.MPLOptionFactory()}))
},
ulpf={
58:
ipv6.ICMPv6Factory(
body_factories={129: ipv6.ICMPv6EchoBodyFactory()})
})
def _any_identifier(self):
return random.getrandbits(16)
def _seq_number(self):
seq_number = 0
while True:
yield seq_number
seq_number += 1
seq_number if seq_number < (1 << 16) else 0
def build_icmp_echo_request(self,
src,
dst,
data,
hop_limit=64,
identifier=None,
sequence_number=None):
identifier = self._any_identifier(
) if identifier is None else identifier
sequence_number = next(
self._seq_number()) if sequence_number is None else sequence_number
ping_req = ipv6.IPv6Packet(
ipv6_header=ipv6.IPv6Header(source_address=src,
destination_address=dst,
hop_limit=hop_limit),
upper_layer_protocol=ipv6.ICMPv6(
header=ipv6.ICMPv6Header(_type=ipv6.ICMP_ECHO_REQUEST, code=0),
body=ipv6.ICMPv6EchoBody(identifier=identifier,
sequence_number=sequence_number,
data=data)))
return ping_req.to_bytes()
def from_bytes(self, data):
return self.ipv6_factory.parse(io.BytesIO(data), common.MessageInfo())
class SpinelCliCmd(Cmd, SpinelCodec):
"""
A command line shell for controlling OpenThread NCP nodes
via the Spinel protocol.
"""
VIRTUAL_TIME = os.getenv('VIRTUAL_TIME') == '1'
icmp_factory = IcmpV6Factory()
def _init_virtual_time(self):
"""
compute addresses used for virtual time.
"""
BASE_PORT = 9000
MAX_NODES = 34
PORT_OFFSET = int(os.getenv("PORT_OFFSET", "0"))
self._addr = ('127.0.0.1', BASE_PORT * 2 + MAX_NODES * PORT_OFFSET)
self._simulator_addr = ('127.0.0.1',
BASE_PORT + MAX_NODES * PORT_OFFSET)
def __init__(self, stream, nodeid, vendor_module, *_a, **kw):
if self.VIRTUAL_TIME:
self._init_virtual_time()
self.nodeid = nodeid
self.tun_if = None
self.wpan_api = WpanApi(stream, nodeid, vendor_module=vendor_module)
self.wpan_api.queue_register(SPINEL.HEADER_DEFAULT)
self.wpan_api.callback_register(SPINEL.PROP_STREAM_NET,
self.wpan_callback)
Cmd.__init__(self)
Cmd.identchars = string.ascii_letters + string.digits + '-'
if sys.stdin.isatty():
self.prompt = NETWORK_PROMPT + " > "
else:
self.use_rawinput = 0
self.prompt = ""
SpinelCliCmd.command_names.sort()
self.history_filename = os.path.expanduser("~/.spinel-cli-history")
try:
import readline
try:
readline.read_history_file(self.history_filename)
except IOError:
pass
except ImportError:
print("Module readline unavailable")
else:
import rlcompleter
if readline.__doc__ and 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
if hasattr(stream, 'pipe'):
self.wpan_api.queue_wait_for_prop(SPINEL.PROP_LAST_STATUS,
SPINEL.HEADER_ASYNC)
self.prop_set_value(SPINEL.PROP_IPv6_ICMP_PING_OFFLOAD, 1)
self.prop_set_value(SPINEL.PROP_THREAD_RLOC16_DEBUG_PASSTHRU, 1)
command_names = [
# Shell commands
'exit',
'quit',
'clear',
'history',
'debug',
'debug-mem',
'v',
'h',
'q',
# OpenThread CLI commands
'help',
'bufferinfo',
'channel',
'child',
'childmax',
'childtimeout',
'commissioner',
'contextreusedelay',
'counters',
'diag',
'discover',
'eidcache',
'extaddr',
'extpanid',
'ifconfig',
'ipaddr',
'joiner',
'keysequence',
'leaderdata',
'leaderweight',
'mac',
'macfilter',
'mfg',
'mode',
'netdata',
'networkidtimeout',
'networkkey',
'networkname',
'panid',
'parent',
'ping',
'prefix',
'releaserouterid',
'reset',
'rloc16',
'route',
'router',
'routerselectionjitter',
'routerupgradethreshold',
'routerdowngradethreshold',
'scan',
'state',
'thread',
'txpower',
'version',
'vendor',
# OpenThread Spinel-specific commands
'ncp-ml64',
'ncp-ll64',
'ncp-tun',
'ncp-raw',
'ncp-filter',
]
@classmethod
def wpan_callback(cls, prop, value, tid):
consumed = False
if prop == SPINEL.PROP_STREAM_NET:
consumed = True
try:
pkt = cls.icmp_factory.from_bytes(value)
if CONFIG.DEBUG_LOG_PKT:
CONFIG.LOGGER.debug(pkt)
timenow = int(round(time.time() * 1000)) & 0xFFFFFFFF
timestamp = (pkt.upper_layer_protocol.body.identifier << 16 |
pkt.upper_layer_protocol.body.sequence_number)
timedelta = (timenow - timestamp)
print("\n%d bytes from %s: icmp_seq=%d hlim=%d time=%dms" %
(len(pkt.upper_layer_protocol.body.data),
pkt.ipv6_header.source_address,
pkt.upper_layer_protocol.body.sequence_number,
pkt.ipv6_header.hop_limit, timedelta))
except RuntimeError:
pass
return consumed
@classmethod
def log(cls, text):
""" Common log handler. """
CONFIG.LOGGER.info(text)
def parseline(self, line):
cmd, arg, line = Cmd.parseline(self, line)
if cmd:
cmd = self.short_command_name(cmd)
line = cmd + ' ' + arg
return cmd, arg, line
def completenames(self, text, *ignored):
return [
name + ' '
for name in SpinelCliCmd.command_names
if name.startswith(text) or
self.short_command_name(name).startswith(text)
]
@classmethod
def short_command_name(cls, cmd):
return cmd.replace('-', '')
def postloop(self):
try:
import readline
try:
readline.write_history_file(self.history_filename)
except IOError:
pass
except ImportError:
pass
def prop_get_value(self, prop_id):
""" Blocking helper to return value for given propery identifier. """
return self.wpan_api.prop_get_value(prop_id)
def prop_set_value(self, prop_id, value, py_format='B'):
""" Blocking helper to set value for given propery identifier. """
return self.wpan_api.prop_set_value(prop_id, value, py_format)
def prop_insert_value(self, prop_id, value, py_format='B'):
""" Blocking helper to insert entry for given list property. """
return self.wpan_api.prop_insert_value(prop_id, value, py_format)
def prop_remove_value(self, prop_id, value, py_format='B'):
""" Blocking helper to remove entry for given list property. """
return self.wpan_api.prop_remove_value(prop_id, value, py_format)
def prop_get_or_set_value(self, prop_id, line, mixed_format='B'):
""" Helper to get or set a property value based on line arguments. """
if line:
value = self.prep_line(line, mixed_format)
py_format = self.prep_format(value, mixed_format)
value = self.prop_set_value(prop_id, value, py_format)
else:
value = self.prop_get_value(prop_id)
return value
@classmethod
def prep_line(cls, line, mixed_format='B'):
""" Convert a command line argument to proper binary encoding (pre-pack). """
value = line
if line != None:
if mixed_format == 'U': # For UTF8, just a pass through line unmodified
line += '\0'
value = line.encode('utf-8')
elif mixed_format in (
'D',
'E'): # Expect raw data to be hex string w/o delimeters
value = util.hex_to_bytes(line)
elif isinstance(line, str):
# Most everything else is some type of integer
value = int(line, 0)
return value
@classmethod
def prep_format(cls, value, mixed_format='B'):
""" Convert a spinel format to a python pack format. """
py_format = mixed_format
if value == "":
py_format = '0s'
elif mixed_format in ('D', 'U', 'E'):
py_format = str(len(value)) + 's'
return py_format
def prop_get(self, prop_id, mixed_format='B'):
""" Helper to get a propery and output the value with Done or Error. """
value = self.prop_get_value(prop_id)
if value is None:
print("Error")
return None
if (mixed_format == 'D') or (mixed_format == 'E'):
print(util.hexify_str(value, ''))
else:
print(str(value))
print("Done")
return value
def prop_set(self, prop_id, line, mixed_format='B', output=True):
""" Helper to set a propery and output Done or Error. """
value = self.prep_line(line, mixed_format)
py_format = self.prep_format(value, mixed_format)
result = self.prop_set_value(prop_id, value, py_format)
if not output:
return result
if result is None:
print("Error")
else:
print("Done")
return result
def handle_property(self, line, prop_id, mixed_format='B', output=True):
""" Helper to set property when line argument passed, get otherwise. """
value = self.prop_get_or_set_value(prop_id, line, mixed_format)
if not output:
return value
if value is None or value == "":
print("Error")
return None
if line is None or line == "":
# Only print value on PROP_VALUE_GET
if mixed_format == '6':
print(str(ipaddress.IPv6Address(value)))
elif (mixed_format == 'D') or (mixed_format == 'E'):
print(binascii.hexlify(value).decode('utf8'))
elif mixed_format == 'H':
if prop_id == SPINEL.PROP_MAC_15_4_PANID:
print("0x%04x" % value)
else:
print("%04x" % value)
else:
print(str(value))
print("Done")
return value
def do_help(self, line):
if line:
cmd, _arg, _unused = self.parseline(line)
try:
doc = getattr(self, 'do_' + cmd).__doc__
except AttributeError:
doc = None
if doc:
self.log("%s\n" % textwrap.dedent(doc))
else:
self.log("No help on %s\n" % (line))
else:
self.print_topics(
"\nAvailable commands (type help <name> for more information):",
SpinelCliCmd.command_names, 15, 80)
def do_v(self, _line):
"""
version
Shows detailed version information on spinel-cli tool:
"""
self.log(NETWORK_PROMPT + " ver. " + __version__)
self.log(__copyright__)
@classmethod
def do_clear(cls, _line):
""" Clean up the display. """
os.system('reset')
def do_history(self, _line):
"""
history
Show previously executed commands.
"""
try:
import readline
hist = readline.get_current_history_length()
for idx in range(1, hist + 1):
self.log(readline.get_history_item(idx))
except ImportError:
pass
def do_h(self, line):
""" Shortcut for history. """
self.do_history(line)
def do_exit(self, _line):
""" Exit the shell. """
self.log("exit")
return True
def do_quit(self, line):
""" Exit the shell. """
return self.do_exit(line)
def do_q(self, line):
""" Exit the shell. """
return self.do_exit(line)
def do_EOF(self, _line):
""" End of file handler for when commands are piped into shell. """
self.log("\n")
return True
def emptyline(self):
pass
def default(self, line):
if line[0] == "#":
CONFIG.LOGGER.debug(line)
else:
CONFIG.LOGGER.info(line + ": command not found")
# exec(line)
def do_debug(self, line):
"""
Enables detail logging of bytes over the wire to the radio modem.
Usage: debug <1=enable | 0=disable>
"""
if line != None and line != "":
level = int(line)
else:
level = 0
CONFIG.debug_set_level(level)
def do_debugmem(self, _line):
""" Profile python memory usage. """
from guppy import hpy
heap_stats = hpy()
print(heap_stats.heap())
print()
print(heap_stats.heap().byrcs)
def do_bufferinfo(self, line):
"""
\033[1mbufferinfo\033[0m
Get the mesh forwarder buffer info.
\033[2m
> bufferinfo
total: 128
free: 128
6lo send: 0 0
6lo reas: 0 0
ip6: 0 0
mpl: 0 0
mle: 0 0
arp: 0 0
coap: 0 0
Done
\033[0m
"""
result = self.prop_get_value(SPINEL.PROP_MSG_BUFFER_COUNTERS)
if result != None:
print("total: %d" % result[0])
print("free: %d" % result[1])
print("6lo send: %d %d" % result[2:4])
print("6lo reas: %d %d" % result[4:6])
print("ip6: %d %d" % result[6:8])
print("mpl: %d %d" % result[8:10])
print("mle: %d %d" % result[10:12])
print("arp: %d %d" % result[12:14])
print("coap: %d %d" % result[14:16])
print("Done")
else:
print("Error")
def do_channel(self, line):
"""
\033[1mchannel\033[0m
Get the IEEE 802.15.4 Channel value.
\033[2m
> channel
11
Done
\033[0m
\033[1mchannel <channel>\033[0m
Set the IEEE 802.15.4 Channel value.
\033[2m
> channel 11
Done
\033[0m
"""
self.handle_property(line, SPINEL.PROP_PHY_CHAN)
def do_child(self, line):
"""\033[1m
child list
\033[0m
List attached Child IDs
\033[2m
> child list
1 2 3 6 7 8
Done
\033[0m\033[1m
child <id>
\033[0m
Print diagnostic information for an attached Thread Child.
The id may be a Child ID or an RLOC16.
\033[2m
> child 1
Child ID: 1
Rloc: 9c01
Ext Addr: e2b3540590b0fd87
Mode: rsn
Net Data: 184
Timeout: 100
Age: 0
LQI: 3
RSSI: -20
Done
\033[0m
"""
child_table = self.prop_get_value(SPINEL.PROP_THREAD_CHILD_TABLE)[0]
if line == 'list':
result = ''
for child_data in child_table:
child_data = child_data[0]
child_id = child_data[1] & 0x1FF
result += '{} '.format(child_id)
print(result)
print("Done")
else:
try:
child_id = int(line)
printed = False
for child_data in child_table:
child_data = child_data[0]
id = child_data[1] & 0x1FF
if id == child_id:
mode = ''
if child_data[7] & 0x08:
mode += 'r'
if child_data[7] & 0x04:
mode += 's'
if child_data[7] & 0x02:
mode += 'd'
if child_data[7] & 0x01:
mode += 'n'
print("Child ID: {}".format(id))
print("Rloc: {:04x}".format(child_data[1]))
print("Ext Addr: {}".format(
binascii.hexlify(child_data[0])))
print("Mode: {}".format(mode))
print("Net Data: {}".format(child_data[4]))
print("Timeout: {}".format(child_data[2]))
print("Age: {}".format(child_data[3]))
print("LQI: {}".format(child_data[5]))
print("RSSI: {}".format(child_data[6]))
print("Done")
printed = True
if not printed:
print("Error")
except ValueError:
print("Error")
def do_childmax(self, line):
"""\033[1m
childmax
\033[0m
Get the Thread Child Count Max value.
\033[2m
> childmax
10
Done
\033[0m\033[1m
childmax <timeout>
\033[0m
Set the Thread Child Count Max value.
\033[2m
> childmax 5
Done
\033[0m
"""
self.handle_property(line, SPINEL.PROP_THREAD_CHILD_COUNT_MAX)
def do_childtimeout(self, line):
"""\033[1m
childtimeout
\033[0m
Get the Thread Child Timeout value.
\033[2m
> childtimeout
300
Done
\033[0m\033[1m
childtimeout <timeout>
\033[0m
Set the Thread Child Timeout value.
\033[2m
> childtimeout 300
Done
\033[0m
"""
self.handle_property(line, SPINEL.PROP_THREAD_CHILD_TIMEOUT, 'L')
def do_commissioner(self, line):
"""
These commands are enabled when configuring with --enable-commissioner.
\033[1m
commissioner start
\033[0m
Start the Commissioner role on this node.
\033[2m
> commissioner start
Done
\033[0m\033[1m
commissioner stop
\033[0m
Stop the Commissioner role on this node.
\033[2m
> commissioner stop
Done
\033[0m\033[1m
commissioner panid <panid> <mask> <destination>
\033[0m
Perform panid query.
\033[2m
> commissioner panid 57005 4294967295 ff33:0040:fdde:ad00:beef:0:0:1
Conflict: dead, 00000800
Done
\033[0m\033[1m
commissioner energy <mask> <count> <period> <scanDuration>
\033[0m
Perform energy scan.
\033[2m
> commissioner energy 327680 2 32 1000 fdde:ad00:beef:0:0:ff:fe00:c00
Energy: 00050000 0 0 0 0
Done
\033[0m
"""
pass
def do_contextreusedelay(self, line):
"""
contextreusedelay
Get the CONTEXT_ID_REUSE_DELAY value.
> contextreusedelay
11
Done
contextreusedelay <delay>
Set the CONTEXT_ID_REUSE_DELAY value.
> contextreusedelay 11
Done
"""
self.handle_property(line, SPINEL.PROP_THREAD_CONTEXT_REUSE_DELAY, 'L')
def do_counters(self, line):
"""
counters
Get the supported counter names.
> counters
mac
mle
Done
counters <countername>
Get the counter value.
> counters mac
TxTotal: 10
TxUnicast: 3
TxBroadcast: 7
TxAckRequested: 3
TxAcked: 3
TxNoAckRequested: 7
TxData: 10
TxDataPoll: 0
TxBeacon: 0
TxBeaconRequest: 0
TxOther: 0
TxRetry: 0
TxDirectRetrySuccess: [ 0:2, 1:2, 2:1 ]
TxDirectMaxRetryExpiry: 1
TxIndirectRetrySuccess: [ 0:0 ]
TxIndirectMaxRetryExpiry: 1
TxErrCca: 0
TxAbort: 0
TxErrBusyChannel: 0
RxTotal: 2
RxUnicast: 1
RxBroadcast: 1
RxData: 2
RxDataPoll: 0
RxBeacon: 0
RxBeaconRequest: 0
RxOther: 0
RxAddressFiltered: 0
RxDestAddrFiltered: 0
RxDuplicated: 0
RxErrNoFrame: 0
RxErrNoUnknownNeighbor: 0
RxErrInvalidSrcAddr: 0
RxErrSec: 0
RxErrFcs: 0
RxErrOther: 0
Done
> counters mle
Role Disabled: 0
Role Detached: 1
Role Child: 0
Role Router: 0
Role Leader: 1
Attach Attempts: 1
Partition Id Changes: 1
Better Partition Attach Attempts: 0
Parent Changes: 0
Done
counters <countername> reset
Reset the counter value.
> counters mac reset
Done
> counters mle reset
Done
"""
params = line.split(" ")
if params[0] == "mac":
if len(params) == 1:
histogram = None
result = self.prop_get_value(SPINEL.PROP_CNTR_ALL_MAC_COUNTERS)
caps_list = self.prop_get_value(SPINEL.PROP_CAPS)
for caps in caps_list[0]:
if SPINEL.CAP_MAC_RETRY_HISTOGRAM == caps[0][0]:
histogram = self.prop_get_value(
SPINEL.PROP_CNTR_MAC_RETRY_HISTOGRAM)
if result != None:
counters_tx = result[0][0]
counters_rx = result[1][0]
print("TxTotal: %d" % counters_tx[0])
print(" TxUnicast: %d" % counters_tx[1])
print(" TxBroadcast: %d" % counters_tx[2])
print(" TxAckRequested: %d" % counters_tx[3])
print(" TxAcked: %d" % counters_tx[4])
print(" TxNoAckRequested: %d" % counters_tx[5])
print(" TxData: %d" % counters_tx[6])
print(" TxDataPoll: %d" % counters_tx[7])
print(" TxBeacon: %d" % counters_tx[8])
print(" TxBeaconRequest: %d" % counters_tx[9])
print(" TxOther: %d" % counters_tx[10])
print(" TxRetry: %d" % counters_tx[11])
if histogram != None:
histogram_direct = histogram[0][0]
if len(histogram_direct) != 0:
print(" TxDirectRetrySuccess: [", end='')
for retry in range(len(histogram_direct)):
print(" %d:%s" %
(retry, histogram_direct[retry][0]),
end=',' if retry !=
(len(histogram_direct) - 1) else " ]\n")
print(" TxDirectMaxRetryExpiry: %s" %
(counters_tx[15][0]))
if histogram != None:
histogram_indirect = histogram[1][0]
if len(histogram_indirect) != 0:
print(" TxIndirectRetrySuccess: [", end='')
for retry in range(len(histogram_indirect)):
print(" %d:%s" %
(retry, histogram_indirect[retry][0]),
end=',' if retry !=
(len(histogram_indirect) - 1) else " ]\n")
print(" TxIndirectMaxRetryExpiry: %s" %
(counters_tx[16][0]))
print(" TxErrCca: %d" % counters_tx[12])
print(" TxAbort: %d" % counters_tx[13])
print(" TxErrBusyChannel: %d" % counters_tx[14])
print("RxTotal: %d" % counters_rx[0])
print(" RxUnicast: %d" % counters_rx[1])
print(" RxBroadcast: %d" % counters_rx[2])
print(" RxData: %d" % counters_rx[3])
print(" RxDataPoll: %d" % counters_rx[4])
print(" RxBeacon: %d" % counters_rx[5])
print(" RxBeaconRequest: %d" % counters_rx[6])
print(" RxOther: %d" % counters_rx[7])
print(" RxAddressFiltered: %d" % counters_rx[8])
print(" RxDestAddrFiltered: %d" % counters_rx[9])
print(" RxDuplicated: %d" % counters_rx[10])
print(" RxErrNoFrame: %d" % counters_rx[11])
print(" RxErrNoUnknownNeighbor: %d" % counters_rx[12])
print(" RxErrInvalidSrcAddr: %d" % counters_rx[13])
print(" RxErrSec: %d" % counters_rx[14])
print(" RxErrFcs: %d" % counters_rx[15])
print(" RxErrOther: %d" % counters_rx[16])
print("Done")
else:
print("Error")
elif len(params) == 2:
if params[1] == "reset":
self.prop_set_value(SPINEL.PROP_CNTR_ALL_MAC_COUNTERS, 1)
self.prop_set_value(SPINEL.PROP_CNTR_MAC_RETRY_HISTOGRAM, 1)
print("Done")
else:
print("Error")
elif params[0] == "mle":
if len(params) == 1:
result = self.prop_get_value(SPINEL.PROP_CNTR_MLE_COUNTERS)
if result != None:
print("Role Disabled: %d" % result[0])
print("Role Detached: %d" % result[1])
print("Role Child: %d" % result[2])
print("Role Router: %d" % result[3])
print("Role Leader: %d" % result[4])
print("Attach Attempts: %d" % result[5])
print("Partition Id Changes: %d" % result[6])
print("Better Partition Attach Attempts: %d" % result[7])
print("Parent Changes: %d" % result[8])
print("Done")
else:
print("Error")
elif len(params) == 2:
if params[1] == "reset":
self.prop_set_value(SPINEL.PROP_CNTR_MLE_COUNTERS, 1)
print("Done")
else:
print("Error")
elif params[0] is None or params[0] == "":
print("mac")
print("mle")
print("Done")
else:
print("Error")
def do_discover(self, line):
"""
discover [channel]
Perform an MLE Discovery operation.
channel: The channel to discover on. If no channel is provided,
the discovery will cover all valid channels.
> discover
| J | Network Name | Extended PAN | PAN | MAC Address | Ch | dBm | LQI |
+---+------------------+------------------+------+------------------+----+-----+-----+
| 0 | OpenThread | dead00beef00cafe | ffff | f1d92a82c8d8fe43 | 11 | -20 | 0 |
Done
"""
pass
def do_eidcache(self, line):
"""
eidcache
Print the EID-to-RLOC cache entries.
> eidcache
fdde:ad00:beef:0:bb1:ebd6:ad10:f33 ac00
fdde:ad00:beef:0:110a:e041:8399:17cd 6000
Done
"""
pass
def do_extaddr(self, line):
"""
extaddr
Get the IEEE 802.15.4 Extended Address.
> extaddr
dead00beef00cafe
Done
extaddr <extaddr>
Set the IEEE 802.15.4 Extended Address.
> extaddr dead00beef00cafe
dead00beef00cafe
Done
"""
self.handle_property(line, SPINEL.PROP_MAC_15_4_LADDR, 'E')
def do_extpanid(self, line):
"""
extpanid
Get the Thread Extended PAN ID value.