feat: refactor mqtt example

This commit is contained in:
Chen Wu
2018-12-14 17:03:21 +08:00
parent f73b6f0b6d
commit 4e03f7ba98
4 changed files with 241 additions and 240 deletions

View File

@ -7,162 +7,15 @@ This MQTT demo is based on the Eclipse Paho MQTT library, and demonstrates a wor
Also, this demo will ping the MQTT broker in the defined interval if no sending or receiving action happens. And we add some APIs to realize the SSL functionality, these SSL APIs provide the one-way certification and two-way certification.
## 2. Configuration
* export `IDF_PATH`
* `make menuconfig` -> `Example Configuration` to config your example
* `make menuconfig` -> `Component config` -> `MQTT(Paho)` -> to config your MQTT parameters
Some basic configurations need to be done before starting this demo and are listed in the include/user_config.h.
## 3. Compiling & Execution
* Wi-Fi SSID & Password
* MQTT Broker Address(can be a domain name) & MQTT Port
>Note: There is a publically accessible sandbox server for the Eclipse IoT projects available at iot.eclipse.org, please get some reference information from the website: https://iot.eclipse.org/getting-started
## 3. Description
### 3.1 MQTT-Normal
This section describes the mqtt informations and API for MQTT client without SSL functionality.
#### 3.1.1 MQTT Info
For this MQTT demo, mqtt-related informations are defined in the mqtt_client_thread(), and they are listed below.
* two buffers(i.e. sendbuf[80] & readbuf[80]) to store packets to be sent and received
* MQTTVersion, ClientID, KeepAliveInterval, etc are defined using **MQTTPacket_connectData_initializer**
* Command_timeout is defined as 30s, and you can use this value as default
* The subscribe topic is defined as "ESP8266/sample/sub"
* The subscribe message handler is "void messageArrived(MessageData* data)"
* The publish topic is defined as "ESP8266/sample/pub"
* The published message's QoS type is QoS2
These informarions are only defined as a demonstration, you can change them appropriately according to your own requirements.
#### 3.1.2 Major API
1.Platform-Related
* NetworkInit(): used to initialize **Network** structure, which includes read/write functions, etc.
* NetworkConnect(): used to create socket and connect to the MQTT broker
2.MQTT-Related
* MQTTClientInit(): used to initialize **MQTTClient** structure, which includes MQTT client information
* MQTTStartTask(): a task used to perform MQTT **keep alive**
* MQTTConnect(): used to perform MQTT connect
* MQTTSubscribe(): used to subscribe to a topic
* MQTTPublish(): used to publish messages to a topic
### 3.2 MQTT-SSL
This section describes the mqtt informations and API for MQTT client with SSL functionality enabled.
#### 3.2.1 MQTT Info
The aforementioned informations in the **MQTT Info** section of **MQTT-Normal** are also used for MQTT-SSL. As for SSL functionality, some more information will be needed and are listed below in the "Added-Info" section.
1.Existed-Info
This section is the same with the **MQTT Info** section of **MQTT-Normal**.
2.Added-Info
* May need header files of CA (and client certificate & key) included in the include/ directory
* May need length of the CA (and client certificate & key) files
* Need a **ssl_ca_crt_key_t** structure initialized using the CA (and client certificate & key) files
#### 3.2.2 Major API
When SSL is enabled, the Platform-related API are different with **MQTT-Normal** section.
1.Platform-related
* NetworkInitSSL(): used to initialize **Network** structure, which includes SSL read/write functions, etc.
* NetworkConnectSSL(): used to create socket and connect to the MQTT broker with SSL enabled
2.MQTT-Related
This section is the same with the "MQTT-Related" section of "MQTT-Normal".
#### 3.2.3 SSL Special
For SSL functionality, three certification ways may be used: no certification, one-way certification and two-way certification. The specific configurations for each of them are described below:
1.No Certification
* No CA file and client certificate & key files need to be included
* Define a **ssl_ca_crt_key_t** structure
* Set the **cacrt**, **cert** and **key** parameters within the structure to be **NULL**
* Recommend to set the **verify_mode** parameter to **SSL_VERIFY_NONE**
* Set the **method** parameter to **TLSv1_1_client_method()** or **TLSv1_2_client_method()**
* Set the **frag_len** parameter with a value between **2048** and **8192**
2.One-way Certification
* CA file shall be included, also length of the CA file shall be provided
* Define a **ssl_ca_crt_key_t** structure
* Set the **cacrt** parameter within the structure to the array in the CA file
* Set the **cacrt_len** parameter to length of the CA file
* Set the **verify_mode** parameter to **SSL_VERIFY_PEER**
* Set the **method** parameter to **TLSv1_1_client_method()** or **TLSv1_2_client_method()**
* Set the **frag_len** parameter with a value between **2048** and **8192**
3.Two-way Certification
* CA file and client certificate & key files shall be included
* Also length of the CA file and client certificate & key files shall be provided
* Define a **ssl_ca_crt_key_t** structure
* Set the **cacrt** parameter within the structure to the array in the CA file
* Set the **cacrt_len** parameter to length of the CA file
* Set the **cert** parameter within the structure to the array in the client certificate file
* Set the **cert_len** parameter to length of the client certificate file
* Set the **key** parameter within the structure to the array in the client key file
* Set the **key_len** parameter to length of the client key file
* Set the **verify_mode** parameter to **SSL_VERIFY_PEER**
* Set the **method** parameter to **TLSv1_1_client_method()** or **TLSv1_2_client_method()**
* Set the **frag_len** parameter with a value between **2048** and **8192**
>Note: two-way certification is decided by the SSL Server side, so on the client side we just provide all the files needed by the two-way certification.
#### 3.2.4 SSL Demo
The following shows a simple demo of the MQTT client SSL functionality, and only the different places compared with MQTT-Normal demo are displayed. The names of CA file, client certificate & key files are just a demonstration, changing these properly according to your own files.
```c
#include "openssl/ssl.h"
#include "CA.h"
#include "cert.h"
#include "key.h"
ssl_ca_crt_key_t ssl_cck;
#define SSL_CA_CERT_KEY_INIT(s,a,b,c,d,e,f) ((ssl_ca_crt_key_t *)s)->cacrt = a;\
((ssl_ca_crt_key_t *)s)->cacrt_len = b;\
((ssl_ca_crt_key_t *)s)->cert = c;\
((ssl_ca_crt_key_t *)s)->cert_len = d;\
((ssl_ca_crt_key_t *)s)->key = e;\
((ssl_ca_crt_key_t *)s)->key_len = f;
static void mqtt_client_thread(void *pvParameters)
{
......
NetworkInitSSL(&network);
......
SSL_CA_CERT_KEY_INIT(&ssl_cck, ca_crt, ca_crt_len, client_crt, client_crt_len, client_key, client_key_len);
if ((rc = NetworkConnectSSL(&network, address, MQTT_PORT, &ssl_cck, TLSv1_1_client_method(), SSL_VERIFY_NONE, 8192)) != 1) {
printf("Return code from network connect ssl is %d\n", rc);
}
......
}
```
## 4. Compiling & Execution
Once all the aforementioned works are done, we can compile and download the MQTT client (SSL) demo, and a few more steps will be needed.
* Export SDK_PATH & BIN_PATH, and run gen_misc.sh to compile and generate binary files
* Download the binary files to flash and run, also you can use UART console to watch the output log
All these being done, the MQTT client demo will:
Once all the aforementioned works are done, the MQTT client demo will:
* Connect to the MQTT Broker
* Subscribe to the topic "ESP8266/sample/sub"
* Publish messages to the topic "ESP8266/sample/pub" every 1 seconds
* MQTT keep alive interval is 60s, so if no sending and receiving actions happended during this interval, ping request will be sent and ping response is expected to be received.
* Subscribe to the topic "/espressif/sub"
* Publish messages to the topic "/espressif/pub"
* MQTT keep alive interval is 30s, so if no sending and receiving actions happended during this interval, ping request will be sent and ping response is expected to be received.

View File

@ -11,7 +11,83 @@ config WIFI_PASSWORD
default "mypassword"
help
WiFi password (WPA or WPA2) for the example to use.
Can be left blank if the network has no security set.
config MQTT_BROKER
string "MQTT broker"
default "mosquitto.org"
help
MQTT broker which you want to login, either IP address or domain name is OK.
config MQTT_PORT
int "Default MQTT port"
default 1883
help
MQTT port.
config MQTT_SUB_TOPIC
string "MQTT subscribe topic"
default "/espressif/sub"
help
MQTT subscribe topic to MQTT broker.
choice MQTT_SUB_QOS
prompt "MQTT Subscribe QoS"
default SUB_QOS1
help
MQTT subcribe QoS level.
config SUB_QOS0
bool "QOS0"
config SUB_QOS1
bool "QOS1"
config SUB_QOS2
bool "QOS2"
endchoice
config DEFAULT_MQTT_SUB_QOS
int
default 0 if SUB_QOS0
default 1 if SUB_QOS1
default 2 if SUB_QOS2
config MQTT_PUB_TOPIC
string "MQTT publish topic"
default "/espressif/pub"
help
MQTT publish topic to MQTT broker.
choice MQTT_PUB_QOS
prompt "MQTT publish QoS"
default PUB_QOS1
help
MQTT publish QoS level.
config PUB_QOS0
bool "QOS0"
config PUB_QOS1
bool "QOS1"
config PUB_QOS2
bool "QOS2"
endchoice
config DEFAULT_MQTT_PUB_QOS
int
default 0 if PUB_QOS0
default 1 if PUB_QOS1
default 2 if PUB_QOS2
config MQTT_PUBLISH_INTERVAL
int "MQTT publish interval(ms)"
default 0
help
Default MQTT publish message interval.
config MQTT_PAYLOAD_BUFFER
int "MQTT payload size(Bytes)"
default 1460
help
1460~2048 is recommended.
MQTT payload size.
endmenu

View File

@ -30,15 +30,6 @@
#include "MQTTClient.h"
/* The examples use simple WiFi configuration that you can set via
'make menuconfig'.
If you'd rather not, just change the below entries to strings with
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
*/
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
/* FreeRTOS event group to signal when we are connected & ready to make a request */
static EventGroupHandle_t wifi_event_group;
@ -47,33 +38,34 @@ static EventGroupHandle_t wifi_event_group;
to the AP with an IP? */
const int CONNECTED_BIT = BIT0;
#define MQTT_BROKER "iot.eclipse.org" /* MQTT Broker Address*/
#define MQTT_PORT 1883 /* MQTT Port*/
#define MQTT_CLIENT_THREAD_NAME "mqtt_client_thread"
#define MQTT_CLIENT_THREAD_STACK_WORDS 8192
#define MQTT_CLIENT_THREAD_STACK_WORDS 4096
#define MQTT_CLIENT_THREAD_PRIO 8
static const char *TAG = "example";
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
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:
/* This is a workaround as ESP32 WiFi libs don't currently
auto-reassociate. */
esp_wifi_connect();
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
break;
default:
break;
}
return ESP_OK;
}
@ -81,110 +73,171 @@ static void initialise_wifi(void)
{
tcpip_adapter_init();
wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) );
ESP_ERROR_CHECK(esp_event_loop_init(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) );
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
wifi_config_t wifi_config = {
.sta = {
.ssid = EXAMPLE_WIFI_SSID,
.password = EXAMPLE_WIFI_PASS,
.ssid = CONFIG_WIFI_SSID,
.password = CONFIG_WIFI_PASSWORD,
},
};
ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
ESP_ERROR_CHECK( esp_wifi_start() );
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
}
static void messageArrived(MessageData* data)
static void messageArrived(MessageData *data)
{
printf("Message arrived: %s\n", (char*)data->message->payload);
ESP_LOGI(TAG, "Message arrived[len:%u]: %.*s", \
data->message->payloadlen, data->message->payloadlen, (char *)data->message->payload);
}
static void mqtt_client_thread(void* pvParameters)
static void mqtt_client_thread(void *pvParameters)
{
char *payload = NULL;
MQTTClient client;
Network network;
unsigned char sendbuf[80], readbuf[80] = {0};
int rc = 0, count = 0;
int rc = 0;
char clientID[32] = {0};
uint32_t count = 0;
ESP_LOGI(TAG, "ssid:%s passwd:%s sub:%s qos:%u pub:%s qos:%u pubinterval:%u payloadsize:%u",
CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD, CONFIG_MQTT_SUB_TOPIC,
CONFIG_DEFAULT_MQTT_SUB_QOS, CONFIG_MQTT_PUB_TOPIC, CONFIG_DEFAULT_MQTT_PUB_QOS,
CONFIG_MQTT_PUBLISH_INTERVAL, CONFIG_MQTT_PAYLOAD_BUFFER);
ESP_LOGI(TAG, "ver:%u clientID:%s keepalive:%d username:%s passwd:%s session:%d level:%u",
CONFIG_DEFAULT_MQTT_VERSION, CONFIG_MQTT_CLIENT_ID,
CONFIG_MQTT_KEEP_ALIVE, CONFIG_MQTT_USERNAME, CONFIG_MQTT_PASSWORD,
CONFIG_DEFAULT_MQTT_SESSION, CONFIG_DEFAULT_MQTT_SECURITY);
ESP_LOGI(TAG, "broker:%s port:%u", CONFIG_MQTT_BROKER, CONFIG_MQTT_PORT);
ESP_LOGI(TAG, "sendbuf:%u recvbuf:%u sendcycle:%u recvcycle:%u",
CONFIG_MQTT_SEND_BUFFER, CONFIG_MQTT_RECV_BUFFER,
CONFIG_MQTT_SEND_CYCLE, CONFIG_MQTT_RECV_CYCLE);
MQTTPacket_connectData connectData = MQTTPacket_connectData_initializer;
printf("mqtt client thread starts\n");
/* Wait for the callback to set the CONNECTED_BIT in the
event group.
*/
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
false, true, portMAX_DELAY);
ESP_LOGI(TAG, "Connected to AP");
NetworkInit(&network);
MQTTClientInit(&client, &network, 30000, sendbuf, sizeof(sendbuf), readbuf, sizeof(readbuf));
char* address = MQTT_BROKER;
if ((rc = NetworkConnect(&network, address, MQTT_PORT)) != 0) {
printf("Return code from network connect is %d\n", rc);
if (MQTTClientInit(&client, &network, 0, NULL, 0, NULL, 0) == false) {
ESP_LOGE(TAG, "mqtt init err");
vTaskDelete(NULL);
}
payload = malloc(CONFIG_MQTT_PAYLOAD_BUFFER);
if (!payload) {
ESP_LOGE(TAG, "mqtt malloc err");
} else {
memset(payload, 0x0, CONFIG_MQTT_PAYLOAD_BUFFER);
}
for (;;) {
ESP_LOGI(TAG, "wait wifi connect...");
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
if ((rc = NetworkConnect(&network, CONFIG_MQTT_BROKER, CONFIG_MQTT_PORT)) != 0) {
ESP_LOGE(TAG, "Return code from network connect is %d", rc);
continue;
}
connectData.MQTTVersion = CONFIG_DEFAULT_MQTT_VERSION;
sprintf(clientID, "%s_%u", CONFIG_MQTT_CLIENT_ID, esp_random());
connectData.clientID.cstring = clientID;
connectData.keepAliveInterval = CONFIG_MQTT_KEEP_ALIVE;
connectData.username.cstring = CONFIG_MQTT_USERNAME;
connectData.password.cstring = CONFIG_MQTT_PASSWORD;
connectData.cleansession = CONFIG_DEFAULT_MQTT_SESSION;
ESP_LOGI(TAG, "MQTT Connecting");
if ((rc = MQTTConnect(&client, &connectData)) != 0) {
ESP_LOGE(TAG, "Return code from MQTT connect is %d", rc);
network.disconnect(&network);
continue;
}
ESP_LOGI(TAG, "MQTT Connected");
#if defined(MQTT_TASK)
if ((rc = MQTTStartTask(&client)) != pdPASS) {
printf("Return code from start tasks is %d\n", rc);
} else {
printf("Use MQTTStartTask\n");
}
if ((rc = MQTTStartTask(&client)) != pdPASS) {
ESP_LOGE(TAG, "Return code from start tasks is %d", rc);
} else {
ESP_LOGI(TAG, "Use MQTTStartTask");
}
#endif
connectData.MQTTVersion = 3;
connectData.clientID.cstring = "ESP8266_sample";
if ((rc = MQTTConnect(&client, &connectData)) != 0) {
printf("Return code from MQTT connect is %d\n", rc);
} else {
printf("MQTT Connected\n");
}
if ((rc = MQTTSubscribe(&client, "ESP8266/sample/sub", 2, messageArrived)) != 0) {
printf("Return code from MQTT subscribe is %d\n", rc);
} else {
printf("MQTT subscribe to topic \"ESP8266/sample/sub\"\n");
}
while (++count) {
MQTTMessage message;
char payload[30];
message.qos = QOS2;
message.retained = 0;
message.payload = payload;
sprintf(payload, "message number %d", count);
message.payloadlen = strlen(payload);
if ((rc = MQTTPublish(&client, "ESP8266/sample/pub", &message)) != 0) {
printf("Return code from MQTT publish is %d\n", rc);
} else {
printf("MQTT publish topic \"ESP8266/sample/pub\", message number is %d\n", count);
if ((rc = MQTTSubscribe(&client, CONFIG_MQTT_SUB_TOPIC, CONFIG_DEFAULT_MQTT_SUB_QOS, messageArrived)) != 0) {
ESP_LOGE(TAG, "Return code from MQTT subscribe is %d", rc);
network.disconnect(&network);
continue;
}
vTaskDelay(1000 / portTICK_RATE_MS); //send every 1 seconds
ESP_LOGI(TAG, "MQTT subscribe to topic %s OK", CONFIG_MQTT_PUB_TOPIC);
for (;;) {
MQTTMessage message;
message.qos = CONFIG_DEFAULT_MQTT_PUB_QOS;
message.retained = 0;
message.payload = payload;
sprintf(payload, "message number %d", ++count);
message.payloadlen = strlen(payload);
if ((rc = MQTTPublish(&client, CONFIG_MQTT_PUB_TOPIC, &message)) != 0) {
ESP_LOGE(TAG, "Return code from MQTT publish is %d", rc);
} else {
ESP_LOGI(TAG, "MQTT published topic %s, len:%u heap:%u", CONFIG_MQTT_PUB_TOPIC, message.payloadlen, esp_get_free_heap_size());
}
if (rc != 0) {
break;
}
vTaskDelay(CONFIG_MQTT_PUBLISH_INTERVAL / portTICK_RATE_MS);
}
network.disconnect(&network);
}
printf("mqtt_client_thread going to be deleted\n");
ESP_LOGW(TAG, "mqtt_client_thread going to be deleted");
vTaskDelete(NULL);
return;
}
void app_main(void)
{
ESP_ERROR_CHECK( nvs_flash_init() );
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
initialise_wifi();
xTaskCreate(&mqtt_client_thread,
MQTT_CLIENT_THREAD_NAME,
MQTT_CLIENT_THREAD_STACK_WORDS,
NULL,
MQTT_CLIENT_THREAD_PRIO,
NULL);
ret = xTaskCreate(&mqtt_client_thread,
MQTT_CLIENT_THREAD_NAME,
MQTT_CLIENT_THREAD_STACK_WORDS,
NULL,
MQTT_CLIENT_THREAD_PRIO,
NULL);
if (ret != pdPASS) {
ESP_LOGE(TAG, "mqtt create client thread %s failed", MQTT_CLIENT_THREAD_NAME);
}
}

View File

@ -0,0 +1,19 @@
#
# Example Configuration
#
CONFIG_MQTT_PUBLISH_INTERVAL=0
#
# ECLIPSE-MQTT
#
CONFIG_MQTT_KEEP_ALIVE=30
CONFIG_CLEAN_SESSION=y
CONFIG_KEEP_SESSION=
CONFIG_DEFAULT_MQTT_CLEAN_SESSION=1
CONFIG_NO_TLS=y
CONFIG_DEFAULT_MQTT_SECURITY=0
CONFIG_MQTT_SEND_BUFFER=2048
CONFIG_MQTT_RECV_BUFFER=2048
CONFIG_MQTT_SEND_CYCLE=30000
CONFIG_MQTT_RECV_CYCLE=0