bleprph_test.py 5.9 KB

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