Textile monitoring (weaving)ESP32 PLCMQTTWiFiCommunication
Offline-first MQTT data logging with SD buffering
The factory WiFi will go down — the only question is whether you lose production data when it does. This example monitors a machine (state inputs + a production pulse counter) and publishes over MQTT, while writing every message to a daily file on the SD card first. When the network returns, nothing is missing. This is the offline-first pattern we run on knitting machines in production.
Events first, snapshots second
A change on any input publishes an event immediately — sub-second visibility of machine stops. A full snapshot with the pulse counter goes out every 20 s as a heartbeat. Both carry a unique message ID (PLC id + RTC timestamp + millis) so the backend can deduplicate and audit.
The SD card is the source of truth
publicar() writes to the daily JSON file BEFORE attempting MQTT. Connectivity becomes an optimisation, not a dependency. Files named YYYY-MM-DD.json make manual recovery and HTTP bulk-upload trivial.
Non-blocking reconnection
WiFi reconnection attempts are rate-limited to one every 10 s and never block the loop: the machine keeps being monitored at full speed while the network is away. A hardware RTC synced by NTP keeps timestamps honest across reboots.
A snippet from the implementation
Straight from the example as deployed on the ESP32 PLC — copy it freely:
void setup() {
Serial.begin(115200);
for (int i = 0; i < NPINS; i++) { pinMode(pins[i], INPUT); lastState[i] = digitalRead(pins[i]); }
attachInterrupt(I0_0, [] { pulses++; }, FALLING); // production counter
SD.begin();
RTC.begin();
checkWiFi();
mqtt.setServer(MQTT_HOST, MQTT_PORT);
uint32_t t0 = millis(); // initial WiFi wait (max 15 s)
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 15000) delay(500);
if (WiFi.status() == WL_CONNECTED) syncRTC();
}The full example is a complete program — wiring header, setup and main loop — ready to adapt to your application.
Frequently asked questions
How do I recover the buffered data?
Either replay the daily files over MQTT on reconnect, or expose an HTTP upload endpoint — our production version posts the files to Node-RED with basic auth.
How fast can the pulse counter go?
The counter runs on a hardware interrupt, so thousands of pulses per second are no problem; the 20 s snapshot just reports the accumulated count.
Which broker should I use?
Any MQTT 3.1.1 broker works; we typically run Mosquitto on an on-prem concentrator with Node-RED for dashboards and database persistence.