MQTT to SQL Server bridge¶
Keep your MQTT devices as they are, and get their history into SQL Server: an ESP32 subscribes to the topics, and stores each message in a table. It replaces the PC that usually does this with Node-RED, Telegraf or a script. SQL Server's JSON functions then pull the values out of the payloads.
You need: an ESP32 or ESP8266, an MQTT broker (e.g. Mosquitto), and SQL Server 2016 or later on the same network.
Set up the database¶
Run setup.sql in your database. It creates the table, the procedure that stores a message, and a login that may only call that procedure:
CREATE TABLE dbo.mqtt_messages (
id BIGINT IDENTITY PRIMARY KEY,
topic VARCHAR(128) NOT NULL,
payload VARCHAR(512) NOT NULL,
received_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME()
);
CREATE INDEX ix_mqtt_messages_topic ON dbo.mqtt_messages (topic, received_at);
GO
CREATE PROCEDURE dbo.store_message
@topic VARCHAR(128),
@payload VARCHAR(512)
AS
INSERT INTO dbo.mqtt_messages (topic, payload) VALUES (@topic, @payload);
GO
-- The bridge may only store messages. Run CREATE LOGIN in master.
CREATE LOGIN mqtt_bridge WITH PASSWORD = '<a long random password>';
CREATE USER mqtt_bridge FOR LOGIN mqtt_bridge;
GRANT EXECUTE ON dbo.store_message TO mqtt_bridge;
GO
Configure the sketch¶
Install the PubSubClient library (by Nick O'Leary), open mqtt_sql_bridge.ino, and fill in the settings:
static const char * wifi_ssid = "<your Wi-Fi name>";
static const char * wifi_password = "<your Wi-Fi password>";
static const char * mqtt_broker = "192.168.1.20";
static const uint16_t mqtt_port = 1883;
static const char * mqtt_user = nullptr; // or "<user>"
static const char * mqtt_password = nullptr; // or "<password>"
static const char * mqtt_topic = "tele/+/SENSOR"; // Tasmota; or e.g. "sensors/#"
static const char db_server [] = "192.168.1.10";
static const char db_name [] = "home";
static const char db_user [] = "mqtt_bridge";
static const char db_password [] = "<password>";
mqtt_topic takes MQTT wildcards: + for one level, # for the rest. The
default, tele/+/SENSOR, gets the sensor readings of every Tasmota device.
For ESPHome, use e.g. esphome/# or your devices' topic prefix.
With PlatformIO, add the library to lib_deps:
How it works¶
The MQTT callback runs inside mqtt.loop(). A database round trip there
would hold up the MQTT client, so the callback only copies the message into
a queue:
// Messages wait here until loop() stores them. The MQTT callback only
// copies: a database round trip inside it would hold up the MQTT client.
struct message {
char topic [128];
char payload [512];
unsigned int payload_size;
};
static constexpr int queue_capacity = 8;
static message queue [queue_capacity];
static int queue_head = 0, queue_count = 0;
static unsigned long dropped = 0;
static void on_mqtt_message(char * topic, uint8_t * payload, unsigned int size) {
if (queue_count == queue_capacity || strlen(topic) >= sizeof(message::topic) ||
size > sizeof(message::payload)) {
dropped++;
return;
}
message & m = queue [(queue_head + queue_count) % queue_capacity];
strcpy(m.topic, topic);
memcpy(m.payload, payload, size);
m.payload_size = size;
queue_count++;
}
loop() stores one queued message per pass. A message that can't be stored
stays in the queue, and is tried again:
void loop() {
if (not mqtt.connected()) {
connect_mqtt();
}
mqtt.loop();
// Store one message per pass, so the MQTT client gets its turn
if (queue_count > 0) {
const message & m = queue [queue_head];
if (store(m)) {
queue_head = (queue_head + 1) % queue_capacity;
queue_count--;
} else {
// Kept in the queue; try again shortly
delay(1000);
}
}
static unsigned long last_report = 0;
if (dropped > 0 && millis() - last_report > 60000) {
last_report = millis();
Serial.printf("%lu message(s) dropped: queue full or message too large\n", dropped);
}
}
Storing binds the topic and the payload as varchar parameters that point
at the queued message, and reconnects once if the connection dropped:
static bool store(const message & m) {
// The parameters point at the message; nothing is copied
tdsl::sql_parameter_varchar topic{tdsl::string_view{m.topic, strlen(m.topic)}};
tdsl::sql_parameter_varchar payload{tdsl::string_view{m.payload, m.payload_size}};
tdsl::sql_parameter_binding params []{topic, payload};
for (int attempt = 0; attempt < 2; attempt++) {
const auto result = driver.execute_rpc(
tdsl::string_view{"EXEC dbo.store_message @topic = @p0, @payload = @p1"}, params);
if (result) {
return true;
}
if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) ||
not connect_to_db()) {
return false;
}
}
return false;
}
Messages larger than 512 bytes, and messages that arrive while the queue is
full, are dropped and counted; the sketch reports the count every minute.
For larger payloads, raise the sizes in struct message and in the table,
and keep an eye on the RAM: each queued message takes about 650 bytes.
Read the messages¶
The payloads are stored as they arrived. SQL Server's JSON_VALUE reads
values out of them; these examples use Tasmota's SENSOR messages, so adjust
the JSON paths for your devices. More in
queries.sql.
The latest message of each topic:
-- The latest message of each topic
SELECT topic, payload, received_at
FROM (
SELECT topic, payload, received_at,
ROW_NUMBER() OVER (PARTITION BY topic ORDER BY received_at DESC, id DESC) AS n
FROM dbo.mqtt_messages
) AS m
WHERE n = 1;
The values, with the device name taken from the topic:
-- Values out of the JSON payloads, one row per message
SELECT PARSENAME(REPLACE(topic, '/', '.'), 2) AS device,
CAST(JSON_VALUE(payload, '$.AM2301.Temperature') AS REAL) AS temperature,
CAST(JSON_VALUE(payload, '$.AM2301.Humidity') AS REAL) AS humidity,
received_at
FROM dbo.mqtt_messages
WHERE topic LIKE 'tele/%/SENSOR' AND ISJSON(payload) = 1;
Hourly averages:
-- Hourly average temperature per device, over the last day
SELECT PARSENAME(REPLACE(topic, '/', '.'), 2) AS device,
DATEADD(HOUR, DATEDIFF(HOUR, 0, received_at), 0) AS hour,
AVG(CAST(JSON_VALUE(payload, '$.AM2301.Temperature') AS REAL)) AS temperature
FROM dbo.mqtt_messages
WHERE topic LIKE 'tele/%/SENSOR' AND ISJSON(payload) = 1
AND received_at > DATEADD(DAY, -1, SYSUTCDATETIME())
GROUP BY PARSENAME(REPLACE(topic, '/', '.'), 2), DATEADD(HOUR, DATEDIFF(HOUR, 0, received_at), 0)
ORDER BY device, hour;
The table grows with every message. Delete old ones from time to time, e.g. with a SQL Server Agent job:
-- Delete messages older than 90 days (e.g. from a SQL Server Agent job)
DELETE FROM dbo.mqtt_messages WHERE received_at < DATEADD(DAY, -90, SYSUTCDATETIME());
The complete sketch¶
mqtt_sql_bridge.ino
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#else
#error "This sketch is for the ESP32 and the ESP8266"
#endif
#include <PubSubClient.h>
#include <tdslite.h>
static const char * wifi_ssid = "<your Wi-Fi name>";
static const char * wifi_password = "<your Wi-Fi password>";
static const char * mqtt_broker = "192.168.1.20";
static const uint16_t mqtt_port = 1883;
static const char * mqtt_user = nullptr; // or "<user>"
static const char * mqtt_password = nullptr; // or "<password>"
static const char * mqtt_topic = "tele/+/SENSOR"; // Tasmota; or e.g. "sensors/#"
static const char db_server [] = "192.168.1.10";
static const char db_name [] = "home";
static const char db_user [] = "mqtt_bridge";
static const char db_password [] = "<password>";
static tdsl::uint8_t net_buf [2048] = {};
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
static WiFiClient mqtt_net;
static PubSubClient mqtt{mqtt_net};
// Messages wait here until loop() stores them. The MQTT callback only
// copies: a database round trip inside it would hold up the MQTT client.
struct message {
char topic [128];
char payload [512];
unsigned int payload_size;
};
static constexpr int queue_capacity = 8;
static message queue [queue_capacity];
static int queue_head = 0, queue_count = 0;
static unsigned long dropped = 0;
static void on_mqtt_message(char * topic, uint8_t * payload, unsigned int size) {
if (queue_count == queue_capacity || strlen(topic) >= sizeof(message::topic) ||
size > sizeof(message::payload)) {
dropped++;
return;
}
message & m = queue [(queue_head + queue_count) % queue_capacity];
strcpy(m.topic, topic);
memcpy(m.payload, payload, size);
m.payload_size = size;
queue_count++;
}
static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
if (not token.is_error()) {
return;
}
Serial.print("SQL Server error: ");
for (const char16_t c : token.msgtext) {
Serial.print(static_cast<char>(c));
}
Serial.println();
}
static bool connect_to_db() {
decltype(driver)::connection_parameters params;
params.server_name = db_server;
params.db_name = db_name;
params.user_name = db_user;
params.password = db_password;
params.app_name = "mqtt-sql-bridge";
params.packet_size = 1024;
return driver.connect(params) == decltype(driver)::e_driver_error_code::success;
}
static bool store(const message & m) {
// The parameters point at the message; nothing is copied
tdsl::sql_parameter_varchar topic{tdsl::string_view{m.topic, strlen(m.topic)}};
tdsl::sql_parameter_varchar payload{tdsl::string_view{m.payload, m.payload_size}};
tdsl::sql_parameter_binding params []{topic, payload};
for (int attempt = 0; attempt < 2; attempt++) {
const auto result = driver.execute_rpc(
tdsl::string_view{"EXEC dbo.store_message @topic = @p0, @payload = @p1"}, params);
if (result) {
return true;
}
if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) ||
not connect_to_db()) {
return false;
}
}
return false;
}
static void connect_mqtt() {
String client_id = "tdslite-bridge-" + String(WiFi.macAddress());
while (not mqtt.connected()) {
if (mqtt.connect(client_id.c_str(), mqtt_user, mqtt_password)) {
mqtt.subscribe(mqtt_topic);
Serial.printf("MQTT: subscribed to %s\n", mqtt_topic);
} else {
Serial.printf("MQTT: connect failed (%d), retrying\n", mqtt.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
driver.set_info_callback(print_message);
while (not connect_to_db()) {
Serial.println("SQL Server: connect failed, retrying");
delay(5000);
}
mqtt.setServer(mqtt_broker, mqtt_port);
// PubSubClient's default buffer (256 bytes) is too small for many
// JSON payloads; it holds the topic and the payload
mqtt.setBufferSize(sizeof(message::topic) + sizeof(message::payload) + 16);
mqtt.setCallback(on_mqtt_message);
connect_mqtt();
}
void loop() {
if (not mqtt.connected()) {
connect_mqtt();
}
mqtt.loop();
// Store one message per pass, so the MQTT client gets its turn
if (queue_count > 0) {
const message & m = queue [queue_head];
if (store(m)) {
queue_head = (queue_head + 1) % queue_capacity;
queue_count--;
} else {
// Kept in the queue; try again shortly
delay(1000);
}
}
static unsigned long last_report = 0;
if (dropped > 0 && millis() - last_report > 60000) {
last_report = millis();
Serial.printf("%lu message(s) dropped: queue full or message too large\n", dropped);
}
}
Going further¶
- Store only what you need: subscribe to specific topics, or filter in
on_mqtt_message, rather than storing everything. - Parse on the device: if your devices send plain numbers, add columns for them and a procedure that takes numbers, instead of storing text.
- Encrypt: for a broker or a SQL Server outside your network, use TLS on both connections; see Connect with TLS.
Related¶
- Log sensor readings: the same reconnect logic, without MQTT
- Call a stored procedure
- Direct connections and gateways