v0.62.0
ReferenceHardwareMQTTRead task

MQTT read task

Subscribe to MQTT topics and record the values in their payloads in channels.

An MQTT read task subscribes to topics on a broker and records the values in their payloads in channels. One task reads any number of topics, and it can also read Sparkplug B tags. Before you start, connect an MQTT broker.

Entries and fields

An entry is one topic. A field is one value in its payload, found by a JSON pointer such as /temperature, and recorded in one channel.

  • Bare values -> an empty pointer reads a topic that carries a bare number or string, such as 42.7. The Add data dialog shows it as Whole payload.
  • Text labels -> the Enum mapping of a field maps text, such as ON, to a channel value.
  • All or nothing -> the task writes all fields of a payload or none. A payload that lacks a field, or holds a value that the channel cannot store, is skipped. In code, a field’s default is written in place of a missing value.

A topic can be in a task once, and it cannot hold the wildcards + or #. The fields of one message share one index channel. Two messages cannot share an index channel, and two topics cannot write to the same channel.

Create an MQTT read task

  1. In the devices toolbar, right-click the broker and select Create read task. You can also run the “Create MQTT read task” command.
  2. Click Add data. The dialog listens to the broker for a few seconds and lists the topics that it saw.
  3. Select a topic to see the last value and the type of each field, then select the fields to record. For a topic that publishes rarely, click Add a topic by name.
  4. Click Add N fields. Each field becomes a channel.
  5. Select a field. Its Field section edits the field in the message format, such as its Pointer. Its Channel section sets the channel name and Data type.
  6. Click (Start).

The Console creates a channel for each field and an index channel for each topic.

Timestamps

The Source of an entry sets the timestamps of its samples:

  • Arrival time -> the time at which the payload arrives at the Core. The default.
  • Payload value -> a time in the payload, at a Pointer, in a Format: ISO 8601, or Unix time in seconds, milliseconds, microseconds, or nanoseconds. The value goes to the index channel of the topic.

Timestamps in an index channel must increase. The task skips a payload whose timestamp is not after the last one it wrote. A broker can send such a payload when it delivers a message twice at quality of service 1.

In code, bind the timestamp field to the index channel, and put the key of the field in index on the message:

# The payload is {"value": 0.42, "ts": 1705312200000}
stamp = sy.icd.TimestampJSONField(
    name="ts", pointer="/ts", time_format="unix_ms"
)
value = sy.icd.FloatJSONField(name="value", pointer="/value")
sample = sy.icd.Message(
    name="sample", payload=sy.icd.JSONPayload(fields=[stamp, value])
)
read = sy.icd.ReadMessage(
    message=sample.key,
    index=stamp.key,
    bindings=[
        sy.icd.ReadBinding(field=stamp.key, channel=sample_time.key),
        sy.icd.ReadBinding(field=value.key, channel=sample_value.key),
    ],
)

Retained messages

When the task subscribes, the broker sends the retained message of each topic, if it has one. The task records it like any other message, but skips it with no warning when its timestamp is not after the last one written. Turn on Ignore retained to always skip it.

Task options

Setting Default Notes
Data saving data_saving_disabled On See data saving.
Auto start auto_start Off Starts the task each time the Core starts.

The task has no sample rate. It writes each payload when it arrives.

Entry and field reference

An entry has these settings:

Setting Default Notes
Topic topic The topic to subscribe to, such as plant/line1/sensors.
Quality of service qos At most once At most once (0), at least once (1), or exactly once (2).
Ignore retained retained_ignored Off Skips the retained message of the topic.
Source index Arrival time The key of the timestamp field, on each ReadMessage.
icd The key of the ICD that holds the messages of the topic.

In code, an entry is PlainReadEntry, of type "plain". The qos values are "at_most_once", "at_least_once", and "exactly_once". Its messages are each an sy.icd.ReadMessage, with the key of the message, its index, and its bindings. An sy.icd.ReadBinding gives the key of a field and the channel that records it.

A field of a message has these settings:

Setting Default Notes
Name name Unique in its message. The Console names channels after it.
Pointer pointer Empty Such as /motor/speed. Empty reads the whole payload.
Type type Float See field types.
Scale scale 1 Multiplies the value. Needs a float channel.
Offset offset 0 Added after the scale. Needs a float channel.
Units units Empty The engineering unit of the value.
Default default None Written when the payload has no value. Set in Optional.
Enum mapping enum_values None Maps text labels to values of the type.

Field types

The data type is that of a new channel. A float channel also reads signed, unsigned, and boolean fields. A signed integer channel also reads unsigned and boolean fields, and an unsigned channel also reads boolean fields. The Data type menu lists only the data types that fit.

Type Python class Data type Notes
Float FloatJSONField float64 A number.
Signed integer IntegerJSONField int64 An integer.
Unsigned integer UnsignedJSONField uint64 An integer of 0 or more.
Boolean BooleanJSONField uint8 true or false, as 1 or 0.
String StringJSONField string A string.
JSON JSONJSONField json Any JSON value.
UUID UuidJSONField uuid A UUID in a string.
Bytes (base64) BytesJSONField bytes Base64 text in a string. Needs a pointer.
Timestamp TimestampJSONField timestamp ISO 8601 text, or Unix time in s, ms, µs, or ns.

In code, the time_format of a timestamp field is "iso8601", "unix_sec", "unix_ms", "unix_us", or "unix_ns".

Troubleshooting

  • Cause

    The task read some messages that it cannot record. The description gives the topic and the reason for the last one, such as field ...: no value at /temperature, or a timestamp that is not after the last one written. The warning clears 5 seconds after the last skip.

    Fix

    Check the pointers and data types against a payload from the topic. Pointers start with / and are case sensitive.

  • Cause

    The task holds up to 4096 messages that wait to be written. More messages arrived, so the task dropped the oldest ones.

    Fix

    Lower the rate at which the devices publish to the topics of the task.

  • Cause

    The broker does not let the user subscribe to the topic, for example because of an access rule. At start, the task does not start. After the connection returns, the task keeps running and shows this warning.

    Fix

    Give the user access to the topic in the broker, then start the task again.

  • Cause

    The connection to the broker is down. The Core connects again on its own, and the warning clears when the connection returns.

  • Cause

    Two entries read the same topic, or two fields write to the same channel.

    Fix

    Move the fields of a topic into one entry, and give each field its own channel.

  • Cause

    The task has no entries, or each entry is disabled.

    Fix

    Add an entry, or enable one.

  • Cause

    The task has no broker. In code, device is empty.

    Fix

    Set device to the key of the broker.

For problems with the connection, see Connect an MQTT broker.