bleprph_test.py 6.5 KB

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