Using an ESP32 with ESP-IDF to push data into a InfluxDB using HTTP or HTTPS
Date: December 26, 2022
Pusing data into a InfluxDB using HTTP or HTTPS is straight forward using the ESP-IDF framework.
#include <esp_http_client.h>
#define INFLUXDB_HOST "192.168.1.1"
#define INFLUXDB_PORT "8086"
#define INFLUXDB_USERNAME "influxuser"
#define INFLUXDB_PASSWORD "influxpassword"
#define INFLUXDB_DATABASE "database"
(...)
esp_http_client_config_t config = {
.url = "http://" INFLUXDB_HOST ":" INFLUXDB_PORT "/write?db=" INFLUXDB_DATABASE,
.auth_type = HTTP_AUTH_TYPE_BASIC,
.username = INFLUXDB_USERNAME,
.password = INFLUXDB_PASSWORD,
};
esp_http_client_handle_t client = esp_http_client_init(&config);
(...)
char data[128];
snprintf(data, sizeof(data), "balcony_sensor temperature=%f,humidity=%f,co2=%u,pressure=%llu", str, temperature, humidity, co2, pressure);
esp_http_client_set_method(client, HTTP_METHOD_POST);
esp_http_client_set_post_field(client, data, strlen(data));
esp_err_t err = esp_http_client_perform(client);
if (err == ESP_OK)
{
ESP_LOGI(TAG, "Data sent to InfluxDB successfully");
}
else
{
ESP_LOGE(TAG, "Error sending data to InfluxDB: %s", esp_err_to_name(err));
}
If you want to use TLS you have to add and modify a few things
esp_http_client_config_t config = {
.url = "https://" INFLUXDB_HOST ":" INFLUXDB_PORT "/write?db=" INFLUXDB_DATABASE,
.auth_type = HTTP_AUTH_TYPE_BASIC,
.username = INFLUXDB_USERNAME,
.password = INFLUXDB_PASSWORD,
.transport_type = HTTP_TRANSPORT_OVER_SSL,
};