1from __future__ import print_function, unicode_literals
2
3import os
4import re
5import sys
6from builtins import str
7from threading import Event, Thread
8
9import paho.mqtt.client as mqtt
10import ttfw_idf
11from tiny_test_fw import DUT
12
13event_client_connected = Event()
14event_stop_client = Event()
15event_client_received_correct = Event()
16message_log = ''
17
18
19# The callback for when the client receives a CONNACK response from the server.
20def on_connect(client, userdata, flags, rc):
21    print('Connected with result code ' + str(rc))
22    event_client_connected.set()
23    client.subscribe('/topic/qos0')
24
25
26def mqtt_client_task(client):
27    while not event_stop_client.is_set():
28        client.loop()
29
30
31# The callback for when a PUBLISH message is received from the server.
32def on_message(client, userdata, msg):
33    global message_log
34    payload = msg.payload.decode()
35    if not event_client_received_correct.is_set() and payload == 'data':
36        client.publish('/topic/qos0', 'data_to_esp32')
37        if msg.topic == '/topic/qos0' and payload == 'data':
38            event_client_received_correct.set()
39    message_log += 'Received data:' + msg.topic + ' ' + payload + '\n'
40
41
42@ttfw_idf.idf_example_test(env_tag='Example_EthKitV1')
43def 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', dut_class=ttfw_idf.ESP32DUT)
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    ttfw_idf.log_performance('mqtt_websocket_bin_size', '{}KB'.format(bin_size // 1024))
58    # Look for host:port in sdkconfig
59    try:
60        value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()['CONFIG_BROKER_URI'])
61        broker_url = value.group(1)
62        broker_port = int(value.group(2))
63    except Exception:
64        print('ENV_TEST_FAILURE: Cannot find broker url in sdkconfig')
65        raise
66    client = None
67    # 1. Test connects to a broker
68    try:
69        client = mqtt.Client(transport='websockets')
70        client.on_connect = on_connect
71        client.on_message = on_message
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        dut1.start_app()
85        try:
86            ip_address = dut1.expect(re.compile(r' eth ip: ([^,]+),'), timeout=30)
87            print('Connected to AP with IP: {}'.format(ip_address))
88        except DUT.ExpectTimeout:
89            print('ENV_TEST_FAILURE: Cannot connect to AP')
90            raise
91        print('Checking py-client received msg published from esp...')
92        if not event_client_received_correct.wait(timeout=30):
93            raise ValueError('Wrong data received, msg log: {}'.format(message_log))
94        print('Checking esp-client received msg published from py-client...')
95        dut1.expect(re.compile(r'DATA=data_to_esp32'), timeout=30)
96    finally:
97        event_stop_client.set()
98        thread1.join()
99
100
101if __name__ == '__main__':
102    test_examples_protocol_mqtt_ws()
103