Home

Awesome

Vue-Paho-Mqtt Plugin

<p align="center"> <img src="https://github.com/kaandesu/vue-paho-mqtt/raw/master/assets/logo.png" height="100" alt="Vue-Paho-Mqtt-Logo" /> </p> <p align="center"> <a href="https://www.npmjs.com/package/vue-paho-mqtt"> <img src="https://img.shields.io/npm/v/vue-paho-mqtt?style=for-the-badge" alt="npm version"> </a> <a href="https://github.com/kaandesu/vue-paho-mqtt/actions/workflows/build.yml"> <img src="https://img.shields.io/github/actions/workflow/status/kaandesu/vue-paho-mqtt/build.yml?style=for-the-badge" alt="build status"> </a> <a href="https://github.com/kaandesu/vue-paho-mqtt/graphs/contributors"> <img src="https://img.shields.io/github/contributors/kaandesu/vue-paho-mqtt?style=for-the-badge" alt="contributors"> </a> <a href="https://github.com/kaandesu/vue-paho-mqtt/issues"> <img src="https://img.shields.io/github/issues/kaandesu/vue-paho-mqtt?style=for-the-badge" alt="issues"> </a> <a href="https://github.com/kaandesu/vue-paho-mqtt/pulls"> <img src="https://img.shields.io/github/issues-pr/kaandesu/vue-paho-mqtt?style=for-the-badge" alt="pr"> </a> <a href="https://github.com/kaandesu/vue-paho-mqtt/commits/master" alt="Commit Activity"> <img src="https://img.shields.io/github/commit-activity/m/kaandesu/vue-paho-mqtt?style=for-the-badge" /> </a> </p>

The vue-paho-mqtt plugin provides a convenient way to use the Eclipse Paho MQTT JavaScript client with Vue 3.

This plugin allows you to connect to a MQTT broker and subscribe to topics in your Vue app. It uses paho-mqtt to connect to the broker and provides several useful features such as auto-reconnect, message handlers, and error notifications.

Live demo

Table of contents

Installation

Install the package using npm:

npm install vue-paho-mqtt

Setup

To use the plugin, you need to create an instance of it and pass it to the use function:

Vite / VueCLI

// src/main.ts
import App from './App.vue';
import { createApp } from 'vue';
import { createPahoMqttPlugin } from 'vue-paho-mqtt';

createApp(App)
  .use(
    createPahoMqttPlugin({
      PluginOptions: {
        autoConnect: true,
        showNotifications: true,
      },

      MqttOptions: {
        host: 'localhost',
        port: 9001,
        clientId: `MyID-${Math.random() * 9999}`,
        mainTopic: 'MAIN',
      },
    }),
  )
  .mount('#app');

Quasar Framework (quasar boot)

import { boot } from 'quasar/wrappers';
import { createPahoMqttPlugin } from 'vue-paho-mqtt';

export default boot(({ app }) => {
  app.use(
    createPahoMqttPlugin({
      PluginOptions: {
        autoConnect: true,
        showNotifications: true,
      },

      MqttOptions: {
        host: 'localhost',
        port: 9001,
        clientId: `MyID-${Math.random() * 9999}`,
        mainTopic: 'MAIN',
      },
    }),
  );
});

Nuxt3 (nuxt plugins)

import { createPahoMqttPlugin } from 'vue-paho-mqtt';
export default defineNuxtPlugin({
  name: 'vue-paho-mqtt',
  enforce: 'pre',
  async setup(nuxtApp) {
    nuxtApp.vueApp.use(
      createPahoMqttPlugin({
        PluginOptions: {
          autoConnect: true,
          showNotifications: true,
        },
        MqttOptions: {
          host: 'localhost',
          port: 9001,
          clientId: `MyID-${Math.random() * 9999}`,
          mainTopic: 'MAIN',
        },
      }),
    );
  },
  hooks: {
    'app:created'() {
      const nuxtApp = useNuxtApp();
    },
  },
});

Options

Plugin Options

You can configure the plugin by passing an object with the following options to createPahoMqttPlugin:

MQTT Options

You can configure the MQTT client by passing an object with the following options to createPahoMqttPlugin:


MQTT Quality of Service (QoS) and Retention Options for Publish

The MQTT protocol provides Quality of Service (QoS) levels to control the reliability of message delivery between a publisher and a subscriber. Additionally, it provides the ability to retain messages, allowing subscribers to receive messages even if they connect after the message has been published.

The following are the MQTT QoS and retention options available for publishing messages:

typeOptionQoS LevelRetain
stringB0false
stringBr0true
stringQ1false
stringQr1true
stringF2true
stringFnr2false
type MqttMode = 'B' | 'F' | 'Q' | 'Qr' | 'Br' | 'Fnr';

Example Usage with the $mqtt.publish

$mqtt.publish('test/topic', 'Hello, world!', 'Fnr');

Notification Alerts

The Vue Paho MQTT plugin comes with built-in notifications using SweetAlert2 library to display the notification alerts. This library is already installed with the plugin. <br>

createPahoMqttPlugin({
      PluginOptions: {
        showNotifications: true,
        ...
      }
      ...
OnIconTitleContentTimer
Connection Successsuccess"Connected""MQTT Connected"1500
Connection Failureerror"Mqtt Error""MQTT failed to connect"-
Connection Timeouterror"Mqtt Error""Broker connection timed out"-
Connection Losterror"Mqtt Error""MQTT connection lost"-
Disconnect Errorerror"Error"catch(error) => error.message-
Connect Errorerror"Error"catch(error) => error.message-

Global MQTT client instance: $mqtt

Connect

Connect to the MQTT broker. Shows a dialog notification in case of error if the plugin is configured to do so. Custom callbacks can be passed to the connect function. Such as onConnect, onFailure, onConnectionLost, onMessageArrived.

Note: Inside the 'subscribe' function a function is passed to the 'onMessageArrived' callback. This function is used to parse the message payload and return the parsed message inside the subscribe function where it is called. You don't really need to handle arriving messages in the 'onMessageArrived' callback.

Type Definition

const connect: ({
  onConnect?: ((...args: unknown[]) => unknown) | undefined;
  onFailure?: ((...args: unknown[]) => unknown) | undefined;
  onConnectionLost?:
    | ((
        responseObject: {
          errorCode: number;
        },
        ...args: unknown[]
      ) => unknown)
    | undefined;
  onMessageArrived?:
    | ((
        message: {
          payloadString: string;
          destinationName: string;
        },
        ...args: unknown[]
      ) => unknown)
    | undefined;
}) => Promise<boolean>;

Usage

// Composition API
import { $mqtt } from 'vue-paho-mqtt';
$mqtt.connect();

// Options API
this.$mqtt.connect();

// or use it with async/await
const result = await $mqtt.connect();
// result will return "true" if the connection was successful

Optional Custom Callbacks

CallbackWhenReturn
onConnectsuccessfully connected to the mqtt broker-
onFailurefailed to connect to the mqtt broker-
onConnectionLostdisconnected or connection lost connectionresponseObject: {errorCode: number}
onMessageArrivedmessage arrived from one of the subscribed topicsmessage: {payloadString: string;destinationName: string;}

Custom Callback Usage example

$mqtt.connect({
  onConnect: () => {
    console.log('Mqtt connected');
  },
  onFailure: () => {
    console.log('Mqtt connection failed');
  },
  onConnectionLost: (error: any) => {
    console.log('Error:', error.message);
  },
  onMessageArrived: (message: {
    payloadString: string;
    destinationName: string;
  }) => {
    console.log(
      'Message Arrived:',
      message.payloadString,
      message.destinationName,
    );
  },
});

Disconnect

Disconnect from the mqtt broker. Shows a dialog notification in case of error if the plugin is configured to do so.

Type Definition

const disconnect: () => Promise<boolean>;

Usage

// Composition API
import { $mqtt } from 'vue-paho-mqtt';
$mqtt.disconnect();

// Options API
this.$mqtt.disconnect();

// or use it with async/await
const result = await $mqtt.disconnect();
// result will return "true" if the disconnection was successful

Subscribe

It is used to subscribe to the topic specified, and to define the function to call when the specified topic recieves a message.

paramtypeexplanationdefault
topicstringMQTT topic to subscribe (ie: 'my/test/topic')-
onMessagefunctionArrow function with a parameter to be fired when a message arrives to the specified topic-
useMainTopicbooleanmain topic defined in the MQTT Options will be prepended to the topic specifiedtrue

Type Definition

const subscribe: (
  topic: string,
  onMessage: (data: string, ...args: unknown[]) => unknown,
  useMainTopic?: boolean,
) => void;

Subscribe usage example

// if the enableMainTopic is true, subscribe to 'MAIN/my/topic'
this.$mqtt.subscribe('my/topic', (data: string) => {
  console.log(data, 'recieved');
});

// even if the enableMainTopic is true, subscribe to 'my/topic'
this.$mqtt.subscribe(
  'my/topic',
  (data: string) => {
    console.log(data, 'recieved');
  },
  false,
);

Composition API

import { $mqtt } from 'vue-paho-mqtt';

$mqtt.subscribe('my/topic', (data: string) => {
  console.log(data, 'recieved');
});

Publish

Used to publish string data to the topic specified.

Type Definition

const publish: (
  topic: string,
  payload: string,
  mode: MqttMode,
  useMainTopic?: boolean,
) => void;
paramtypeexplanationdefault
topicstringMQTT topic to publish (ie: 'my/test/topic')-
payloadstringstring payload to send-
modeMqttModeSee MQTT Quality of Service (QoS) and Retention Options for Publish for detailed explanation for mqtt mode options.  ["B" | "F" | "Q" | "Qr" | "Br" | "Fnr"]-
useMainTopicbooleanmain topic defined in the MQTT Options will be prepended to the topic specifiedtrue

Publish usage example

// if the enableMainTopic is true, publish to 'MAIN/my/topic'
// 'Fnr' => Qos: 2 , retained: false
this.$mqtt.publish('test/topic', 'Hello, world!', 'Fnr');

// even if the enableMainTopic is true, publish to 'my/topic'
// 'B' => Qos: 0 , retained: false
this.$mqtt.publish('test/topic', 'Hello, world!', 'B', false);

// if the enableMainTopic is true, publish to 'MAIN/my/topic'
// 'Qr' => Qos: 1 , retained: true
this.$mqtt.publish('test/topic', 'Hello, world!', 'Qr');

// payload: "Hello, world!"

Composition API

import { $mqtt } from 'vue-paho-mqtt';

$mqtt.publish('test/topic', 'Hello, world!', 'Qr');

Host

Get or set the host parameter from the MQTT Options.

Type Definition

const host: (e?: string) => string;

Get Host

$mqtt.host(); // ie: "localhost"

Set MQTT host

$mqtt.host('192.168.0.1');

Example usage

<template>
  <label>MQTT host: {{ $mqtt.host() }}</label>
</template>
onMounted(() => {
  console.log(this.$mqtt.host());
});

Composition API

import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';

onMounted(() => {
  console.log($mqtt.host());
});

Port

Get or set the port parameter from the MQTT Options.

Type Definition

const port: (e?: number) => number;

Get Port

$mqtt.port(); // ie: 9001

Set MQTT port

$mqtt.port(1234);

Example usage

<template>
  <label>MQTT port: {{ $mqtt.port() }}</label>
</template>
onMounted(() => {
  console.log(this.$mqtt.port());
});

Composition API

import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
  console.log($mqtt.port());
});

Path

Get or set the path parameter from the MQTT Options.

Type Definition

const path: (e?: string) => string;

Get Path

$mqtt.path(); // ie: "/mqtt"

Set MQTT path

$mqtt.path('/ws/mqtt');

Example usage

<template>
  <label>MQTT path: {{ $mqtt.path() }}</label>
</template>
onMounted(() => {
  console.log(this.$mqtt.path());
});

Composition API

import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';

onMounted(() => {
  console.log($mqtt.path());
});

Username

Get or set the username parameter from the MQTT Options.

Type Definition

const username: (e?: string) => string;

Get Username

$mqtt.username(); // ie: ""

Set MQTT username

$mqtt.username('testUsername');

Example usage

<template>
  <label>MQTT username: {{ $mqtt.username() }}</label>
</template>
onMounted(() => {
  console.log(this.$mqtt.username());
});

Composition API

import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';

onMounted(() => {
  console.log($mqtt.username());
});

Password

[!CAUTION] Exposing the password to the client can cause security issues if not used properly.

Get or set the password parameter from the MQTT Options.

Type Definition

const password: (e?: string) => string;

Get Password

$mqtt.password(); // ie: ""

Set MQTT password

$mqtt.password('secret');

Example usage

<template>
  <label>MQTT password: {{ $mqtt.password() }}</label>
</template>
onMounted(() => {
  console.log(this.$mqtt.password());
});

Composition API

import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';

onMounted(() => {
  console.log($mqtt.password());
});

Client ID

Get or set the clientId parameter from the MQTT Options.

Type Definition

const clientId: (e?: string) => string;

Get clientId

$mqtt.clientId(); // ie: "MyID-234"

Set clientId

$mqtt.clientId('MyNewClientId');

Example usage

<template>
  <label>MQTT client id: {{ $mqtt.clientId() }}</label>
</template>
onMounted(() => {
  console.log(this.$mqtt.clientId());
});

Composition API

import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';

onMounted(() => {
  console.log($mqtt.clientId());
});

Main Topic

Get or set the mainTopic parameter from the MQTT Options.

Type Definition

const mainTopic: (e?: string) => string | undefined;

Get mainTopic

$mqtt.mainTopic(); // ie: "MyID-234"

Set MQTT mainTopic

$mqtt.mainTopic('MyNewClientId');

Example usage

<template>
  <label>MQTT mainTopic: {{ $mqtt.mainTopic() }}</label>
</template>
onMounted(() => {
  console.log(this.$mqtt.mainTopic());
});

Composition API

import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';

onMounted(() => {
  console.log($mqtt.mainTopic());
});

Unsubscribe

Used to unsubscribe from the topic specified

Type Definition

const unsubscribe: (topic: string, useMainTopic?: boolean) => void;
paramtypeexplanationdefault
topicstringMQTT topic to unsubscribe (ie: 'my/test/topic')-
useMainTopicbooleanmain topic defined in the MQTT Options will be prepended to the topic specifiedtrue

Unsubscribe usage example

// if the enableMainTopic is true, unsubscribe from 'MAIN/my/topic'
$mqtt.unsubscribe('test/topic');

// even if the enableMainTopic is true, unsubscribe from 'my/topic'
$mqtt.unsubscribe('test/topic', false);

Unsubscribe All

Used to unsubscribe from all the topics subscribed previously.

Type Definition

const unsubscribeAll: () => void;

Usage

$mqtt.unsubscribeAll();

Status

Used to get the status of the mqtt connection.

Type Definition

type MqttStatus =
  | 'connected'
  | 'disconnected'
  | 'connecting'
  | 'error'
  | 'lost'
  | null;

const status: () => MqttStatus;

Get MQTT Status

$mqtt.status(); // ie: "connected"

Example usage

<template>
  <label>MQTT Status: {{ $mqtt.status() }}</label>
</template>
onMounted(() => {
  console.log($mqtt.status());
});

Usage Example

Vue Options API

mounted() {
  // Connect to the mqtt broker
  this.$mqtt.connect();

  // Subscribe to a topic
  this.$mqtt.subscribe("test/topic", (message: string) => {
    console.log("Received message:",  message);
  });

  // Publish a message
  this.$mqtt.publish("test/topic",  "Hello, world!",  "F");

  // Disconnect from the broker
  this.$mqtt.disconnect();
}

Vue Composition API

<script setup lang="ts">

import { onMounted }  from  "vue";
import { $mqtt } from 'vue-paho-mqtt';

onMounted(() => {
  // Connect to the mqtt broker
  $mqtt.connect();

  // Subscribe to a topic
  $mqtt.subscribe("test/topic", (message: string) => {
    console.log("Received message:",  message);
  });

  // Publish a message
  $mqtt.publish("test/topic",  "Hello, world!",  "F");

   // Disconnect from the broker
  $mqtt.disconnect();
});

</script>

Contributing

Contributions to the project is highly appreciated. If you have any suggestions/questions/requests please consider opening an issue. If you want to contribute to the project, fixing an open issue is greatly recommended and appreciated. To see the all contribution rules please check the contribution rules.

License

This project is licensed under MIT License if you want to see more, please check LICENSE for more information.

Credits

This project is created and actively maintained by kaandesu and EgeOnder

Contact

MaintainerE-MailTwitter
kaandesukaandesu00@gmail.com-
EgeOnder40398628+EgeOnder@users.noreply.github.com@EgeOnder23

Changelog

Please see CHANGELOG for more information on what has changed recently.

Security

The security policy of the project can be found in SECURITY.md. If you find any security issues, please refer to the policy. Thank you.