# MQTT (WIP)

MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe network protocol that transports messages between devices. Designed for constrained environments, it is ideal for machine-to-machine (M2M) or Internet of Things (IoT) scenarios. MQTT operates over TCP/IP and aims to be simple and efficient, ensuring high performance and reliability even on low-bandwidth networks.

In MQTT, topics are used to filter and direct messages between clients. A topic is a string, typically representing a hierarchy, that defines the destination of the message. Topics are case-sensitive and use a forward slash (`/`) as a delimiter to create levels of hierarchy. For example, `home/kitchen/temperature` and `home/livingroom/humidity` are distinct topics.

## Creating an MQTT instance

### Creating an MQTT instance

The `create` function creates an MQTT instance with which a client connection to an MQTT broker over an arbitrary transport method (TCP, TLS, WebSocket, ecc) can be [created](#connect). The MQTT client automatically handles the following:

* Regular server pings
* QoS flow
* Automatic reconnections
* Start publishing before being connected

Simply drag the `create` function onto the board, name your instance and trigger.

<figure><img src="https://3495989837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FE5Ketpww1s7TauSAJrJ8%2Fuploads%2F7OZHaW1NJ1cZwfmNpcGl%2Fimage.png?alt=media&#x26;token=91c0be83-8c91-4cbf-9759-98fbfca49649" alt="" width="563"><figcaption><p>Create an MQTT instance</p></figcaption></figure>

### Deleting an MQTT instance

Drag the `delete` function onto the board, insert the name of the instance to be deleted and trigger it.

<figure><img src="https://3495989837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FE5Ketpww1s7TauSAJrJ8%2Fuploads%2F3rCNVHFeDhnWfixGeXRT%2Fimage.png?alt=media&#x26;token=3c2fdd09-0b65-4e97-b4f2-39434b53f6f1" alt="" width="563"><figcaption><p>Delete an MQTT instance</p></figcaption></figure>

## MQTT functions

### connect

With the connect function, you can connect the MQTT instance to a broker.

To create the connection, drag the connect function onto the board. Insert `url: {url}` into the url field, where you replace the curly brackets and their content with your URL. The following protocols are supported: `mqtt`, `mqtts`, `tcp`, `tls`, `ws`, `wss`, `wxs`, `alis`.

Then, in the second input field, add `options: {}` as the main key and insert the following parameters in object format in the brackets as needed.

<table><thead><tr><th width="182">Parameter</th><th width="94">Type</th><th width="92">Default</th><th>Description</th></tr></thead><tbody><tr><td>username</td><td>String</td><td></td><td>The username required by your broker, if any.</td></tr><tr><td>password</td><td>String</td><td></td><td>The password required by your broker, if any.</td></tr><tr><td>wsOptions</td><td>Object</td><td><code>{}</code></td><td>Specific options for WebSockets. Have a look at: <a href="https://github.com/websockets/ws/blob/master/doc/ws.md">https://github.com/websockets/ws/blob/master/doc/ws.md</a>.</td></tr><tr><td>keepalive</td><td>Integer</td><td><code>60</code></td><td>Keep alive interval, set to 0 to disable.</td></tr><tr><td>reschedulePings</td><td>Boolean</td><td><code>true</code></td><td>Reschedule ping messages after sending packets.</td></tr><tr><td>protocolId</td><td>String</td><td><code>MQTT</code></td><td>Protocol ID</td></tr><tr><td>protocolVersion</td><td>Integer</td><td><code>4</code></td><td>Protocol Version</td></tr><tr><td>clean</td><td>Boolean</td><td><code>true</code></td><td>Set to false to receive QoS 1 and 2 messages while offline.</td></tr><tr><td>reconnectPeriod</td><td>Integer</td><td><code>1000</code></td><td>Interval between two reconnections in milliseconds. Disable auto reconnect by setting to 0.</td></tr><tr><td>connectTimeout</td><td>Integer</td><td><code>30000</code></td><td>Time to wait before a CONNACK is received in milliseconds.</td></tr><tr><td>queueQoSZero</td><td>Boolean</td><td><code>true</code></td><td>If connection is broken, queue outgoing QoS zero messages.</td></tr><tr><td>autoUseTopicAlias</td><td>Boolean</td><td><code>false</code></td><td>Enabling automatic Topic Alias assign functionality.</td></tr><tr><td>resubscribe</td><td>Boolean</td><td><code>true</code></td><td>If connection is broken and reconnects, subscribed topics are automatically subscribed again.</td></tr></tbody></table>

### publish

With the publish function, you can send a message to a topic. Insert the topic in the first box, the message in the second one and lastly, decide on the options to publish with.

The options need to be constructed as an object, with the highest key being `options` with the following three parameters nested inside, as needed:

<table><thead><tr><th width="138">Parameter</th><th width="95">Type</th><th width="89">Default</th><th>Description</th></tr></thead><tbody><tr><td>qos</td><td>Integer</td><td>0</td><td>Quality of Service level</td></tr><tr><td>retain</td><td>Boolean</td><td>false</td><td>Whether to retain the message or not. For an explanation of retained messages, see <a href="https://www.hivemq.com/blog/mqtt-essentials-part-8-retained-messages/">here</a>.</td></tr><tr><td>dup</td><td>Boolean</td><td>false</td><td>Marks the message as duplicate.</td></tr></tbody></table>

### publishJson

The `publishJson` function works in the same way as the [publish](#publish) function, but delivers a JSON message instead. Therefore, in the second input field, you should insert a JSON object.

### subscribe

With the `subscribe` function, you can subscribe to one or multiple topics. If you only want to subscribe to one topic or with a wildcard, insert the topic in the first input box and the qos setting in the second one. If you want to subscribe to multiple topics, ignore the options box and insert an object into the topic input box in the following scheme:&#x20;

```javascript
topic1: {qos: 0}
topic2: {qos: 1}
```

{% hint style="info" %}

#### Topic Wildcards

MQTT supports two types of wildcards for subscribing to multiple topics:

1. **Single-level wildcard (`+`)**: Matches exactly one topic level. For instance, `home/+/temperature` matches `home/kitchen/temperature` and `home/livingroom/temperature`.
2. **Multi-level wildcard (`#`)**: Matches all subsequent levels. For example, `home/#` matches `home/kitchen/temperature`, `home/livingroom/humidity`, and any other topic starting with `home/`.

Using these wildcards, you can flexibly subscribe to a range of topics.
{% endhint %}

### onJsonMessage

The `onJsonMessage` function needs to be triggered once after the app is started to start listening to events. It then converts the received events into JSON objects.

### onStringMessage

The `onStringMessage` function needs to be triggered once after the app is started to start listening to events. It then converts the received events into strings.

### onBinaryMessage

The `onBinaryMessage` function needs to be triggered once after the app is started to start listening to events. It leaves the received events in binary format.

### unsubscribe

With the unsubscribe function, you can remove a subscription by inserting the topic name in the input field and triggering.

### end

With `end`, you can disconnect from the MQTT broker. The disconnect may take a second, but can be forced to immediately happen, without waiting for the inflight messages to be handled, by inserting `forced: true` in the input field.

### isConnected

`isConnected` simply returns `true` if a connection to an MQTT broker is open and `false` if not.

<figure><img src="https://3495989837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FE5Ketpww1s7TauSAJrJ8%2Fuploads%2FoIn4X7XclgwWMY2ZyPcv%2Fimage.png?alt=media&#x26;token=89d7c7a1-efe1-4f33-a6aa-fd65b6855a94" alt="" width="563"><figcaption><p>Checking if MQTT connection is open</p></figcaption></figure>

### isReconnecting

With `isReconnecting` you can check if the client is currently trying to reconnect to the MQTT broker. A reconnection in progress is indicated by `true`.

<figure><img src="https://3495989837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FE5Ketpww1s7TauSAJrJ8%2Fuploads%2FLDh7oh0bOzfGL9COLWSp%2Fimage.png?alt=media&#x26;token=62034678-7034-4113-a2d1-0d2ef0bf1bc5" alt="" width="563"><figcaption><p>Checking if MQTT connection is being reestablished</p></figcaption></figure>

### getLastMessageId

You can output the message ID of the last message sent by the client with `getLastMessageId`.

<figure><img src="https://3495989837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FE5Ketpww1s7TauSAJrJ8%2Fuploads%2FivCQ8LtrSKON1Ph7melU%2Fimage.png?alt=media&#x26;token=c566c639-d1ef-4a6c-a487-7012ef85cff5" alt="" width="563"><figcaption><p>Readout of last MQTT message ID</p></figcaption></figure>
