How-to
Write tags on an edge gateway from an MQTT JSON payload
Short answer
Yes. Subscribe the gateway to one command topic with QoS 0, publish a flat JSON object whose property names match tag names exactly, and run a BASIC callback that splits the payload at commas, writes strings directly when the tag type is "6", converts numerics through VAL, and skips any name that fails to load with LSTERR -4.
On this page
- What the write path requires
- Define the payload the handler can parse
- Register the callback and the subscription
- The handler and its helper function
- How a fragment becomes a tag write
- Why an undefined name is skipped, not fatal
- Test the write path
- When the platform's own writeback fits better
- Questions asked
Yes, and without a server in the middle. Subscribe the gateway to a single command topic at QoS 0, have the publishing client send one flat JSON object whose property names are the gateway's tag names, and let a BASIC callback do the rest: split the payload at every comma, resolve each name, write strings directly when the loaded tag reports type "6", convert everything else through VAL, and skip any name whose load fails with LSTERR -4. One wrong property costs one skip; the remaining properties still land. Below are the two setup lines, the handler, the parse arithmetic on a real payload, and the tests that prove the writes.
What the write path requires #
Most gateway MQTT setups only publish: tags flow up to the broker and the SCADA side subscribes. Writing tags the other way needs three capabilities on the gateway, and the BASIC dialect used here has all of them:
- an MQTT implementation that can subscribe, not just publish — if yours cannot, that limitation has its own answers beyond this handler (when an edge gateway has no MQTT subscribe function);
- an incoming-message callback,
ONMQTT, so the script reacts the moment a message arrives instead of polling; - runtime tag resolution through
SETSYS Tag, "load"and a write throughSETIO, so a name read out of the payload becomes a value in a tag.
Accepting writes by subscription is an established pattern rather than a hack: commercial IoT-gateway products document MQTT subscriptions specifically to accept write operations. Whether you use a native function or the handler below, the shape is identical — one command topic in, values into tags.
Define the payload the handler can parse #
Publish one flat JSON object whose property names match configured tag names exactly:
{"TestMQTT":0,"TestMQTT1":12.3,"TestMQTT3_StringTag":"test string value"}
TestMQTT, TestMQTT1 and TestMQTT3_StringTag stand for the tag names you configure. Full JSON as specified in RFC 8259 allows objects and arrays as values; this handler accepts a deliberate subset — a flat object whose values are bare numbers or quoted strings. No nesting, no arrays, and no commas inside string values, because the handler splits the payload at every comma and treats each fragment as one name/value pair: a comma inside a batch-id string would start a new fragment and corrupt both writes. Flat payloads also spare the consuming side, since nested JSON is a recognized fault class where a subscriber shows blank points (SCADA MQTT points blank with nested JSON payloads).
Register the callback and the subscription #
- Open the gateway's existing MQTT script and locate the
MQTT "Connect"statement. - Immediately after it, add
ONMQTT "Goto MqttRx". Every message the broker delivers on a subscribed topic now jumps the script to theMqttRxlabel. - On the next line, add
MQTT "subscribe", "topicToUpdateTag", 0, replacingtopicToUpdateTagwith your command topic. The publishing client must publish to exactly that topic text. - Accept the delivery semantics of QoS 0: at most once. A publish lost between broker and gateway is a missed write with no retry. That is acceptable for state the publisher re-sends on a cycle; for a one-shot setpoint, send it twice or confirm it by reading the tag back.
Anyone who can publish to this topic can change your process values, so use broker-side ACLs to allow only the intended publisher onto it.
The handler and its helper function #
The handler is written in the BASIC scripting dialect used by this class of edge gateway. The system and IO statement names — ONMQTT, MQTT, SETSYS, GETSYS, SETIO, VAL, INSTR — belong to that dialect; names like MsgData$ and TagNameToWrite$ are the script's own variables, where the % suffix marks an integer and $ a string, and the helper's locals carry a $ prefix.
MqttRx:
MessageQty% = MQTT "READ"
IF (MessageQty% > 0) THEN
MsgTopic$ = MQTT "MSGTOPIC"
MsgData$ = MQTT "MSGDATA"
PRINT "Subscribe Message Received:" + MsgTopic$
PRINT "Message:" + MsgData$
posJson% = 1
ReadJsonNext:
JsonPart$ = @SplitString$(MsgData$, posJson%, ",")
posJson% = posJson% + 1
IF JsonPart$ = "" THEN GOTO ReadJsonEnd
JsonPart$ = JsonPart$ + "}"
Pos1stQuote% = INSTR 1, JsonPart$, '"'
Pos1stQuote% = Pos1stQuote% + 1
Pos2stQuote% = INSTR Pos1stQuote%, JsonPart$, '"'
TagNameToWrite$ = JsonPart$(Pos1stQuote% TO Pos2stQuote%-1)
Pos1stColumn% = INSTR 1, JsonPart$, ':'
Pos1stColumn% = Pos1stColumn% + 1
Pos2stBraket% = INSTR Pos1stColumn%, JsonPart$, '}'
TagValueToWrite$ = JsonPart$(Pos1stColumn% TO Pos2stBraket%-1)
IF TagValueToWrite$ > "" THEN
SETSYS PRG, "RESUMENEXT", 1
SETSYS Tag, "load", TagNameToWrite$
LastError% = GETSYS PRG, "LSTERR"
IF LastError% = -4 THEN
SETSYS PRG, "RESUMENEXT", 0
GOTO ReadJsonNext
ENDIF
myType$ = GETSYS TAG, "Type"
IF myType$ = "6" THEN
TagValueToWrite$ = JsonPart$(Pos1stColumn%+1 TO Pos2stBraket%-2)
SETIO TagNameToWrite$, TagValueToWrite$
ELSE
SETIO TagNameToWrite$, VAL TagValueToWrite$
ENDIF
SETSYS PRG, "RESUMENEXT", 0
ENDIF
GOTO ReadJsonNext
ReadJsonEnd:
GOTO MqttRx
ENDIF
END
FUNCTION SplitString$ ($StringToParse$, $Pos%, $char$)
$e% = 1
$loopnbr% = 0
$NextItem:
$f% = INSTR $e%, $StringToParse$, $char$
IF $f% = 0 THEN
$B$ = $StringToParse$($e% TO LEN $StringToParse$)
IF $Pos% > $loopnbr% + 1 THEN $B$ = ""
GOTO $EndOfLine
ENDIF
$loopnbr% = $loopnbr% + 1
$B$ = $StringToParse$($e% TO $f%-1)
IF $Pos% = $loopnbr% THEN GOTO $EndOfLine
$e% = $f% + 1
GOTO $NextItem
$EndOfLine:
$SplitString$ = $B$
ENDFN
Each pass drains one message. MQTT "READ" returns how many messages are pending, and the GOTO MqttRx after the parse loop re-reads that count until it returns 0, so a burst of publishes is processed in arrival order rather than one overwriting the next.
How a fragment becomes a tag write #
The two commas in the example payload split it into three fragments, and each gets a } appended before parsing. The positions below are the actual character positions in each fragment:
Fragment with } appended |
Characters | Name found | Raw value | Written |
|---|---|---|---|---|
{"TestMQTT":0} |
14 | JsonPart$(3 TO 10) → TestMQTT |
JsonPart$(13 TO 13) → 0 |
VAL "0" → 0 |
"TestMQTT1":12.3} |
17 | JsonPart$(2 TO 10) → TestMQTT1 |
JsonPart$(13 TO 16) → 12.3 |
VAL "12.3" → 12.3 |
"TestMQTT3_StringTag":"test string value"}} |
43 | JsonPart$(2 TO 20) → TestMQTT3_StringTag |
JsonPart$(23 TO 41) |
JsonPart$(24 TO 40) → test string value |
In the first fragment the leading { pushes the opening quote to position 2, so the name runs from 3 to 10; in the later fragments the quote sits at 1 and the name starts at 2. The value runs from just after the colon to just before the first } that follows it. The third fragment ends with two braces — the payload's own at position 42 and the appended one at 43 — and parsing stops at the first, so the extra brace is never read. The string path writes characters 24 to 40, dropping positions 23 and 41, which are exactly the two JSON quotation marks; the numeric path hands its raw text to VAL, so "12.3" becomes the number 12.3.
Why an undefined name is skipped, not fatal #
SETSYS PRG, "RESUMENEXT", 1 tells the runtime to keep executing after a statement fails. The next statement, SETSYS Tag, "load", TagNameToWrite$, fails when the name matches no configured tag, and GETSYS PRG, "LSTERR" returns -4 for that condition. The handler restores RESUMENEXT to 0 and jumps to the next fragment: one wrong property costs one skip, not the payload. Console errors can still appear during the skip even while the valid tags update; in the reported runs they were cosmetic and the defined tags wrote correctly. To avoid the noise, pre-validate the names — read the tag count with GETSYS PRG, "NBTAGS", fill a name array with GETSYS Tag, "name", and compare inside the handler, indexing the array in place as described in the FAQ above rather than passing it to a helper function.
Test the write path #
- Confirm the two added lines sit after
MQTT "Connect"; a subscription registered before the connection exists will not hold. - Publish a payload holding one existing numeric tag and one existing string tag. Check that the numeric landed as a number and the string landed without its quotation marks.
- Publish the same payload with an undefined property placed first. Check that it is skipped and the two real tags still update.
- Publish a second time with a changed value. A second publish that does not register on a JSON subscriber is a known symptom in its own right (an MQTT Engine JSON payload not updating on the second publish).
- If nothing writes at all, compare the topic in the handler's console print against the subscribed topic text, then compare each property name against the tag name character for character.
- Read the tags back from the gateway to prove the values landed.
When the platform's own writeback fits better #
Hand-rolling this path makes sense when the publisher is foreign to the gateway — any MQTT client on any platform. When both ends already belong to one ecosystem, use its native path instead. MQTT Transmission on the edge gateway supports publish, subscribe and writeback over Sparkplug, with the write-down-to-edge direction enabled from the central gateway's Engine settings (Ignition Edge MQTT Transmission publish, subscribe and writeback). SCADA servers with a matched pair of publish and subscribe topics do the same in a bidirectional MQTT configuration (WinCC OA bidirectional MQTT publish and subscribe setup).
The decision, by case: flat JSON over a QoS 0 subscription when the publisher is foreign and the gateway is BASIC-programmable; native writeback when both ends already speak the same ecosystem's MQTT; either way, one command topic and one authorized publisher.
Questions asked
How many tags can one MQTT message update?
The loop runs until the splitter returns an empty fragment, so the handler imposes no tag count; the practical limit is the payload size your broker and gateway accept. Three properties in one object is the documented working case, and processing follows the order the properties appear in the JSON text, left to right.
Why do console errors appear even though the tags updated?
The failed tag load on the undefined name raises the console error while RESUMENEXT keeps the script running, so the properties after it still write. In the reported runs the errors were cosmetic and the defined tags updated correctly. Silence them by validating names before the load, not by removing the skip.
How do I validate tag names before writing them?
At startup, read the tag count with GETSYS PRG, "NBTAGS", dimension a string array for the names, and fill it with GETSYS Tag, "name" in a loop. Compare each JSON property name against that array inside the handler. Arrays cannot be passed as function arguments in this BASIC dialect, so index the array directly rather than passing it to a helper.
What happens if I publish a string value without quotation marks?
The string path always removes one character from each end of the raw value because it assumes they are the JSON quotes. An unquoted value therefore arrives with its first and last character missing. Publish string values as quoted JSON strings so the characters stripped are the quotes and nothing else.
Does the gateway acknowledge the write back to the publisher?
No. The handler prints the received topic and payload to the console and writes the tags, but it publishes nothing in return. If the sender needs confirmation, add a publish to a status topic after the parse loop finishes, or have the sender verify by reading the tag back through its own subscription.