Machine to machine communication with IoT Edge and HiveMQ

Machine-to-machine communication(M2M) considers two or more machines communicating with each other.
This communication can involve exchanging data, sending commands in order to regulate sensors, raise alarms, start/stop processes, etc., without human interaction.
Some of the protocols that are widely used in M2M communication are MQTT, OPC-UA, CoAP, LWM2M, etc.

Architecture

In scenarios where devices/machines need to exchange data over MQTT broker, Azure IoT Edge can be useful for managing broker and other container deployments(subscribers, data processors, etc) over the cloud. Another role of IoT Edge in these scenarios is to enable a secure connection to the cloud and to send the telemetry to the cloud.
As a broker, HiveMQ broker is used, which is 100% compliant with MQTT standard(including MQTT 5.0), and makes it a perfect option for M2M communication, especially in cases where machines require specific MQTT features.
More about HiveMQ can be found here.
The following example is composed out of the following components:
– Publisher Machine, that sends the telemetry, temperature, and humidity
– Subscriber Machine(also can act as a publisher if required), that subscribes to the telemetry topic and reacts on the sensor data from Publisher Machine
– IoT Edge as a module(container) deployment orchestrator and cloud communication gateway
– HiveMQ module(container) as MQTT broker
– Subscriber module, processes telemetry data, before sending to the cloud
Architecture of the sample
The architecture of the sample
A MessageSender application was used as a simulator for the publisher machine. This is a UWP application that can send messages to various targets, including the MQTT broker. Any other MQTT client can be used for this purpose.
Subscriber, in this case, is a simple Java application that leverages the HiveMQ library for MQTT brokers.
The following code demonstrates how the topic listener can be implemented with HiveMQ library in Java:
    public static final Mqtt5AsyncClient mqttClient = Mqtt5Client.builder().serverHost("hivemq.test.iotlab").buildAsync();
    private static final MessageConsumer messageConsumer = new MessageConsumer();
    private static final String TopicName = "telemetry";

    protected static class MessageConsumer implements Consumer<Mqtt5Publish> {
      
        @Override
        public void accept(Mqtt5Publish t) {

            byte[] payload = t.getPayloadAsBytes();

            String str = new String(payload, StandardCharsets.UTF_8);

            System.out.println("Received message from the broker: " + str);
        }
    }

    public static void main( String[] args )
    {
        ConnectToMqttBroker();
        try
        {
            System.in.read();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    public static void ConnectToMqttBroker()
    {
        mqttClient.connectWith()
        .send()
        .whenComplete((connAck, throwable) -> {
            if (throwable != null) {
                System.out.println("Authentication failed. Please check your credentials!");
            } else {
                // Handle successful publish, e.g. logging or incrementing a metric
                
                System.out.println("Connected to HiveMQ broker, subscribing to the topic " + TopicName);
                mqttClient.subscribeWith()
                .topicFilter(TopicName)
                .callback(messageConsumer)
                .send()
                .whenComplete((subAck, throwable2) -> {
                    if (throwable2 != null) {
                        System.out.println("Failed to subscribe to the topic " + TopicName);
                    } else {
                        System.out.println("Subscribed to the topic " + TopicName);
                    }
                });
            }
        });
    }
The core part of IoT Edge deployment is the manifest file that describes the deployment. HiveMQ can be found on the DockerHub, and the following configuration is an example of how to pull the HiveMQ docker image and start it via IoT Edge deployment.
        "modules": {
          "HiveMQModule": {
            "settings": {
                "image": "docker.io/hivemq/hivemq4:latest",
				"createOptions": {
					"HostConfig": {
					    "PortBindings": {
						    "1883/tcp": [
						        {
							        "HostPort": "1883"
						        }
						    ],
						    "8080/tcp": [
						        {
							        "HostPort": "8080"
						        }
						    ]
					    }
					}
				}
            },
            "type": "docker",
            "version": "1.0",
            "status": "running",
            "restartPolicy": "always"
          },
          "TelemetrySubscriberModule": {
            "version": "1.0",
            "type": "docker",
            "status": "running",
            "restartPolicy": "always",
            "settings": {
              "image": "${MODULES.TelemetrySubscriberModule}",
              "createOptions": {
                "HostConfig": {
                  "ExtraHosts": [
                    "hivemq.test.iotlab:ip_address_of_iot_edge_host"
                    ]
                }
              }
            }
          }
        }
HiveMQ needs to bind 1883 port for MQTT and 8080 for the broker dashboard.
The full code sample with ‘how to run’ instructions can be found on GitHub.
In order to make the sample working, it is required that the publisher and subscriber machines add additional ‘hosts’ configuration:
#Linux: the hosts can be added in /etc/hosts
IoTEdge_ip_address hivemq.test.iotlab #or any other hostname that will be used in the code
After running the sample and sending the message from the publisher, the subscriber machine console should show that the message came through the HiveMQ broker deployed on Azure IoT Edge.
Simulation of the Publisher machine
The subscriber machine console output after sending the message from the publisher

Finally, the Subscriber Module makes sure that the message ends up on the output, that is passed to the Azure IoT Hub via Routes in Azure IoT Edge Deployment manifest.

"routes": { "TelemetrySubscriberModuleToIoTHub": "FROM /messages/modules/TelemetrySubscriberModule/outputs/* INTO $upstream" }

References:

– HiveMQ documentation: https://www.hivemq.com/docs/4.2/hivemq/introduction.html
– IoT Edge documentation: https://docs.microsoft.com/en-us/azure/iot-edge/

3 Comments on “Machine to machine communication with IoT Edge and HiveMQ”

  1. Hi, how to connect real device to HiveMQ?
    what is the script code for connect a real device to HiveMQ?
    it is possible to integrate HiveMQ with azure Iot Hub as a broker!

    I read some articles here and it seems response to what i want, but i dont know how to start? specialy i want for real device to device communication

  2. Hello,

    Thanks for the question!
    It is possible in a way as presented in the blog. Essentially, the idea is to install/deploy the broker to the Edge(Azure IoT Edge) and have device to device communication implemented over the HiveMQ broker. Regarding the device-to-cloud communication, the idea would be to leverage the IoT Edge Runtime with potentially a custom module that can filter/enrich the messages coming from devices before pushing to the cloud(IoT Hub).

    Please refer to github link below to find the example of IoT Edge Solution with custom module that is subscribed to specific MQTT broker topic and that forwards the messages to IoT Hub.
    https://github.com/kgalic/IoTEdgeM2MWithHiveMQ

    Regarding HiveMQ, since it is a broker that fully implements MQTT you can use any MQTT client to send/subscribe to the topic. In the mentioned repository you can find a Java sample for a subscriber.

  3. Thank you for the answer
    who i can deploy the broker in iot Edge ? there is a documentation for that ? ( step by step )
    the devices they will be connected to iot hub or to HiveMQ ?
    i want to take this solution but i dont know how to begin ! thank you for your answers !

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from

Subscribe now to keep reading and get access to the full archive.

Continue reading