Index
In IoT applications, HTTP and MQTT are two popular protocols for communication with cloud servers or other networked devices. Here’s an example using ESP-IDF and FreeRTOS to demonstrate how to set up and use both protocols.
- HTTP: Used for web-based communication where the ESP32 can act as a client to make GET or POST requests.
- MQTT: A lightweight messaging protocol ideal for IoT, where the ESP32 can publish messages to a broker or subscribe to topics for message updates.
Example: HTTP GET Request and MQTT Communication
In this example, we’ll set up:
- A HTTP GET request task to fetch data from a server endpoint.
- An MQTT client task to publish and subscribe to topics for message exchange.
Setup
- Update
WIFI_SSID
andWIFI_PASS
with your Wi-Fi credentials. - For HTTP, set
HTTP_URL
to a public HTTP endpoint (e.g.,http://jsonplaceholder.typicode.com/posts/1
). - For MQTT, provide an MQTT broker address (e.g.,
mqtt://broker.hivemq.com
).
Code Example
In IoT applications, HTTP and MQTT are two popular protocols for communication with cloud servers or other networked devices. Here’s an example using ESP-IDF and FreeRTOS to demonstrate how to set up and use both protocols.
- HTTP: Used for web-based communication where the ESP32 can act as a client to make GET or POST requests.
- MQTT: A lightweight messaging protocol ideal for IoT, where the ESP32 can publish messages to a broker or subscribe to topics for message updates.
Example: HTTP GET Request and MQTT Communication
In this example, we’ll set up:
- A HTTP GET request task to fetch data from a server endpoint.
- An MQTT client task to publish and subscribe to topics for message exchange.
Setup
- Update
WIFI_SSID
andWIFI_PASS
with your Wi-Fi credentials. - For HTTP, set
HTTP_URL
to a public HTTP endpoint (e.g.,http://jsonplaceholder.typicode.com/posts/1
). - For MQTT, provide an MQTT broker address (e.g.,
mqtt://broker.hivemq.com
).
Code Example
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_client.h"
#include "mqtt_client.h"
#define WIFI_SSID "your_ssid"
#define WIFI_PASS "your_password"
#define HTTP_URL "http://jsonplaceholder.typicode.com/posts/1" // Replace with your endpoint
#define MQTT_BROKER_URI "mqtt://broker.hivemq.com" // Public MQTT broker
static const char *TAG_HTTP = "HTTP_CLIENT";
static const char *TAG_MQTT = "MQTT_CLIENT";
// Wi-Fi Event Handler
static void wifi_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
ESP_LOGI("Wi-Fi", "Reconnecting to Wi-Fi...");
esp_wifi_connect();
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ESP_LOGI("Wi-Fi", "Connected with IP");
}
}
void wifi_init_sta() {
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
wifi_config_t wifi_config = {
.sta = {
.ssid = WIFI_SSID,
.password = WIFI_PASS,
},
};
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());
}
// HTTP GET Request Task
void http_get_task(void *pvParameters) {
esp_http_client_config_t config = {
.url = HTTP_URL,
};
esp_http_client_handle_t client = esp_http_client_init(&config);
while (1) {
esp_http_client_perform(client); // Initiate GET request
ESP_LOGI(TAG_HTTP, "HTTP GET Request to %s", HTTP_URL);
char buffer[512];
int content_length = esp_http_client_get_content_length(client);
esp_http_client_read(client, buffer, content_length);
ESP_LOGI(TAG_HTTP, "Response: %s", buffer);
vTaskDelay(pdMS_TO_TICKS(10000)); // Delay between requests
}
esp_http_client_cleanup(client);
}
// MQTT Event Handler
static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
switch (event->event_id) {
case MQTT_EVENT_CONNECTED:
esp_mqtt_client_subscribe(event->client, "/example/topic", 0);
esp_mqtt_client_publish(event->client, "/example/topic", "Hello MQTT", 0, 0, 0);
break;
case MQTT_EVENT_DATA:
ESP_LOGI(TAG_MQTT, "Received topic: %.*s, data: %.*s",
event->topic_len, event->topic, event->data_len, event->data);
break;
default:
break;
}
return ESP_OK;
}
// MQTT Client Task
void mqtt_client_task(void *pvParameters) {
esp_mqtt_client_config_t mqtt_cfg = {
.uri = MQTT_BROKER_URI,
.event_handle = mqtt_event_handler_cb,
};
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_start(client);
while (1) {
esp_mqtt_client_publish(client, "/example/topic", "Hello from ESP32", 0, 0, 0);
vTaskDelay(pdMS_TO_TICKS(5000)); // Publish message every 5 seconds
}
}
void app_main() {
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
wifi_init_sta();
// Create tasks for HTTP and MQTT communication
xTaskCreate(http_get_task, "http_get_task", 4096, NULL, 5, NULL);
xTaskCreate(mqtt_client_task, "mqtt_client_task", 4096, NULL, 5, NULL);
}
Explanation
- Wi-Fi Setup:
- The
wifi_init_sta()
function sets up the Wi-Fi station, configures it with SSID and password, and connects to the network. wifi_event_handler()
manages connection and disconnection events.
- The
- HTTP Client Task:
- The
http_get_task()
function initializes an HTTP client, sets up the URL, and performs a GET request to retrieve data. - It reads the server response and logs it, repeating every 10 seconds.
- The
- MQTT Client Task:
mqtt_client_task()
initializes the MQTT client with the specified broker URI and starts it.- On connection, it subscribes to
/example/topic
and publishes “Hello MQTT” to the same topic. - The MQTT event handler logs received messages and topics.
- Event Handling:
- The
mqtt_event_handler_cb()
handles MQTT events, including logging data received from the subscribed topic.
- The
Key Concepts
- HTTP and MQTT Protocols: ESP-IDF’s libraries for HTTP and MQTT simplify complex protocol handling.
- Task-Based Operation: Each protocol runs in its own FreeRTOS task, allowing parallel execution.
- Event-Driven: Both protocols rely on event callbacks for connection and data handling, making the system efficient.
- Network Integration with FreeRTOS: Wi-Fi, HTTP, and MQTT integration within FreeRTOS tasks allow complex IoT applications with reliable communication.
Example Output
The output should look like this in the ESP32’s serial monitor:
I (2000) Wi-Fi: Connected with IP
I (3000) HTTP_CLIENT: HTTP GET Request to http://jsonplaceholder.typicode.com/posts/1
I (3000) HTTP_CLIENT: Response: {"userId":1,"id":1,"title":"Sample Title","body":"Sample Body"}
I (4000) MQTT_CLIENT: MQTT_EVENT_CONNECTED
I (4000) MQTT_CLIENT: Sent topic: /example/topic, data: Hello MQTT
I (9000) MQTT_CLIENT: Received topic: /example/topic, data: Hello from ESP32
This example shows how to set up HTTP and MQTT communication using FreeRTOS tasks in ESP-IDF, enabling both types of data exchange for versatile IoT applications.