mqtt_ssl_example_test.py 5.2 KB

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