forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chip-device-ctrl.py
executable file
·1051 lines (900 loc) · 36.3 KB
/
chip-device-ctrl.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 python
#
# Copyright (c) 2020-2021 Project CHIP Authors
# Copyright (c) 2013-2018 Nest Labs, Inc.
# 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.
#
#
# @file
# This file implements the Python-based Chip Device Controller Shell.
#
from __future__ import absolute_import
from __future__ import print_function
from chip import ChipDeviceCtrl
from chip import ChipCommissionableNodeCtrl
from chip import exceptions
import argparse
import ctypes
import sys
import os
import platform
import random
from optparse import OptionParser, OptionValueError
import shlex
import base64
import textwrap
import time
import string
import traceback
from cmd import Cmd
from chip.setup_payload import SetupPayload
# Extend sys.path with one or more directories, relative to the location of the
# running script, in which the chip package might be found . This makes it
# possible to run the device manager shell from a non-standard install location,
# as well as directly from its location the CHIP source tree.
#
# Note that relative package locations are prepended to sys.path so as to give
# the local version of the package higher priority over any version installed in
# a standard location.
#
scriptDir = os.path.dirname(os.path.abspath(__file__))
relChipPackageInstallDirs = [
".",
"../lib/python",
"../lib/python%s.%s" % (sys.version_info.major, sys.version_info.minor),
"../lib/Python%s%s" % (sys.version_info.major, sys.version_info.minor),
]
for relInstallDir in relChipPackageInstallDirs:
absInstallDir = os.path.realpath(os.path.join(scriptDir, relInstallDir))
if os.path.isdir(os.path.join(absInstallDir, "chip")):
sys.path.insert(0, absInstallDir)
if platform.system() == 'Darwin':
from chip.ChipCoreBluetoothMgr import CoreBluetoothManager as BleManager
elif sys.platform.startswith('linux'):
from chip.ChipBluezMgr import BluezManager as BleManager
# The exceptions for CHIP Device Controller CLI
class ChipDevCtrlException(exceptions.ChipStackException):
pass
class ParsingError(ChipDevCtrlException):
def __init__(self, msg=None):
self.msg = "Parsing Error: " + msg
def __str__(self):
return self.msg
def DecodeBase64Option(option, opt, value):
try:
return base64.standard_b64decode(value)
except TypeError:
raise OptionValueError(
"option %s: invalid base64 value: %r" % (opt, value))
def DecodeHexIntOption(option, opt, value):
try:
return int(value, 16)
except ValueError:
raise OptionValueError("option %s: invalid value: %r" % (opt, value))
def ParseEncodedString(value):
if value.find(":") < 0:
raise ParsingError(
"value should be encoded in encoding:encodedvalue format")
enc, encValue = value.split(":", 1)
if enc == "str":
return encValue.encode("utf-8") + b'\x00'
elif enc == "hex":
return bytes.fromhex(encValue)
raise ParsingError("only str and hex encoding is supported")
def ParseValueWithType(value, type):
if type == 'int':
return int(value)
elif type == 'str':
return value
elif type == 'bytes':
return ParseEncodedString(value)
elif type == 'bool':
return (value.upper() not in ['F', 'FALSE', '0'])
else:
raise ParsingError('cannot recognize type: {}'.format(type))
def FormatZCLArguments(args, command):
commandArgs = {}
for kvPair in args:
if kvPair.find("=") < 0:
raise ParsingError("Argument should in key=value format")
key, value = kvPair.split("=", 1)
valueType = command.get(key, None)
commandArgs[key] = ParseValueWithType(value, valueType)
return commandArgs
class DeviceMgrCmd(Cmd):
def __init__(self, rendezvousAddr=None, controllerNodeId=0, bluetoothAdapter=None):
self.lastNetworkId = None
Cmd.__init__(self)
Cmd.identchars = string.ascii_letters + string.digits + "-"
if sys.stdin.isatty():
self.prompt = "chip-device-ctrl > "
else:
self.use_rawinput = 0
self.prompt = ""
DeviceMgrCmd.command_names.sort()
self.bleMgr = None
self.devCtrl = ChipDeviceCtrl.ChipDeviceController(
controllerNodeId=controllerNodeId, bluetoothAdapter=bluetoothAdapter)
self.commissionableNodeCtrl = ChipCommissionableNodeCtrl.ChipCommissionableNodeController()
# If we are on Linux and user selects non-default bluetooth adapter.
if sys.platform.startswith("linux") and (bluetoothAdapter is not None):
try:
self.bleMgr = BleManager(self.devCtrl)
self.bleMgr.ble_adapter_select(
"hci{}".format(bluetoothAdapter))
except Exception as ex:
traceback.print_exc()
print(
"Failed to initialize BLE, if you don't have BLE, run chip-device-ctrl with --no-ble")
raise ex
self.historyFileName = os.path.expanduser(
"~/.chip-device-ctrl-history")
try:
import readline
if "libedit" in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
readline.set_completer_delims(" ")
try:
readline.read_history_file(self.historyFileName)
except IOError:
pass
except ImportError:
pass
command_names = [
"setup-payload",
"ble-scan",
"ble-adapter-select",
"ble-adapter-print",
"ble-debug-log",
"connect",
"close-ble",
"close-session",
"resolve",
"zcl",
"zclread",
"zclsubscribe",
"discover",
"set-pairing-wifi-credential",
"set-pairing-thread-credential",
"open-commissioning-window",
"get-fabricid",
]
def parseline(self, line):
cmd, arg, line = Cmd.parseline(self, line)
if cmd:
cmd = self.shortCommandName(cmd)
line = cmd + " " + arg
return cmd, arg, line
def completenames(self, text, *ignored):
return [
name + " "
for name in DeviceMgrCmd.command_names
if name.startswith(text) or self.shortCommandName(name).startswith(text)
]
def shortCommandName(self, cmd):
return cmd.replace("-", "")
def precmd(self, line):
if not self.use_rawinput and line != "EOF" and line != "":
print(">>> " + line)
return line
def postcmd(self, stop, line):
if not stop and self.use_rawinput:
self.prompt = "chip-device-ctrl > "
return stop
def postloop(self):
try:
import readline
try:
readline.write_history_file(self.historyFileName)
except IOError:
pass
except ImportError:
pass
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.stdout.write("%s\n" % textwrap.dedent(doc))
else:
self.stdout.write("No help on %s\n" % (line))
else:
self.print_topics(
"\nAvailable commands (type help <name> for more information):",
DeviceMgrCmd.command_names,
15,
80,
)
def do_closeble(self, line):
"""
close-ble
Close the ble connection to the device.
"""
args = shlex.split(line)
if len(args) != 0:
print("Usage:")
self.do_help("close")
return
try:
self.devCtrl.CloseBLEConnection()
except exceptions.ChipStackException as ex:
print(str(ex))
def do_setlogoutput(self, line):
"""
set-log-output [ none | error | progress | detail ]
Set the level of Chip logging output.
"""
args = shlex.split(line)
if len(args) == 0:
print("Usage:")
self.do_help("set-log-output")
return
if len(args) > 1:
print("Unexpected argument: " + args[1])
return
category = args[0].lower()
if category == "none":
category = 0
elif category == "error":
category = 1
elif category == "progress":
category = 2
elif category == "detail":
category = 3
else:
print("Invalid argument: " + args[0])
return
try:
self.devCtrl.SetLogFilter(category)
except exceptions.ChipStackException as ex:
print(str(ex))
return
def do_setuppayload(self, line):
"""
setup-payload generate [options]
Options:
-vr Version
-vi Vendor ID
-pi Product ID
-cf Custom Flow [Standard = 0, UserActionRequired = 1, Custom = 2]
-dc Discovery Capabilities [SoftAP = 1 | BLE = 2 | OnNetwork = 4]
-dv Discriminator Value
-ps Passcode
setup-payload parse-manual <manual-pairing-code>
setup-payload parse-qr <qr-code-payload>
"""
try:
arglist = shlex.split(line)
if arglist[0] not in ("generate", "parse-manual", "parse-qr"):
self.do_help("setup-payload")
return
if arglist[0] == "generate":
parser = argparse.ArgumentParser()
parser.add_argument("-vr", type=int, default=0, dest='version')
parser.add_argument(
"-pi", type=int, default=0, dest='productId')
parser.add_argument(
"-vi", type=int, default=0, dest='vendorId')
parser.add_argument(
'-cf', type=int, default=0, dest='customFlow')
parser.add_argument(
"-dc", type=int, default=0, dest='capabilities')
parser.add_argument(
"-dv", type=int, default=0, dest='discriminator')
parser.add_argument("-ps", type=int, dest='passcode')
args = parser.parse_args(arglist[1:])
SetupPayload().PrintOnboardingCodes(args.passcode, args.vendorId, args.productId,
args.discriminator, args.customFlow, args.capabilities, args.version)
if arglist[0] == "parse-manual":
SetupPayload().ParseManualPairingCode(arglist[1]).Print()
if arglist[0] == "parse-qr":
SetupPayload().ParseQrCode(arglist[1]).Print()
except exceptions.ChipStackException as ex:
print(str(ex))
return
def do_bleadapterselect(self, line):
"""
ble-adapter-select
Start BLE adapter select, deprecated, you can select adapter by command line arguments.
"""
if sys.platform.startswith("linux"):
if not self.bleMgr:
self.bleMgr = BleManager(self.devCtrl)
self.bleMgr.ble_adapter_select(line)
print(
"This change only applies to ble-scan\n"
"Please run device controller with --bluetooth-adapter=<adapter-name> to select adapter\n" +
"e.g. chip-device-ctrl --bluetooth-adapter hci0"
)
else:
print(
"ble-adapter-select only works in Linux, ble-adapter-select mac_address"
)
return
def do_bleadapterprint(self, line):
"""
ble-adapter-print
Print attached BLE adapter.
"""
if sys.platform.startswith("linux"):
if not self.bleMgr:
self.bleMgr = BleManager(self.devCtrl)
self.bleMgr.ble_adapter_print()
else:
print("ble-adapter-print only works in Linux")
return
def do_bledebuglog(self, line):
"""
ble-debug-log 0:1
0: disable BLE debug log
1: enable BLE debug log
"""
if not self.bleMgr:
self.bleMgr = BleManager(self.devCtrl)
self.bleMgr.ble_debug_log(line)
return
def do_blescan(self, line):
"""
ble-scan
Start BLE scanning operations.
"""
if not self.bleMgr:
self.bleMgr = BleManager(self.devCtrl)
self.bleMgr.scan(line)
return
def ConnectFromSetupPayload(self, setupPayload, nodeid):
# TODO(cecille): Get this from the C++ code?
ble = 1 << 1
# Devices may be uncommissioned, or may already be on the network. Need to check both ways.
# TODO(cecille): implement soft-ap connection.
# Any device that is already commissioned into a fabric needs to use on-network
# pairing, so look first on the network regardless of the QR code contents.
print("Attempting to find device on Network")
longDiscriminator = ctypes.c_uint16(
int(setupPayload.attributes['Discriminator']))
self.devCtrl.DiscoverCommissionableNodesLongDiscriminator(
longDiscriminator)
print("Waiting for device responses...")
strlen = 100
addrStrStorage = ctypes.create_string_buffer(strlen)
# If this device is on the network and we're looking specifically for 1 device,
# expect a quick response.
if self.wait_for_one_discovered_device():
self.devCtrl.GetIPForDiscoveredDevice(
0, addrStrStorage, strlen)
addrStr = addrStrStorage.value.decode('utf-8')
print("Connecting to device at " + addrStr)
pincode = ctypes.c_uint32(
int(setupPayload.attributes['SetUpPINCode']))
try:
self.devCtrl.ConnectIP(addrStrStorage, pincode, nodeid)
print("Connected")
return 0
except Exception as ex:
print(f"Unable to connect on network: {ex}")
else:
print("Unable to locate device on network")
if int(setupPayload.attributes["RendezvousInformation"]) & ble:
print("Attempting to connect via BLE")
longDiscriminator = ctypes.c_uint16(
int(setupPayload.attributes['Discriminator']))
pincode = ctypes.c_uint32(
int(setupPayload.attributes['SetUpPINCode']))
try:
self.devCtrl.ConnectBLE(longDiscriminator, pincode, nodeid)
print("Connected")
return 0
except Exception as ex:
print(f"Unable to connect: {ex}")
return -1
def do_connect(self, line):
"""
connect -ip <ip address> <setup pin code> [<nodeid>]
connect -ble <discriminator> <setup pin code> [<nodeid>]
connect -qr <qr code> [<nodeid>]
connect -code <manual pairing code> [<nodeid>]
connect command is used for establishing a rendezvous session to the device.
currently, only connect using setupPinCode is supported.
-qr option will connect to the first device with a matching long discriminator.
TODO: Add more methods to connect to device (like cert for auth, and IP
for connection)
"""
try:
args = shlex.split(line)
if len(args) <= 1:
print("Usage:")
self.do_help("connect SetupPinCode")
return
nodeid = random.randint(1, 1000000) # Just a random number
if len(args) == 4:
nodeid = int(args[3])
print("Device is assigned with nodeid = {}".format(nodeid))
if args[0] == "-ip" and len(args) >= 3:
self.devCtrl.ConnectIP(args[1].encode(
"utf-8"), int(args[2]), nodeid)
elif args[0] == "-ble" and len(args) >= 3:
self.devCtrl.ConnectBLE(int(args[1]), int(args[2]), nodeid)
elif args[0] in ['-qr', '-code'] and len(args) >= 2:
if len(args) == 3:
nodeid = int(args[2])
print("Parsing QR code {}".format(args[1]))
setupPayload = None
if args[0] == '-qr':
setupPayload = SetupPayload().ParseQrCode(args[1])
elif args[0] == '-code':
setupPayload = SetupPayload(
).ParseManualPairingCode(args[1])
if not int(setupPayload.attributes.get("RendezvousInformation", 0)):
print("No rendezvous information provided, default to all.")
setupPayload.attributes["RendezvousInformation"] = 0b111
setupPayload.Print()
self.ConnectFromSetupPayload(setupPayload, nodeid)
else:
print("Usage:")
self.do_help("connect SetupPinCode")
return
print(
"Device temporary node id (**this does not match spec**): {}".format(nodeid))
except exceptions.ChipStackException as ex:
print(str(ex))
return
def do_closesession(self, line):
"""
close-session <nodeid>
Close any session associated with a given node ID.
"""
try:
parser = argparse.ArgumentParser()
parser.add_argument('nodeid', type=int, help='Peer node ID')
args = parser.parse_args(shlex.split(line))
self.devCtrl.CloseSession(args.nodeid)
except exceptions.ChipStackException as ex:
print(str(ex))
except:
self.do_help("close-session")
def do_resolve(self, line):
"""
resolve <nodeid>
Resolve DNS-SD name corresponding with the given node ID and
update address of the node in the device controller.
"""
try:
args = shlex.split(line)
if len(args) == 1:
err = self.devCtrl.ResolveNode(int(args[0]))
if err == 0:
address = self.devCtrl.GetAddressAndPort(int(args[0]))
address = "{}:{}".format(
*address) if address else "unknown"
print("Current address: " + address)
else:
self.do_help("resolve")
except exceptions.ChipStackException as ex:
print(str(ex))
return
def wait_for_one_discovered_device(self):
print("Waiting for device responses...")
strlen = 100
addrStrStorage = ctypes.create_string_buffer(strlen)
count = 0
maxWaitTime = 2
while (not self.devCtrl.GetIPForDiscoveredDevice(0, addrStrStorage, strlen) and count < maxWaitTime):
time.sleep(0.2)
count = count + 0.2
return count < maxWaitTime
def wait_for_many_discovered_devices(self):
# Discovery happens through mdns, which means we need to wait for responses to come back.
# TODO(cecille): I suppose we could make this a command line arg. Or Add a callback when
# x number of responses are received. For now, just 2 seconds. We can all wait that long.
print("Waiting for device responses...")
time.sleep(2)
def do_discover(self, line):
"""
discover -qr qrcode
discover -all
discover -l long_discriminator
discover -s short_discriminator
discover -v vendor_id
discover -t device_type
discover -c
discover command is used to discover available devices.
"""
try:
arglist = shlex.split(line)
if len(arglist) < 1:
print("Usage:")
self.do_help("discover")
return
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-all', help='discover all commissionable nodes and commissioners', action='store_true')
group.add_argument(
'-qr', help='discover commissionable nodes matching provided QR code', type=str)
group.add_argument(
'-l', help='discover commissionable nodes with given long discriminator', type=int)
group.add_argument(
'-s', help='discover commissionable nodes with given short discriminator', type=int)
group.add_argument(
'-v', help='discover commissionable nodes wtih given vendor ID', type=int)
group.add_argument(
'-t', help='discover commissionable nodes with given device type', type=int)
group.add_argument(
'-c', help='discover commissionable nodes in commissioning mode', action='store_true')
args = parser.parse_args(arglist)
if args.all:
self.commissionableNodeCtrl.DiscoverCommissioners()
self.wait_for_many_discovered_devices()
self.commissionableNodeCtrl.PrintDiscoveredCommissioners()
self.devCtrl.DiscoverAllCommissioning()
self.wait_for_many_discovered_devices()
elif args.qr is not None:
setupPayload = SetupPayload().ParseQrCode(args.qr)
longDiscriminator = ctypes.c_uint16(
int(setupPayload.attributes['Discriminator']))
self.devCtrl.DiscoverCommissionableNodesLongDiscriminator(
longDiscriminator)
self.wait_for_one_discovered_device()
elif args.l is not None:
self.devCtrl.DiscoverCommissionableNodesLongDiscriminator(
ctypes.c_uint16(args.l))
self.wait_for_one_discovered_device()
elif args.s is not None:
self.devCtrl.DiscoverCommissionableNodesShortDiscriminator(
ctypes.c_uint16(args.s))
self.wait_for_one_discovered_device()
elif args.v is not None:
self.devCtrl.DiscoverCommissionableNodesVendor(
ctypes.c_uint16(args.v))
self.wait_for_many_discovered_devices()
elif args.t is not None:
self.devCtrl.DiscoverCommissionableNodesDeviceType(
ctypes.c_uint16(args.t))
self.wait_for_many_discovered_devices()
elif args.c is not None:
self.devCtrl.DiscoverCommissionableNodesCommissioningEnabled()
self.wait_for_many_discovered_devices()
else:
self.do_help("discover")
return
self.devCtrl.PrintDiscoveredDevices()
except exceptions.ChipStackException as ex:
print('exception')
print(str(ex))
return
except:
self.do_help("discover")
return
def do_zcl(self, line):
"""
To send ZCL message to device:
zcl <cluster> <command> <nodeid> <endpoint> <groupid> [key=value]...
To get a list of clusters:
zcl ?
To get a list of commands in cluster:
zcl ? <cluster>
Send ZCL command to device nodeid
"""
try:
args = shlex.split(line)
all_commands = self.devCtrl.ZCLCommandList()
if len(args) == 1 and args[0] == '?':
print('\n'.join(all_commands.keys()))
elif len(args) == 2 and args[0] == '?':
if args[1] not in all_commands:
raise exceptions.UnknownCluster(args[1])
for commands in all_commands.get(args[1]).items():
args = ", ".join(["{}: {}".format(argName, argType)
for argName, argType in commands[1].items()])
print(commands[0])
if commands[1]:
print(" ", args)
else:
print(" <no arguments>")
elif len(args) > 4:
if args[0] not in all_commands:
raise exceptions.UnknownCluster(args[0])
command = all_commands.get(args[0]).get(args[1], None)
# When command takes no arguments, (not command) is True
if command is None:
raise exceptions.UnknownCommand(args[0], args[1])
err, res = self.devCtrl.ZCLSend(args[0], args[1], int(
args[2]), int(args[3]), int(args[4]), FormatZCLArguments(args[5:], command), blocking=True)
if err != 0:
print("Failed to receive command response: {}".format(res))
elif res != None:
print("Received command status response:")
print(res)
else:
print("Success, no status code is attached with response.")
else:
self.do_help("zcl")
except exceptions.ChipStackException as ex:
print("An exception occurred during process ZCL command:")
print(str(ex))
except Exception as ex:
print("An exception occurred during processing input:")
traceback.print_exc()
print(str(ex))
def do_zclread(self, line):
"""
To read ZCL attribute:
zclread <cluster> <attribute> <nodeid> <endpoint> <groupid>
"""
try:
args = shlex.split(line)
all_attrs = self.devCtrl.ZCLAttributeList()
if len(args) == 1 and args[0] == '?':
print('\n'.join(all_attrs.keys()))
elif len(args) == 2 and args[0] == '?':
if args[1] not in all_attrs:
raise exceptions.UnknownCluster(args[1])
print('\n'.join(all_attrs.get(args[1]).keys()))
elif len(args) == 5:
if args[0] not in all_attrs:
raise exceptions.UnknownCluster(args[0])
res = self.devCtrl.ZCLReadAttribute(args[0], args[1], int(
args[2]), int(args[3]), int(args[4]))
if res != None:
print(repr(res))
else:
self.do_help("zclread")
except exceptions.ChipStackException as ex:
print("An exception occurred during reading ZCL attribute:")
print(str(ex))
except Exception as ex:
print("An exception occurred during processing input:")
print(str(ex))
def do_zclwrite(self, line):
"""
To write ZCL attribute:
zclwrite <cluster> <attribute> <nodeid> <endpoint> <groupid> <value>
"""
try:
args = shlex.split(line)
all_attrs = self.devCtrl.ZCLAttributeList()
if len(args) == 1 and args[0] == '?':
print('\n'.join(all_attrs.keys()))
elif len(args) == 2 and args[0] == '?':
if args[1] not in all_attrs:
raise exceptions.UnknownCluster(args[1])
cluster_attrs = all_attrs.get(args[1], {})
print('\n'.join(["{}: {}".format(key, cluster_attrs[key]["type"])
for key in cluster_attrs.keys() if cluster_attrs[key].get("writable", False)]))
elif len(args) == 6:
if args[0] not in all_attrs:
raise exceptions.UnknownCluster(args[0])
attribute_type = all_attrs.get(args[0], {}).get(
args[1], {}).get("type", None)
res = self.devCtrl.ZCLWriteAttribute(args[0], args[1], int(
args[2]), int(args[3]), int(args[4]), ParseValueWithType(args[5], attribute_type))
print(repr(res))
else:
self.do_help("zclwrite")
except exceptions.ChipStackException as ex:
print("An exception occurred during writing ZCL attribute:")
print(str(ex))
except Exception as ex:
print("An exception occurred during processing input:")
print(str(ex))
def do_zclsubscribe(self, line):
"""
To subscribe ZCL attribute reporting:
zclsubscribe <cluster> <attribute> <nodeid> <endpoint> <minInterval> <maxInterval>
To shut down a subscription:
zclsubscribe -shutdown <subscriptionId>
"""
try:
args = shlex.split(line)
all_attrs = self.devCtrl.ZCLAttributeList()
if len(args) == 1 and args[0] == '?':
print('\n'.join(all_attrs.keys()))
elif len(args) == 2 and args[0] == '?':
if args[1] not in all_attrs:
raise exceptions.UnknownCluster(args[1])
cluster_attrs = all_attrs.get(args[1], {})
print('\n'.join([key for key in cluster_attrs.keys(
) if cluster_attrs[key].get("reportable", False)]))
elif len(args) == 6:
if args[0] not in all_attrs:
raise exceptions.UnknownCluster(args[0])
self.devCtrl.ZCLSubscribeAttribute(args[0], args[1], int(
args[2]), int(args[3]), int(args[4]), int(args[5]))
elif len(args) == 2 and args[0] == '-shutdown':
subscriptionId = int(args[1], base=0)
self.devCtrl.ZCLShutdownSubscription(subscriptionId)
else:
self.do_help("zclsubscribe")
except exceptions.ChipStackException as ex:
print("An exception occurred during configuring reporting of ZCL attribute:")
print(str(ex))
except Exception as ex:
print("An exception occurred during processing input:")
print(str(ex))
def do_setpairingwificredential(self, line):
"""
set-pairing-wifi-credential
Removed, use network commissioning cluster instead.
"""
print("Pairing WiFi Credential is nolonger available, use NetworkCommissioning cluster instead.")
def do_setpairingthreadcredential(self, line):
"""
set-pairing-thread-credential
Removed, use network commissioning cluster instead.
"""
print("Pairing Thread Credential is nolonger available, use NetworkCommissioning cluster instead.")
def do_opencommissioningwindow(self, line):
"""
open-commissioning-window <nodeid> [options]
Options:
-t Timeout (in seconds)
-o Option [TokenWithRandomPIN = 1, TokenWithProvidedPIN = 2]
-d Discriminator Value
-i Iteration
This command is used by a current Administrator to instruct a Node to go into commissioning mode
"""
try:
arglist = shlex.split(line)
if len(arglist) <= 1:
print("Usage:")
self.do_help("open-commissioning-window")
return
parser = argparse.ArgumentParser()
parser.add_argument(
"-t", type=int, default=0, dest='timeout')
parser.add_argument(
"-o", type=int, default=1, dest='option')
parser.add_argument(
"-i", type=int, default=0, dest='iteration')
parser.add_argument(
"-d", type=int, default=0, dest='discriminator')
args = parser.parse_args(arglist[1:])
if args.option < 1 or args.option > 2:
print("Invalid option specified!")
raise ValueError("Invalid option specified")
self.devCtrl.OpenCommissioningWindow(
int(arglist[0]), args.timeout, args.iteration, args.discriminator, args.option)
except exceptions.ChipStackException as ex:
print(str(ex))
return
except:
self.do_help("open-commissioning-window")
return
def do_getfabricid(self, line):
"""
get-fabricid
Read the current Compressed Fabric Id of the controller device, return 0 if not available.
"""
try:
args = shlex.split(line)
if (len(args) > 0):
print("Unexpected argument: " + args[1])
return
compressed_fabricid = self.devCtrl.GetCompressedFabricId()
raw_fabricid = self.devCtrl.GetFabricId()
except exceptions.ChipStackException as ex:
print("An exception occurred during reading FabricID:")
print(str(ex))
return
print("Get fabric ID complete")
print("Raw Fabric ID: 0x{:016x}".format(raw_fabricid)
+ " (" + str(raw_fabricid) + ")")
print("Compressed Fabric ID: 0x{:016x}".format(compressed_fabricid)
+ " (" + str(compressed_fabricid) + ")")
def do_history(self, line):
"""
history
Show previously executed commands.
"""
try:
import readline
h = readline.get_current_history_length()
for n in range(1, h + 1):
print(readline.get_history_item(n))
except ImportError:
pass
def do_h(self, line):
self.do_history(line)
def do_exit(self, line):
return True
def do_quit(self, line):
return True
def do_q(self, line):
return True
def do_EOF(self, line):
print()
return True
def emptyline(self):
pass
def main():
optParser = OptionParser()
optParser.add_option(
"-r",
"--rendezvous-addr",
action="store",
dest="rendezvousAddr",
help="Device rendezvous address",
metavar="<ip-address>",
)
optParser.add_option(
"-n",
"--controller-nodeid",
action="store",
dest="controllerNodeId",
default=0,
type='int',
help="Controller node ID",
metavar="<nodeid>",
)
if sys.platform.startswith("linux"):
optParser.add_option(
"-b",
"--bluetooth-adapter",
action="store",
dest="bluetoothAdapter",
default="hci0",
type="str",
help="Controller bluetooth adapter ID, use --no-ble to disable bluetooth functions.",
metavar="<bluetooth-adapter>",
)
optParser.add_option(
"--no-ble",
action="store_true",
dest="disableBluetooth",