pytest_mqtt_wss_example.py 4.0 KB

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