vue-paho-mqtt
v0.6.5
Published
Easy-to-use Paho MQTT client for Vue 3 with centralized subscription management, type support, and built-in optional alert notification library.
Downloads
351
Readme
Vue-Paho-Mqtt Plugin
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.
Table of contents
- Installation
- Setup
- Options
- Notification Alerts
- Global MQTT client instance: $mqtt
- Usage Example
- Contributing
- License
- Credits
- Changelog
- Security
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
:
showNotifications
(boolean
, default:true
) - Whether to show error and success notifications.autoConnect
(boolean
, default:true
) - Whether to automatically connect to the broker when the plugin is initialized.
MQTT Options
You can configure the MQTT client by passing an object with the following options to createPahoMqttPlugin
:
host
(string
, default:"localhost"
) - The hostname or IP address of the MQTT broker.port
(number
, default:9001
) - The port number of the MQTT broker.useSSL
(boolean
, default:false
) - Whether to use SSL when connecting to the broker.clientId
(string
, default:"ClientID-${Math.random() * 9999}}"
) - The client identifier to use when connecting to the broker.username
(string
, default:""
) - The username to use when connecting to the broker.password
(string
, default:""
) - The password to use when connecting to the broker.mainTopic
(string
, default:"MAIN"
) - If enaled, the topic that will be prepended to the topic specified during the $mqtt.publish and $mqtt.subscribe (can be manually disabled in $mqtt.publish and $mqtt.subscribe).enableMainTopic
(boolean
, default:true
) - Enables usage of the main topic.watchdogTimeout
(number
, default:30000
) - The time in milliseconds to wait for a connection to the broker before timing out.reconnectTimeout
(number
, default:5000
) - The time in milliseconds to wait before attempting to reconnect to the broker after a disconnection.keepAliveInterval
(number
, default:60000
) - The server disconnects this client if there is no activity for this number of milliseconds.cleanSession
(boolean
, default:true
) - Whether to delete the server persistent state on a new connection.
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:
| type | Option | QoS Level | Retain | | ------ | ------ | :-------: | -----: | | string | B | 0 | false | | string | Br | 0 | true | | string | Q | 1 | false | | string | Qr | 1 | true | | string | F | 2 | true | | string | Fnr | 2 | false |
B: QoS 0, non-retained message. The message is delivered at most once, and the broker does not store the message for future subscribers.
Br: QoS 0, retained message. The message is delivered at most once, and the broker stores the message for future subscribers.
Q: QoS 1, non-retained message. The message is delivered at least once, and the broker stores it until the publisher receives an acknowledgment from the subscriber.
Qr: QoS 1, retained message. The message is delivered at least once, and the broker stores it until the publisher receives an acknowledgment from the subscriber. The broker also stores the message for future subscribers.
F: QoS 2, retained message. The message is delivered exactly once, and the broker stores it for future subscribers.
Fnr: QoS 2, non-retained message. The message is delivered exactly once, and the broker does not store it for future subscribers.
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.
PluginOptions.showNotifications
(boolean
, default:true
) - Whether to show error and success alert notifications.
createPahoMqttPlugin({
PluginOptions: {
showNotifications: true,
...
}
...
| On | Icon | Title | Content | Timer | | :----------------: | :-----: | :----------: | :---------------------------: | :---: | | Connection Success | success | "Connected" | "MQTT Connected" | 1500 | | Connection Failure | error | "Mqtt Error" | "MQTT failed to connect" | - | | Connection Timeout | error | "Mqtt Error" | "Broker connection timed out" | - | | Connection Lost | error | "Mqtt Error" | "MQTT connection lost" | - | | Disconnect Error | error | "Error" | catch(error) => error.message | - | | Connect Error | error | "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
.
onConnect()
: resolves the promise totrue
if the connection was successful.onFailure()
: rejects the promise tofalse
if the connection was unsuccessful.onConnectionLost()
: returns an response object with the following properties:errorCode
: the error code.
onMessageArrived()
: returns a message object with the following properties:payloadString
: the message payload as a string.destinationName
: the name of the topic that the message was published to.
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
| Callback | When | Return |
| :----------------: | :-----------------------------------------------: | :-------------------------------------------------------: |
| onConnect
| successfully connected to the mqtt broker | - |
| onFailure
| failed to connect to the mqtt broker | - |
| onConnectionLost
| disconnected or connection lost connection | responseObject: {errorCode: number} |
| onMessageArrived
| message arrived from one of the subscribed topics | message: {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.
| param | type | explanation | default |
| :-----: | :------: | :----: | :---: |
| topic
| string
| MQTT topic to subscribe (ie: 'my/test/topic') | - |
| onMessage
| function
| Arrow function with a parameter to be fired when a message arrives to the specified topic | - |
| useMainTopic
| boolean
| main topic defined in the MQTT Options will be prepended to the topic specified | true
|
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;
| param | type | explanation | default |
| :------------: | :--------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----: |
| topic
| string
| MQTT topic to publish (ie: 'my/test/topic') | - |
| payload
| string
| string payload to send | - |
| mode
| MqttMode
| See MQTT Quality of Service (QoS) and Retention Options for Publish for detailed explanation for mqtt mode options. ["B"
| "F"
| "Q"
| "Qr"
| "Br"
| "Fnr"
] | - |
| useMainTopic
| boolean
| main topic defined in the MQTT Options will be prepended to the topic specified | true
|
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;
| param | type | explanation | default |
| :------------: | :-------: | :----------------------------------------------------------------------------------------------: | :-----: |
| topic
| string
| MQTT topic to unsubscribe (ie: 'my/test/topic') | - |
| useMainTopic
| boolean
| main topic defined in the MQTT Options will be prepended to the topic specified | true
|
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
| Maintainer | E-Mail | Twitter | | --------------------------------------- | ------------------------------------------ | --------------------------------------------- | | kaandesu | [email protected] | - | | EgeOnder | [email protected] | @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.