Skip to content

Log sensor readings to SQL Server

Send a reading to SQL Server every few seconds: the table, a login that may only insert, the insert itself, and reconnecting when the connection drops. The sketch is for an ESP32. For an ESP8266, include ESP8266WiFi.h in place of WiFi.h; for other boards, see Install the library and the Arduino tutorial.

Create the table and a login

Let the server set the time of each reading: the device then needs no clock, and every reading uses the same one.

CREATE DATABASE sensors;
GO
USE sensors;
CREATE TABLE dbo.readings (
    id          INT IDENTITY PRIMARY KEY,
    device      VARCHAR(32) NOT NULL,
    temperature REAL        NOT NULL,
    humidity    REAL        NOT NULL,
    recorded_at DATETIME2   NOT NULL DEFAULT SYSUTCDATETIME()
);

Give the devices a login of their own that can insert into this table and nothing else. Anyone with the device can read the password from its flash, so don't use sa or your own login:

CREATE LOGIN logger WITH PASSWORD = '<a long random password>';
CREATE USER logger FOR LOGIN logger;
GRANT INSERT ON dbo.readings TO logger;

Direct connections and gateways explains what else to consider before putting a database login on a device.

Connect

Set the database in the connection parameters, so the inserts don't depend on the login's default database. app_name names the device in sys.dm_exec_sessions, which helps when several devices log to one server:

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            = device_name; // shows up in sys.dm_exec_sessions
    params.conn_retry_count    = 3;
    params.conn_retry_delay_ms = 2000;
    return driver.connect(params) == decltype(driver)::e_driver_error_code::success;
}

Insert a reading

Use a parameterized INSERT. Bind the parameters once; execute_rpc reads their current values each time, so set them and send again:

// Bound once: execute_rpc reads the parameters' current values
static tdsl::sql_parameter_varchar device{device_name};
static tdsl::sql_parameter_float4 temperature{};
static tdsl::sql_parameter_float4 humidity{};
static tdsl::sql_parameter_binding parameters []{device, temperature, humidity};

static bool log_reading(const reading & r) {
    temperature = r.temperature;
    humidity    = r.humidity;
    for (int attempt = 0; attempt < 2; attempt++) {
        const auto result = driver.execute_rpc(
            tdsl::string_view{"INSERT INTO dbo.readings (device, temperature, humidity) "
                              "VALUES (@p0, @p1, @p2)"},
            parameters);
        if (result) {
            return true;
        }
        // A server error (e.g. a constraint) won't go away by retrying;
        // the message went to print_message
        if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error)) {
            return false;
        }
        // The connection dropped (server restart, Wi-Fi, idle timeout):
        // connect() starts a new session on the same driver
        Serial.println("Connection lost, reconnecting");
        if (not connect_to_db()) {
            return false;
        }
    }
    return false;
}

REAL columns take sql_parameter_float4. For other column types, see the parameter types in Data types.

Reconnect when the connection drops

Connections drop: the server restarts, Wi-Fi goes away for a while, a firewall closes idle connections. A request on a dropped connection fails with network_error, and calling connect again starts a new session on the same driver. log_reading above does that, then sends the reading once more.

Retry only on network_error. A server_error (e.g. a value that breaks a constraint, or a missing permission) fails the same way every time, and its message went to the info callback. With network_error, the server may still have run the insert before the connection broke, so a retry can, rarely, store a reading twice. If that matters, send a reading ID from the device and make it unique in the table.

Send it every 30 seconds

Use millis() rather than delay(), so the loop is free for other work:

void loop() {
    static unsigned long last = 0;
    if (last != 0 && millis() - last < 30000) {
        return;
    }
    last = millis();

    const reading r = read_sensor();
    Serial.printf("%.2f C, %.2f %% -> %s\n", r.temperature, r.humidity,
                  log_reading(r) ? "logged" : "not logged");
}

read_sensor() is a stand-in; replace it with your sensor library's code:

struct reading {
    float temperature;
    float humidity;
};

// Replace with your sensor's code (DHT22, BME280, ...)
static reading read_sensor() {
    return {21.5f, 40.25f};
}

The complete sketch

CI builds it for esp32dev.

sensor-logging.ino
#include <WiFi.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 db_server []    = "192.168.1.10";
static const char db_name []      = "sensors";
static const char db_user []      = "logger";
static const char db_password []  = "<password>";
static const char device_name []  = "greenhouse-1";

static tdsl::uint8_t net_buf [4096] = {};
static tdsl::arduino_driver<WiFiClient> driver{net_buf};

struct reading {
    float temperature;
    float humidity;
};

// Replace with your sensor's code (DHT22, BME280, ...)
static reading read_sensor() {
    return {21.5f, 40.25f};
}

static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
    Serial.print(token.is_error() ? "server error: " : "server info: ");
    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            = device_name; // shows up in sys.dm_exec_sessions
    params.conn_retry_count    = 3;
    params.conn_retry_delay_ms = 2000;
    return driver.connect(params) == decltype(driver)::e_driver_error_code::success;
}

// Bound once: execute_rpc reads the parameters' current values
static tdsl::sql_parameter_varchar device{device_name};
static tdsl::sql_parameter_float4 temperature{};
static tdsl::sql_parameter_float4 humidity{};
static tdsl::sql_parameter_binding parameters []{device, temperature, humidity};

static bool log_reading(const reading & r) {
    temperature = r.temperature;
    humidity    = r.humidity;
    for (int attempt = 0; attempt < 2; attempt++) {
        const auto result = driver.execute_rpc(
            tdsl::string_view{"INSERT INTO dbo.readings (device, temperature, humidity) "
                              "VALUES (@p0, @p1, @p2)"},
            parameters);
        if (result) {
            return true;
        }
        // A server error (e.g. a constraint) won't go away by retrying;
        // the message went to print_message
        if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error)) {
            return false;
        }
        // The connection dropped (server restart, Wi-Fi, idle timeout):
        // connect() starts a new session on the same driver
        Serial.println("Connection lost, reconnecting");
        if (not connect_to_db()) {
            return false;
        }
    }
    return false;
}

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);
    if (not connect_to_db()) {
        Serial.println("Could not connect to SQL Server; retrying in loop()");
    }
}

void loop() {
    static unsigned long last = 0;
    if (last != 0 && millis() - last < 30000) {
        return;
    }
    last = millis();

    const reading r = read_sensor();
    Serial.printf("%.2f C, %.2f %% -> %s\n", r.temperature, r.humidity,
                  log_reading(r) ? "logged" : "not logged");
}

Going further

  • Readings while offline: if a reading can't be sent, keep it in a small array and send the backlog after reconnecting. Without a clock on the device, add the age of each reading to the insert, e.g. DATEADD(SECOND, -@p3, SYSUTCDATETIME()).
  • Several readings at once: one INSERT ... VALUES (@p0, @p1, @p2), (@p3, @p4, @p5) takes fewer round trips than one insert per reading.
  • A stored procedure keeps the SQL on the server, so you can change the table without updating the firmware. See Call a stored procedure.
  • Encrypt the connection when the network isn't yours: see Connect with TLS.