TapHome

Listener scripts

TapHome Packet parser listener scripts — process incoming TCP, UDP and MQTT messages with RECEIVEDMSG (topic, payload, protocol) and the older RECEIVEDBYTES byte collection.

A listener script of a Packet parser module or device processes incoming messages — TCP and UDP packets, including answers to a request sent with SENDDATA, and MQTT messages. The message is in the constant RECEIVEDMSG, or in the older RECEIVEDBYTES. Requests and commands are sent with the Packet parser functions.

Listener script

The listener script runs for every message the module receives — a TCP or UDP packet, or an MQTT message whose topic matches the topic filter of the device or module that owns the listener script — and reads it from RECEIVEDMSG.

Remarks

  • An MQTT broker can deliver hundreds of messages a minute. Set the topic filter as narrow as possible, check the topic first and finish with RETURN(0) for messages you do not need.
  • Empty messages do not start the script.
  • More on topic filters in Listener script.

Example — MQTT listener of a Shelly plug

IF INDEXOF(RECEIVEDMSG.TOPIC, "shellies/" + plugTopic) <> 0
    RETURN(0);
END

IF RECEIVEDMSG.TOPIC = "shellies/" + plugTopic + "/relay/0"
    VAR value := TOSTRING(RECEIVEDMSG.PAYLOAD);
    IF value = "on"
        St := 1;
    ELSEIF value = "off"
        St := 0;
    END
ELSEIF RECEIVEDMSG.TOPIC = "shellies/" + plugTopic + "/temperature"
    internalTemp := TODOUBLE(TOSTRING(RECEIVEDMSG.PAYLOAD));
END

RECEIVEDMSG

RECEIVEDMSG holds the message that started the listener script, as a receivedmessage value with the payload and, for MQTT, the topic and metadata.

PropertyTypeMeaning
PROTOCOLstring"tcp", "udp" or "mqtt".
PAYLOADblobRaw payload. Read it as text with TOSTRING(RECEIVEDMSG.PAYLOAD), a single byte with GETAT.
LENGTHnumberPayload length in bytes.
TOPICstringMQTT topic.
CONTENTTYPE, CLIENTIDstringMQTT 5 metadata.
PAYLOADFORMATenumMQTT 5 payload format indicator.
EXPIRYnumberMQTT 5 message expiry interval in seconds.
DUPboolMQTT duplicate flag.

Remarks — For TCP and UDP only PROTOCOL, PAYLOAD and LENGTH carry data. The payload is a blob, which UNPACKVALUE does not accept — use RECEIVEDBYTES for that.

Available — Core 2024.1 or newer.

RECEIVEDBYTES

RECEIVEDBYTES is the older form of the received message: a byte collection (collection<uint8>) that still works and that UNPACKVALUE and GETAT can read directly.

Remarks

  • For TCP and UDP it is the raw payload.
  • For MQTT it is a JSON text with Topic, Payload, PayloadRaw, Dup, ContentType, PayloadFormatIndicator and MessageExpiryInterval, and payloads over 64 kB stop the script. Prefer RECEIVEDMSG, which is faster.

Example — TCP answer to a request sent with SENDDATA

VAR cmd := GETAT(RECEIVEDBYTES, 0);
IF cmd = 0
    Rc := (GETAT(RECEIVEDBYTES, 1) & 0x01) > 0;
END

See also — Binary data, Parsing functions.