ESP32: a device that is called, and that calls
The Connectivitizer library for ESP32 makes a web server (or any TCP port) on the ESP32 reachable from an app anywhere, without opening a port in any router. The ESP32 can also call another device of the workspace: that device's service appears on a local port of the ESP32. The library needs no other library, runs in a task of its own, and works with the Arduino core, PlatformIO and ESP-IDF. The ESP32 trusts the other side through a shared key; certificates are not available on the ESP32.
Install
Arduino IDE: Tools → Manage Libraries…, search for "Connectivitizer" and install it (or
arduino-cli lib install Connectivitizer). Examples then appear under File → Examples → Connectivitizer.PlatformIO: in
platformio.iniINIlib_deps = huelakesoftwaresolutions/ConnectivitizerESP-IDF (ESP-IDF 5.x):
idf.py add-dependency "huelake/connectivitizer"in the project. It adds the library tomain/idf_component.yml; usecz.hinstead of the Arduino wrapper. On the newer chips the application needs the 1.5 MB app partition (CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE=y).
Chips: ESP32, S2, S3, C3 with Arduino core 2.x; with ESP-IDF also C2, C5, C6, C61.
What you need
- The board (ESP32, S2, S3, C3, C5, C6, …) and the toolchain (Arduino IDE, PlatformIO or ESP-IDF); see the chips above.
- The Wi-Fi name and password. They go into the git-ignored secrets file, like the keys.
- A device key (
czd_…; web app: Credentials → Create a device key) and the device name: the name apps address the device by. One device key serves any number of devices; each logs in under its own name. - A shared key (
czs_…; web app: Credentials → Generate a shared key). The same key goes into the app that connects to the device. - The port the sketch's web server listens on, and a service name for it (usually
api). - If the ESP32 calls another device: that device's name and service, and a device key with Its devices may open sessions to other devices switched on (web app: Credentials, when you create or edit the key). If the other device has a shared key of its own, that key as well.
Code
Keep the secrets in a header that is not committed, for example include/secrets.h (add it to .gitignore), and commit a secrets.example.h with placeholders:
// secrets.h - not committed
#define WIFI_SSID "your-wifi"
#define WIFI_PASSWORD "your-wifi-password"
#define DEVICE_KEY "czd_..."
#define DEVICE_NAME "living-room-lamp" // how apps address this device
#define SHARED_KEY "czs_..." // the same key the app has#include <WiFi.h>
#include <WebServer.h>
#include <Connectivitizer.h>
#include "secrets.h"
WebServer server(80); // an ordinary web server; it knows nothing about Connectivitizer
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
server.on("/state", HTTP_GET, []() { server.send(200, "application/json", "{\"ok\":true}"); });
server.begin();
Connectivitizer.setLog(Serial); // what happens, per session
Connectivitizer.setSharedKey(SHARED_KEY);
Connectivitizer.expose("api", 80); // the web server above, under the name "api"
if (!Connectivitizer.begin(DEVICE_KEY, DEVICE_NAME)) { // last in setup()
Serial.println("Connectivitizer: check DEVICE_KEY, DEVICE_NAME and SHARED_KEY");
}
}
void loop() {
server.handleClient(); // nothing to call for Connectivitizer
}The device appears under Devices in the web app the first time it connects, under the name it sent. An app then reaches it by that name, for example in TypeScript client.connect('living-room-lamp', ['api']).
Calling another device
link makes a service of another device appear on a port of the ESP32. Whatever connects to 127.0.0.1 on that port talks to the other device, end-to-end encrypted, directly where the networks allow it and through the relay otherwise. The other device can be anything that runs a Connectivitizer agent: a second ESP32, a Raspberry Pi, a PC.
String answer;
unsigned long lastAsked = 0;
void setup() {
// ... Wi-Fi, web server, setSharedKey and expose as above ...
Connectivitizer.link("cabin", "api", 8081); // the service "api" of the device "cabin", on port 8081 here
Connectivitizer.begin(DEVICE_KEY, DEVICE_NAME);
}
void loop() {
server.handleClient();
if (Connectivitizer.connected() && millis() - lastAsked > 10000) { // every 10 seconds
lastAsked = millis();
int status = Connectivitizer.get("cabin", "/state", answer); // HTTP status, or -1
if (status == 200) {
Serial.println(answer);
}
}
}- The device key decides whether this works. A key without Its devices may open sessions to other devices gets
FORBIDDEN; the key's access rules say which devices and services it may reach. - The session to the other device is opened by the first connection to the port, which takes a few seconds (measured on an ESP32-S3: 4 s peer to peer, 6 s through the relay), and is closed when the port has not been used for 30 seconds. The next connection opens it again.
getandpost(Arduino only) wait for the answer (15 seconds at most unless told otherwise) and are meant for the sketch'sloop(). For anything else, connect to the port yourself:HTTPClientwithhttp://127.0.0.1:8081/..., a WebSocket client, an MQTT client.- The port listens on the loopback address only. Nothing in the network can use it.
- The shared key is the one the other device holds. When that is not the first key given to
setSharedKey, pass it as the fourth argument oflink. - Up to 2 links (
-DCZ_MAX_LINKS=4for more). Each has a session of its own while in use.
More than one app at a time
By default an ESP32 serves one app at a time: an app that connects takes the place of the one before, whose session ends. The limit is memory. Measured on an ESP32-S3 with about 200 KB free, a peer-to-peer session costs about 21 KB and a relayed one about 65 KB, because it brings a TLS connection of its own. Three ways to serve more people:
- Allow more sessions.
-DCZ_MAX_SESSIONS=2(or 3) in the build flags. This is the simplest way and fits an ESP32-S3 when sessions run peer to peer. Plan for the relayed case, since the network decides which one a session gets: checkESP.getFreeHeap()with all sessions open. - Put a bigger device in front. A Raspberry Pi or a PC runs an agent and is the device people open. The ESP32 reports to it with
link(see above) andpost, or the bigger device calls the ESP32 and keeps the one session. The libraries for those machines have no limit of this kind, and the ESP32 only ever has one peer. This is the way for a display many people watch. - Take turns. An app that only reads now and then connects, reads and disconnects instead of holding its session. With the default of one session this works without a change on the ESP32: each app has the device for the moment of its request. Give each app a slot of its own (for example the second of the minute its id hashes to) or wait a random time before a retry, so that two apps do not keep replacing each other. An app that is replaced sees its session end with
SESSION_CLOSED; it should not reconnect at once.
Sessions the ESP32 opens itself with link are counted separately and are never replaced by an app.
Reference
| Call | Meaning |
|---|---|
setSharedKey(key) | A key apps must hold to reach the device. Call again to add more (up to 4), for example one per app. |
expose(name, port, host, protocol) | Makes a TCP service reachable under name. host may be another machine in the same network; leave it out for the ESP32 itself. protocol is http unless given. Up to 4 services. |
link(device, service, port, sharedKey) | Makes service of another device reachable at 127.0.0.1:port on the ESP32. Before begin(). See above. |
get(device, path, response), post(device, path, body, response) | An HTTP request to a linked device (Arduino only). Returns the HTTP status, or -1 when the device was not reached in time. |
linkPort(device, service), links() | The port of a link (0 when there is none; service may be left out), and how many sessions the ESP32 has open to other devices right now. |
setPeerToPeer(false) | Never connect directly; always use the relay. Peer to peer is on by default. |
setReplaceWhenFull(true) | When the ESP32 has no memory for a new connection next to the running one, the running one ends and the new one gets in, instead of being refused (DEVICE_REJECTED). Off by default; see below. |
setLog(Serial) | Print what the library does. |
begin(deviceKey, name) | Start. Returns false when a setting is not valid. Settings are made before begin(). |
connected(), sessions(), refused(), lastError() | State, for a status LED or a display. lastError() is an error code. |
end() | Stop and free everything. |
Good to know
- Peer to peer, IPv6 and the device's local address are handled by the library; your sketch does not need
WiFi.enableIPv6()or anything else for it. Whether a session ends up direct depends on the networks: Troubleshooting explains the log lines. - Whatever serves the port works unchanged:
WebServer, ESPAsyncWebServer,esp_http_server, WebSockets included. - One app at a time by default; a new session replaces the old one.
-DCZ_MAX_SESSIONS=2allows more. With less than 72 KB of free heap next to a running session a new one is refused (DEVICE_REJECTED, "the device refused the connection"), for example a phone while a viewer on a computer still has the device open.setReplaceWhenFull(true)ends the running session instead. It ends before the newcomer has proved that it holds the shared key, so anyone your workspace's access rules let connect could end the session; turn it on for a device used from one place at a time. The sessions the ESP32 opens itself for its links are counted separately and are not replaced. - Memory: an idle device holds one TLS connection to the platform (roughly 40 KB) and about 9 KB besides; a session adds about 10 KB, plus a second TLS connection when relayed. An app connected through the relay while the ESP32 calls through the relay means three TLS connections at once; peer-to-peer sessions need none of them. Measured on an ESP32-S3 (Arduino core 2.0.17, a web server and one link): 207 KB free while online and idle; a session the ESP32 opened costs about 21 KB peer to peer and about 65 KB through the relay; with an app connected through the relay at the same time the lowest free heap was 67 KB. After the sessions ended the free heap was back at 205 KB. A classic ESP32 has less memory to begin with. Check
ESP.getFreeHeap()on the board. - The device takes the time from the platform; no NTP is needed.
- Both keys are in the firmware. Whoever reads the flash has them; use flash encryption if that matters. A device key alone lets someone register devices in the workspace and, if the key allows its devices to open sessions, ask for sessions within the key's access rules; it does not let anyone read traffic or take part in a session without the shared key.
A screen in the Connectivitizer app
Your device can bring its own screen: one HTML page that the Connectivitizer app shows when someone taps the device, so there is no app to write. The device serves two files on the service the app connects to (ui, else api): GET /.cz/ui.json, the manifest {"name": "Desk lamp", "entry": "/.cz/ui.html", "version": "1"}, and GET /.cz/ui.html, the page.
Put these routes on the sketch's web server, the one exposed as "api" above (they replace the example's /state). The page is a string in flash; keep it to tens of KB.
// In the sketch: the routes go on the WebServer that is exposed as "api" (port 80).
static const char UI_JSON[] PROGMEM = R"({"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"})";
static const char UI_HTML[] PROGMEM = R"html(<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { margin: 0; padding: 24px; font: 16px system-ui, sans-serif; background: #fdf6e3; color: #3b3526; }
h1 { font-size: 44px; margin: 4px 0 24px; }
label { display: block; margin: 28px 0 8px; }
button { font: inherit; padding: 12px 24px; border-radius: 12px; border: 0; background: #b58900; color: #fff; }
input, select { font: inherit; padding: 10px; border-radius: 10px; border: 1px solid #c8b98a; background: #fff; color: inherit; }
input[type=range] { width: 100%; padding: 0; border: 0; background: none; accent-color: #b58900; }
</style>
<p>Desk lamp</p>
<h1 id="state">…</h1>
<button id="toggle">Switch</button>
<label for="level">Brightness: <b id="level-value">…</b> %</label>
<input id="level" type="range" min="0" max="100" step="5">
<p>Running for <b id="uptime">…</b> s</p>
<script>
const $ = (id) => document.getElementById(id);
// The device answers every request with its state, e.g. {"on":true,"level":40,"uptime":120}.
// show() puts it on the page: one line per value.
const show = async (response) => {
const s = await response.json();
$('state').textContent = s.on ? 'On' : 'Off';
$('level-value').textContent = s.level;
if (document.activeElement !== $('level')) $('level').value = s.level;
$('uptime').textContent = s.uptime;
};
const refresh = () => fetch('/state').then(show).catch(() => { $('state').textContent = 'No /state yet'; });
// A tap or a change sends a request; the answer is shown right away.
$('toggle').onclick = () => fetch('/toggle', { method: 'POST' }).then(show);
$('level').oninput = () => { $('level-value').textContent = $('level').value; };
$('level').onchange = () => fetch('/level?value=' + $('level').value, { method: 'POST' }).then(show);
refresh();
setInterval(refresh, 2000); // new values every 2 seconds
</script>
</html>)html";
static bool on = false;
static int level = 50;
static void sendState() {
String json = String("{\"on\":") + (on ? "true" : "false") + ",\"level\":" + level +
",\"uptime\":" + (millis() / 1000) + "}";
server.send(200, "application/json", json);
}
// in setup(), before server.begin():
server.on("/.cz/ui.json", HTTP_GET, [] { server.send_P(200, "application/json", UI_JSON); });
server.on("/.cz/ui.html", HTTP_GET, [] { server.send_P(200, "text/html; charset=utf-8", UI_HTML); });
server.on("/state", HTTP_GET, sendState);
server.on("/toggle", HTTP_POST, [] {
on = !on; // switch your pin here: digitalWrite(LED_PIN, on);
sendState();
});
server.on("/level", HTTP_POST, [] {
level = constrain(server.arg("value").toInt(), 0, 100); // e.g. analogWrite(LED_PIN, level * 255 / 100);
sendState();
});More controls to copy, a preview on your computer that needs no device, what a page can do (colours for the app's bar, the camera, the location, links), and finished examples, with a short start for anyone new to HTML: Device screens.