Send ESPHome sensor data to SQL Server¶
ESPHome builds firmware for ESP32 boards from a YAML
file. tdslite's sql_server component connects it to SQL Server:
- the action
sql_server.executesends a query or a stored procedure call, for example each time a sensor has a new reading, and can act on the result; - the
sql_serversensor, text sensor and binary sensor platforms show a query's result as a sensor's state, in Home Assistant too.
There's no code to write, and nothing runs between the board and the server.
Experimental
The component is new. It's built in CI with the current ESPHome and tested against a real server there, and it has run on ESP32 boards with both frameworks, with and without TLS, including a soak test with sessions killed under it (see Tested hardware). It hasn't run on many other boards yet. Please report problems.
What it does and doesn't do:
- Boards: ESP32 boards (ESP32, -S2, -S3, -C3, ...), with either of ESPHome's frameworks (ESP-IDF, the default, or Arduino). Not the ESP8266 or RP2040: the queries run on a thread of their own, which these don't have.
- The first row: of a query's result, ESPHome sees the first row, and how many rows there were.
- Encryption: with
tls:, on servers that support TDS 8.0 strict mode (SQL Server 2025, SQL Server 2022 on Windows, Azure SQL). Without it, the connection isn't encrypted. Either way, give the device a login that may do one thing only (below). - Size: a request (the query and its parameters) and each row of a result must fit in the component's 4 KB network buffer. Text travels as UTF-16, two bytes a character, so a query and its text parameters can be about 2000 characters long together. See Limits.
- Not durable: requests wait in RAM while the server is unreachable,
up to
queue_size, and the oldest are dropped first. A restart loses them. - Several servers: add one
sql_serverper server or login; see Several servers or logins.
Prepare the database¶
This guide reuses the battery weather station's
database: a table, a procedure that checks and stores a reading, and a
login that may only call that procedure. Run the station's setup.sql:
CREATE TABLE dbo.weather (
id INT IDENTITY PRIMARY KEY,
station VARCHAR(32) NOT NULL,
temperature REAL NOT NULL,
humidity REAL NOT NULL,
pressure_hpa REAL NOT NULL,
recorded_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME()
);
CREATE INDEX ix_weather_station ON dbo.weather (station, recorded_at);
GO
-- Rejects readings that a working BME280 can't produce (e.g. after
-- a loose wire). THROW makes the call fail on the device.
CREATE PROCEDURE dbo.add_weather
@station VARCHAR(32),
@temperature REAL,
@humidity REAL,
@pressure_hpa REAL
AS
BEGIN
IF @temperature NOT BETWEEN -40 AND 85 OR @humidity NOT BETWEEN 0 AND 100
OR @pressure_hpa NOT BETWEEN 300 AND 1100
THROW 50001, 'Reading out of the BME280''s range', 1;
INSERT INTO dbo.weather (station, temperature, humidity, pressure_hpa)
VALUES (@station, @temperature, @humidity, @pressure_hpa);
END
GO
-- The station may only add readings. Run CREATE LOGIN in master.
CREATE LOGIN weather WITH PASSWORD = '<a long random password>';
CREATE USER weather FOR LOGIN weather;
GRANT EXECUTE ON dbo.add_weather TO weather;
GO
SQL Server must accept SQL Server logins and TCP connections; see Troubleshoot if the device can't connect.
Add the component¶
Load the component from the tdslite repository, and tell it where the server is:
external_components:
- source:
type: git
url: https://github.com/tdslite/tdslite
ref: main
path: extras/esphome/components
components: [sql_server]
sql_server:
host: 192.168.1.10
database: home
username: weather
password: !secret sql_password
ref picks the tdslite version. main is the latest; once a release
includes the component, use its tag (for example v0.10.0) so that your
firmware doesn't change when the repository does.
| Option | Default | Meaning |
|---|---|---|
host |
required | The server's name or IP address |
port |
1433 |
The server's TCP port |
database |
the login's default | The database to use |
username |
required | A SQL Server login (not a Windows account) |
password |
required | Its password; keep it in secrets.yaml |
app_name |
esphome |
Shown as the program name in SQL Server's session list |
id |
Names this server, when there are several | |
queue_size |
16 |
Requests that may wait for the server; beyond this, the oldest are dropped |
max_text_size |
255 |
Text values of a result are cut to this many bytes. The row must still fit in the 4 KB network buffer: a longer value can't be read whatever this is |
connect_timeout |
5s |
How long a connection attempt may take |
response_timeout |
10s |
How long each wait for the server may take: set it above the time your slowest query takes |
tls |
Encrypt the connection; see below |
The component connects when the first request comes, stays connected, and reconnects when the connection drops, waiting longer after each failure (2 seconds at first, up to a minute). It doesn't try while the device's network is down, and when the network comes back, it connects at once.
Store readings¶
Call sql_server.execute from any automation. The query refers to the
parameters as @p0, @p1, ... in the order of the parameters list:
sensor:
- platform: bme280_i2c
address: 0x76
update_interval: 60s
temperature:
id: temperature
name: "Temperature"
pressure:
id: pressure
name: "Pressure"
humidity:
id: humidity
name: "Humidity"
# The BME280 publishes temperature, pressure, then humidity: store
# all three readings once the humidity arrives
on_value:
- sql_server.execute:
query: >-
EXEC dbo.add_weather @station = @p0, @temperature = @p1,
@humidity = @p2, @pressure_hpa = @p3
parameters:
- "greenhouse"
- !lambda "return id(temperature).state;"
- !lambda "return x;"
- !lambda "return id(pressure).state;"
Each parameter is a constant or a !lambda. Its C++ type picks the SQL
type:
| Value | Sent as |
|---|---|
float (a sensor's state) |
REAL |
double, a constant number with a decimal point |
FLOAT |
integers (int, uint32_t, ...) |
BIGINT |
bool |
BIT |
std::string, text |
NVARCHAR, from UTF-8 |
SQL Server converts them to the procedure's or the column's types, so a
BIGINT parameter can go into an INT column, for example. Comparing a
text parameter with an indexed VARCHAR column, CAST the parameter, so
that the index is used: WHERE code = CAST(@p0 AS VARCHAR(20)).
Many requests at once
The queue holds queue_size requests: send more at once, and the
oldest are dropped. And ESPHome's repeat runs its body one level
deeper on the loop task's stack for each iteration, unless the body
waits (delay, wait_until). Measured on an ESP32: about 140 bytes an
iteration, of an 8 KB stack, so more than about 40
sql_server.execute actions in one repeat without a wait crash the
device. To store many rows, put them in one request (a stored
procedure, or INSERT ... VALUES (...), (...)), or let each iteration
wait_until the previous one is done.
A sensor that has no reading yet has the state NaN. SQL Server can't
store it, so a request with a NaN or infinite parameter is skipped, with
a warning in the log, and so is one with an unsigned value beyond
BIGINT's range. on_error runs for them.
Two more options of sql_server.execute say what happens when the server
can't be reached; see When a request fails:
| Option | Default | Meaning |
|---|---|---|
wait_for_connection |
true |
While the server is unreachable, wait in the queue (true), or fail at once (false) |
retry |
false |
If the connection is lost after sending, send it again (up to 3 times in all) |
Act on the result¶
Give sql_server.execute an on_result, an on_error, or both. They run
when the server has answered, in ESPHome's loop as any other automation.
In them, result is the outcome and the first row of the result, and the
trigger's own variables (such as x) still have the values they had when
the action ran.
This check-in reader asks SQL Server about each card, and lights a
"welcome" LED for a known one. It uses the
RFID attendance project's database, whose
dbo.scan_card logs the scan and returns one row: accepted and
holder. The reader's login may only call that procedure, and the
connection uses TLS, so that nobody on the
network can answer in the server's place:
rc522_spi:
cs_pin: GPIO5
reset_pin: GPIO27
on_tag:
# x is the card's UID, e.g. "04-A2-3B-1C". dbo.scan_card logs the scan,
# and returns one row: accepted (bit) and holder (NULL for unknown cards).
- sql_server.execute:
query: >-
DECLARE @uid VARCHAR(20) = REPLACE(@p0, '-', '');
EXEC dbo.scan_card @uid = @uid, @reader = @p1
parameters:
- !lambda "return x;"
- "front-desk"
# Someone is waiting at the reader: if the server is unreachable,
# say so at once (on_error), rather than answer minutes later
wait_for_connection: false
on_result:
- if:
condition:
lambda: "return result.get_bool(0);"
then:
- text_sensor.template.publish:
id: last_holder
state: !lambda "return result.get_string(1);"
- switch.turn_on: welcome_light
- delay: 3s
- switch.turn_off: welcome_light
else:
- logger.log:
format: "Card %s refused"
args: ["x.c_str()"]
on_error:
# The server is unreachable, or reported an error
- logger.log:
format: "Card %s not checked: %s"
args: ["x.c_str()", "result.error.c_str()"]
The whole config is in
extras/esphome/rfid-checkin.yaml.
Not for a door lock
The reader knows a card by its UID, which is easy to copy. For a door, use cards with cryptographic authentication; see Before you use it for a door.
on_error runs instead of on_result when the request failed: a server
error, a lost connection, a request dropped from a full queue, or a NaN
parameter. While the server is unreachable, a request with
wait_for_connection: true waits in the queue, and neither runs yet. The
check-in reader sets it to false, so that someone at the reader hears at
once that the server can't be reached.
An action in on_result or on_error can be another sql_server.execute.
In its own on_result and on_error, result is its result, and
outer_result the enclosing one's.
Read the values¶
Columns are numbered from 0, in the order of the SELECT list:
| In a lambda | Gives |
|---|---|
result.get_float(i) |
The value as a number; NAN for NULL, text that isn't a number, or no such column |
result.get_double(i) |
The same, with a float column's full precision |
result.get_int(i) |
A whole number, exact also for BIGINT; 0 for NULL |
result.get_bool(i) |
true for non-zero numbers and the text 1 or true |
result.get_string(i) |
Text, or a number written out; "" for NULL |
result.is_null(i) |
true for NULL, or if there's no such column |
result.has_row() |
false if the query returned no rows |
result.row_count |
How many rows the query returned (all result sets) |
result.ok |
true in on_result, false in on_error |
result.error, result.error_code |
In on_error: the message, and SQL Server's error number (0 for other errors) |
nchar, nvarchar and ntext arrive as UTF-8. char, varchar and
text arrive as stored, which is UTF-8 only under a UTF-8 collation: for
other text than ASCII, CAST(x AS NVARCHAR(100)) in the query. Text longer
than max_text_size is cut, at a character boundary. A uniqueidentifier
arrives in its usual text form; binary values as hex.
Most column types read as you'd expect; a few need a CAST in the query:
decimalandnumeric:CAST(x AS FLOAT), or read them as text withCAST(x AS VARCHAR(40)).datetimeandsmalldatetime:CAST(x AS VARCHAR(30)), or compute what you need on the server, for exampleDATEDIFF(MINUTE, x, SYSUTCDATETIME()).datetime2,dateandtimearrive as text.
Show database values as sensors¶
The sql_server platforms run a query on an interval, and publish a
column of its first row:
# Needs: GRANT SELECT ON dbo.scans TO door_reader;
sensor:
- platform: sql_server
name: "Scans today"
query: >-
SELECT COUNT(*) FROM dbo.scans
WHERE scanned_at >= CAST(SYSUTCDATETIME() AS DATE)
update_interval: 5min
binary_sensor:
- platform: sql_server
name: "Refused card in the last hour"
query: >-
SELECT CASE WHEN EXISTS (SELECT 1 FROM dbo.scans WHERE accepted = 0
AND scanned_at > DATEADD(HOUR, -1, SYSUTCDATETIME())) THEN 1 ELSE 0 END
update_interval: 1min
| Option | Default | Meaning |
|---|---|---|
query |
required | The query; use SELECT or a stored procedure that returns a row |
column |
0 |
The column to publish |
update_interval |
60s |
How often to run the query |
Plus the usual options of sensors,
text sensors and
binary sensors (name,
unit_of_measurement, filters, ...).
| Platform | Publishes | For NULL, no rows, or an error |
|---|---|---|
sensor |
get_float(column) |
unknown (NaN) |
text_sensor |
get_string(column) |
keeps the last state |
binary_sensor |
get_bool(column) |
unknown |
Errors are also logged (the same error again only at debug level), and set the component's warning status. While the server is unreachable, a sensor's query fails at once, so the sensor doesn't keep showing an old value. A query that runs into a lost connection is sent again: it only reads. If a query is still running at the next interval, that run is skipped.
Encrypt the connection¶
Add tls:, and say which certificate authority (CA) to trust. The
component then makes a TDS 8.0 strict connection: TLS first, before the
login, with the server's certificate verified. There's no option to skip
the verification.
The certificate's validity dates are checked too, against the device's clock, so the configuration needs a time component to set it. The component doesn't connect until the clock is set:
For a server with a certificate from your own CA, give the CA's certificate:
sql_server:
host: 192.168.1.10
database: home
username: weather
password: !secret sql_password
tls:
ca_certificate: |
-----BEGIN CERTIFICATE-----
MIIDBTCCAe2gAwIBAgIUQ...
-----END CERTIFICATE-----
# Connecting by IP address: the name in the server's certificate
server_name: sql.home.lan
For a server with a certificate from a public CA, such as Azure SQL Database, use ESP-IDF's certificate bundle:
sql_server:
host: myserver.database.windows.net
database: mydb
username: esphome
password: "<password>"
tls:
# Azure SQL's certificate is from a public CA
use_certificate_bundle: true
| Option | Meaning |
|---|---|
ca_certificate |
PEM text of the CA certificate(s) to trust |
use_certificate_bundle |
true: trust the public CAs of ESP-IDF's bundle |
server_name |
The name to check the certificate against (and to send as SNI); default: host |
Give exactly one of ca_certificate and use_certificate_bundle.
ESPHome's bundle has only the most common CAs; if the certificate isn't
accepted, set use_full_certificate_bundle: true under esp32: →
advanced:.
The certificate is checked against server_name, or host without it:
connecting by IP address works when the IP address is in the
certificate's subject alternative names.
What it costs, measured on ESP32 boards: about 68 KB of flash with Wi-Fi (Wi-Fi already uses part of mbedTLS; about 125 KB with Ethernet), and about 28 KB more heap while connected. The first connection, with the handshake and the login, took about 0.6 s over Wi-Fi; after that, requests are as fast as without TLS.
The server must support strict mode, and have a certificate: see Connect with TLS. If it doesn't connect, the warning says why, for example:
[W][sql_server]: could not connect to 192.168.1.10:1433: TLS: the server's certificate was rejected, not signed by a CA you trust (mbedTLS -0x2700)
TLS is for ESP32 only; the host platform has no TLS.
Check that it works¶
The log shows the connection, and each error the server reports:
[I][sql_server]: Connected to 192.168.1.10, database home
[E][sql_server]: SQL Server error 50001: Reading out of the BME280's range
The component's settings, and the counts of succeeded, failed and dropped requests, are in the configuration dump at the top of the log. On the server, check the latest rows:
-- The latest reading of each station, and how old it is
SELECT station, temperature, humidity, pressure_hpa, recorded_at,
DATEDIFF(MINUTE, recorded_at, SYSUTCDATETIME()) AS minutes_ago
FROM (
SELECT station, temperature, humidity, pressure_hpa, recorded_at,
ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at DESC, id DESC) AS n
FROM dbo.weather
) AS w
WHERE n = 1;
To act on the connection state in an automation, use the
sql_server.is_connected condition:
interval:
- interval: 5min
then:
- if:
condition:
not: sql_server.is_connected
then:
- logger.log: "SQL Server unreachable; readings are waiting"
When a request fails¶
- Server errors (a
THROWin the procedure, a missing permission, a wrong column) are logged and counted as failed. The request isn't sent again: it would fail the same way. - A connection the server closed while it was idle (a
KILL, a restart): the component notices before sending, reconnects, and sends the request. - A lost connection after sending: the request fails, and the
component reconnects for the next one. The same goes for a session the
server ends during the request (a
KILL, error 596, or an error of severity 20 or more):on_errorsees the server's error. The server may or may not have run it, so it isn't sent again unless the action hasretry: true. Use that only where running twice does no harm, or have the procedure ignore repeats, for example by a unique key on the device and the reading's time. Withretry: true, a request that loses the connection 3 times in a row is given up, in case it's what breaks the connection. - A slow query: one that takes longer than
response_timeoutcounts as a lost connection. The server may still finish it. - Too large: a request that doesn't fit in the network buffer isn't
sent (
Request rejected by tdslite: too large for the 4 KB network buffer). A row of the result that doesn't fit ends the request withResponse too large; the server ran it, so it isn't sent again, and the component reconnects. - An unreachable server: the component keeps trying to connect,
waiting longer after each failure; while the network is down, it
doesn't try, and once it's back, it connects at once. Requests with
wait_for_connection: true(the default forsql_server.execute) wait in the queue; others, and the sensors' queries, fail at once. The request being sent when the server became unreachable waits too, soqueue_sizemore can wait behind it. - A transaction left open over TLS: after a
BEGIN TRANsent on its own, every later request of a strict TLS session fails with error 3989 (see Transactions over TLS). The component then reconnects. Begin and end each transaction in one request, or in a stored procedure. - A restart or an OTA update: requests still waiting fail;
on_errormay not run before the restart.
Several servers or logins¶
Add a sql_server for each server, or each login on one server: for
example, so that each part of the device has a login that may do only its
own job, or a different database or tls: setting. Give each an id,
and say which one each action uses with id, and each sensor with
sql_server_id:
sql_server:
- id: weather_db
host: 192.168.1.10
database: home
username: weather
password: !secret weather_password
- id: door_db
host: 192.168.1.10
database: home
username: door_reader
password: !secret door_reader_password
tls:
ca_certificate: !secret sql_ca
sensor:
- platform: bme280_i2c
# ...
humidity:
name: "Humidity"
on_value:
- sql_server.execute:
id: weather_db
query: "EXEC dbo.add_weather @station = @p0, @temperature = @p1, @humidity = @p2, @pressure_hpa = @p3"
parameters: [...]
- platform: sql_server
sql_server_id: door_db
name: "Scans today"
query: "SELECT COUNT(*) FROM dbo.scans WHERE scanned_at >= CAST(SYSUTCDATETIME() AS DATE)"
Each has its own connection, thread and queue: about 14 KB of RAM each,
and 28 KB more for one with TLS. With more than one, ESPHome asks for the
id in every action and sensor.
How it works¶
ESPHome runs all components in one loop, which must not wait: a
component that blocks for more than a few milliseconds holds up Wi-Fi,
the API connection and every other sensor. tdslite waits for each
response. So the component runs tdslite on a thread of its own, with a
queue between the two: sql_server.execute puts the request in the queue
and returns at once, and the thread sends the requests one at a time.
Results go back the same way: the thread queues them and wakes ESPHome's
loop, which runs on_result, on_error and the sensor updates.
The component builds against the tdslite headers in the same repository
(src/), so the component and the library are always the same version.
See also¶
- Log sensor readings: the same in an Arduino sketch.
- MQTT to SQL Server bridge: for devices that already publish to an MQTT broker.
- Direct connections and gateways: when a device should talk to the database itself.