Debian Codegraph @

test/test-mesh

raw symbols SCIP
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 ###################################################################
5 #
6 # This is a unified test sample for BT Mesh
7 #
8 # To run the test:
9 # test-mesh [token]
10 #
11 # 'token' is an optional argument. It must be a 16-digit
12 # hexadecimal number. The token must be associated with
13 # an existing node. The token is generated and assigned
14 # to a node as a result of successful provisioning (see
15 # explanation of "join" option).
16 # When the token is set, the menu operations "attach"
17 # and "remove" may be performed on a node specified
18 # by this token.
19 #
20 # The test imitates a device with 2 elements:
21 # element 0: OnOff Server model
22 # Sample Vendor model
23 # element 1: OnOff Client model
24 #
25 # The main menu:
26 # token
27 # join
28 # attach
29 # remove
30 # dest
31 # uuid
32 # app-index
33 # client-menu
34 # exit
35 #
36 # The main menu options explained:
37 # token
38 # Set the unique node token.
39 # The token can be set from command line arguments as
40 # well.
41 #
42 # join
43 # Request provisioning of a device to become a node
44 # on a mesh network. The test generates device UUID
45 # which is displayed and will need to be provided to
46 # an outside entity that acts as a Provisioner. Also,
47 # during the provisioning process, an agent that is
48 # part of the test, will request (or will be requested)
49 # to perform a specified operation, e.g., a number will
50 # be displayed and this number will need to be entered
51 # on the Provisioner's side.
52 # In case of successful provisioning, the application
53 # automatically attaches as a node to the daemon. A node
54 # 'token' is returned to the application and is used
55 # for the runtime of the test.
56 #
57 # attach
58 # Attach the application to bluetoothd-daemon as a node.
59 # For the call to be successful, the valid node token must
60 # be already set, either from command arguments or by
61 # executing "set token" operation or automatically after
62 # successfully executing "join" operation in the same
63 # test run.
64 #
65 # remove
66 # Permanently removes any node configuration from daemon
67 # and persistent storage. After this operation, the node
68 # is permanently forgotten by the daemon and the associated
69 # node token is no longer valid.
70 #
71 # dest
72 # Set destination address to send messages: 4 hex digits
73 #
74 # app-index
75 # Set AppKey index to indicate which application key to use
76 # to encode outgoing messages: up to 3 hex digits
77 #
78 # vendor-send
79 # Allows to send an arbitrary endor message.
80 # The destination is set based on previously executed "dest"
81 # command (if not set, the outbound message will fail).
82 # User is prompted to enter hex bytearray payload.
83 # The message is originated from the vendor model registered
84 # on element 0. For the command to succeed, the AppKey index
85 # that is set by executing "app-key" must correspond to the
86 # application key to which the Sample Vendor model is bound.
87 #
88 # client-menu
89 # Enter On/Off client submenu.
90 #
91 # quit
92 # Exits the test.
93 #
94 ###################################################################
95 import sys
96 import struct
97 import fcntl
98 import os
99 import numpy
100 import random
101 import dbus
102 import dbus.service
103 import dbus.exceptions
104
105 from threading import Timer
106 import time
107 import uuid
108
109 try:
110 from gi.repository import GLib
111 except ImportError:
112 import glib as GLib
113 from dbus.mainloop.glib import DBusGMainLoop
114
115 try:
116 from termcolor import colored, cprint
117 set_error = lambda x: colored('!' + x, 'red', attrs=['bold'])
118 set_cyan = lambda x: colored(x, 'cyan', attrs=['bold'])
119 set_green = lambda x: colored(x, 'green', attrs=['bold'])
120 set_yellow = lambda x: colored(x, 'yellow', attrs=['bold'])
121 except ImportError:
122 print('!!! Install termcolor module for better experience !!!')
123 set_error = lambda x: x
124 set_cyan = lambda x: x
125 set_green = lambda x: x
126 set_yellow = lambda x: x
127
128 # Provisioning agent
129 try:
130 import agent
131 except ImportError:
132 agent = None
133
134 MESH_SERVICE_NAME = 'org.bluez.mesh'
135 DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties'
136 DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager'
137
138 MESH_MGR_IFACE = 'org.bluez.mesh.Management1'
139 MESH_NETWORK_IFACE = 'org.bluez.mesh.Network1'
140 MESH_NODE_IFACE = 'org.bluez.mesh.Node1'
141 MESH_APPLICATION_IFACE = 'org.bluez.mesh.Application1'
142 MESH_ELEMENT_IFACE = 'org.bluez.mesh.Element1'
143
144 APP_COMPANY_ID = 0x05f1
145 APP_PRODUCT_ID = 0x0001
146 APP_VERSION_ID = 0x0001
147
148 VENDOR_ID_NONE = 0xffff
149
150 TRANSACTION_TIMEOUT = 6
151
152 app = None
153 bus = None
154 mainloop = None
155 node = None
156 node_mgr = None
157 mesh_net = None
158
159 dst_addr = 0x0000
160 app_idx = 0
161
162 # Node token housekeeping
163 token = None
164 have_token = False
165 attached = False
166
167 # Remote device UUID
168 have_uuid = False
169 remote_uuid = None
170
171 # Menu housekeeping
172 MAIN_MENU = 0
173 ON_OFF_CLIENT_MENU = 1
174
175 INPUT_NONE = 0
176 INPUT_TOKEN = 1
177 INPUT_DEST_ADDRESS = 2
178 INPUT_APP_KEY_INDEX = 3
179 INPUT_MESSAGE_PAYLOAD = 4
180 INPUT_UUID = 5
181
182 menus = []
183 current_menu = None
184
185 user_input = 0
186 input_error = False
187
188 send_opts = dbus.Dictionary(signature='sv')
189 send_opts = {'ForceSegmented' : dbus.Boolean(True)}
190
191 def raise_error(str_value):
192 global input_error
193
194 input_error = True
195 print(set_error(str_value))
196
197 def clear_error():
198 global input_error
199 input_error = False
200
201 def is_error():
202 return input_error
203
204 def app_exit():
205 global mainloop
206 global app
207
208 for el in app.elements:
209 for model in el.models:
210 if model.timer != None:
211 model.timer.cancel()
212 mainloop.quit()
213
214 def set_token(str_value):
215 global token
216 global have_token
217
218 if len(str_value) != 16:
219 raise_error('Expected 16 digits')
220 return
221
222 try:
223 input_number = int(str_value, 16)
224 except ValueError:
225 raise_error('Not a valid hexadecimal number')
226 return
227
228 token = numpy.uint64(input_number)
229 have_token = True
230
231 def set_uuid(str_value):
232 global remote_uuid
233 global have_uuid
234
235 if len(str_value) != 32:
236 raise_error('Expected 32 digits')
237 return
238
239 remote_uuid = bytearray.fromhex(str_value)
240 have_uuid = True
241
242 def array_to_string(b_array):
243 str_value = ""
244 for b in b_array:
245 str_value += "%02x" % b
246 return str_value
247
248 def generic_error_cb(error):
249 print(set_error('D-Bus call failed: ') + str(error))
250
251 def generic_reply_cb():
252 return
253
254 def attach_app_error_cb(error):
255 print(set_error('Failed to register application: ') + str(error))
256
257 def attach(token):
258 print('Attach mesh node to bluetooth-meshd daemon')
259
260 mesh_net.Attach(app.get_path(), token,
261 reply_handler=attach_app_cb,
262 error_handler=attach_app_error_cb)
263
264 def join_cb():
265 print('Join procedure started')
266
267 def join_error_cb(reason):
268 print('Join procedure failed: ', reason)
269
270 def remove_node_cb():
271 global attached
272 global have_token
273
274 print(set_yellow('Node removed'))
275 attached = False
276 have_token = False
277
278 def unwrap(item):
279 if isinstance(item, dbus.Boolean):
280 return bool(item)
281 if isinstance(item, (dbus.UInt16, dbus.Int16, dbus.UInt32, dbus.Int32,
282 dbus.UInt64, dbus.Int64)):
283 return int(item)
284 if isinstance(item, dbus.Byte):
285 return bytes([int(item)])
286 if isinstance(item, dbus.String):
287 return item
288 if isinstance(item, (dbus.Array, list, tuple)):
289 return [unwrap(x) for x in item]
290 if isinstance(item, (dbus.Dictionary, dict)):
291 return dict([(unwrap(x), unwrap(y)) for x, y in item.items()])
292
293 print(set_error('Dictionary item not handled: ') + type(item))
294
295 return item
296
297 def attach_app_cb(node_path, dict_array):
298 global attached
299
300 attached = True
301
302 print(set_yellow('Mesh app registered: ') + set_green(node_path))
303
304 obj = bus.get_object(MESH_SERVICE_NAME, node_path)
305
306 global node_mgr
307 node_mgr = dbus.Interface(obj, MESH_MGR_IFACE)
308
309 global node
310 node = dbus.Interface(obj, MESH_NODE_IFACE)
311
312 els = unwrap(dict_array)
313
314 for el in els:
315 idx = struct.unpack('b', el[0])[0]
316
317 models = el[1]
318 element = app.get_element(idx)
319 element.set_model_config(models)
320
321 def interfaces_removed_cb(object_path, interfaces):
322 print('Removed')
323 if not mesh_net:
324 return
325
326 print(object_path)
327 if object_path == mesh_net[2]:
328 print('Service was removed')
329 app_exit()
330
331 def print_state(state):
332 print('State is ', end='')
333 if state == 0:
334 print('OFF')
335 elif state == 1:
336 print('ON')
337 else:
338 print('UNKNOWN')
339 class ModTimer():
340 def __init__(self):
341 self.seconds = None
342 self.func = None
343 self.thread = None
344 self.busy = False
345
346 def _timeout_cb(self):
347 self.func()
348 self.busy = True
349 self._schedule_timer()
350 self.busy =False
351
352 def _schedule_timer(self):
353 self.thread = Timer(self.seconds, self._timeout_cb)
354 self.thread.start()
355
356 def start(self, seconds, func):
357 self.func = func
358 self.seconds = seconds
359 if not self.busy:
360 self._schedule_timer()
361
362 def cancel(self):
363 if self.thread is not None:
364 self.thread.cancel()
365 self.thread = None
366
367 class Application(dbus.service.Object):
368
369 def __init__(self, bus):
370 self.path = '/example'
371 self.agent = None
372 self.elements = []
373 dbus.service.Object.__init__(self, bus, self.path)
374
375 def set_agent(self, agent):
376 self.agent = agent
377
378 def get_path(self):
379 return dbus.ObjectPath(self.path)
380
381 def add_element(self, element):
382 self.elements.append(element)
383
384 def get_element(self, idx):
385 for ele in self.elements:
386 if ele.get_index() == idx:
387 return ele
388
389 def get_properties(self):
390 return {
391 MESH_APPLICATION_IFACE: {
392 'CompanyID': dbus.UInt16(APP_COMPANY_ID),
393 'ProductID': dbus.UInt16(APP_PRODUCT_ID),
394 'VersionID': dbus.UInt16(APP_VERSION_ID)
395 }
396 }
397
398 @dbus.service.method(DBUS_OM_IFACE, out_signature='a{oa{sa{sv}}}')
399 def GetManagedObjects(self):
400 response = {}
401 response[self.path] = self.get_properties()
402 response[self.agent.get_path()] = self.agent.get_properties()
403 for element in self.elements:
404 response[element.get_path()] = element.get_properties()
405 return response
406
407 @dbus.service.method(MESH_APPLICATION_IFACE,
408 in_signature="t", out_signature="")
409 def JoinComplete(self, value):
410 global token
411 global have_token
412 global attach
413
414 print(set_yellow('Joined mesh network with token ') +
415 set_green(format(value, '016x')))
416
417 token = value
418 have_token = True
419
420 @dbus.service.method(MESH_APPLICATION_IFACE,
421 in_signature="s", out_signature="")
422 def JoinFailed(self, value):
423 print(set_error('JoinFailed '), value)
424
425
426 class Element(dbus.service.Object):
427 PATH_BASE = '/example/ele'
428
429 def __init__(self, bus, index):
430 self.path = self.PATH_BASE + format(index, '02x')
431 self.models = []
432 self.bus = bus
433 self.index = index
434 dbus.service.Object.__init__(self, bus, self.path)
435
436 def _get_sig_models(self):
437 mods = []
438 for model in self.models:
439 opts = []
440 id = model.get_id()
441 vendor = model.get_vendor()
442 if vendor == VENDOR_ID_NONE:
443 mod = (id, opts)
444 mods.append(mod)
445 return mods
446
447 def _get_v_models(self):
448 mods = []
449 for model in self.models:
450 opts = []
451 id = model.get_id()
452 v = model.get_vendor()
453 if v != VENDOR_ID_NONE:
454 mod = (v, id, opts)
455 mods.append(mod)
456 return mods
457
458 def get_properties(self):
459 vendor_models = self._get_v_models()
460 sig_models = self._get_sig_models()
461
462 props = {'Index' : dbus.Byte(self.index)}
463 props['Models'] = dbus.Array(sig_models, signature='(qa{sv})')
464 props['VendorModels'] = dbus.Array(vendor_models,
465 signature='(qqa{sv})')
466 #print(props)
467 return { MESH_ELEMENT_IFACE: props }
468
469 def add_model(self, model):
470 model.set_path(self.path)
471 self.models.append(model)
472
473 def get_index(self):
474 return self.index
475
476 def set_model_config(self, configs):
477 for config in configs:
478 mod_id = config[0]
479 self.update_model_config(mod_id, config[1])
480
481 @dbus.service.method(MESH_ELEMENT_IFACE,
482 in_signature="qqvay", out_signature="")
483 def MessageReceived(self, source, key, dest, data):
484 print(('Message Received on Element %02x') % self.index, end='')
485 print(', src=', format(source, '04x'), end='')
486
487 if isinstance(dest, int):
488 print(', dst=%04x' % dest)
489 elif isinstance(dest, dbus.Array):
490 dst_str = array_to_string(dest)
491 print(', dst=' + dst_str)
492
493 for model in self.models:
494 model.process_message(source, dest, key, data)
495
496 @dbus.service.method(MESH_ELEMENT_IFACE,
497 in_signature="qa{sv}", out_signature="")
498
499 def UpdateModelConfiguration(self, model_id, config):
500 cfg = unwrap(config)
501 print(cfg)
502 self.update_model_config(model_id, cfg)
503
504 def update_model_config(self, model_id, config):
505 print(('Update Model Config '), end='')
506 print(format(model_id, '04x'))
507 for model in self.models:
508 if model_id == model.get_id():
509 model.set_config(config)
510 return
511
512 @dbus.service.method(MESH_ELEMENT_IFACE,
513 in_signature="", out_signature="")
514
515 def get_path(self):
516 return dbus.ObjectPath(self.path)
517
518 class Model():
519 def __init__(self, model_id):
520 self.cmd_ops = []
521 self.model_id = model_id
522 self.vendor = VENDOR_ID_NONE
523 self.bindings = []
524 self.pub_period = 0
525 self.pub_id = 0
526 self.path = None
527 self.timer = None
528
529 def set_path(self, path):
530 self.path = path
531
532 def get_id(self):
533 return self.model_id
534
535 def get_vendor(self):
536 return self.vendor
537
538 def process_message(self, source, dest, key, data):
539 return
540
541 def set_publication(self, period):
542 self.pub_period = period
543
544 def send_publication(self, data):
545 pub_opts = dbus.Dictionary(signature='sv')
546
547 print('Send publication ', end='')
548 print(data)
549 node.Publish(self.path, self.model_id, pub_opts, data,
550 reply_handler=generic_reply_cb,
551 error_handler=generic_error_cb)
552
553 def send_message(self, dest, key, data):
554 global send_opts
555
556 node.Send(self.path, dest, key, send_opts, data,
557 reply_handler=generic_reply_cb,
558 error_handler=generic_error_cb)
559
560 def set_config(self, config):
561 if 'Bindings' in config:
562 self.bindings = config.get('Bindings')
563 print('Bindings: ', end='')
564 print(self.bindings)
565 if 'PublicationPeriod' in config:
566 self.set_publication(config.get('PublicationPeriod'))
567 print('Model publication period ', end='')
568 print(self.pub_period, end='')
569 print(' ms')
570 if 'Subscriptions' in config:
571 print('Model subscriptions ', end='')
572 self.print_subscriptions(config.get('Subscriptions'))
573 print()
574
575 def print_subscriptions(self, subscriptions):
576 for sub in subscriptions:
577 if isinstance(sub, int):
578 print('%04x,' % sub, end=' ')
579
580 if isinstance(sub, list):
581 label = uuid.UUID(bytes=b''.join(sub))
582 print(label, ',', end=' ')
583
584 ########################
585 # On Off Server Model
586 ########################
587 class OnOffServer(Model):
588 def __init__(self, model_id):
589 Model.__init__(self, model_id)
590 self.tid = None
591 self.last_src = 0x0000
592 self.last_dst = 0x0000
593 self.cmd_ops = { 0x8201, # get
594 0x8202, # set
595 0x8203, # set unacknowledged
596 0x8204 } # status
597
598 print("OnOff Server ")
599 self.state = 0
600 print_state(self.state)
601 self.pub_timer = ModTimer()
602 self.t_timer = ModTimer()
603
604 def process_message(self, source, dest, key, data):
605 datalen = len(data)
606
607 if datalen != 2 and datalen != 4:
608 # The opcode is not recognized by this model
609 return
610
611 if datalen == 2:
612 op_tuple=struct.unpack('>H',bytes(data))
613 opcode = op_tuple[0]
614
615 if opcode != 0x8201:
616 # The opcode is not recognized by this model
617 return
618 print('Get state')
619 elif datalen == 4:
620 opcode,self.state, tid = struct.unpack('>HBB',
621 bytes(data))
622
623 if opcode != 0x8202 and opcode != 0x8203:
624 # The opcode is not recognized by this model
625 return
626 print_state(self.state)
627
628 if (self.tid != None and self.tid == tid and
629 self.last_src == source and
630 self.last_dst == dest):
631 # Ignore duplicate transaction
632 return
633
634 self.t_timer.cancel()
635 self.tid = tid
636 self.last_src = source
637 self.last_dst = dest
638 self.t_timer.start(TRANSACTION_TIMEOUT, self.t_track)
639
640 # Unacknowledged "set"
641 if opcode == 0x8203:
642 return
643
644 rsp_data = struct.pack('>HB', 0x8204, self.state)
645 self.send_message(source, key, rsp_data)
646
647 def t_track(self):
648 self.t_timer.cancel()
649 self.tid = None
650 self.last_src = 0x0000
651 self.last_dst = 0x0000
652
653 def set_publication(self, period):
654
655 self.pub_period = period
656 if period == 0:
657 self.pub_timer.cancel()
658 return
659
660 # We do not handle ms in this example
661 if period < 1000:
662 return
663
664 self.pub_timer.start(period/1000, self.publish)
665
666 def publish(self):
667 print('Publish')
668 data = struct.pack('>HB', 0x8204, self.state)
669 self.send_publication(data)
670
671 ########################
672 # On Off Client Model
673 ########################
674 class OnOffClient(Model):
675 def __init__(self, model_id):
676 Model.__init__(self, model_id)
677 self.tid = 0
678 self.data = None
679 self.cmd_ops = { 0x8201, # get
680 0x8202, # set
681 0x8203, # set unacknowledged
682 0x8204 } # status
683 print('OnOff Client')
684
685 def _send_message(self, dest, key, data):
686 print('OnOffClient send command')
687 self.send_message(dest, key, data)
688
689 def get_state(self, dest, key):
690 opcode = 0x8201
691 self.data = struct.pack('>H', opcode)
692 self._send_message(dest, key, self.data)
693
694 def set_state(self, dest, key, state):
695 opcode = 0x8202
696 print('Set state:', state)
697 self.data = struct.pack('>HBB', opcode, state, self.tid)
698 self.tid = (self.tid + 1) % 255
699 self._send_message(dest, key, self.data)
700
701 def repeat(self, dest, key):
702 if self.data != None:
703 self._send_message(dest, key, self.data)
704 else:
705 print('No previous command stored')
706
707 def process_message(self, source, dest, key, data):
708 print('OnOffClient process message len = ', end = '')
709 datalen = len(data)
710 print(datalen)
711
712 if datalen != 3:
713 # The opcode is not recognized by this model
714 return
715
716 opcode, state = struct.unpack('>HB',bytes(data))
717
718 if opcode != 0x8204 :
719 # The opcode is not recognized by this model
720 return
721
722 print(set_yellow('Got state '), end = '')
723
724 state_str = "ON"
725 if state == 0:
726 state_str = "OFF"
727
728 print(set_green(state_str), set_yellow('from'),
729 set_green('%04x' % source))
730
731 ########################
732 # Sample Vendor Model
733 ########################
734 class SampleVendor(Model):
735 def __init__(self, model_id):
736 Model.__init__(self, model_id)
737 self.vendor = 0x05F1 # Linux Foundation Company ID
738
739 ########################
740 # Menu functions
741 ########################
742 class MenuItem():
743 def __init__(self, desc, func):
744 self.desc = desc
745 self.func = func
746
747 class Menu():
748 def __init__(self, title, menu):
749 self.title = title
750 self.menu = menu
751
752 def show(self):
753 print(set_cyan('*** ' + self.title.upper() + ' ***'))
754 for k, v in self.menu.items():
755 print(set_green(k), set_cyan(v.desc))
756
757 def process_cmd(self, str_value):
758 if is_error():
759 self.show()
760 clear_error()
761 return
762
763 cmds = []
764 for key in self.menu.keys():
765 if key.startswith(str_value):
766 cmds.append(key)
767
768 if len(cmds) == 0:
769 print(set_error('Unknown menu option: '), str_value)
770 self.show()
771 return
772 if len(cmds) > 1:
773 for cmd in cmds:
774 print(set_cyan(cmd + '?'))
775 return
776
777 self.menu.get(cmds[0]).func()
778
779 class MenuHandler(object):
780 def __init__(self, callback):
781 self.cb = callback
782 flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
783 flags |= os.O_NONBLOCK
784 fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags)
785 sys.stdin.flush()
786 GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.input_callback)
787
788 def input_callback(self, fd, condition):
789 chunk = fd.read()
790 buffer = ''
791 for char in chunk:
792 buffer += char
793 if char == '\n':
794 self.cb(buffer)
795
796 return True
797
798 def process_input(input_str):
799 str_value = input_str.strip()
800
801 # Allow entering empty lines for better output visibility
802 if len(str_value) == 0:
803 return
804
805 current_menu.process_cmd(str_value)
806
807 def switch_menu(level):
808 global current_menu
809
810 if level >= len(menus):
811 return
812
813 current_menu = menus[level]
814 current_menu.show()
815
816 ########################
817 # Main menu class
818 ########################
819 class MainMenu(Menu):
820 def __init__(self):
821 menu_items = {
822 'token': MenuItem(' - set node ID (token)',
823 self.__cmd_set_token),
824 'join': MenuItem(' - join mesh network',
825 self.__cmd_join),
826 'attach': MenuItem(' - attach mesh node',
827 self.__cmd_attach),
828 'remove': MenuItem(' - delete node',
829 self.__cmd_remove),
830 'dest': MenuItem(' - set destination address',
831 self.__cmd_set_dest),
832 'uuid': MenuItem(' - set remote uuid',
833 self.__cmd_set_uuid),
834 'app-index': MenuItem(' - set AppKey index',
835 self.__cmd_set_app_idx),
836 'vendor-send': MenuItem(' - send raw vendor message',
837 self.__cmd_vendor_msg),
838 'client-menu': MenuItem(' - On/Off client menu',
839 self.__cmd_client_menu),
840 'quit': MenuItem(' - exit the test', app_exit)
841 }
842
843 Menu.__init__(self, 'Main Menu', menu_items)
844
845 def __cmd_client_menu(self):
846 if attached != True:
847 print(set_error('Disallowed: node is not attached'))
848 return
849 switch_menu(ON_OFF_CLIENT_MENU)
850
851 def __cmd_set_token(self):
852 global user_input
853
854 if have_token == True:
855 print('Token already set')
856 return
857
858 user_input = INPUT_TOKEN
859 print(set_cyan('Enter 16-digit hex node ID:'))
860
861 def __cmd_set_dest(self):
862 global user_input
863
864 user_input = INPUT_DEST_ADDRESS
865 print(set_cyan('Enter 4-digit hex destination address:'))
866
867 def __cmd_set_uuid(self):
868 global user_input
869
870 user_input = INPUT_UUID
871 print(set_cyan('Enter 32-digit hex remote UUID:'))
872
873 def __cmd_set_app_idx(self):
874 global user_input
875
876 user_input = INPUT_APP_KEY_INDEX;
877 print(set_cyan('Enter app key index (up to 3 digit hex):'))
878
879 def __cmd_vendor_msg(self):
880 global user_input
881
882 user_input = INPUT_MESSAGE_PAYLOAD;
883 print(set_cyan('Enter message payload (hex):'))
884
885 def __cmd_join(self):
886 if agent == None:
887 print(set_error('Provisioning agent not found'))
888 return
889
890 uuid_bytes = uuid.uuid4().bytes
891 uuid_str = array_to_string(uuid_bytes)
892
893 print(set_yellow('Joining with UUID ') + set_green(uuid_str))
894 mesh_net.Join(app.get_path(), uuid_bytes,
895 reply_handler=join_cb,
896 error_handler=join_error_cb)
897
898 def __cmd_attach(self):
899 if have_token == False:
900 print(set_error('Token is not set'))
901 self.show()
902 return
903
904 attach(token)
905
906 def __cmd_remove(self):
907 if have_token == False:
908 print(set_error('Token is not set'))
909 self.show()
910 return
911
912 print('Removing mesh node')
913 mesh_net.Leave(token, reply_handler=remove_node_cb,
914 error_handler=generic_error_cb)
915
916 def __send_vendor_msg(self, str_value):
917 try:
918 msg_data = bytearray.fromhex(str_value)
919 except ValueError:
920 raise_error('Not a valid hexadecimal input')
921 return
922
923 print(set_yellow('Send data: ' + set_green(str_value)))
924 app.elements[0].models[1].send_message(dst_addr, app_idx,
925 msg_data)
926
927 def process_cmd(self, str_value):
928 global user_input
929 global dst_addr
930 global app_idx
931
932 if user_input == INPUT_TOKEN:
933 set_token(str_value)
934 elif user_input == INPUT_UUID:
935 set_uuid(str_value)
936 elif user_input == INPUT_DEST_ADDRESS:
937 res = set_value(str_value, 4, 4)
938 if is_error() != True:
939 dst_addr = res
940 print(set_yellow("Destination address: ") +
941 set_green(format(dst_addr, '04x')))
942 elif user_input == INPUT_APP_KEY_INDEX:
943 res = set_value(str_value, 1, 3)
944 if is_error() != True:
945 app_idx = res
946 print(set_yellow("Application index: ") +
947 set_green(format(app_idx, '03x')))
948 elif user_input == INPUT_MESSAGE_PAYLOAD:
949 self.__send_vendor_msg(str_value)
950
951 if user_input != INPUT_NONE:
952 user_input = INPUT_NONE
953 if is_error() != True:
954 return
955
956 Menu.process_cmd(self, str_value)
957
958 ##############################
959 # On/Off Client menu class
960 ##############################
961 class ClientMenu(Menu):
962 def __init__(self):
963 menu_items = {
964 'get-state': MenuItem(' - get server state',
965 self.__cmd_get_state),
966 'off': MenuItem(' - set state OFF',
967 self.__cmd_set_state_off),
968 'on': MenuItem(' - set state ON',
969 self.__cmd_set_state_on),
970 'repeat': MenuItem(' - repeat last command',
971 self.__cmd_repeat_transaction),
972 'back': MenuItem(' - back to main menu',
973 self.__cmd_main_menu),
974 'quit': MenuItem(' - exit the test', app_exit)
975 }
976
977 Menu.__init__(self, 'On/Off Client Menu', menu_items)
978
979 def __cmd_main_menu(self):
980 switch_menu(MAIN_MENU)
981
982 def __cmd_get_state(self):
983 app.elements[1].models[0].get_state(dst_addr, app_idx)
984
985 def __cmd_set_state_off(self):
986 app.elements[1].models[0].set_state(dst_addr, app_idx, 0)
987
988 def __cmd_set_state_on(self):
989 app.elements[1].models[0].set_state(dst_addr, app_idx, 1)
990
991 def __cmd_repeat_transaction(self):
992 app.elements[1].models[0].repeat(dst_addr, app_idx)
993
994 def set_value(str_value, min, max):
995
996 if len(str_value) > max or len(str_value) < min:
997 raise_error('Bad input length %d' % len(str_value))
998 return -1
999
1000 try:
1001 value = int(str_value, 16)
1002 except ValueError:
1003 raise_error('Not a valid hexadecimal number')
1004 return -1
1005
1006 return value
1007
1008
1009 ########################
1010 # Main entry
1011 ########################
1012 def main():
1013
1014 DBusGMainLoop(set_as_default=True)
1015
1016 global bus
1017 bus = dbus.SystemBus()
1018 global mainloop
1019 global app
1020 global mesh_net
1021 global menu
1022 global current_menu
1023
1024 if len(sys.argv) > 1 :
1025 set_token(sys.argv[1])
1026
1027 mesh_net = dbus.Interface(bus.get_object(MESH_SERVICE_NAME,
1028 "/org/bluez/mesh"),
1029 MESH_NETWORK_IFACE)
1030
1031 mesh_net.connect_to_signal('InterfacesRemoved', interfaces_removed_cb)
1032
1033 app = Application(bus)
1034
1035 # Provisioning agent
1036 if agent != None:
1037 app.set_agent(agent.Agent(bus))
1038
1039 first_ele = Element(bus, 0x00)
1040 second_ele = Element(bus, 0x01)
1041
1042 print(set_yellow('Register OnOff Server model on element 0'))
1043 first_ele.add_model(OnOffServer(0x1000))
1044
1045 print(set_yellow('Register Vendor model on element 0'))
1046 first_ele.add_model(SampleVendor(0x0001))
1047
1048 print(set_yellow('Register OnOff Client model on element 1'))
1049 second_ele.add_model(OnOffClient(0x1001))
1050
1051 app.add_element(first_ele)
1052 app.add_element(second_ele)
1053
1054 mainloop = GLib.MainLoop()
1055
1056 menus.append(MainMenu())
1057 menus.append(ClientMenu())
1058 switch_menu(MAIN_MENU)
1059
1060 event_catcher = MenuHandler(process_input);
1061 mainloop.run()
1062
1063 if __name__ == '__main__':
1064 main()