mirror of
https://github.com/espressif/ESP8266_RTOS_SDK.git
synced 2025-08-06 15:15:15 +08:00
feat(esp-mqtt): Add ESP-MQTT example
This commit is contained in:
9
examples/protocols/esp-mqtt/ssl/CMakeLists.txt
Normal file
9
examples/protocols/esp-mqtt/ssl/CMakeLists.txt
Normal file
@ -0,0 +1,9 @@
|
||||
# The following four lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
|
||||
project(mqtt_ssl)
|
||||
|
||||
target_add_binary_data(mqtt_ssl.elf "main/iot_eclipse_org.pem" TEXT)
|
7
examples/protocols/esp-mqtt/ssl/Makefile
Normal file
7
examples/protocols/esp-mqtt/ssl/Makefile
Normal file
@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := mqtt_ssl
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
67
examples/protocols/esp-mqtt/ssl/README.md
Normal file
67
examples/protocols/esp-mqtt/ssl/README.md
Normal file
@ -0,0 +1,67 @@
|
||||
# ESP-MQTT SSL Sample application
|
||||
|
||||
(See the README.md file in the upper level 'examples' directory for more information about examples.)
|
||||
|
||||
This example connects to the broker iot.eclipse.org using ssl transport and as a demonstration subscribes/unsubscribes and send a message on certain topic.
|
||||
|
||||
It uses ESP-MQTT library which implements mqtt client to connect to mqtt broker.
|
||||
|
||||
## How to use example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet.
|
||||
|
||||
### Configure the project
|
||||
|
||||
```
|
||||
make menuconfig
|
||||
```
|
||||
|
||||
* Set serial port under Serial Flasher Options.
|
||||
|
||||
* Set ssid and password for the board to connect to AP.
|
||||
|
||||
Note how to create a PEM certificate for iot.eclipse.org:
|
||||
```
|
||||
openssl s_client -showcerts -connect iot.eclipse.org:8883 </dev/null 2>/dev/null|openssl x509 -outform PEM >iot_eclipse_org.pem
|
||||
```
|
||||
|
||||
### Build and Flash
|
||||
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
|
||||
```
|
||||
make -j4 flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
|
||||
```
|
||||
I (3714) event: sta ip: 192.168.0.139, mask: 255.255.255.0, gw: 192.168.0.2
|
||||
I (3714) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
|
||||
I (3964) MQTT_CLIENT: Sending MQTT CONNECT message, type: 1, id: 0000
|
||||
I (4164) MQTTS_EXAMPLE: MQTT_EVENT_CONNECTED
|
||||
I (4174) MQTTS_EXAMPLE: sent publish successful, msg_id=41464
|
||||
I (4174) MQTTS_EXAMPLE: sent subscribe successful, msg_id=17886
|
||||
I (4174) MQTTS_EXAMPLE: sent subscribe successful, msg_id=42970
|
||||
I (4184) MQTTS_EXAMPLE: sent unsubscribe successful, msg_id=50241
|
||||
I (4314) MQTTS_EXAMPLE: MQTT_EVENT_PUBLISHED, msg_id=41464
|
||||
I (4484) MQTTS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=17886
|
||||
I (4484) MQTTS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4684) MQTTS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=42970
|
||||
I (4684) MQTTS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4884) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (4884) MQTTS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
I (5194) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (5194) MQTTS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
```
|
||||
|
4
examples/protocols/esp-mqtt/ssl/main/CMakeLists.txt
Normal file
4
examples/protocols/esp-mqtt/ssl/main/CMakeLists.txt
Normal file
@ -0,0 +1,4 @@
|
||||
set(COMPONENT_SRCS "app_main.c")
|
||||
set(COMPONENT_ADD_INCLUDEDIRS ".")
|
||||
|
||||
register_component()
|
31
examples/protocols/esp-mqtt/ssl/main/Kconfig.projbuild
Normal file
31
examples/protocols/esp-mqtt/ssl/main/Kconfig.projbuild
Normal file
@ -0,0 +1,31 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config BROKER_URI
|
||||
string "Broker URL"
|
||||
default "mqtts://iot.eclipse.org:8883"
|
||||
help
|
||||
URL of an mqtt broker which this example connects to.
|
||||
|
||||
config BROKER_CERTIFICATE_OVERRIDE
|
||||
string "Broker certificate override"
|
||||
default ""
|
||||
help
|
||||
Please leave empty if broker certificate included from a textfile; otherwise fill in a base64 part of PEM format certificate
|
||||
|
||||
config BROKER_CERTIFICATE_OVERRIDDEN
|
||||
bool
|
||||
default y if BROKER_CERTIFICATE_OVERRIDE != ""
|
||||
|
||||
endmenu
|
154
examples/protocols/esp-mqtt/ssl/main/app_main.c
Normal file
154
examples/protocols/esp-mqtt/ssl/main/app_main.c
Normal file
@ -0,0 +1,154 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_event_loop.h"
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#include "lwip/sockets.h"
|
||||
#include "lwip/dns.h"
|
||||
#include "lwip/netdb.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "mqtt_client.h"
|
||||
|
||||
static const char *TAG = "MQTTS_EXAMPLE";
|
||||
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
const static int CONNECTED_BIT = BIT0;
|
||||
|
||||
|
||||
|
||||
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch (event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
|
||||
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void wifi_init(void)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = CONFIG_WIFI_SSID,
|
||||
.password = CONFIG_WIFI_PASSWORD,
|
||||
},
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_LOGI(TAG, "start the WIFI SSID:[%s]", CONFIG_WIFI_SSID);
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
ESP_LOGI(TAG, "Waiting for wifi");
|
||||
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
|
||||
}
|
||||
|
||||
#if CONFIG_BROKER_CERTIFICATE_OVERRIDDEN == 1
|
||||
static const uint8_t iot_eclipse_org_pem_start[] = "-----BEGIN CERTIFICATE-----\n" CONFIG_BROKER_CERTIFICATE_OVERRIDE "\n-----END CERTIFICATE-----";
|
||||
#else
|
||||
extern const uint8_t iot_eclipse_org_pem_start[] asm("_binary_iot_eclipse_org_pem_start");
|
||||
#endif
|
||||
extern const uint8_t iot_eclipse_org_pem_end[] asm("_binary_iot_eclipse_org_pem_end");
|
||||
|
||||
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
|
||||
{
|
||||
esp_mqtt_client_handle_t client = event->client;
|
||||
int msg_id;
|
||||
// your_context_t *context = event->context;
|
||||
switch (event->event_id) {
|
||||
case MQTT_EVENT_CONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
|
||||
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
|
||||
break;
|
||||
|
||||
case MQTT_EVENT_SUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
|
||||
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_UNSUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_PUBLISHED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DATA:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
|
||||
printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
|
||||
printf("DATA=%.*s\r\n", event->data_len, event->data);
|
||||
break;
|
||||
case MQTT_EVENT_ERROR:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
|
||||
static void mqtt_app_start(void)
|
||||
{
|
||||
const esp_mqtt_client_config_t mqtt_cfg = {
|
||||
.uri = CONFIG_BROKER_URI,
|
||||
.event_handle = mqtt_event_handler,
|
||||
.cert_pem = (const char *)iot_eclipse_org_pem_start,
|
||||
};
|
||||
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
|
||||
esp_mqtt_client_start(client);
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
ESP_LOGI(TAG, "[APP] Startup..");
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
|
||||
|
||||
esp_log_level_set("*", ESP_LOG_INFO);
|
||||
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
|
||||
|
||||
nvs_flash_init();
|
||||
wifi_init();
|
||||
mqtt_app_start();
|
||||
|
||||
}
|
1
examples/protocols/esp-mqtt/ssl/main/component.mk
Normal file
1
examples/protocols/esp-mqtt/ssl/main/component.mk
Normal file
@ -0,0 +1 @@
|
||||
COMPONENT_EMBED_TXTFILES := iot_eclipse_org.pem
|
27
examples/protocols/esp-mqtt/ssl/main/iot_eclipse_org.pem
Normal file
27
examples/protocols/esp-mqtt/ssl/main/iot_eclipse_org.pem
Normal file
@ -0,0 +1,27 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/
|
||||
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
|
||||
DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow
|
||||
SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT
|
||||
GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC
|
||||
AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF
|
||||
q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8
|
||||
SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0
|
||||
Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA
|
||||
a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj
|
||||
/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T
|
||||
AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG
|
||||
CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv
|
||||
bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k
|
||||
c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw
|
||||
VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC
|
||||
ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz
|
||||
MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu
|
||||
Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF
|
||||
AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo
|
||||
uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/
|
||||
wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu
|
||||
X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG
|
||||
PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6
|
||||
KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==
|
||||
-----END CERTIFICATE-----
|
121
examples/protocols/esp-mqtt/ssl/mqtt_ssl_example_test.py
Normal file
121
examples/protocols/esp-mqtt/ssl/mqtt_ssl_example_test.py
Normal file
@ -0,0 +1,121 @@
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import str
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import ssl
|
||||
import paho.mqtt.client as mqtt
|
||||
from threading import Thread, Event
|
||||
|
||||
|
||||
try:
|
||||
import IDF
|
||||
except ImportError:
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
import IDF
|
||||
|
||||
import DUT
|
||||
|
||||
|
||||
event_client_connected = Event()
|
||||
event_stop_client = Event()
|
||||
event_client_received_correct = Event()
|
||||
message_log = ""
|
||||
|
||||
|
||||
# The callback for when the client receives a CONNACK response from the server.
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print("Connected with result code " + str(rc))
|
||||
event_client_connected.set()
|
||||
client.subscribe("/topic/qos0")
|
||||
|
||||
|
||||
def mqtt_client_task(client):
|
||||
while not event_stop_client.is_set():
|
||||
client.loop()
|
||||
|
||||
|
||||
# The callback for when a PUBLISH message is received from the server.
|
||||
def on_message(client, userdata, msg):
|
||||
global message_log
|
||||
payload = msg.payload.decode()
|
||||
if not event_client_received_correct.is_set() and payload == "data":
|
||||
client.publish("/topic/qos0", "data_to_esp32")
|
||||
if msg.topic == "/topic/qos0" and payload == "data":
|
||||
event_client_received_correct.set()
|
||||
message_log += "Received data:" + msg.topic + " " + payload + "\n"
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_mqtt_ssl(env, extra_data):
|
||||
broker_url = ""
|
||||
broker_port = 0
|
||||
"""
|
||||
steps: |
|
||||
1. join AP and connects to ssl broker
|
||||
2. Test connects a client to the same broker
|
||||
3. Test evaluates python client received correct qos0 message
|
||||
4. Test ESP32 client received correct qos0 message
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_ssl", "examples/protocols/mqtt/ssl")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_ssl.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("mqtt_ssl_bin_size", "{}KB"
|
||||
.format(bin_size // 1024))
|
||||
IDF.check_performance("mqtt_ssl_size", bin_size // 1024)
|
||||
# Look for host:port in sdkconfig
|
||||
try:
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
|
||||
broker_url = value.group(1)
|
||||
broker_port = int(value.group(2))
|
||||
except Exception:
|
||||
print('ENV_TEST_FAILURE: Cannot find broker url in sdkconfig')
|
||||
raise
|
||||
client = None
|
||||
# 1. Test connects to a broker
|
||||
try:
|
||||
client = mqtt.Client()
|
||||
client.on_connect = on_connect
|
||||
client.on_message = on_message
|
||||
client.tls_set(None,
|
||||
None,
|
||||
None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1, ciphers=None)
|
||||
client.tls_insecure_set(True)
|
||||
print("Connecting...")
|
||||
client.connect(broker_url, broker_port, 60)
|
||||
except Exception:
|
||||
print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
|
||||
raise
|
||||
# Starting a py-client in a separate thread
|
||||
thread1 = Thread(target=mqtt_client_task, args=(client,))
|
||||
thread1.start()
|
||||
try:
|
||||
print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
|
||||
if not event_client_connected.wait(timeout=30):
|
||||
raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
|
||||
dut1.start_app()
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
print('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
raise
|
||||
print("Checking py-client received msg published from esp...")
|
||||
if not event_client_received_correct.wait(timeout=30):
|
||||
raise ValueError('Wrong data received, msg log: {}'.format(message_log))
|
||||
print("Checking esp-client received msg published from py-client...")
|
||||
dut1.expect(re.compile(r"DATA=data_to_esp32"), timeout=30)
|
||||
finally:
|
||||
event_stop_client.set()
|
||||
thread1.join()
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_mqtt_ssl()
|
2
examples/protocols/esp-mqtt/ssl/sdkconfig.ci
Normal file
2
examples/protocols/esp-mqtt/ssl/sdkconfig.ci
Normal file
@ -0,0 +1,2 @@
|
||||
CONFIG_BROKER_URI="mqtts://${EXAMPLE_MQTT_BROKER_SSL}"
|
||||
CONFIG_BROKER_CERTIFICATE_OVERRIDE="${EXAMPLE_MQTT_BROKER_CERTIFICATE}"
|
10
examples/protocols/esp-mqtt/ssl_mutual_auth/CMakeLists.txt
Normal file
10
examples/protocols/esp-mqtt/ssl_mutual_auth/CMakeLists.txt
Normal file
@ -0,0 +1,10 @@
|
||||
# The following four lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
|
||||
project(mqtt_ssl_mutual_auth)
|
||||
|
||||
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/client.crt" TEXT)
|
||||
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/client.key" TEXT)
|
7
examples/protocols/esp-mqtt/ssl_mutual_auth/Makefile
Normal file
7
examples/protocols/esp-mqtt/ssl_mutual_auth/Makefile
Normal file
@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := mqtt_ssl_mutual_auth
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
81
examples/protocols/esp-mqtt/ssl_mutual_auth/README.md
Normal file
81
examples/protocols/esp-mqtt/ssl_mutual_auth/README.md
Normal file
@ -0,0 +1,81 @@
|
||||
# ESP-MQTT SSL Sample application (mutual authentication)
|
||||
|
||||
(See the README.md file in the upper level 'examples' directory for more information about examples.)
|
||||
|
||||
This example connects to the broker test.mosquitto.org using ssl transport with client certificate and as a demonstration subscribes/unsubscribes and send a message on certain topic.
|
||||
|
||||
It uses ESP-MQTT library which implements mqtt client to connect to mqtt broker.
|
||||
|
||||
## How to use example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet.
|
||||
|
||||
### Configure the project
|
||||
|
||||
```
|
||||
make menuconfig
|
||||
```
|
||||
|
||||
* Set serial port under Serial Flasher Options.
|
||||
|
||||
* Set ssid and password for the board to connect to AP.
|
||||
|
||||
* Generate your client keys and certificate
|
||||
|
||||
Navigate to the main directory
|
||||
|
||||
```
|
||||
cd main
|
||||
```
|
||||
|
||||
Generate a client key and a CSR. When you are generating the CSR, do not use the default values. At a minimum, the CSR must include the Country, Organisation and Common Name fields.
|
||||
|
||||
```
|
||||
openssl genrsa -out client.key
|
||||
openssl req -out client.csr -key client.key -new
|
||||
```
|
||||
|
||||
Paste the generated CSR in the [Mosquitto test certificate signer](https://test.mosquitto.org/ssl/index.php), click Submit and copy the downloaded `client.crt` in the `main` directory.
|
||||
|
||||
Please note, that the supplied files `client.crt` and `client.key` in the `main` directory are only placeholders for your client certificate and key (i.e. the example "as is" would compile but would not connect to the broker)
|
||||
|
||||
### Build and Flash
|
||||
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
|
||||
```
|
||||
make -j4 flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
|
||||
```
|
||||
I (3714) event: sta ip: 192.168.0.139, mask: 255.255.255.0, gw: 192.168.0.2
|
||||
I (3714) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
|
||||
I (3964) MQTT_CLIENT: Sending MQTT CONNECT message, type: 1, id: 0000
|
||||
I (4164) MQTTS_EXAMPLE: MQTT_EVENT_CONNECTED
|
||||
I (4174) MQTTS_EXAMPLE: sent publish successful, msg_id=41464
|
||||
I (4174) MQTTS_EXAMPLE: sent subscribe successful, msg_id=17886
|
||||
I (4174) MQTTS_EXAMPLE: sent subscribe successful, msg_id=42970
|
||||
I (4184) MQTTS_EXAMPLE: sent unsubscribe successful, msg_id=50241
|
||||
I (4314) MQTTS_EXAMPLE: MQTT_EVENT_PUBLISHED, msg_id=41464
|
||||
I (4484) MQTTS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=17886
|
||||
I (4484) MQTTS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4684) MQTTS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=42970
|
||||
I (4684) MQTTS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4884) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (4884) MQTTS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
I (5194) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (5194) MQTTS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
```
|
||||
|
@ -0,0 +1,4 @@
|
||||
set(COMPONENT_SRCS "app_main.c")
|
||||
set(COMPONENT_ADD_INCLUDEDIRS ".")
|
||||
|
||||
register_component()
|
@ -0,0 +1,15 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
endmenu
|
152
examples/protocols/esp-mqtt/ssl_mutual_auth/main/app_main.c
Normal file
152
examples/protocols/esp-mqtt/ssl_mutual_auth/main/app_main.c
Normal file
@ -0,0 +1,152 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_event_loop.h"
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#include "lwip/sockets.h"
|
||||
#include "lwip/dns.h"
|
||||
#include "lwip/netdb.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "mqtt_client.h"
|
||||
|
||||
static const char *TAG = "MQTTS_EXAMPLE";
|
||||
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
const static int CONNECTED_BIT = BIT0;
|
||||
|
||||
|
||||
|
||||
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch (event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
|
||||
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void wifi_init(void)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = CONFIG_WIFI_SSID,
|
||||
.password = CONFIG_WIFI_PASSWORD,
|
||||
},
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_LOGI(TAG, "start the WIFI SSID:[%s]", CONFIG_WIFI_SSID);
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
ESP_LOGI(TAG, "Waiting for wifi");
|
||||
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
|
||||
}
|
||||
|
||||
extern const uint8_t client_cert_pem_start[] asm("_binary_client_crt_start");
|
||||
extern const uint8_t client_cert_pem_end[] asm("_binary_client_crt_end");
|
||||
extern const uint8_t client_key_pem_start[] asm("_binary_client_key_start");
|
||||
extern const uint8_t client_key_pem_end[] asm("_binary_client_key_end");
|
||||
|
||||
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
|
||||
{
|
||||
esp_mqtt_client_handle_t client = event->client;
|
||||
int msg_id;
|
||||
// your_context_t *context = event->context;
|
||||
switch (event->event_id) {
|
||||
case MQTT_EVENT_CONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
|
||||
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
|
||||
break;
|
||||
|
||||
case MQTT_EVENT_SUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
|
||||
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_UNSUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_PUBLISHED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DATA:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
|
||||
printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
|
||||
printf("DATA=%.*s\r\n", event->data_len, event->data);
|
||||
break;
|
||||
case MQTT_EVENT_ERROR:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void mqtt_app_start(void)
|
||||
{
|
||||
const esp_mqtt_client_config_t mqtt_cfg = {
|
||||
.uri = "mqtts://test.mosquitto.org:8884",
|
||||
.event_handle = mqtt_event_handler,
|
||||
.client_cert_pem = (const char *)client_cert_pem_start,
|
||||
.client_key_pem = (const char *)client_key_pem_start,
|
||||
};
|
||||
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
|
||||
esp_mqtt_client_start(client);
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
ESP_LOGI(TAG, "[APP] Startup..");
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
|
||||
|
||||
esp_log_level_set("*", ESP_LOG_INFO);
|
||||
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
|
||||
|
||||
nvs_flash_init();
|
||||
wifi_init();
|
||||
mqtt_app_start();
|
||||
|
||||
}
|
@ -0,0 +1 @@
|
||||
Please paste your client certificate here (follow instructions in README.md)
|
@ -0,0 +1 @@
|
||||
Please paste here your client key (follow instructions in README.md)
|
@ -0,0 +1 @@
|
||||
COMPONENT_EMBED_TXTFILES := client.crt client.key
|
7
examples/protocols/esp-mqtt/tcp/CMakeLists.txt
Normal file
7
examples/protocols/esp-mqtt/tcp/CMakeLists.txt
Normal file
@ -0,0 +1,7 @@
|
||||
# The following four lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
|
||||
project(mqtt_tcp)
|
7
examples/protocols/esp-mqtt/tcp/Makefile
Normal file
7
examples/protocols/esp-mqtt/tcp/Makefile
Normal file
@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := mqtt_tcp
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
61
examples/protocols/esp-mqtt/tcp/README.md
Normal file
61
examples/protocols/esp-mqtt/tcp/README.md
Normal file
@ -0,0 +1,61 @@
|
||||
# ESP-MQTT sample application
|
||||
(See the README.md file in the upper level 'examples' directory for more information about examples.)
|
||||
|
||||
This example connects to the broker URI selected using `make menuconfig` (using mqtt tcp transport) and as a demonstration subscribes/unsubscribes and send a message on certain topic.
|
||||
Note: If the URI equals `FROM_STDIN` then the broker address is read from stdin upon application startup (used for testing)
|
||||
|
||||
It uses ESP-MQTT library which implements mqtt client to connect to mqtt broker.
|
||||
|
||||
## How to use example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet.
|
||||
|
||||
### Configure the project
|
||||
|
||||
```
|
||||
make menuconfig
|
||||
```
|
||||
|
||||
* Set serial port under Serial Flasher Options.
|
||||
|
||||
* Set ssid and password for the board to connect to AP.
|
||||
|
||||
### Build and Flash
|
||||
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
|
||||
```
|
||||
make -j4 flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
|
||||
```
|
||||
I (3714) event: sta ip: 192.168.0.139, mask: 255.255.255.0, gw: 192.168.0.2
|
||||
I (3714) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
|
||||
I (3964) MQTT_CLIENT: Sending MQTT CONNECT message, type: 1, id: 0000
|
||||
I (4164) MQTT_EXAMPLE: MQTT_EVENT_CONNECTED
|
||||
I (4174) MQTT_EXAMPLE: sent publish successful, msg_id=41464
|
||||
I (4174) MQTT_EXAMPLE: sent subscribe successful, msg_id=17886
|
||||
I (4174) MQTT_EXAMPLE: sent subscribe successful, msg_id=42970
|
||||
I (4184) MQTT_EXAMPLE: sent unsubscribe successful, msg_id=50241
|
||||
I (4314) MQTT_EXAMPLE: MQTT_EVENT_PUBLISHED, msg_id=41464
|
||||
I (4484) MQTT_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=17886
|
||||
I (4484) MQTT_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4684) MQTT_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=42970
|
||||
I (4684) MQTT_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4884) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (4884) MQTT_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
I (5194) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (5194) MQTT_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
```
|
4
examples/protocols/esp-mqtt/tcp/main/CMakeLists.txt
Normal file
4
examples/protocols/esp-mqtt/tcp/main/CMakeLists.txt
Normal file
@ -0,0 +1,4 @@
|
||||
set(COMPONENT_SRCS "app_main.c")
|
||||
set(COMPONENT_ADD_INCLUDEDIRS ".")
|
||||
|
||||
register_component()
|
25
examples/protocols/esp-mqtt/tcp/main/Kconfig.projbuild
Normal file
25
examples/protocols/esp-mqtt/tcp/main/Kconfig.projbuild
Normal file
@ -0,0 +1,25 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config BROKER_URL
|
||||
string "Broker URL"
|
||||
default "mqtt://iot.eclipse.org"
|
||||
help
|
||||
URL of the broker to connect to
|
||||
|
||||
config BROKER_URL_FROM_STDIN
|
||||
bool
|
||||
default y if BROKER_URL = "FROM_STDIN"
|
||||
|
||||
endmenu
|
171
examples/protocols/esp-mqtt/tcp/main/app_main.c
Normal file
171
examples/protocols/esp-mqtt/tcp/main/app_main.c
Normal file
@ -0,0 +1,171 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_event_loop.h"
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#include "lwip/sockets.h"
|
||||
#include "lwip/dns.h"
|
||||
#include "lwip/netdb.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "mqtt_client.h"
|
||||
|
||||
static const char *TAG = "MQTT_EXAMPLE";
|
||||
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
const static int CONNECTED_BIT = BIT0;
|
||||
|
||||
|
||||
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
|
||||
{
|
||||
esp_mqtt_client_handle_t client = event->client;
|
||||
int msg_id;
|
||||
// your_context_t *context = event->context;
|
||||
switch (event->event_id) {
|
||||
case MQTT_EVENT_CONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
|
||||
msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 0);
|
||||
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
|
||||
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
|
||||
break;
|
||||
|
||||
case MQTT_EVENT_SUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
|
||||
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_UNSUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_PUBLISHED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DATA:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
|
||||
printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
|
||||
printf("DATA=%.*s\r\n", event->data_len, event->data);
|
||||
break;
|
||||
case MQTT_EVENT_ERROR:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch (event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
|
||||
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void wifi_init(void)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = CONFIG_WIFI_SSID,
|
||||
.password = CONFIG_WIFI_PASSWORD,
|
||||
},
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_LOGI(TAG, "start the WIFI SSID:[%s]", CONFIG_WIFI_SSID);
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
ESP_LOGI(TAG, "Waiting for wifi");
|
||||
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
|
||||
}
|
||||
|
||||
static void mqtt_app_start(void)
|
||||
{
|
||||
esp_mqtt_client_config_t mqtt_cfg = {
|
||||
.uri = CONFIG_BROKER_URL,
|
||||
.event_handle = mqtt_event_handler,
|
||||
// .user_context = (void *)your_context
|
||||
};
|
||||
|
||||
#if CONFIG_BROKER_URL_FROM_STDIN
|
||||
char line[128];
|
||||
|
||||
if (strcmp(mqtt_cfg.uri, "FROM_STDIN") == 0) {
|
||||
int count = 0;
|
||||
printf("Please enter url of mqtt broker\n");
|
||||
while (count < 128) {
|
||||
int c = fgetc(stdin);
|
||||
if (c == '\n') {
|
||||
line[count] = '\0';
|
||||
break;
|
||||
} else if (c > 0 && c < 127) {
|
||||
line[count] = c;
|
||||
++count;
|
||||
}
|
||||
vTaskDelay(10 / portTICK_PERIOD_MS);
|
||||
}
|
||||
mqtt_cfg.uri = line;
|
||||
printf("Broker url: %s\n", line);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
|
||||
abort();
|
||||
}
|
||||
#endif /* CONFIG_BROKER_URL_FROM_STDIN */
|
||||
|
||||
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
|
||||
esp_mqtt_client_start(client);
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
ESP_LOGI(TAG, "[APP] Startup..");
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
|
||||
|
||||
esp_log_level_set("*", ESP_LOG_INFO);
|
||||
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
|
||||
|
||||
nvs_flash_init();
|
||||
wifi_init();
|
||||
mqtt_app_start();
|
||||
}
|
0
examples/protocols/esp-mqtt/tcp/main/component.mk
Normal file
0
examples/protocols/esp-mqtt/tcp/main/component.mk
Normal file
109
examples/protocols/esp-mqtt/tcp/mqtt_tcp_example_test.py
Normal file
109
examples/protocols/esp-mqtt/tcp/mqtt_tcp_example_test.py
Normal file
@ -0,0 +1,109 @@
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
from socket import *
|
||||
from threading import Thread
|
||||
import struct
|
||||
import time
|
||||
|
||||
msgid=-1
|
||||
|
||||
def get_my_ip():
|
||||
s1 = socket(AF_INET, SOCK_DGRAM)
|
||||
s1.connect(("8.8.8.8", 80))
|
||||
my_ip = s1.getsockname()[0]
|
||||
s1.close()
|
||||
return my_ip
|
||||
|
||||
def mqqt_server_sketch(my_ip, port):
|
||||
global msgid
|
||||
print("Starting the server on {}".format(my_ip))
|
||||
s = None
|
||||
try:
|
||||
s=socket(AF_INET, SOCK_STREAM)
|
||||
s.settimeout(60)
|
||||
s.bind((my_ip, port))
|
||||
s.listen(1)
|
||||
q,addr=s.accept()
|
||||
q.settimeout(30)
|
||||
print("connection accepted")
|
||||
except:
|
||||
print("Local server on {}:{} listening/accepting failure: {}"
|
||||
"Possibly check permissions or firewall settings"
|
||||
"to accept connections on this address".format(my_ip, port, sys.exc_info()[0]))
|
||||
raise
|
||||
data = q.recv(1024)
|
||||
# check if received initial empty message
|
||||
print("received from client {}".format(data))
|
||||
data = bytearray([0x20, 0x02, 0x00, 0x00])
|
||||
q.send(data)
|
||||
# try to receive qos1
|
||||
data = q.recv(1024)
|
||||
msgid = struct.unpack(">H", data[15:17])[0]
|
||||
print("received from client {}, msgid: {}".format(data, msgid))
|
||||
data = bytearray([0x40, 0x02, data[15], data[16]])
|
||||
q.send(data)
|
||||
time.sleep(5)
|
||||
s.close()
|
||||
print("server closed")
|
||||
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
import DUT
|
||||
|
||||
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_mqtt_qos1(env, extra_data):
|
||||
global msgid
|
||||
"""
|
||||
steps: (QoS1: Happy flow)
|
||||
1. start the broker broker (with correctly sending ACK)
|
||||
2. DUT client connects to a broker and publishes qos1 message
|
||||
3. Test evaluates that qos1 message is queued and removed from queued after ACK received
|
||||
4. Test the broker received the same message id evaluated in step 3
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_tcp", "examples/protocols/mqtt/tcp")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_tcp.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("mqtt_tcp_bin_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("mqtt_tcp_size", bin_size//1024)
|
||||
# 1. start mqtt broker sketch
|
||||
host_ip = get_my_ip()
|
||||
thread1 = Thread(target = mqqt_server_sketch, args = (host_ip,1883))
|
||||
thread1.start()
|
||||
# 2. start the dut test and wait till client gets IP address
|
||||
dut1.start_app()
|
||||
# waiting for getting the IP address
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
|
||||
print ("writing to device: {}".format("mqtt://" + host_ip + "\n"))
|
||||
dut1.write("mqtt://" + host_ip + "\n")
|
||||
thread1.join()
|
||||
print ("Message id received from server: {}".format(msgid))
|
||||
# 3. check the message id was enqueued and then deleted
|
||||
msgid_enqueued = dut1.expect(re.compile(r"OUTBOX: ENQUEUE msgid=([0-9]+)"), timeout=30)
|
||||
msgid_deleted = dut1.expect(re.compile(r"OUTBOX: DELETED msgid=([0-9]+)"), timeout=30)
|
||||
# 4. check the msgid of received data are the same as that of enqueued and deleted from outbox
|
||||
if (msgid_enqueued[0] == str(msgid) and msgid_deleted[0] == str(msgid)):
|
||||
print("PASS: Received correct msg id")
|
||||
else:
|
||||
print("Failure!")
|
||||
raise ValueError('Mismatch of msgid: received: {}, enqueued {}, deleted {}'.format(msgid, msgid_enqueued, msgid_deleted))
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_mqtt_qos1()
|
2
examples/protocols/esp-mqtt/tcp/sdkconfig.ci
Normal file
2
examples/protocols/esp-mqtt/tcp/sdkconfig.ci
Normal file
@ -0,0 +1,2 @@
|
||||
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y
|
||||
CONFIG_BROKER_URL="FROM_STDIN"
|
7
examples/protocols/esp-mqtt/ws/CMakeLists.txt
Normal file
7
examples/protocols/esp-mqtt/ws/CMakeLists.txt
Normal file
@ -0,0 +1,7 @@
|
||||
# The following four lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
|
||||
project(mqtt_websocket)
|
7
examples/protocols/esp-mqtt/ws/Makefile
Normal file
7
examples/protocols/esp-mqtt/ws/Makefile
Normal file
@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := mqtt_websocket
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
62
examples/protocols/esp-mqtt/ws/README.md
Normal file
62
examples/protocols/esp-mqtt/ws/README.md
Normal file
@ -0,0 +1,62 @@
|
||||
# ESP-MQTT MQTT over Websocket
|
||||
|
||||
(See the README.md file in the upper level 'examples' directory for more information about examples.)
|
||||
|
||||
This example connects to the broker iot.eclipse.org over web sockets as a demonstration subscribes/unsubscribes and send a message on certain topic.
|
||||
|
||||
It uses ESP-MQTT library which implements mqtt client to connect to mqtt broker.
|
||||
|
||||
## How to use example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet.
|
||||
|
||||
### Configure the project
|
||||
|
||||
```
|
||||
make menuconfig
|
||||
```
|
||||
|
||||
* Set serial port under Serial Flasher Options.
|
||||
|
||||
* Set ssid and password for the board to connect to AP.
|
||||
|
||||
### Build and Flash
|
||||
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
|
||||
```
|
||||
make -j4 flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
|
||||
```
|
||||
I (3714) event: sta ip: 192.168.0.139, mask: 255.255.255.0, gw: 192.168.0.2
|
||||
I (3714) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
|
||||
I (3964) MQTT_CLIENT: Sending MQTT CONNECT message, type: 1, id: 0000
|
||||
I (4164) MQTTWS_EXAMPLE: MQTT_EVENT_CONNECTED
|
||||
I (4174) MQTTWS_EXAMPLE: sent publish successful, msg_id=41464
|
||||
I (4174) MQTTWS_EXAMPLE: sent subscribe successful, msg_id=17886
|
||||
I (4174) MQTTWS_EXAMPLE: sent subscribe successful, msg_id=42970
|
||||
I (4184) MQTTWS_EXAMPLE: sent unsubscribe successful, msg_id=50241
|
||||
I (4314) MQTTWS_EXAMPLE: MQTT_EVENT_PUBLISHED, msg_id=41464
|
||||
I (4484) MQTTWS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=17886
|
||||
I (4484) MQTTWS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4684) MQTTWS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=42970
|
||||
I (4684) MQTTWS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4884) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (4884) MQTTWS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
I (5194) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (5194) MQTTWS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
```
|
||||
|
4
examples/protocols/esp-mqtt/ws/main/CMakeLists.txt
Normal file
4
examples/protocols/esp-mqtt/ws/main/CMakeLists.txt
Normal file
@ -0,0 +1,4 @@
|
||||
set(COMPONENT_SRCS "app_main.c")
|
||||
set(COMPONENT_ADD_INCLUDEDIRS ".")
|
||||
|
||||
register_component()
|
21
examples/protocols/esp-mqtt/ws/main/Kconfig.projbuild
Normal file
21
examples/protocols/esp-mqtt/ws/main/Kconfig.projbuild
Normal file
@ -0,0 +1,21 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config BROKER_URI
|
||||
string "Broker URL"
|
||||
default "ws://iot.eclipse.org:80/ws"
|
||||
help
|
||||
URL of an mqtt broker which this example connects to.
|
||||
|
||||
endmenu
|
144
examples/protocols/esp-mqtt/ws/main/app_main.c
Normal file
144
examples/protocols/esp-mqtt/ws/main/app_main.c
Normal file
@ -0,0 +1,144 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_event_loop.h"
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#include "lwip/sockets.h"
|
||||
#include "lwip/dns.h"
|
||||
#include "lwip/netdb.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "mqtt_client.h"
|
||||
|
||||
static const char *TAG = "MQTTWS_EXAMPLE";
|
||||
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
const static int CONNECTED_BIT = BIT0;
|
||||
|
||||
|
||||
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
|
||||
{
|
||||
esp_mqtt_client_handle_t client = event->client;
|
||||
int msg_id;
|
||||
// your_context_t *context = event->context;
|
||||
switch (event->event_id) {
|
||||
case MQTT_EVENT_CONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
|
||||
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
|
||||
break;
|
||||
|
||||
case MQTT_EVENT_SUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
|
||||
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_UNSUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_PUBLISHED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DATA:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
|
||||
printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
|
||||
printf("DATA=%.*s\r\n", event->data_len, event->data);
|
||||
break;
|
||||
case MQTT_EVENT_ERROR:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch (event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
|
||||
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void wifi_init(void)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = CONFIG_WIFI_SSID,
|
||||
.password = CONFIG_WIFI_PASSWORD,
|
||||
},
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_LOGI(TAG, "start the WIFI SSID:[%s]", CONFIG_WIFI_SSID);
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
ESP_LOGI(TAG, "Waiting for wifi");
|
||||
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
|
||||
}
|
||||
|
||||
static void mqtt_app_start(void)
|
||||
{
|
||||
const esp_mqtt_client_config_t mqtt_cfg = {
|
||||
.uri = CONFIG_BROKER_URI,
|
||||
.event_handle = mqtt_event_handler,
|
||||
// .user_context = (void *)your_context
|
||||
};
|
||||
|
||||
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
|
||||
esp_mqtt_client_start(client);
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
ESP_LOGI(TAG, "[APP] Startup..");
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
|
||||
|
||||
esp_log_level_set("*", ESP_LOG_INFO);
|
||||
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_WS", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
|
||||
|
||||
nvs_flash_init();
|
||||
wifi_init();
|
||||
mqtt_app_start();
|
||||
}
|
0
examples/protocols/esp-mqtt/ws/main/component.mk
Normal file
0
examples/protocols/esp-mqtt/ws/main/component.mk
Normal file
115
examples/protocols/esp-mqtt/ws/mqtt_ws_example_test.py
Normal file
115
examples/protocols/esp-mqtt/ws/mqtt_ws_example_test.py
Normal file
@ -0,0 +1,115 @@
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import str
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import paho.mqtt.client as mqtt
|
||||
from threading import Thread, Event
|
||||
|
||||
|
||||
try:
|
||||
import IDF
|
||||
except Exception:
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
import IDF
|
||||
|
||||
import DUT
|
||||
|
||||
event_client_connected = Event()
|
||||
event_stop_client = Event()
|
||||
event_client_received_correct = Event()
|
||||
message_log = ""
|
||||
|
||||
|
||||
# The callback for when the client receives a CONNACK response from the server.
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print("Connected with result code " + str(rc))
|
||||
event_client_connected.set()
|
||||
client.subscribe("/topic/qos0")
|
||||
|
||||
|
||||
def mqtt_client_task(client):
|
||||
while not event_stop_client.is_set():
|
||||
client.loop()
|
||||
|
||||
|
||||
# The callback for when a PUBLISH message is received from the server.
|
||||
def on_message(client, userdata, msg):
|
||||
global message_log
|
||||
payload = msg.payload.decode()
|
||||
if not event_client_received_correct.is_set() and payload == "data":
|
||||
client.publish("/topic/qos0", "data_to_esp32")
|
||||
if msg.topic == "/topic/qos0" and payload == "data":
|
||||
event_client_received_correct.set()
|
||||
message_log += "Received data:" + msg.topic + " " + payload + "\n"
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_mqtt_ws(env, extra_data):
|
||||
broker_url = ""
|
||||
broker_port = 0
|
||||
"""
|
||||
steps: |
|
||||
1. join AP and connects to ws broker
|
||||
2. Test connects a client to the same broker
|
||||
3. Test evaluates it received correct qos0 message
|
||||
4. Test ESP32 client received correct qos0 message
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_websocket", "examples/protocols/mqtt/ws")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_websocket.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("mqtt_websocket_bin_size", "{}KB".format(bin_size // 1024))
|
||||
IDF.check_performance("mqtt_websocket_size", bin_size // 1024)
|
||||
# Look for host:port in sdkconfig
|
||||
try:
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
|
||||
broker_url = value.group(1)
|
||||
broker_port = int(value.group(2))
|
||||
except Exception:
|
||||
print('ENV_TEST_FAILURE: Cannot find broker url in sdkconfig')
|
||||
raise
|
||||
client = None
|
||||
# 1. Test connects to a broker
|
||||
try:
|
||||
client = mqtt.Client(transport="websockets")
|
||||
client.on_connect = on_connect
|
||||
client.on_message = on_message
|
||||
client.ws_set_options(path="/ws", headers=None)
|
||||
print("Connecting...")
|
||||
client.connect(broker_url, broker_port, 60)
|
||||
except Exception:
|
||||
print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
|
||||
raise
|
||||
# Starting a py-client in a separate thread
|
||||
thread1 = Thread(target=mqtt_client_task, args=(client,))
|
||||
thread1.start()
|
||||
try:
|
||||
print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
|
||||
if not event_client_connected.wait(timeout=30):
|
||||
raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
|
||||
dut1.start_app()
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
print('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
raise
|
||||
print("Checking py-client received msg published from esp...")
|
||||
if not event_client_received_correct.wait(timeout=30):
|
||||
raise ValueError('Wrong data received, msg log: {}'.format(message_log))
|
||||
print("Checking esp-client received msg published from py-client...")
|
||||
dut1.expect(re.compile(r"DATA=data_to_esp32"), timeout=30)
|
||||
finally:
|
||||
event_stop_client.set()
|
||||
thread1.join()
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_mqtt_ws()
|
1
examples/protocols/esp-mqtt/ws/sdkconfig.ci
Normal file
1
examples/protocols/esp-mqtt/ws/sdkconfig.ci
Normal file
@ -0,0 +1 @@
|
||||
CONFIG_BROKER_URI="ws://${EXAMPLE_MQTT_BROKER_WS}/ws"
|
9
examples/protocols/esp-mqtt/wss/CMakeLists.txt
Normal file
9
examples/protocols/esp-mqtt/wss/CMakeLists.txt
Normal file
@ -0,0 +1,9 @@
|
||||
# The following four lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
|
||||
project(mqtt_websocket_secure)
|
||||
|
||||
target_add_binary_data(mqtt_websocket_secure.elf "main/iot_eclipse_org.pem" TEXT)
|
7
examples/protocols/esp-mqtt/wss/Makefile
Normal file
7
examples/protocols/esp-mqtt/wss/Makefile
Normal file
@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := mqtt_websocket_secure
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
69
examples/protocols/esp-mqtt/wss/README.md
Normal file
69
examples/protocols/esp-mqtt/wss/README.md
Normal file
@ -0,0 +1,69 @@
|
||||
# ESP-MQTT MQTT over WSS Sample application
|
||||
(See the README.md file in the upper level 'examples' directory for more information about examples.)
|
||||
|
||||
This example connects to the broker iot.eclipse.org over secure websockets and as a demonstration subscribes/unsubscribes and send a message on certain topic.
|
||||
|
||||
It uses ESP-MQTT library which implements mqtt client to connect to mqtt broker.
|
||||
|
||||
## How to use example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet.
|
||||
|
||||
### Configure the project
|
||||
|
||||
```
|
||||
make menuconfig
|
||||
```
|
||||
|
||||
* Set serial port under Serial Flasher Options.
|
||||
|
||||
* Set ssid and password for the board to connect to AP.
|
||||
|
||||
Note how to create a PEM certificate for iot.eclipse.org:
|
||||
|
||||
```
|
||||
openssl s_client -showcerts -connect iot.eclipse.org:8883 </dev/null 2>/dev/null|openssl x509 -outform PEM >iot_eclipse_org.pem
|
||||
```
|
||||
|
||||
### Build and Flash
|
||||
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
|
||||
```
|
||||
make -j4 flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
|
||||
```
|
||||
I (3714) event: sta ip: 192.168.0.139, mask: 255.255.255.0, gw: 192.168.0.2
|
||||
I (3714) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
|
||||
I (3964) MQTT_CLIENT: Sending MQTT CONNECT message, type: 1, id: 0000
|
||||
I (4164) MQTTWSS_EXAMPLE: MQTT_EVENT_CONNECTED
|
||||
I (4174) MQTTWSS_EXAMPLE: sent publish successful, msg_id=41464
|
||||
I (4174) MQTTWSS_EXAMPLE: sent subscribe successful, msg_id=17886
|
||||
I (4174) MQTTWSS_EXAMPLE: sent subscribe successful, msg_id=42970
|
||||
I (4184) MQTTWSS_EXAMPLE: sent unsubscribe successful, msg_id=50241
|
||||
I (4314) MQTTWSS_EXAMPLE: MQTT_EVENT_PUBLISHED, msg_id=41464
|
||||
I (4484) MQTTWSS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=17886
|
||||
I (4484) MQTTWSS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4684) MQTTWSS_EXAMPLE: MQTT_EVENT_SUBSCRIBED, msg_id=42970
|
||||
I (4684) MQTTWSS_EXAMPLE: sent publish successful, msg_id=0
|
||||
I (4884) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (4884) MQTTWSS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
I (5194) MQTT_CLIENT: deliver_publish, message_length_read=19, message_length=19
|
||||
I (5194) MQTTWSS_EXAMPLE: MQTT_EVENT_DATA
|
||||
TOPIC=/topic/qos0
|
||||
DATA=data
|
||||
```
|
||||
|
||||
|
||||
|
4
examples/protocols/esp-mqtt/wss/main/CMakeLists.txt
Normal file
4
examples/protocols/esp-mqtt/wss/main/CMakeLists.txt
Normal file
@ -0,0 +1,4 @@
|
||||
set(COMPONENT_SRCS "app_main.c")
|
||||
set(COMPONENT_ADD_INCLUDEDIRS ".")
|
||||
|
||||
register_component()
|
31
examples/protocols/esp-mqtt/wss/main/Kconfig.projbuild
Normal file
31
examples/protocols/esp-mqtt/wss/main/Kconfig.projbuild
Normal file
@ -0,0 +1,31 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config BROKER_URI
|
||||
string "Broker URL"
|
||||
default "wss://iot.eclipse.org:443/ws"
|
||||
help
|
||||
URL of an mqtt broker which this example connects to.
|
||||
|
||||
config BROKER_CERTIFICATE_OVERRIDE
|
||||
string "Server certificate override"
|
||||
default ""
|
||||
help
|
||||
Please leave empty if server certificate included from a textfile; otherwise fill in a base64 part of PEM format certificate
|
||||
|
||||
config BROKER_CERTIFICATE_OVERRIDDEN
|
||||
bool
|
||||
default y if BROKER_CERTIFICATE_OVERRIDE != ""
|
||||
|
||||
endmenu
|
152
examples/protocols/esp-mqtt/wss/main/app_main.c
Normal file
152
examples/protocols/esp-mqtt/wss/main/app_main.c
Normal file
@ -0,0 +1,152 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_event_loop.h"
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#include "lwip/sockets.h"
|
||||
#include "lwip/dns.h"
|
||||
#include "lwip/netdb.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "mqtt_client.h"
|
||||
|
||||
static const char *TAG = "MQTTWSS_EXAMPLE";
|
||||
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
const static int CONNECTED_BIT = BIT0;
|
||||
|
||||
|
||||
|
||||
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch (event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
|
||||
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void wifi_init(void)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = CONFIG_WIFI_SSID,
|
||||
.password = CONFIG_WIFI_PASSWORD,
|
||||
},
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_LOGI(TAG, "start the WIFI SSID:[%s]", CONFIG_WIFI_SSID);
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
ESP_LOGI(TAG, "Waiting for wifi");
|
||||
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
|
||||
}
|
||||
|
||||
#if CONFIG_BROKER_CERTIFICATE_OVERRIDDEN == 1
|
||||
static const uint8_t iot_eclipse_org_pem_start[] = "-----BEGIN CERTIFICATE-----\n" CONFIG_BROKER_CERTIFICATE_OVERRIDE "\n-----END CERTIFICATE-----";
|
||||
#else
|
||||
extern const uint8_t iot_eclipse_org_pem_start[] asm("_binary_iot_eclipse_org_pem_start");
|
||||
#endif
|
||||
extern const uint8_t iot_eclipse_org_pem_end[] asm("_binary_iot_eclipse_org_pem_end");
|
||||
|
||||
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
|
||||
{
|
||||
esp_mqtt_client_handle_t client = event->client;
|
||||
int msg_id;
|
||||
// your_context_t *context = event->context;
|
||||
switch (event->event_id) {
|
||||
case MQTT_EVENT_CONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
|
||||
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
|
||||
|
||||
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
|
||||
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
|
||||
break;
|
||||
|
||||
case MQTT_EVENT_SUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
|
||||
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_UNSUBSCRIBED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_PUBLISHED:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
|
||||
break;
|
||||
case MQTT_EVENT_DATA:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
|
||||
printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
|
||||
printf("DATA=%.*s\r\n", event->data_len, event->data);
|
||||
break;
|
||||
case MQTT_EVENT_ERROR:
|
||||
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void mqtt_app_start(void)
|
||||
{
|
||||
const esp_mqtt_client_config_t mqtt_cfg = {
|
||||
.uri = CONFIG_BROKER_URI,
|
||||
.event_handle = mqtt_event_handler,
|
||||
.cert_pem = (const char *)iot_eclipse_org_pem_start,
|
||||
};
|
||||
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
|
||||
esp_mqtt_client_start(client);
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
ESP_LOGI(TAG, "[APP] Startup..");
|
||||
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
|
||||
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
|
||||
|
||||
esp_log_level_set("*", ESP_LOG_INFO);
|
||||
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
|
||||
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
|
||||
|
||||
nvs_flash_init();
|
||||
wifi_init();
|
||||
mqtt_app_start();
|
||||
}
|
1
examples/protocols/esp-mqtt/wss/main/component.mk
Normal file
1
examples/protocols/esp-mqtt/wss/main/component.mk
Normal file
@ -0,0 +1 @@
|
||||
COMPONENT_EMBED_TXTFILES := iot_eclipse_org.pem
|
27
examples/protocols/esp-mqtt/wss/main/iot_eclipse_org.pem
Normal file
27
examples/protocols/esp-mqtt/wss/main/iot_eclipse_org.pem
Normal file
@ -0,0 +1,27 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/
|
||||
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
|
||||
DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow
|
||||
SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT
|
||||
GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC
|
||||
AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF
|
||||
q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8
|
||||
SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0
|
||||
Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA
|
||||
a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj
|
||||
/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T
|
||||
AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG
|
||||
CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv
|
||||
bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k
|
||||
c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw
|
||||
VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC
|
||||
ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz
|
||||
MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu
|
||||
Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF
|
||||
AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo
|
||||
uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/
|
||||
wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu
|
||||
X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG
|
||||
PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6
|
||||
KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==
|
||||
-----END CERTIFICATE-----
|
118
examples/protocols/esp-mqtt/wss/mqtt_wss_example_test.py
Normal file
118
examples/protocols/esp-mqtt/wss/mqtt_wss_example_test.py
Normal file
@ -0,0 +1,118 @@
|
||||
from __future__ import unicode_literals
|
||||
from __future__ import unicode_literals
|
||||
from builtins import str
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import ssl
|
||||
import paho.mqtt.client as mqtt
|
||||
from threading import Thread, Event
|
||||
|
||||
|
||||
try:
|
||||
import IDF
|
||||
except ImportError:
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
import IDF
|
||||
|
||||
import DUT
|
||||
|
||||
event_client_connected = Event()
|
||||
event_stop_client = Event()
|
||||
event_client_received_correct = Event()
|
||||
message_log = ""
|
||||
|
||||
|
||||
# The callback for when the client receives a CONNACK response from the server.
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print("Connected with result code " + str(rc))
|
||||
event_client_connected.set()
|
||||
client.subscribe("/topic/qos0")
|
||||
|
||||
|
||||
def mqtt_client_task(client):
|
||||
while not event_stop_client.is_set():
|
||||
client.loop()
|
||||
|
||||
|
||||
# The callback for when a PUBLISH message is received from the server.
|
||||
def on_message(client, userdata, msg):
|
||||
global message_log
|
||||
payload = msg.payload.decode()
|
||||
if not event_client_received_correct.is_set() and payload == "data":
|
||||
client.publish("/topic/qos0", "data_to_esp32")
|
||||
if msg.topic == "/topic/qos0" and payload == "data":
|
||||
event_client_received_correct.set()
|
||||
message_log += "Received data:" + msg.topic + " " + payload + "\n"
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_mqtt_wss(env, extra_data):
|
||||
broker_url = ""
|
||||
broker_port = 0
|
||||
"""
|
||||
steps: |
|
||||
1. join AP and connects to wss broker
|
||||
2. Test connects a client to the same broker
|
||||
3. Test evaluates it received correct qos0 message
|
||||
4. Test ESP32 client received correct qos0 message
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_websocket_secure", "examples/protocols/mqtt/wss")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_websocket_secure.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("mqtt_websocket_secure_bin_size", "{}KB".format(bin_size // 1024))
|
||||
IDF.check_performance("mqtt_websocket_secure_size", bin_size // 1024)
|
||||
# Look for host:port in sdkconfig
|
||||
try:
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
|
||||
broker_url = value.group(1)
|
||||
broker_port = int(value.group(2))
|
||||
except Exception:
|
||||
print('ENV_TEST_FAILURE: Cannot find broker url in sdkconfig')
|
||||
raise
|
||||
client = None
|
||||
# 1. Test connects to a broker
|
||||
try:
|
||||
client = mqtt.Client(transport="websockets")
|
||||
client.on_connect = on_connect
|
||||
client.on_message = on_message
|
||||
client.tls_set(None,
|
||||
None,
|
||||
None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1, ciphers=None)
|
||||
print("Connecting...")
|
||||
client.connect(broker_url, broker_port, 60)
|
||||
except Exception:
|
||||
print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
|
||||
raise
|
||||
# Starting a py-client in a separate thread
|
||||
thread1 = Thread(target=mqtt_client_task, args=(client,))
|
||||
thread1.start()
|
||||
try:
|
||||
print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
|
||||
if not event_client_connected.wait(timeout=30):
|
||||
raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
|
||||
dut1.start_app()
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
print('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
raise
|
||||
print("Checking py-client received msg published from esp...")
|
||||
if not event_client_received_correct.wait(timeout=30):
|
||||
raise ValueError('Wrong data received, msg log: {}'.format(message_log))
|
||||
print("Checking esp-client received msg published from py-client...")
|
||||
dut1.expect(re.compile(r"DATA=data_to_esp32"), timeout=30)
|
||||
finally:
|
||||
event_stop_client.set()
|
||||
thread1.join()
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_mqtt_wss()
|
3
examples/protocols/esp-mqtt/wss/sdkconfig.ci
Normal file
3
examples/protocols/esp-mqtt/wss/sdkconfig.ci
Normal file
@ -0,0 +1,3 @@
|
||||
CONFIG_BROKER_URI="wss://${EXAMPLE_MQTT_BROKER_WSS}/ws"
|
||||
CONFIG_BROKER_CERTIFICATE_OVERRIDE="${EXAMPLE_MQTT_BROKER_CERTIFICATE}"
|
||||
|
Reference in New Issue
Block a user