mqtt_ssl_example_test.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. from __future__ import print_function
  2. from __future__ import unicode_literals
  3. from builtins import str
  4. import re
  5. import os
  6. import sys
  7. import ssl
  8. import paho.mqtt.client as mqtt
  9. from threading import Thread, Event
  10. try:
  11. import IDF
  12. from IDF.IDFDUT import ESP32DUT
  13. except ImportError:
  14. # this is a test case write with tiny-test-fw.
  15. # to run test cases outside tiny-test-fw,
  16. # we need to set environment variable `TEST_FW_PATH`,
  17. # then get and insert `TEST_FW_PATH` to sys path before import FW module
  18. test_fw_path = os.getenv("TEST_FW_PATH")
  19. if test_fw_path and test_fw_path not in sys.path:
  20. sys.path.insert(0, test_fw_path)
  21. import IDF
  22. import DUT
  23. event_client_connected = Event()
  24. event_stop_client = Event()
  25. event_client_received_correct = Event()
  26. event_client_received_binary = Event()
  27. message_log = ""
  28. # The callback for when the client receives a CONNACK response from the server.
  29. def on_connect(client, userdata, flags, rc):
  30. print("Connected with result code " + str(rc))
  31. event_client_connected.set()
  32. client.subscribe("/topic/qos0")
  33. def mqtt_client_task(client):
  34. while not event_stop_client.is_set():
  35. client.loop()
  36. # The callback for when a PUBLISH message is received from the server.
  37. def on_message(client, userdata, msg):
  38. global message_log
  39. global event_client_received_correct
  40. global event_client_received_binary
  41. if msg.topic == "/topic/binary":
  42. binary = userdata
  43. size = os.path.getsize(binary)
  44. print("Receiving binary from esp and comparing with {}, size {}...".format(binary, size))
  45. with open(binary, "rb") as f:
  46. bin = f.read()
  47. if bin == msg.payload[:size]:
  48. print("...matches!")
  49. event_client_received_binary.set()
  50. return
  51. else:
  52. recv_binary = binary + ".received"
  53. with open(recv_binary, "w") as fw:
  54. fw.write(msg.payload)
  55. raise ValueError('Received binary (saved as: {}) does not match the original file: {}'.format(recv_binary, binary))
  56. payload = msg.payload.decode()
  57. if not event_client_received_correct.is_set() and payload == "data":
  58. client.subscribe("/topic/binary")
  59. client.publish("/topic/qos0", "send binary please")
  60. if msg.topic == "/topic/qos0" and payload == "data":
  61. event_client_received_correct.set()
  62. message_log += "Received data:" + msg.topic + " " + payload + "\n"
  63. @IDF.idf_example_test(env_tag="Example_WIFI")
  64. def test_examples_protocol_mqtt_ssl(env, extra_data):
  65. broker_url = ""
  66. broker_port = 0
  67. """
  68. steps: |
  69. 1. join AP and connects to ssl broker
  70. 2. Test connects a client to the same broker
  71. 3. Test evaluates python client received correct qos0 message
  72. 4. Test ESP32 client received correct qos0 message
  73. 5. Test python client receives binary data from running partition and compares it with the binary
  74. """
  75. dut1 = env.get_dut("mqtt_ssl", "examples/protocols/mqtt/ssl", dut_class=ESP32DUT)
  76. # check and log bin size
  77. binary_file = os.path.join(dut1.app.binary_path, "mqtt_ssl.bin")
  78. bin_size = os.path.getsize(binary_file)
  79. IDF.log_performance("mqtt_ssl_bin_size", "{}KB"
  80. .format(bin_size // 1024))
  81. IDF.check_performance("mqtt_ssl_size", bin_size // 1024)
  82. # Look for host:port in sdkconfig
  83. try:
  84. value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
  85. broker_url = value.group(1)
  86. broker_port = int(value.group(2))
  87. except Exception:
  88. print('ENV_TEST_FAILURE: Cannot find broker url in sdkconfig')
  89. raise
  90. client = None
  91. # 1. Test connects to a broker
  92. try:
  93. client = mqtt.Client()
  94. client.on_connect = on_connect
  95. client.on_message = on_message
  96. client.user_data_set(binary_file)
  97. client.tls_set(None,
  98. None,
  99. None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
  100. client.tls_insecure_set(True)
  101. print("Connecting...")
  102. client.connect(broker_url, broker_port, 60)
  103. except Exception:
  104. print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
  105. raise
  106. # Starting a py-client in a separate thread
  107. thread1 = Thread(target=mqtt_client_task, args=(client,))
  108. thread1.start()
  109. try:
  110. print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
  111. if not event_client_connected.wait(timeout=30):
  112. raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
  113. dut1.start_app()
  114. try:
  115. ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
  116. print("Connected to AP with IP: {}".format(ip_address))
  117. except DUT.ExpectTimeout:
  118. print('ENV_TEST_FAILURE: Cannot connect to AP')
  119. raise
  120. print("Checking py-client received msg published from esp...")
  121. if not event_client_received_correct.wait(timeout=30):
  122. raise ValueError('Wrong data received, msg log: {}'.format(message_log))
  123. print("Checking esp-client received msg published from py-client...")
  124. dut1.expect(re.compile(r"DATA=send binary please"), timeout=30)
  125. print("Receiving binary data from running partition...")
  126. if not event_client_received_binary.wait(timeout=30):
  127. raise ValueError('Binary not received within timeout')
  128. finally:
  129. event_stop_client.set()
  130. thread1.join()
  131. if __name__ == '__main__':
  132. test_examples_protocol_mqtt_ssl()