How-to
Buffering MQTT messages while the broker connection is down
Short answer
From firmware 14 the Flexy can detect its own MQTT disconnection from BASIC: the script publishes live while the connection is up, appends each payload as a line to /usr/mqttmsg_db.txt while it is down, and replays the file at QoS 2 when the connection returns. The 5000000-byte cap covers roughly a day of outage at a 5-second publish rate for 300-byte payloads.

On this page
- How does the script know the broker connection is down?
- Which firmware do I need before I deploy this buffering?
- How do I connect the Flexy to the broker in the init section?
- Why does MQTT CONNECT fail even with the right script?
- How do I save messages to the buffer file while the connection is down?
- How does replay work when the connection comes back?
- How much outage can the buffer cover before it fills?
- How do I verify the buffer end to end?
- Questions asked
A broker outage does not have to mean lost tag data. On a Flexy running firmware 14 or later, a BASIC script can detect the disconnection itself, store every outbound payload as one line in a buffer file, and push the whole file back to the broker at QoS 2 the moment the link returns. This article gives the documented settings the sample uses, the two functions that do the saving and the replay, the arithmetic that tells you how long an outage your buffer actually covers, and the two places where the pattern can still lose records. If your edge data flows through Node-RED instead of a gateway script, the same store-and-forward idea is laid out in buffer MQTT data in Node-RED during an internet outage.
How does the script know the broker connection is down? #
The script polls MQTT "STATUS" and treats a returned 5 as connected, so it publishes each payload live, while any other value counts as disconnected and routes the payload into the buffer file until the connection returns.
The check is a plain BASIC expression, so it sits anywhere the script makes a send-or-store decision. The sample keeps the previous reading in Last_ConnStatus%, initialized to -1 in the init section so the very first read is processed as a change, and reacts only to a transition: connected fires the replay function once, anything else logs the disconnect and lets the save path take over. The send cycle itself, with the message build and the re-arm of timer 1, looks like this:
SENDDATA:
TSET 1, 0
ConnStatus% = MQTT "STATUS"
IF Last_ConnStatus% <> ConnStatus% THEN
IF ConnStatus% = 5 THEN
LOGEVENT "[MQTT SCRIPT] Flexy connected to Broker",100
@SendSavedEvents()
ELSE
LOGEVENT "[MQTT SCRIPT] Flexy disconnected from Broker",1
ENDIF
Last_ConnStatus% = ConnStatus%
ENDIF
MyMSG$ = STR$ MsgId% + " - Hello From Flexy " + SerNum$
IF ConnStatus% = 5 THEN
MQTT "PUBLISH", TopicUsed$, MyMSG$, 2,0
ELSE
@SaveMQTTEvent(MyMSG$)
ENDIF
MsgId% = MsgId% + 1
TSET 1, 5
END
The QoS flag on MQTT "PUBLISH" protects a message only while the session is up; nothing is queued on behalf of a publisher that is already offline, and that gap is exactly what the file buffer fills. What the broker can hold for you when the queuing happens on its side instead is the subject of a comparison of broker-side offline delivery with standard QoS.
Which firmware do I need before I deploy this buffering? #
Run firmware 14 or later, because detecting an MQTT disconnection from BASIC exists only from that release, and a Flexy on firmware 13.0s0 cannot run this design as written no matter how carefully the script is pasted in.
The connect and publish calls existed earlier; what firmware 14 adds is the ability to read the MQTT connection state from BASIC, which the entire branch above depends on. The sample's own header restricts it to firmware 14 and later, and the reported symptom on older releases is simply a console message about a failed MQTT "CONNECT" — the detection the branch needs is not there. Take upgrades only through the vendor's official update channel, and treat the release running on the gateway, not the script text, as the gate for this design.
How do I connect the Flexy to the broker in the init section? #
The sample opens the client with the serial number as its client ID, points it at the broker on TCP port 1883 with a keepalive of 10 seconds, wraps the connect call in error recovery, and treats a reported error 28 as the WAN interface not yet ready.
Everything the buffering needs is configured once, in the init section:
Rem --- eWON start section: Init Section
eWON_init_section:
MsgDBPath$ = "/usr/mqttmsg_db.txt"
MaxMsgBufferFileSize% = 5000000
TopicUsed$ = "/topic/flexy/data"
SETSYS INF, "LOAD"
SerNum$ = GETSYS INF, "SERNUM"
MQTT "OPEN", SerNum$, "ewonsupport.biz"
MQTT "SETPARAM", "PORT", "1883"
MQTT "SETPARAM", "KEEPALIVE", "10"
MQTT "SUBSCRIBE", "/cmd/flexy", 2
SETSYS PRG, "RESUMENEXT", 1
MQTT "CONNECT"
ErrorReturned% = GETSYS PRG, "LSTERR"
IF ErrorReturned% = 28 THEN
LOGEVENT "[MQTT SCRIPT] WAN interface not yet ready", -1
ENDIF
SETSYS PRG, "RESUMENEXT", 0
MsgId% = 0
Last_ConnStatus% = -1
ONMQTT "GOTO MQTTRECEIVEMSG"
ONTIMER 1, "GOTO SENDDATA"
TSET 1, 3
END
SETSYS INF, "LOAD" with GETSYS INF, "SERNUM" reads the gateway serial that becomes the MQTT client ID. SETSYS PRG, "RESUMENEXT", 1 lets the script survive a failed connect long enough to read GETSYS PRG, "LSTERR": a value of 28 means the WAN interface was not up yet, the sample logs it and carries on, and the flag returns to 0 so later errors stop the script again. Timer 1 drives the send cycle, first firing after 3 seconds and re-arming itself from inside the send routine.
The sample also subscribes to /cmd/flexy at QoS 2 and drains inbound messages through the ONMQTT handler with MQTT "READ", MQTT "MSGTOPIC" and MQTT "MSGDATA"; none of that touches the buffering logic. MQTT "OPEN" points at ewonsupport.biz, the sample broker — replace it with your production broker's host before anything else.
| Item in the sample | Setting | What it decides |
|---|---|---|
| Connection gate | MQTT "STATUS" returns 5 when connected | Live publish versus buffer |
| Buffer file | /usr/mqttmsg_db.txt in MsgDBPath$ | Where offline records live |
| Buffer cap | 5000000 bytes in MaxMsgBufferFileSize% | Outage length covered |
| Record delimiter | CHR$(10) | One payload per line |
| Publish topic | /topic/flexy/data in TopicUsed$ | Same topic live and replayed |
| Publish flags | QoS 2, retain 0 | Live and replayed publishes |
| Send cycle | 3 s first run, then 5 s interval | Rate records enter the buffer |
| Transport | TCP 1883, KEEPALIVE 10 | 8883 when MQTT runs over TLS |
Why does MQTT CONNECT fail even with the right script? #
A failed MQTT "CONNECT" is almost always the network, not the script: TCP port 1883 must be reachable from the router's Internet or mobile interface, or 8883 when MQTT runs over TLS, and DNS must resolve on that same interface.
Work the interface before the script. Confirm the SIM or line contract allows outbound TCP 1883 to the broker's address; operators block ports more often than scripts fail. On mobile interfaces the documented repeat offender has been DNS: a connection failure of exactly this kind on a 4G setup was traced to DNS on the modem interface, and the vendor states the underlying DNS bug is fixed in firmware 13.2s1 and later. If the connect still fails with the port open and DNS working on a current release, read the code from GETSYS PRG, "LSTERR" and take that value to the vendor's documentation rather than guessing.
How do I save messages to the buffer file while the connection is down? #
Each unsent payload is appended to /usr/mqttmsg_db.txt as one record terminated by a CHR$(10) line feed, and the save function writes only while FS "size" reports the file below the 5000000-byte limit held in MaxMsgBufferFileSize%.
FUNCTION SaveMQTTEvent($Msg$)
$filesize% = FS "size", MsgDBPath$
IF $filesize% < MaxMsgBufferFileSize% THEN
OPEN "file:" + MsgDBPath$ FOR BINARY APPEND AS 1
PUT 1, $Msg$ + CHR$(10)
CLOSE 1
LOGEVENT "[MQTT SCRIPT] Flexy not connected - event saved", -1
ELSE
LOGEVENT "[MQTT SCRIPT] Flexy not connected - event not saved, buffer file is full", -1
ENDIF
ENDFN
Two behaviors matter when you size this. The size test runs before the append and ignores the length of the incoming record, so the last accepted record can push the file slightly past the cap. And once the file sits at or above the limit, records are refused outright — the sample never overwrites old records to make room, and the only trace of a refused record is the log entry.
If the outage can outlast the buffer, the fix is a larger MaxMsgBufferFileSize% or a slower stored-data rate, both decided in the init section before deployment; the next section gives you the number to size it against.
How does replay work when the connection comes back? #
On the transition back to a status of 5, the replay function reads the buffer byte by byte, publishes each completed line on the same topic at QoS 2 with retain 0, logs how many records it sent, and erases the file.
FUNCTION SendSavedEvents()
$FileExist% = FS "isFile", MsgDBPath$
IF $FileExist% = -1 THEN RETURN
$NbrMsg% = 0
OPEN "file:" + MsgDBPath$ FOR BINARY INPUT AS 1
$Line$ = ""
$ReadNext:
IF EOF 1 THEN GOTO $ReadDone
$CHAR$ = GET 1, 1
IF $CHAR$ = CHR$(10) THEN
MQTT "PUBLISH", TopicUsed$, $Line$, 2, 0
$Line$ = ""
$NbrMsg% = $NbrMsg% + 1
ELSE
$Line$ = $Line$ + $CHAR$
ENDIF
GOTO $ReadNext
$ReadDone:
CLOSE 1
LOGEVENT "[MQTT SCRIPT] " + STR$ $NbrMsg% + " saved messages published", 100
ERASE MsgDBPath$
ENDFN
Keep the file-existence guard at the top when you adapt the sample, and expect replay in file order, oldest line first. The loop is synchronous: until it finishes, the script neither publishes live data nor stores new records, and the vendor's caution is that a large buffer takes minutes to clear. The retention risk sits at the end: ERASE runs once the last publish has been issued, with no inspection of publish results and no re-check of the connection inside the loop, so the code never proves broker receipt before deleting the buffer.
If your records must survive until the broker confirms them, that is a different design — MQTT store and forward backfill after a connection outage covers holding records until delivery is confirmed. And when a consumer reports buffered records arriving corrupt or out of order, why buffered MQTT records replay corrupt or out of order diagnoses that failure mode separately.
One boundary to respect: this path is for telemetry and history, never for a signal a safety function acts on.
How much outage can the buffer cover before it fills? #
With a 300-byte payload plus its 1-byte line feed, 301 bytes per record, the cap of 5000000 bytes ends up holding 16612 records, which at one message every 5 seconds covers about 23 hours of continuous outage.
Worked example — the 300-byte payload is illustrative, so weigh one of your real messages and substitute its size:
- Record size: 300 bytes of payload plus the 1-byte line feed = 301 bytes per buffered record.
- Records stored: the size test runs on the file before each append, so the 16612th record passes with the file at 16611 × 301 = 4999911 bytes and lands at 16612 × 301 = 5000212 bytes, just past the cap.
- Outage covered: 16612 records × 5 s = 83060 s = 23.1 hours of continuous outage.
- Replay time: at an assumed 50 milliseconds per publish over a responsive broker link, 16612 × 0.05 s = 830.6 s, about 14 minutes with no live data moving.
Both directions scale linearly, so commit a size before an outage ever happens: double the average record size and the covered outage halves; publish every 10 seconds instead of 5 and it doubles. For this sample's default cap, periodic records at these sizes are protected for roughly a day; a worse outage needs a bigger MaxMsgBufferFileSize% or a slower stored rate, set in the init section, because records past the cap are refused, not queued.
How do I verify the buffer end to end? #
Prove the loop with four checks: a live publish while the status reads connected, a buffer file that grows during an induced outage, a replay log whose count matches the buffered line count, and the broker showing the buffered payloads before live traffic resumes.
- With the gateway on the required release and the broker reachable, confirm MQTT "STATUS" reports the connected value and that live records appear on /topic/flexy/data.
- Break broker connectivity — pull the WAN link or block the broker port at the firewall — and confirm the disconnect log entry appears while /usr/mqttmsg_db.txt grows line by line.
- Restore the link, confirm the connected log entry, and compare the logged replay count with the number of lines you counted in the file; the file is erased after replay.
- On the broker or the receiving platform, confirm the buffered payloads arrived in file order and that live publishing resumed; the payload counter in the sample message makes gaps easy to spot.
Decision, by case: periodic telemetry whose consumers accept replayed records minutes late and without capture timestamps — deploy the sample as-is with the default cap. Trend or historian data that needs original capture times — add a timestamp field to each payload first. Records that must not be lost even across a mid-replay disconnection — move to a confirm-then-delete design rather than this erase-on-issue replay.
Questions asked
Can this buffering script run over TLS?
Yes. Only the connection parameters change: point the MQTT client at the TLS port, TCP 8883 in the sample's convention, and configure the certificate settings your firmware release expects. Status detection, the buffer file and both functions are untouched, because they key on the reported connection state, not on the port.
Do buffered messages survive a gateway restart?
Yes. The buffer is a file in the gateway's permanent user file area, the same place the BASIC program itself is stored, and the script initializes Last_ConnStatus% to -1 so the first connected status read after any start counts as a change and fires the replay. Records saved before a restart are therefore published once the connection is up again.
What happens if the connection drops again during replay?
The replay loop does not recheck the connection state or inspect publish results, and the file is erased once the last line has been handed to the client, so delivery inside that window rests on the QoS 2 acknowledgement alone. If records must not be lost, treat any mid-replay disconnection as an incident and verify receipt on the broker side afterward.
Do replayed records arrive with their original timestamps?
Not in this design. The sample payload is a text line with a counter and no capture time, so a replayed record looks like any live one and the consumer cannot tell when it was measured. If your historian or trend needs the original capture time, add a timestamp field to each payload before buffering is ever needed.
Where should I take the sample script and the firmware upgrade from?
From the gateway vendor's own support portal only. The vendor publishes the sample this article follows in its support knowledge base and ships firmware through its official download channels; matched versions matter, because the script depends on behavior added in a specific firmware release. Copies of scripts on unrelated sites may not match the release they claim.

