Messaging#
Once a profile is provisioned and assigned to a thing, publishing messages can begin. The following sections will provide an example of message publishing for each of the supported protocols.
Configure Profile Config#
For successful publishing of messages, when creating a profile, it is necessary to define configuration parameters within the structure config.
The config structure consists of the following fields: content_type and transformer.
A content_type field defines the payload format of messages in order to transform and store them properly.
Available formats are SenML, CBOR, and JSON and they can be defined correspondingly with values application/senml+json, application/senml+cbor and application/json.
Here's an example of a SenML-JSON profile config:
{
"config": {
"content_type": "application/senml+json"
}
}
Here's an example of a SenML-CBOR profile config:
{
"config": {
"content_type": "application/senml+cbor"
}
}
The payload of the IoT message often contains message time. It can be in different formats (like base time and record time in the case of SenML) and the message field can be under the arbitrary key. Usually, we would want to map that time to the Mainflux Message field created, and for that reason, we need to configure the transformer to be able to read the field, parse it using proper format and location (if devices time is different from the service time), and map it to Mainflux Message.
When content_type is defined as application/json, inside the transformer structure it is possible to configure the field time_field which is the name of the JSON key to use as a timestamp, time_format to use for the field value and time_location.
Here's an example of a JSON profile config:
{
"config": {
"content_type": "application/json",
"transformer": {
"data_filters": ["val1", "val2"],
"data_field": "field1",
"time_field": "t",
"time_format": "unix",
"time_location": "UTC"
}
}
}
In case it is necessary to extract the received payload and use a specific object within the payload, it is possible to define a value within the data_field field that will be used to extract the payload.
If we have a payload from which we want to get a list of "params", then the config should look like this:
{
"config": {
"content_type": "application/json",
"transformer": {
"data_filters": [],
"data_field": "root.params",
"time_field": "created",
"time_format": "rfc3339",
"time_location": "UTC"
}
}
}
Received payload with params:
{
"root": {
"params": [
{
"field": "temperature",
"value": 20,
"created": "2024-12-24T17:15:55.000Z"
},
{
"field": "humidity",
"value": 45,
"created": "2024-12-24T17:17:00.000Z"
}
]
}
}
The extraction result is:
[
{
"field": "temperature",
"value": 20,
"created": "2024-12-24T17:15:55.000Z"
},
{
"field": "humidity",
"value": 45,
"created": "2024-12-24T17:17:00.000Z"
}
]
Field data_field represents a string containing dot-separated values, unless only first-level extraction is used, then only the field name is enough (for example, "root"). Each of those words represents the level of the JSON payload to be extracted, which is important to specify them correctly for nested objects.
For the messages that contain JSON array as the root element, JSON Transformer does normalization of the data: it creates a separate JSON message for each JSON object in the root.
The data_filters field inside the transformer contains the values based on which the transformer filters incoming payload messages.
If there is certain data that you want to store, you can define it in the data_filters field.
For the previous example, we can filter the extracted payload and save only the fields under the key "field" and "value", then the updated config structure would look like this:
{
"config": {
"content_type": "application/json",
"transformer": {
"data_filters": ["field", "value"],
"data_field": "root.params",
"time_field": "created",
"time_format": "rfc3339",
"time_location": "UTC"
}
}
}
If the data_filters and data_field fields are empty, the whole payload will be used.
Dispatcher Flags#
In addition to content_type and transformer, the profile config accepts three boolean dispatcher flags that control where an incoming message is routed once it's received:
| Flag | Description |
|---|---|
write_enabled |
Publish the message to storage (writers/readers) |
webhook_enabled |
Forward the message to any webhooks registered for the thing |
rule_enabled |
Evaluate the message against rules/scripts assigned to the thing |
These flags are independent — a message can be written to storage without triggering rules, forwarded to webhooks without being persisted, etc. They default to false on newly created profiles — if you leave all three unset, published messages are received by the adapter but never written, forwarded, or evaluated (a silent no-op, with no error returned to the publishing thing). Set the ones you need explicitly:
{
"config": {
"content_type": "application/senml+json",
"write_enabled": true,
"webhook_enabled": true,
"rule_enabled": true
}
}
Webhook delivery itself is configured per-thing — see the Webhooks page. Rule-triggered SMTP/SMPP notifications are configured via rule actions — see the Rules and Notifiers pages.
Subtopics#
In order to use subtopics and give more meaning about the content of messages published or received by subscription, you can simply add any suffix to base /messages topic.
Example subtopic publish/subscribe for bedroom temperature would be /messages/bedroom/temperature.
Subtopics are generic and multilevel. You can use almost any suffix with any depth.
Topics with subtopics are propagated to NATS broker in the following format <format>.messages.<optional_subtopic>.
The format prefix is included in the topic which is obtained from the content_type field specified in the transformer part of the config structure in the Profile.
The prefix value can be set to json or senml.
Our example topic /messages/bedroom/temperature with content_type defined as application/senml+json will be translated to appropriate NATS topic senml.messages.bedroom.temperature.
You can use multilevel subtopics, that have multiple parts. These parts are separated by . or / separators.
When you use combination of these two, have in mind that behind the scene, / separator will be replaced with ..
Every empty part of subtopic will be removed. What this means is that subtopic a///b is equivalent to a/b.
When you want to subscribe, you can use NATS wildcards * and >. A subtopic part can be * or >, but a part that combines a wildcard with other characters is invalid. For example, a.b*c.d is invalid, while a.b.*.c.d is valid.
Note: When using MQTT, it's recommended that you use standard MQTT wildcards + and #.
For more information and examples checkout official nats.io documentation
HTTP#
To publish a message, a thing with a proper profile should send the following request:
curl -s -S -i --cacert docker/ssl/certs/ca.crt -X POST -H "Authorization: Thing <thing_key>" -H "Content-Type: application/senml+json" https://localhost/http/messages -d '[{"bn":"some-base-name:","bt":1.276020076001e+09, "bu":"A","bver":5, "n":"voltage","u":"V","v":120.1}, {"n":"current","t":-5,"v":1.2}, {"n":"current","t":-4,"v":1.3}]'
Note: If you're going to use senml message format, you should always send messages as an array.
The HTTP adapter also supports sending downlink commands to a specific thing or to every thing in a group. A command's payload is an arbitrary JSON body — there's no required envelope shape (the {"command": ..., "params": ...} shown below is just a convention, not an enforced schema). The command is published on NATS and delivered to the target thing over whichever protocol adapter (MQTT, CoAP, WS) it's currently connected through.
Commands can be sent two ways:
- User token (
Authorization: Bearer <user_token>) — the caller must haveeditorrole (or higher) on the target thing's/group's group. No thing-type restrictions apply. - Thing key (
Authorization: Thing <thing_key>) — machine-to-machine (M2M). The sending thing's type must be authorized to command the target thing's type, per this same-group-only policy matrix:
| Sending thing type | Can command |
|---|---|
controller |
sensor, actuator, device |
gateway |
sensor, actuator, device |
device |
device |
sensor |
(none) |
actuator |
(none) |
For group commands sent via thing key, only the sending thing's type is checked (it must have some command authority) — filtering by individual recipient type is left to the receiving things.
# Send a command to a thing (M2M, via thing key)
curl -s -S -i -X POST \
-H "Authorization: Thing <thing_key>" \
-H "Content-Type: application/json" \
https://localhost/http/things/<thing_id>/commands \
-d '{"command":"reboot","params":{"delay":5}}'
# Send a command to all things in a group (as a user)
curl -s -S -i -X POST \
-H "Authorization: Bearer <user_token>" \
-H "Content-Type: application/json" \
https://localhost/http/groups/<group_id>/commands \
-d '{"command":"set_threshold","params":{"value":80}}'
For more information about the HTTP messaging service API, please check out the API documentation.
MQTT#
To send and receive messages over MQTT you could use Mosquitto tools, or Paho if you want to use MQTT over WebSocket.
For example, when using Mosquitto, one could publish a message using the following command:
mosquitto_pub -u [internal|external] -P <key> -t /messages -h localhost -m '[{"bn":"some-base-name:","bt":1.276020076001e+09, "bu":"A","bver":5, "n":"voltage","u":"V","v":120.1}, {"n":"current","t":-5,"v":1.2}, {"n":"current","t":-4,"v":1.3}]'
Note that the MQTT username should be either the literal internal or external depending on if you're authenticating with an internal or external thing key.
To subscribe to a topic, for example:
mosquitto_sub -u [internal|external] -P <key> -t /messages -h localhost
If you are using TLS to secure MQTT connection, add --cafile docker/ssl/certs/ca.crt
to every command.
Subscriptions#
The MQTT adapter records each topic, as sent by the client, that the things of a group subscribe to. Listing them requires the viewer role in the group and supports offset, limit and topic (partial match) query parameters:
curl -s -S -i \
-H "Authorization: Bearer <user_token>" \
"https://localhost/subs/groups/<group_id>/subscriptions?offset=0&limit=10"
{
"total": 1,
"offset": 0,
"limit": 10,
"subscriptions": [
{
"topic": "/messages/bedroom/temperature",
"thing_id": "111e4567-e89b-12d3-a456-426614174000",
"group_id": "211e4567-e89b-12d3-a456-426614174000",
"created_at": 1774342578.003
}
]
}
created_at is the Unix time of the subscription in seconds. Subscriptions are removed when the thing or the group is removed.
CoAP#
CoAP adapter implements CoAP protocol using underlying UDP and according to RFC 7252. It listens on two ports:
| Port | Scheme | Authentication |
|---|---|---|
| 5684 | coaps:// |
DTLS handshake with a pre-shared key (recommended) |
| 5683 | coap:// |
Thing key in the auth query of every request |
DTLS#
Over DTLS a thing authenticates once, in the handshake, and its requests carry no key. The key itself is never sent over the network.
- PSK identity: the thing ID
- PSK: the first 32 hex characters of the SHA-256 hash of the thing key
The PSK is derived from the key because constrained DTLS stacks (mbedTLS, tinydtls, nRF91 modems) accept pre-shared keys of at most 32 bytes, and the key is longer. Compute it with:
echo -n <thing_key> | sha256sum | cut -c1-32
A wrong key or an unknown thing ID fails the handshake. The adapter supports the TLS_PSK_WITH_AES_128_CCM_8 and TLS_PSK_WITH_AES_128_GCM_SHA256 cipher suites, and DTLS Connection IDs (RFC 9146): a client that negotiates one keeps its session when NAT changes its address or port.
For example, with libcoap:
PSK=$(echo -n <thing_key> | sha256sum | cut -c1-32)
coap-client-openssl -m post -e '{"v":1}' -u <thing_id> -k "$PSK" "coaps://localhost/things/<thing_id>/messages"
A DTLS session with no traffic from the thing for MF_COAP_ADAPTER_DTLS_IDLE_TIMEOUT (5 minutes by default) is closed, together with its observations. A thing that only observes commands should send something more often, for example a message or a CoAP ping, which also keeps carrier NAT mappings alive.
Plain CoAP#
Plain CoAP sends everything in cleartext, including the thing key, so it should be disabled with MF_COAP_ADAPTER_PLAIN_ENABLED=false once things use DTLS. To send and receive messages over plain CoAP, you can use CoAP CLI. To set the add-on, please follow the installation instructions provided here.
Examples:
coap-cli get /messages/subtopic -auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -o
coap-cli post /messages/subtopic -auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -d "hello world"
coap-cli post /messages/subtopic -auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -d "hello world" -h 0.0.0.0 -p 1234
Observing#
To send a message, use a POST request. To observe a resource (RFC 7641), send a GET request with the Observe option set to 0 (register, flag -o in CoAP CLI). Notifications are confirmable, so the thing must acknowledge them.
An observation ends when the thing sends a GET request with the Observe option set to 1 (deregister), or when its connection closes.
Configuration#
| Variable | Description | Default |
|---|---|---|
MF_COAP_ADAPTER_PLAIN_ENABLED |
Whether the plain CoAP listener (5683) is started | true |
MF_COAP_ADAPTER_DTLS_PORT |
DTLS (coaps) listening port |
5684 |
MF_COAP_ADAPTER_DTLS_IDLE_TIMEOUT |
Time after which an idle DTLS session is closed | 5m |
For all variables, see the adapter documentation.
Sending Commands#
Commands (see Downlink Commands above) can also be sent over CoAP, using the same things/<id>/commands and groups/<id>/commands paths as the HTTP adapter, via POST. CoAP only supports thing-key (M2M) authentication for commands — there is no user-token path over CoAP.
coap-cli post things/<thing_id>/commands -auth <thing_key> -d '{"command":"reboot","params":{"delay":5}}'
coap-cli post groups/<group_id>/commands -auth <thing_key> -d '{"command":"set_threshold","params":{"value":80}}'
Over DTLS, use the same paths without the auth query, since the session already authenticates the thing.
WS#
Mainflux supports MQTT-over-WS, rather than pure WS protocol. This brings numerous benefits for IoT applications that are derived from the properties of MQTT - like QoS and PUB/SUB features.
There are 2 recommended Javascript libraries for implementing browser support for Mainflux MQTT-over-WS connectivity:
Mainflux exposes MQTT-over-WS on the HTTP port (80) under the /mqtt path, so the connection URL is ws://<host_addr>/mqtt.
For quick testing you can use HiveMQ UI tool.
Here is an example of a browser application connecting to Mainflux server and sending and receiving messages over WebSocket using MQTT.js library:
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
// Initialize a mqtt variable globally
console.log(mqtt)
// connection option
const options = {
clean: true, // retain session
connectTimeout: 4000, // Timeout period
// Authentication information
clientId: '14d6c682-fb5a-4d28-b670-ee565ab5866c',
username: 'internal',
password: '<thing_key>',
}
var topic = '/messages'
// Connect string, and specify the connection method by the protocol
// ws Unencrypted WebSocket connection
// wss Encrypted WebSocket connection
const connectUrl = 'ws://localhost/mqtt'
const client = mqtt.connect(connectUrl, options)
client.on('reconnect', (error) => {
console.log('reconnecting:', error)
})
client.on('error', (error) => {
console.log('Connection failed:', error)
})
client.on('connect', function () {
console.log('client connected:' + options.clientId)
client.subscribe(topic, { qos: 0 })
client.publish(topic, 'WS connection demo!', { qos: 0, retain: false })
})
client.on('message', function (topic, message, packet) {
console.log('Received Message:= ' + message.toString() + '\nOn topic:= ' + topic)
})
client.on('close', function () {
console.log(options.clientId + ' disconnected')
})
</script>
N.B. Eclipse Paho lib adds sub-URL /mqtt automatically, so procedure for connecting to the server can be something like this:
var loc = { hostname: "localhost", port: 80 };
// Create a client instance
client = new Paho.MQTT.Client(loc.hostname, Number(loc.port), "clientId");
// Connect the client
client.connect({ onSuccess: onConnect });
Native WebSocket Adapter (Commands)#
Sending downlink commands over WebSocket uses a separate service from the MQTT-over-WS connection described above — the native ws-adapter, which speaks plain WebSocket (not MQTT) and listens on its own port (MF_WS_ADAPTER_PORT, default 8190), not the nginx /mqtt path. Each WS connection is scoped to one thing or group; every text/binary frame the client sends over that connection becomes the payload of one command.
Authentication can be supplied either via headers or, for browser clients that can't set custom headers on a WebSocket handshake, via query parameters:
- Thing key (M2M):
Authorization: Thing <thing_key>header, or?key=<thing_key>&keyType=<internal|external> - User token:
Authorization: Bearer <user_token>header, or?token=<user_token>
// Connect and send a command to a thing (M2M, via thing key query params)
const ws = new WebSocket(
"ws://localhost:8190/things/<thing_id>/commands?key=<thing_key>&keyType=internal",
);
ws.onopen = () => {
ws.send(JSON.stringify({ command: "reboot", params: { delay: 5 } }));
};
// Connect and send a command to a group, authenticated as a user
const ws = new WebSocket(
"ws://localhost:8190/groups/<group_id>/commands?token=<user_token>",
);
ws.onopen = () => {
ws.send(JSON.stringify({ command: "set_threshold", params: { value: 80 } }));
};