bleprph_test.py 5.9 KB

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