pytest_mqtt_ws_example.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. import logging
  6. import os
  7. import re
  8. import sys
  9. from threading import Event, Thread
  10. import paho.mqtt.client as mqtt
  11. import pytest
  12. from pytest_embedded import Dut
  13. event_client_connected = Event()
  14. event_stop_client = Event()
  15. event_client_received_correct = 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): # type: (mqtt.Client, tuple, bool, str) -> None
  19. _ = (userdata, flags)
  20. print('Connected with result code ' + str(rc))
  21. event_client_connected.set()
  22. client.subscribe('/topic/qos0')
  23. def mqtt_client_task(client): # type: (mqtt.Client) -> None
  24. while not event_stop_client.is_set():
  25. client.loop()
  26. # The callback for when a PUBLISH message is received from the server.
  27. def on_message(client, userdata, msg): # type: (mqtt.Client, tuple, mqtt.client.MQTTMessage) -> None
  28. _ = userdata
  29. global message_log
  30. payload = msg.payload.decode()
  31. if not event_client_received_correct.is_set() and payload == 'data':
  32. client.publish('/topic/qos0', 'data_to_esp32')
  33. if msg.topic == '/topic/qos0' and payload == 'data':
  34. event_client_received_correct.set()
  35. message_log += 'Received data:' + msg.topic + ' ' + payload + '\n'
  36. @pytest.mark.esp32
  37. @pytest.mark.ethernet
  38. def test_examples_protocol_mqtt_ws(dut): # type: (Dut) -> None
  39. broker_url = ''
  40. broker_port = 0
  41. """
  42. steps: |
  43. 1. join AP and connects to ws broker
  44. 2. Test connects a client to the same broker
  45. 3. Test evaluates it received correct qos0 message
  46. 4. Test ESP32 client received correct qos0 message
  47. """
  48. # check and log bin size
  49. binary_file = os.path.join(dut.app.binary_path, 'mqtt_websocket.bin')
  50. bin_size = os.path.getsize(binary_file)
  51. logging.info('[Performance][mqtt_websocket_bin_size]: %s KB', bin_size // 1024)
  52. # Look for host:port in sdkconfig
  53. try:
  54. value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut.app.sdkconfig.get('BROKER_URI'))
  55. assert value is not None
  56. broker_url = value.group(1)
  57. broker_port = int(value.group(2))
  58. except Exception:
  59. print('ENV_TEST_FAILURE: Cannot find broker url in sdkconfig')
  60. raise
  61. client = None
  62. # 1. Test connects to a broker
  63. try:
  64. client = mqtt.Client(transport='websockets')
  65. client.on_connect = on_connect
  66. client.on_message = on_message
  67. print('Connecting...')
  68. client.connect(broker_url, broker_port, 60)
  69. except Exception:
  70. print('ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:'.format(broker_url, sys.exc_info()[0]))
  71. raise
  72. # Starting a py-client in a separate thread
  73. thread1 = Thread(target=mqtt_client_task, args=(client,))
  74. thread1.start()
  75. try:
  76. print('Connecting py-client to broker {}:{}...'.format(broker_url, broker_port))
  77. if not event_client_connected.wait(timeout=30):
  78. raise ValueError('ENV_TEST_FAILURE: Test script cannot connect to broker: {}'.format(broker_url))
  79. try:
  80. ip_address = dut.expect(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)[^\d]', timeout=30)[0]
  81. print('Connected to AP with IP: {}'.format(ip_address))
  82. except Dut.ExpectTimeout:
  83. print('ENV_TEST_FAILURE: Cannot connect to AP')
  84. raise
  85. print('Checking py-client received msg published from esp...')
  86. if not event_client_received_correct.wait(timeout=30):
  87. raise ValueError('Wrong data received, msg log: {}'.format(message_log))
  88. print('Checking esp-client received msg published from py-client...')
  89. dut.expect(r'DATA=data_to_esp32', timeout=30)
  90. finally:
  91. event_stop_client.set()
  92. thread1.join()