bleprph_test.py 6.5 KB

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