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