Keep it running when the network does not
On this page
Your node ran on your desk for a week without a fault. You install it on a site two hours away. On the first night the router restarts at 3am, and the node never comes back. Or the power blinks, the board restarts, waits for a Wi-Fi network that is still booting, and sits there forever with the pump relay switched off. Someone has to drive out and press reset. This lesson is about the code that makes that drive unnecessary.
What happens on a real site
On a desk, the network is always there. On a site, it comes and goes, and each kind of failure needs its own answer:
| Event | How long | What your node must do |
|---|---|---|
| Wi-Fi signal drops for a moment | seconds | Keep working; reconnect without a restart. |
| The router restarts | 1 to 3 minutes | Keep readings; reconnect Wi-Fi, then MQTT. |
| The internet line is down | minutes to hours | Keep readings in memory; send them later with their time. |
| The broker restarts for an update | seconds to minutes | Retry calmly, with a growing gap, not every second. |
| The power cuts and comes back | any time | Start working at once, even with no network. |
| The firmware gets stuck inside a library call | for ever, if nothing acts | Restart itself, by watchdog. |
The sketch from the last lesson handles the first row and part of the second. Every piece below comes from the capstone firmware, which has them all in one program.
Rule 1: never block
The first sketch waited in setup() until Wi-Fi connected. On a desk that takes two seconds. After a power cut on a site, the router may take three minutes to start, or may not start at all, and during that time the board does nothing: no readings, no local safety limit, nothing. The capstone starts Wi-Fi and the time server and then goes straight on:
WiFi.mode(WIFI_STA);WiFi.setAutoReconnect(true);WiFi.begin(WIFI_SSID, WIFI_PASS); // no waiting here: loop() works offlineconfigTime(0, 0, "pool.ntp.org", "time.nist.gov"); // UTC, set in the backgroundFrom then on, loop() does its local work every time, and the network parts run only when the network is there. A node that does its job first and reports second is a node that a network fault cannot stop.
Rule 2: reconnect with a growing gap
When the broker is down, retrying every second does not bring it back sooner. It wastes power, fills the serial log, and when the broker restarts, every node hits it at the same moment. The capstone waits 5 seconds after the first failure, then 10, 20, 40, and then 60 seconds between tries, plus a small random part so that many nodes spread out:
bool connectMqtt() { if (mqtt.connected()) return true; if (WiFi.status() != WL_CONNECTED || !clockSet()) return false; // TLS needs the right time if (millis() - lastTry < retryMs) return false; lastTry = millis(); if (mqtt.connect(DEVICE_ID, DEVICE_ID, MQTT_PASS)) { // no last will: the platform sees silence itself fails = 0; retryMs = 0; mqtt.subscribe(topic("c").c_str()); // again after every reconnect Serial.println("MQTT connected"); return true; } fails++; retryMs = min(5000UL << min(fails - 1, 4), 60000UL) // 5, 10, 20, 40, then 60 s + random(1000); // plus up to 1 s, so many nodes do not retry together Serial.printf("MQTT connect failed, state %d, next try in %lu s\n", mqtt.state(), retryMs / 1000); return false;}Two lines in it are easy to forget. The subscribe runs again after every reconnect: a new connection starts with no subscriptions, so a node that subscribes only once in setup() stops receiving commands after its first reconnect, and nothing tells you. And the clock check: after a power cut the board has no time until the time server answers, and TLS cannot work without it.
A broker is down for 5 minutes. How many times does one node try to connect, with a retry every second, and with the capstone's growing gap? What if there are 200 nodes?
Show the worked solution, 3 steps
- Every second
5 minutes is 300 seconds, so about 300 attempts, each with a full TLS handshake. ✅
- With the growing gap
Tries at 0, 5, 15, 35, 75, 135, 195 and 255 seconds (each gap: 5, 10, 20, 40, then 60). That is 8 attempts, and the node is back within about a minute of the broker. ✅
- 200 nodes
Retrying every second, the broker meets 200 handshakes a second the moment it starts, which can knock it over again. With the gap and the random part, the same 200 nodes arrive spread out over a minute. ✅
Rule 3: look after the Wi-Fi
The ESP32 tries to rejoin Wi-Fi by itself once setAutoReconnect(true) is set. On some boards and core versions it can stop trying after a long outage. A gentle nudge every 30 seconds covers that case, and costs nothing when the Wi-Fi is up:
void keepWifi() { if (WiFi.status() == WL_CONNECTED) return; if (millis() - lastWifiTry < 30000) return; // the radio also retries by itself lastWifiTry = millis(); Serial.println("Wi-Fi down, trying again"); WiFi.reconnect();}Rule 4: keep the readings you could not send
A one-hour internet outage on the night the cold room warmed is the hour you most need on the record. So when the node cannot publish, it keeps the reading in memory, with the time it was taken, and sends it when the connection comes back.
siliconwit.io accepts a reserved key, ts, for exactly this. It is the time the reading was taken, as Unix seconds (or milliseconds, or an ISO 8601 text). The platform removes it from the reading and uses it as the reading's time. The rules are short:
- A
tsfrom 7 days back to 5 minutes ahead is accepted. Outside that window, the reading is stored at the time it arrived. - A reading more than 2 minutes old is stored and charted, but it does not fire rules, commands or webhooks. That is what you want: a high reading from an hour ago should go on the record, not wake someone now.
- Late readings are not held to the data interval. Send them oldest first, at up to 120 a minute.
Every reading the capstone sends carries ts once the clock is set:
// one reading as JSON; with a time when the clock is set, so a late reading lands at the right momentbool sendReading(float t, float h, unsigned long atMs) { char payload[96]; if (clockSet()) { unsigned long ts = (unsigned long)time(nullptr) - (millis() - atMs) / 1000; snprintf(payload, sizeof(payload), "{\"temperature\":%.1f,\"humidity\":%.1f,\"ts\":%lu}", t, h, ts); } else { snprintf(payload, sizeof(payload), "{\"temperature\":%.1f,\"humidity\":%.1f}", t, h); } return mqtt.publish(topic("t").c_str(), payload);}Notice that the node stores millis(), not the date. If the power cut happened before the clock was ever set, the node still knows how many seconds ago each reading was taken, and works out its real time when it sends it. The readings it could not send go into a ring buffer: when it is full, the oldest is dropped to make room for the newest.
// readings taken while the broker could not be reached, oldest firststruct Kept { unsigned long atMs; float t, h; };const int KEEP_MAX = 720; // 6 hours of readings at one every 30 sKept kept[KEEP_MAX];int keptFirst = 0, keptCount = 0;
void keep(float t, float h) { if (keptCount == KEEP_MAX) { // full: drop the oldest keptFirst = (keptFirst + 1) % KEEP_MAX; keptCount--; } kept[(keptFirst + keptCount) % KEEP_MAX] = { millis(), t, h }; keptCount++;}
// send kept readings, oldest first, about 100 a minute (the limit is 120),// once the newest of them is over 2.5 minutes old: then none is held to the data intervalvoid sendBacklog() { if (!keptCount || !mqtt.connected() || !clockSet()) return; const Kept& newest = kept[(keptFirst + keptCount - 1) % KEEP_MAX]; if (millis() - newest.atMs < 150000UL) return; if (millis() - lastBacklog < 600) return; lastBacklog = millis(); const Kept& k = kept[keptFirst]; if (sendReading(k.t, k.h, k.atMs)) { keptFirst = (keptFirst + 1) % KEEP_MAX; keptCount--; }}The backlog waits until the newest kept reading is two and a half minutes old. By then every kept reading is "late", so none of them counts against the data interval, and the live readings keep flowing next to them at the normal rate. In loop(), one line decides between sending now and keeping for later:
if (!mqtt.connected() || !sendReading(avgT, avgH, millis())) keep(avgT, avgH); // kept for laterThe site's internet is down for 47 minutes. The node takes a reading every 30 seconds. How many readings does it keep, how much memory do they use, and how long does the backlog take to send?
Show the worked solution, 4 steps
- Readings kept
47 minutes × 2 readings a minute = 94 readings. The buffer holds 720, so nothing is lost. ✅
- Memory
Each kept reading is a time and two numbers, 4 bytes each: 12 bytes. 94 × 12 = 1,128 bytes. The full buffer of 720 is 8,640 bytes, a small part of the ESP32's 320 KB. ✅
- The wait
The connection comes back. The node waits until its newest kept reading is 2.5 minutes old, so that all 94 count as late. ✅
- The send
One every 0.6 seconds is 100 a minute, under the limit of 120. 94 readings take about 56 seconds. A few minutes after the line returns, the chart has no gap. ✅
Rule 5: a watchdog for when the code itself gets stuck
Rarely, the firmware gets stuck: a library waits for an answer that never comes, or a bug loops for ever. No reconnect logic helps, because the code that would run it is not running. A watchdog is a hardware timer that restarts the chip unless the program tells it "still alive" in time. The capstone gives it 60 seconds:
// in setup():#if ESP_ARDUINO_VERSION_MAJOR >= 3 esp_task_wdt_config_t wdt = { .timeout_ms = WDT_S * 1000, .idle_core_mask = 0, .trigger_panic = true }; esp_task_wdt_reconfigure(&wdt);#else esp_task_wdt_init(WDT_S, true);#endif esp_task_wdt_add(NULL); // watch this loop
// and the first line of loop():esp_task_wdt_reset(); // "still alive"The two branches are there because the ESP32 Arduino core changed this function in version 3; the right one is chosen for you. The watchdog time must be longer than anything the loop is allowed to wait for. That is why the capstone also limits the TLS handshake to 20 seconds with net.setHandshakeTimeout(20): a slow handshake fails on its own, well before the watchdog would restart the board.
A restart must be safe. In the capstone, the relay is switched off at the top of setup(), and setup() does not wait for anything, so a restart costs a few seconds of readings and nothing else.
Keep-alive, and why there is no last will
The capstone keeps the 60 second keep-alive from the earlier lessons, so a dead connection is noticed within about 90 seconds on both sides. It sets no last will: siliconwit.io does not accept one, and does not need one, because it marks a device as not reporting when nothing has arrived for three data intervals (never sooner than 5 minutes). With a reading every 30 seconds, that is 5 minutes after the last reading.
Test it the way the site will
Do not wait for the site to test your code. Do these on your desk, with the Serial Monitor open and the device page on your phone:
- Unplug the router for 10 minutes. Serial keeps printing readings. The device shows as not reporting after about 5 minutes. Plug it back in: Wi-Fi returns, MQTT connects, and a few minutes later the 10 minute gap on the chart fills in.
- Power the board off and on with the router off. Readings start on serial at once. Nothing waits for Wi-Fi.
- Block the broker (on your own broker, stop Mosquitto for 3 minutes). The serial log shows the gap growing: 5, 10, 20, 40 seconds.
- Send a command after a reconnect. If the node does not answer, it did not subscribe again.
Common mistakes
while (!connected) delay(...)anywhere after setup. It turns any network fault into a stopped machine.- Subscribing only once. Commands work until the first reconnect, then silently stop.
- A late reading without
ts. It is stored at the time it arrives, so an hour of readings lands on the chart in one minute, all wrong. - Sending the backlog as fast as possible. Over 120 a minute is too fast. Pace it.
- A watchdog shorter than the longest wait. The board restarts in the middle of every slow handshake and never connects.
Check yourself
After a power cut, why must setup() not wait for Wi-Fi?
After its first reconnect, a node still sends readings but no longer obeys commands. What is the most likely bug?
A node sends a reading taken 40 minutes ago, with its ts. The value is above an alert limit. What does siliconwit.io do?
What does a watchdog protect against that reconnect logic cannot?
- Never block: the node does its local job every loop, with or without a network.
- Reconnect with a growing gap (5, 10, 20, 40, then 60 seconds, plus a random part), and subscribe again after every connect.
- Keep readings you could not send, with their time, and send them later with
ts: up to 7 days back, oldest first, at most 120 a minute. Late readings do not fire rules. - A watchdog restarts a stuck board; make every wait shorter than it, and make a restart safe.
Your node now survives a real site. Next, it does more than report: an alert a person will answer, and a command the device obeys and confirms.
Discussion
No comments yet. Ask a question, share a result from your own build, or suggest a clearer way to explain it.
Join the discussion. Anyone can read. To comment, reply or mark a comment helpful, sign in with your SiliconWit account.
My notes on this page
Kept on this device. To have them on every device, turn on keeping in My notes.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.