mqtt_ssl_example_test.py 5.3 KB

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