mqtt_ssl_example_test.py 5.2 KB

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