MQTT IMPLEMENTATION

MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for constrained devices and low-bandwidth, high-latency, or unreliable networks.

Prerequisites

Before you get started, ensure that you have the following prerequisites installed on your system:

Installation

npm install mqtt

'mqtt' is a popular JavaScript library that provides an MQTT client implementation.

An MQTT client allows your Vue.js application to establish a connection to an MQTT broker (server) and exchange messages with other clients connected to the same broker.

npm install paho-mqtt

'paho-mqtt' is primarily used for JavaScript applications.

It's part of the Eclipse Paho project, which provides MQTT client implementations in various programming languages.

npm install url

'url' helps manage and format URLs, which are essential for connecting to the MQTT broker and specifying the topics you want to subscribe to or publish messages on.

MQTT Variable Setup

Below shows the code That enables the user to connect to the MQTT using Paho-mqtt

import Paho from 'paho-mqtt';

export default {
  data() {
    return {
      client: null, // MQTT client instance
      brokerUrl: 'WebsocketURL', // Replace with your EMQ X WebSocket URL
      username: 'Username', // Replace with your MQTT username
      password: 'Password', // Replace with your MQTT password
    };
  },
}

the code above allows the user to connect to the mqtt using important information like brokerUrl, Username and Password.

The username and password is optional based on if the Mqtt broker is username and password locked.

Websocket URL Types

There are 2 types of websocket URL :

mqtt://

This stands for Message Queuing Telemetry Transport.

Typically the URL format used to connect to MQTT brokers:

  • mqtt://<username>:<password>@<broker_address>:<port>

  • mqtt://<broker_address>:<port>

Commonly used for IoT applications where bandwidth and resources are limited.

ws://

This stands for Websocket.

Typically the URL format:

  • ws://<broker_address>:<port>/mqtt.

This allows real-time, interactive communication between a client (like a web browser) and a server.

Used in web applications to establish a persistent connection between the client and server.

Ports Available

Port Type
Port Number

TCP Port

1883

WebSocket Port

8083

WebSocket Secure Port

8084

Connection Setup

Create a client and connect to the MQTT broker

Replace the test/topic with the topic inside your broker.

connectToMQTT() {
      this.client = new Paho.Client(this.brokerUrl, this.options);

      this.client.onConnectionLost = (responseObject) => {
        if (responseObject.errorCode !== 0) {
          console.error('Connection lost:', responseObject.errorMessage);
        }
      };

      this.client.onMessageArrived = (message) => {
        console.log('Received message:', message.payloadString);
        this.receivedMessages.unshift(message.payloadString);
      };

      this.client.connect({
        onSuccess: () => {
          console.log('Connected to MQTT broker');
          this.client.subscribe('test/topic'); // Subscribe to a topic
        },
        onFailure: (error) => {
          console.error('MQTT Connection Error:', error.errorMessage);
        },
      });
    },
    publishMessage() {
      if (this.messageToSend) {
        const message = new Paho.Message(this.messageToSend);
        message.destinationName = 'test/topic'; // Publish to a topic
        this.client.send(message);
        this.messageToSend = '';
      }
    },

Publishing Message

For publishing messages the following line can be used with the connection code

<input v-model="messageToSend" placeholder="Enter Message" />
    <button @click="publishMessage">Publish</button>

Receiving Message

For Receiving messages the following line can be used with the connection code

<li v-for="(message, index) in receivedMessages" :key="index">{{ message }}</li>

Last updated