mqtt_ws_example_test.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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 paho.mqtt.client as mqtt
  8. from threading import Thread, Event
  9. try:
  10. import IDF
  11. except Exception:
  12. # this is a test case write with tiny-test-fw.
  13. # to run test cases outside tiny-test-fw,
  14. # we need to set environment variable `TEST_FW_PATH`,
  15. # then get and insert `TEST_FW_PATH` to sys path before import FW module
  16. test_fw_path = os.getenv("TEST_FW_PATH")
  17. if test_fw_path and test_fw_path not in sys.path:
  18. sys.path.insert(0, test_fw_path)
  19. import IDF
  20. import DUT
  21. event_client_connected = Event()
  22. event_stop_client = Event()
  23. event_client_received_correct = Event()
  24. message_log = ""
  25. # The callback for when the client receives a CONNACK response from the server.
  26. def on_connect(client, userdata, flags, rc):
  27. print("Connected with result code " + str(rc))
  28. event_client_connected.set()
  29. client.subscribe("/topic/qos0")
  30. def mqtt_client_task(client):
  31. while not event_stop_client.is_set():
  32. client.loop()
  33. # The callback for when a PUBLISH message is received from the server.
  34. def on_message(client, userdata, msg):
  35. global message_log
  36. payload = msg.payload.decode()
  37. if not event_client_received_correct.is_set() and payload == "data":
  38. client.publish("/topic/qos0", "data_to_esp32")
  39. if msg.topic == "/topic/qos0" and payload == "data":
  40. event_client_received_correct.set()
  41. message_log += "Received data:" + msg.topic + " " + payload + "\n"
  42. @IDF.idf_example_test(env_tag="Example_WIFI")
  43. def test_examples_protocol_mqtt_ws(env, extra_data):
  44. broker_url = ""
  45. broker_port = 0
  46. """
  47. steps: |
  48. 1. join AP and connects to ws broker
  49. 2. Test connects a client to the same broker
  50. 3. Test evaluates it received correct qos0 message
  51. 4. Test ESP32 client received correct qos0 message
  52. """
  53. dut1 = env.get_dut("mqtt_websocket", "examples/protocols/mqtt/ws")
  54. # check and log bin size
  55. binary_file = os.path.join(dut1.app.binary_path, "mqtt_websocket.bin")
  56. bin_size = os.path.getsize(binary_file)
  57. IDF.log_performance("mqtt_websocket_bin_size", "{}KB".format(bin_size // 1024))
  58. IDF.check_performance("mqtt_websocket_size", bin_size // 1024)
  59. # Look for host:port in sdkconfig
  60. try:
  61. value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
  62. broker_url = value.group(1)
  63. broker_port = int(value.group(2))
  64. except Exception:
  65. print('ENV_TEST_FAILURE: Cannot find broker url in sdkconfig')
  66. raise
  67. client = None
  68. # 1. Test connects to a broker
  69. try:
  70. client = mqtt.Client(transport="websockets")
  71. client.on_connect = on_connect
  72. client.on_message = on_message
  73. print("Connecting...")
  74. client.connect(broker_url, broker_port, 60)
  75. except Exception:
  76. print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
  77. raise
  78. # Starting a py-client in a separate thread
  79. thread1 = Thread(target=mqtt_client_task, args=(client,))
  80. thread1.start()
  81. try:
  82. print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
  83. if not event_client_connected.wait(timeout=30):
  84. raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
  85. dut1.start_app()
  86. try:
  87. ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
  88. print("Connected to AP with IP: {}".format(ip_address))
  89. except DUT.ExpectTimeout:
  90. print('ENV_TEST_FAILURE: Cannot connect to AP')
  91. raise
  92. print("Checking py-client received msg published from esp...")
  93. if not event_client_received_correct.wait(timeout=30):
  94. raise ValueError('Wrong data received, msg log: {}'.format(message_log))
  95. print("Checking esp-client received msg published from py-client...")
  96. dut1.expect(re.compile(r"DATA=data_to_esp32"), timeout=30)
  97. finally:
  98. event_stop_client.set()
  99. thread1.join()
  100. if __name__ == '__main__':
  101. test_examples_protocol_mqtt_ws()