Connect to MQTT Broker

This chapter serves as a short tutorial how to connect to a MQTT broker. In this example we will be using a RabbitMQ docker image. For other MQTT brokers the example should only differ in the connection string (mainBrokerURL) and most, if not all, brokers which are supported by Eclipse Paho should be supported by structr.

Step 1: Install RabbitMQ

First we need to start a RabbitMQ docker instance. We select and modify one of the default docker images provided by RabbitMQ (https://hub.docker.com/_/rabbitmq)

We expose port 15675 to connect to it later locally.

docker run -d --hostname my-rabbit --name some-rabbit -p 8080:15672 -p 5672:5672 -p 15675:15675 rabbitmq:3-management

Let’s assume the docker container id is 459dbf747dac. We need this in the next step.

Step 2: Install RabbitMQ Web MQTT plugin

First, we open a shell inside the docker container:

docker exec -it 459dbf747dac /bin/sh

Inside the container we now enable the necessary plugin:

rabbitmq-plugins enable rabbitmq_web_mqtt

Step 3: Create MQTTClient and MessageSubscriber

In our structr instance we navigate to the data section and select the type MQTTClient.

We create a new object with the following attributes (the default settings for RabbitMQ)

mainBrokerURL = 'ws://localhost:15675/ws'
username = 'guest'
password = 'guest'

Afterwards we check the isEnabled checkbox which triggers the client to connect to the server. If everything is configured properly it will blink green - otherwise it will blink red and result in an error.

Then we select the type MessageSubscriber and create a new MessageSubscriber with the following attributes:

topic = '*'
callback = "{ $.log($.topic, ': ', $.message) }"

This instructs the subscriber to listen to any topic and simply log the messages to the server log. We could also forward the messages to any global schema method - for example handleIncomingMQTTMessage like this:

{
  $.call('handleIncomingMQTTMessage', { topic: $.topic, message: $.message });
}