bleprph_test.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2019 Espressif Systems (Shanghai) PTE LTD
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. import re
  20. import traceback
  21. import threading
  22. import subprocess
  23. try:
  24. import Queue
  25. except ImportError:
  26. import queue as Queue
  27. try:
  28. # This environment variable is expected on the host machine
  29. test_fw_path = os.getenv("TEST_FW_PATH")
  30. if test_fw_path and test_fw_path not in sys.path:
  31. sys.path.insert(0, test_fw_path)
  32. import IDF
  33. except ImportError as e:
  34. print(e)
  35. print("Try `export TEST_FW_PATH=$IDF_PATH/tools/tiny-test-fw` for resolving the issue")
  36. print("Try `pip install -r $IDF_PATH/tools/tiny-test-fw/requirements.txt` for resolving the issue")
  37. import IDF
  38. try:
  39. import lib_ble_client
  40. except ImportError:
  41. lib_ble_client_path = os.getenv("IDF_PATH") + "/tools/ble"
  42. if lib_ble_client_path and lib_ble_client_path not in sys.path:
  43. sys.path.insert(0, lib_ble_client_path)
  44. import lib_ble_client
  45. import Utility
  46. # When running on local machine execute the following before running this script
  47. # > make app bootloader
  48. # > make print_flash_cmd | tail -n 1 > build/download.config
  49. # > export TEST_FW_PATH=~/esp/esp-idf/tools/tiny-test-fw
  50. def bleprph_client_task(prph_obj, dut, dut_addr):
  51. interface = 'hci0'
  52. ble_devname = 'nimble-bleprph'
  53. srv_uuid = '2f12'
  54. # Get BLE client module
  55. ble_client_obj = lib_ble_client.BLE_Bluez_Client(interface, devname=ble_devname, devaddr=dut_addr)
  56. if not ble_client_obj:
  57. raise RuntimeError("Failed to get DBus-Bluez object")
  58. # Discover Bluetooth Adapter and power on
  59. is_adapter_set = ble_client_obj.set_adapter()
  60. if not is_adapter_set:
  61. raise RuntimeError("Adapter Power On failed !!")
  62. # Connect BLE Device
  63. is_connected = ble_client_obj.connect()
  64. if not is_connected:
  65. # Call disconnect to perform cleanup operations before exiting application
  66. ble_client_obj.disconnect()
  67. raise RuntimeError("Connection to device " + ble_devname + " failed !!")
  68. # Check dut responses
  69. dut.expect("GAP procedure initiated: advertise;", timeout=30)
  70. # Read Services
  71. services_ret = ble_client_obj.get_services(srv_uuid)
  72. if services_ret:
  73. Utility.console_log("\nServices\n")
  74. Utility.console_log(str(services_ret))
  75. else:
  76. ble_client_obj.disconnect()
  77. raise RuntimeError("Failure: Read Services failed")
  78. # Read Characteristics
  79. chars_ret = {}
  80. chars_ret = ble_client_obj.read_chars()
  81. if chars_ret:
  82. Utility.console_log("\nCharacteristics retrieved")
  83. for path, props in chars_ret.items():
  84. Utility.console_log("\n\tCharacteristic: " + str(path))
  85. Utility.console_log("\tCharacteristic UUID: " + str(props[2]))
  86. Utility.console_log("\tValue: " + str(props[0]))
  87. Utility.console_log("\tProperties: : " + str(props[1]))
  88. else:
  89. ble_client_obj.disconnect()
  90. raise RuntimeError("Failure: Read Characteristics failed")
  91. '''
  92. Write Characteristics
  93. - write 'A' to characteristic with write permission
  94. '''
  95. chars_ret_on_write = {}
  96. chars_ret_on_write = ble_client_obj.write_chars(b'A')
  97. if chars_ret_on_write:
  98. Utility.console_log("\nCharacteristics after write operation")
  99. for path, props in chars_ret_on_write.items():
  100. Utility.console_log("\n\tCharacteristic:" + str(path))
  101. Utility.console_log("\tCharacteristic UUID: " + str(props[2]))
  102. Utility.console_log("\tValue:" + str(props[0]))
  103. Utility.console_log("\tProperties: : " + str(props[1]))
  104. else:
  105. ble_client_obj.disconnect()
  106. raise RuntimeError("Failure: Write Characteristics failed")
  107. # Call disconnect to perform cleanup operations before exiting application
  108. ble_client_obj.disconnect()
  109. class BlePrphThread(threading.Thread):
  110. def __init__(self, dut, dut_addr, exceptions_queue):
  111. threading.Thread.__init__(self)
  112. self.dut = dut
  113. self.dut_addr = dut_addr
  114. self.exceptions_queue = exceptions_queue
  115. def run(self):
  116. try:
  117. bleprph_client_task(self, self.dut, self.dut_addr)
  118. except Exception:
  119. self.exceptions_queue.put(traceback.format_exc(), block=False)
  120. @IDF.idf_example_test(env_tag="Example_WIFI_BT")
  121. def test_example_app_ble_peripheral(env, extra_data):
  122. """
  123. Steps:
  124. 1. Discover Bluetooth Adapter and Power On
  125. 2. Connect BLE Device
  126. 3. Read Services
  127. 4. Read Characteristics
  128. 5. Write Characteristics
  129. """
  130. subprocess.check_output(['rm','-rf','/var/lib/bluetooth/*'])
  131. subprocess.check_output(['hciconfig','hci0','reset'])
  132. # Acquire DUT
  133. dut = env.get_dut("bleprph", "examples/bluetooth/nimble/bleprph")
  134. # Get binary file
  135. binary_file = os.path.join(dut.app.binary_path, "bleprph.bin")
  136. bin_size = os.path.getsize(binary_file)
  137. IDF.log_performance("bleprph_bin_size", "{}KB".format(bin_size // 1024))
  138. IDF.check_performance("bleprph_bin_size", bin_size // 1024)
  139. # Upload binary and start testing
  140. Utility.console_log("Starting bleprph simple example test app")
  141. dut.start_app()
  142. dut.reset()
  143. # Get device address from dut
  144. dut_addr = dut.expect(re.compile(r"Device Address: ([a-fA-F0-9:]+)"), timeout=30)[0]
  145. exceptions_queue = Queue.Queue()
  146. # Starting a py-client in a separate thread
  147. bleprph_thread_obj = BlePrphThread(dut, dut_addr, exceptions_queue)
  148. bleprph_thread_obj.start()
  149. bleprph_thread_obj.join()
  150. exception_msg = None
  151. while True:
  152. try:
  153. exception_msg = exceptions_queue.get(block=False)
  154. except Queue.Empty:
  155. break
  156. else:
  157. Utility.console_log("\n" + exception_msg)
  158. if exception_msg:
  159. raise Exception("Thread did not run successfully")
  160. # Check dut responses
  161. dut.expect("connection established; status=0", timeout=30)
  162. dut.expect("disconnect;", timeout=30)
  163. if __name__ == '__main__':
  164. test_example_app_ble_peripheral()