Skip to content

Connect an ESP8266 to SQL Server

The ESP8266 works like the ESP32 with the Arduino core, as in the PlatformIO tutorial, with three differences: the Wi-Fi header, less RAM, and a TLS client (BearSSL) that needs some setup. This guide covers those differences. It applies to any ESP8266 board: NodeMCU, Wemos D1 mini, ESP-01 and others.

Install

Install tdslite and the ESP8266 core:

  • Arduino IDE: install the ESP8266 board package, then tdslite from the Library Manager. See Install the library.
  • PlatformIO: use platform = espressif8266, e.g. with board = nodemcuv2 or board = d1_mini, and add tdslite to lib_deps:

    [env:nodemcuv2]
    platform = espressif8266
    board = nodemcuv2
    framework = arduino
    lib_deps = mustafakemalgilor/tdslite
    monitor_speed = 115200
    

Connect without TLS

The Wi-Fi client is WiFiClient from ESP8266WiFi.h:

#include <ESP8266WiFi.h>
#include <tdslite.h>

The ESP8266 has about 80 kB of RAM, of which around 50 kB is free once Wi-Fi runs. Keep the network buffer at 2 kB and the TDS packet size at 1 kB:

#if not SKETCH_USE_TLS
// 2048 bytes of buffer, 1024-byte packets: plenty for typical rows,
// and light on the ESP8266's ~50 kB of free heap
static tdsl::uint8_t net_buf [2048] = {};
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
static constexpr tdsl::uint32_t packet_size = 1024;
#endif

Then connect and query as on any board:

    driver.set_info_callback(print_message);

    decltype(driver)::connection_parameters params;
    params.server_name = db_server;
    params.user_name   = db_user;
    params.password    = db_password;
    params.packet_size = packet_size;

    if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) {
        Serial.println("Could not connect to SQL Server");
        return;
    }

    // varchar(128): the server's version, e.g. "16.0.4135.4"
    driver.execute_query("SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(128))",
                         print_row);
    Serial.printf("Free heap: %u bytes\n", ESP.getFreeHeap());

ESP.getFreeHeap() shows how much RAM is left. tdslite allocates the fields of each row while it's processed, so check it after a query on your widest rows. Fit tdslite into a small RAM budget explains what takes the space.

Connect with TLS

BearSSL::WiFiClientSecure does the TLS part. It needs four things:

  1. The CA certificate, as a BearSSL::X509List that outlives the connection: a global or static, not a local variable.
  2. A record size that fits a TDS packet. BearSSL puts at most 512 bytes into a TLS record by default, and SQL Server drops a strict connection when a TDS packet is split over several records. Raise the send buffer to the packet size with setBufferSizes, tell tdslite that limit with set_tls_client(true, packet_size), and use the same packet_size in the connection parameters.
  3. The current time, to check the certificate's dates. Get it over NTP before connecting.
  4. A host name that the certificate lists, as server_name, and that the ESP8266 can resolve. Not an IP address: BearSSL checks only the certificate's DNS names, so it refuses an IP address even when the certificate lists it ("Expected server name was not found in the chain").

The globals:

#if SKETCH_USE_TLS
// PEM text of the CA that signed the server's certificate
static const char ca_pem []        = R"(-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
)";

// BearSSL's trust anchors must outlive the connection
static BearSSL::X509List trusted_ca{ca_pem};

static tdsl::uint8_t net_buf [4096] = {};
static tdsl::arduino_driver<BearSSL::WiFiClientSecure> driver{net_buf};
// A TDS packet must fit into one TLS record (see setBufferSizes below)
static constexpr tdsl::uint32_t packet_size = 2048;
#endif

and in setup(), after Wi-Fi is up and before connect:

#if SKETCH_USE_TLS
    // Checking the certificate needs the current time
    configTime(0, 0, "pool.ntp.org");
    while (time(nullptr) < 1700000000) {
        delay(500);
    }

    auto & tls = driver.network().client();
    tls.setTrustAnchors(&trusted_ca);
    // BearSSL puts at most 512 bytes into a TLS record by default: raise
    // it to the TDS packet size, and tell tdslite the limit
    tls.setBufferSizes(16384, packet_size);
    driver.network().set_tls_client(true, packet_size);
#endif

The server must accept TDS 8.0 strict connections: see Connect with TLS for what that needs. With TLS, the sketch's static RAM grows by about 2.6 kB (mostly the larger network buffer), and BearSSL takes about 31 kB of heap when it connects, its 16 kB receive buffer included: of the ~45 kB free, about 12 kB is left. With setBufferSizes(4096, 1024) (below), about 25 kB is left.

The complete sketch

SKETCH_USE_TLS switches between the two ways to connect. CI builds both, for nodemcuv2.

esp8266.ino
#include <ESP8266WiFi.h>
#include <time.h>
#include <tdslite.h>

#ifndef SKETCH_USE_TLS
#define SKETCH_USE_TLS 0 // 1: TLS (TDS 8.0 strict), needs SQL Server 2022+ with a certificate
#endif

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"; // with TLS: a host name the certificate lists
static const char db_user []       = "sa";
static const char db_password []   = "<password>";

#if not SKETCH_USE_TLS
// 2048 bytes of buffer, 1024-byte packets: plenty for typical rows,
// and light on the ESP8266's ~50 kB of free heap
static tdsl::uint8_t net_buf [2048] = {};
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
static constexpr tdsl::uint32_t packet_size = 1024;
#endif

#if SKETCH_USE_TLS
// PEM text of the CA that signed the server's certificate
static const char ca_pem []        = R"(-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
)";

// BearSSL's trust anchors must outlive the connection
static BearSSL::X509List trusted_ca{ca_pem};

static tdsl::uint8_t net_buf [4096] = {};
static tdsl::arduino_driver<BearSSL::WiFiClientSecure> driver{net_buf};
// A TDS packet must fit into one TLS record (see setBufferSizes below)
static constexpr tdsl::uint32_t packet_size = 2048;
#endif

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 void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) {
    const auto version = row [0].as<tdsl::char_view>();
    Serial.write(version.data(), version.size());
    Serial.println();
}

void setup() {
    Serial.begin(115200);

    WiFi.mode(WIFI_STA);
    WiFi.begin(wifi_ssid, wifi_password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
    }
    Serial.print("Wi-Fi connected, IP address ");
    Serial.println(WiFi.localIP());

#if SKETCH_USE_TLS
    // Checking the certificate needs the current time
    configTime(0, 0, "pool.ntp.org");
    while (time(nullptr) < 1700000000) {
        delay(500);
    }

    auto & tls = driver.network().client();
    tls.setTrustAnchors(&trusted_ca);
    // BearSSL puts at most 512 bytes into a TLS record by default: raise
    // it to the TDS packet size, and tell tdslite the limit
    tls.setBufferSizes(16384, packet_size);
    driver.network().set_tls_client(true, packet_size);
#endif

    driver.set_info_callback(print_message);

    decltype(driver)::connection_parameters params;
    params.server_name = db_server;
    params.user_name   = db_user;
    params.password    = db_password;
    params.packet_size = packet_size;

    if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) {
        Serial.println("Could not connect to SQL Server");
        return;
    }

    // varchar(128): the server's version, e.g. "16.0.4135.4"
    driver.execute_query("SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(128))",
                         print_row);
    Serial.printf("Free heap: %u bytes\n", ESP.getFreeHeap());
}

void loop() {
    delay(1000);
}

If it doesn't work

  • It resets while connecting, or connect fails with TLS: the heap is probably exhausted. Lower packet_size (e.g. to 1024, in both setBufferSizes and set_tls_client) and the receive buffer, e.g. setBufferSizes(4096, 1024). TLS records can be up to 16 kB, so a smaller receive buffer only works if the server never sends larger ones: try it, and go back to 16384 if the connection fails.
  • The sketch hangs before connecting: the NTP loop waits until the clock is set; check that the network can reach pool.ntp.org, or use a local NTP server.
  • For everything else, see Troubleshoot.