forked from openthread/pyspinel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spinel-cli.py
executable file
·2108 lines (1676 loc) · 57.8 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/python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
"""
spinel-cli.py
available commands (type help <name> for more information):
============================================================
channel diag-sleep leaderdata releaserouterid
child diag-start leaderweight rloc16
childmax diag-stats masterkey route
childtimeout diag-stop mode router
clear discover ncp-ll64 routerupgradethreshold
commissioner eidcache ncp-ml64 scan
contextreusedelay exit ncp-tun state
counter extaddr netdataregister thread
debug extpanid networkidtimeout tun
debug-mem h networkname v
diag help panid version
diag-channel history ping whitelist
diag-power ifconfig prefix
diag-repeat ipaddr q
diag-send keysequence quit
"""
from __future__ import print_function
import os
import sys
import time
import traceback
import optparse
import binascii
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
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.layers.inet6 import IPv6
from scapy.layers.inet6 import ICMPv6EchoReply
from scapy.layers.inet6 import ICMPv6EchoRequest
__copyright__ = "Copyright (c) 2016 The OpenThread Authors."
__version__ = "0.1.0"
MASTER_PROMPT = "spinel-cli"
class SpinelCliCmd(Cmd, SpinelCodec):
"""
A command line shell for controlling OpenThread NCP nodes
via the Spinel protocol.
"""
def __init__(self, stream_desc, nodeid, *_a, **kw):
self.nodeid = kw.get('nodeid', '1')
self.tun_if = None
self.wpan_api = WpanApi(stream_desc, nodeid)
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 = MASTER_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
readline.parse_and_bind("tab: complete")
if sys.platform == 'darwin':
readline.parse_and_bind("bind ^I rl_complete")
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',
'counter',
'discover',
'eidcache',
'extaddr',
'extpanid',
'ifconfig',
'ipaddr',
'joiner',
'keysequence',
'leaderdata',
'leaderweight',
'masterkey',
'mode',
'netdataregister',
'networkidtimeout',
'networkname',
'panid',
'parent',
'ping',
'prefix',
'releaserouterid',
'rloc16',
'route',
'router',
'routerselectionjitter',
'routerupgradethreshold',
'routerdowngradethreshold',
'scan',
'state',
'thread',
'version',
'whitelist',
# OpenThread Diagnostics Module CLI
'diag',
'diag-start',
'diag-channel',
'diag-power',
'diag-send',
'diag-repeat',
'diag-sleep',
'diag-stats',
'diag-stop',
# 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
pkt = IPv6(value[2:])
if CONFIG.DEBUG_LOG_PKT:
pkt.show()
if ICMPv6EchoReply in pkt:
timenow = int(round(time.time() * 1000)) & 0xFFFFFFFF
timedelta = (timenow - struct.unpack('>I', pkt.data)[0])
print("\n%d bytes from %s: icmp_seq=%d hlim=%d time=%dms" % (
pkt.plen, pkt.src, pkt.seq, pkt.hlim, timedelta))
return consumed
@classmethod
def log(cls, text):
""" Common log handler. """
logging.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
value = line.encode('utf-8') + '\0'
elif mixed_format == 'D': # Expect raw data to be hex string w/o delimeters
value = util.hex_to_bytes(line)
else:
# Most everything else is some type of integer
value = int(line)
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 == 'D' or mixed_format == 'U':
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'):
""" 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 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(util.hexify_str(value, ''))
elif mixed_format == 'H':
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(MASTER_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] == "#":
logging.debug(line)
else:
logging.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:
result = result[0]
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_counter(self, line):
"""
counter
Get the supported counter names.
>counter
mac
Done
counter <countername>
Get the counter value.
>counter mac
TxTotal: 10
TxAckRequested: 4
TxAcked: 4
TxNoAckRequested: 6
TxData: 10
TxDataPoll: 0
TxBeacon: 0
TxBeaconRequest: 0
TxOther: 0
TxRetry: 0
TxErrCca: 0
RxTotal: 11
RxData: 11
RxDataPoll: 0
RxBeacon: 0
RxBeaconRequest: 0
RxOther: 0
RxWhitelistFiltered: 0
RxDestAddrFiltered: 0
RxErrNoFrame: 0
RxErrNoUnknownNeighbor: 0
RxErrInvalidSrcAddr: 0
RxErrSec: 0
RxErrFcs: 0
RxErrOther: 0
"""
pass
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.
> extpanid
dead00beef00cafe
Done
extpanid <extpanid>
Set the Thread Extended PAN ID value.
> extpanid dead00beef00cafe
Done
"""
self.handle_property(line, SPINEL.PROP_NET_XPANID, 'D')
def do_joiner(self, line):
"""
These commands are enabled when configuring with --enable-joiner.
joiner start <pskd> <provisioningUrl>
Start the Joiner role.
* pskd: Pre-Shared Key for the Joiner.
* provisioningUrl: Provisioning URL for the Joiner (optional).
This command will cause the device to perform an MLE Discovery and
initiate the Thread Commissioning process.
> joiner start PSK
Done
joiner stop
Stop the Joiner role.
> joiner stop
Done
"""
PSKd = ""
params = line.split(" ")
if len(params) > 0:
sub_command = params[0]
if len(params) > 1:
PSKd = params[1]
PSKd = self.prep_line(PSKd, 'U')
if sub_command == "":
pass
elif sub_command == "start":
py_format = self.prep_format(PSKd, 'U')
self.prop_set_value(SPINEL.PROP_MESHCOP_JOINER_CREDENTIAL,
PSKd, py_format)
self.prop_set_value(SPINEL.PROP_MESHCOP_JOINER_ENABLE, 1)
print("Done")
return
elif sub_command == "stop":
self.prop_set_value(SPINEL.PROP_MESHCOP_JOINER_ENABLE, 0)
print("Done")
return
print("Error")
def complete_ifconfig(self, text, _line, _begidx, _endidx):
""" Subcommand completion handler for ifconfig command. """
map_sub_commands = ('up', 'down')
return [i for i in map_sub_commands if i.startswith(text)]
def do_ifconfig(self, line):
"""
ifconfig up
Bring up the IPv6 interface.
> ifconfig up
Done
ifconfig down
Bring down the IPv6 interface.
> ifconfig down
Done
ifconfig
Show the status of the IPv6 interface.
> ifconfig
down
Done
"""
params = line.split(" ")
if params[0] == "":
value = self.prop_get_value(SPINEL.PROP_NET_IF_UP)
if value != None:
map_arg_value = {
0: "down",
1: "up",
}
print(map_arg_value[value])
elif params[0] == "up":
self.prop_set(SPINEL.PROP_NET_IF_UP, '1')
return
elif params[0] == "down":
self.prop_set(SPINEL.PROP_NET_IF_UP, '0')
return
print("Done")
def complete_ipaddr(self, text, _line, _begidx, _endidx):
""" Subcommand completion handler for ipaddr command. """
map_sub_commands = ('add', 'remove')
return [i for i in map_sub_commands if i.startswith(text)]
def do_ipaddr(self, line):
"""
ipaddr
List all IPv6 addresses assigned to the Thread interface.
> ipaddr
fdde:ad00:beef:0:0:ff:fe00:0
fe80:0:0:0:0:ff:fe00:0
fdde:ad00:beef:0:558:f56b:d688:799
fe80:0:0:0:f3d9:2a82:c8d8:fe43
Done
ipaddr add <ipaddr>
Add an IPv6 address to the Thread interface.
> ipaddr add 2001::dead:beef:cafe
Done
ipaddr del <ipaddr>
Delete an IPv6 address from the Thread interface.
> ipaddr del 2001::dead:beef:cafe
Done
"""
params = line.split(" ")
valid = 1
preferred = 1
flags = 0
# always use /64, as prefix.network.prefixlen returns /128.
prefix_len = 64
num = len(params)
if num > 1:
ipaddr = params[1]
prefix = ipaddress.IPv6Interface(unicode(ipaddr))
arr = prefix.ip.packed
if params[0] == "":
addrs = self.wpan_api.get_ipaddrs()
for addr in addrs:
print(str(addr))
elif params[0] == "add":
arr += self.wpan_api.encode_fields('CLLC',
prefix_len,
valid,
preferred,
flags)
self.prop_insert_value(SPINEL.PROP_IPV6_ADDRESS_TABLE,
arr, str(len(arr)) + 's')
if self.tun_if:
self.tun_if.addr_add(ipaddr)
elif params[0] == "remove":
arr += self.wpan_api.encode_fields('CLLC',
prefix_len,
valid,
preferred,
flags)
self.prop_remove_value(SPINEL.PROP_IPV6_ADDRESS_TABLE,
arr, str(len(arr)) + 's')
if self.tun_if:
self.tun_if.addr_del(ipaddr)
print("Done")
def do_keysequence(self, line):
"""
keysequence counter
Get the Thread Key Sequence Counter.
> keysequence counter
10
Done
keysequence counter <counter>
Set the Thread Key Sequence Counter.