Gathering detailed insights and metrics for vue-paho-mqtt
Gathering detailed insights and metrics for vue-paho-mqtt
Gathering detailed insights and metrics for vue-paho-mqtt
Gathering detailed insights and metrics for vue-paho-mqtt
Easy-to-use MQTT client for Vue 3 with centralized subscription management, type support, and built-in alert notifications.
npm install vue-paho-mqtt
Typescript
Module System
Node Version
NPM Version
54.9
Supply Chain
98.2
Quality
82.7
Maintenance
50
Vulnerability
98.2
License
TypeScript (69.07%)
Vue (27.24%)
CSS (3.08%)
HTML (0.61%)
Total Downloads
5,764
Last Day
10
Last Week
64
Last Month
259
Last Year
3,639
23 Stars
194 Commits
3 Forks
4 Watching
3 Branches
2 Contributors
Minified
Minified + Gzipped
Latest Version
0.6.5
Package Id
vue-paho-mqtt@0.6.5
Unpacked Size
289.71 kB
Size
71.63 kB
File Count
27
NPM Version
10.5.0
Node Version
21.7.1
Publised On
21 Jul 2024
Cumulative downloads
Total Downloads
Last day
-9.1%
10
Compared to previous day
Last week
-7.2%
64
Compared to previous week
Last month
-17%
259
Compared to previous month
Last year
71.2%
3,639
Compared to previous year
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.
Install the package using npm:
1npm install vue-paho-mqtt
To use the plugin, you need to create an instance of it and pass it to the use
function:
1// src/main.ts 2import App from './App.vue'; 3import { createApp } from 'vue'; 4import { createPahoMqttPlugin } from 'vue-paho-mqtt'; 5 6createApp(App) 7 .use( 8 createPahoMqttPlugin({ 9 PluginOptions: { 10 autoConnect: true, 11 showNotifications: true, 12 }, 13 14 MqttOptions: { 15 host: 'localhost', 16 port: 9001, 17 clientId: `MyID-${Math.random() * 9999}`, 18 mainTopic: 'MAIN', 19 }, 20 }), 21 ) 22 .mount('#app');
1import { boot } from 'quasar/wrappers'; 2import { createPahoMqttPlugin } from 'vue-paho-mqtt'; 3 4export default boot(({ app }) => { 5 app.use( 6 createPahoMqttPlugin({ 7 PluginOptions: { 8 autoConnect: true, 9 showNotifications: true, 10 }, 11 12 MqttOptions: { 13 host: 'localhost', 14 port: 9001, 15 clientId: `MyID-${Math.random() * 9999}`, 16 mainTopic: 'MAIN', 17 }, 18 }), 19 ); 20});
1import { createPahoMqttPlugin } from 'vue-paho-mqtt';
2export default defineNuxtPlugin({
3 name: 'vue-paho-mqtt',
4 enforce: 'pre',
5 async setup(nuxtApp) {
6 nuxtApp.vueApp.use(
7 createPahoMqttPlugin({
8 PluginOptions: {
9 autoConnect: true,
10 showNotifications: true,
11 },
12 MqttOptions: {
13 host: 'localhost',
14 port: 9001,
15 clientId: `MyID-${Math.random() * 9999}`,
16 mainTopic: 'MAIN',
17 },
18 }),
19 );
20 },
21 hooks: {
22 'app:created'() {
23 const nuxtApp = useNuxtApp();
24 },
25 },
26});
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.
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.
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.
1type MqttMode = 'B' | 'F' | 'Q' | 'Qr' | 'Br' | 'Fnr';
1$mqtt.publish('test/topic', 'Hello, world!', 'Fnr');
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.1createPahoMqttPlugin({ 2 PluginOptions: { 3 showNotifications: true, 4 ... 5 } 6 ...
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 | - |
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 to true
if the connection was successful.onFailure()
: rejects the promise to false
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.
1const connect: ({ 2 onConnect?: ((...args: unknown[]) => unknown) | undefined; 3 onFailure?: ((...args: unknown[]) => unknown) | undefined; 4 onConnectionLost?: 5 | (( 6 responseObject: { 7 errorCode: number; 8 }, 9 ...args: unknown[] 10 ) => unknown) 11 | undefined; 12 onMessageArrived?: 13 | (( 14 message: { 15 payloadString: string; 16 destinationName: string; 17 }, 18 ...args: unknown[] 19 ) => unknown) 20 | undefined; 21}) => Promise<boolean>;
1// Composition API 2import { $mqtt } from 'vue-paho-mqtt'; 3$mqtt.connect(); 4 5// Options API 6this.$mqtt.connect(); 7 8// or use it with async/await 9const result = await $mqtt.connect(); 10// result will return "true" if the connection was successful
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;} |
1$mqtt.connect({ 2 onConnect: () => { 3 console.log('Mqtt connected'); 4 }, 5 onFailure: () => { 6 console.log('Mqtt connection failed'); 7 }, 8 onConnectionLost: (error: any) => { 9 console.log('Error:', error.message); 10 }, 11 onMessageArrived: (message: { 12 payloadString: string; 13 destinationName: string; 14 }) => { 15 console.log( 16 'Message Arrived:', 17 message.payloadString, 18 message.destinationName, 19 ); 20 }, 21});
Disconnect from the mqtt broker. Shows a dialog notification in case of error if the plugin is configured to do so.
1const disconnect: () => Promise<boolean>;
1// Composition API 2import { $mqtt } from 'vue-paho-mqtt'; 3$mqtt.disconnect(); 4 5// Options API 6this.$mqtt.disconnect(); 7 8// or use it with async/await 9const result = await $mqtt.disconnect(); 10// result will return "true" if the disconnection was successful
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 |
1const subscribe: ( 2 topic: string, 3 onMessage: (data: string, ...args: unknown[]) => unknown, 4 useMainTopic?: boolean, 5) => void;
1// if the enableMainTopic is true, subscribe to 'MAIN/my/topic' 2this.$mqtt.subscribe('my/topic', (data: string) => { 3 console.log(data, 'recieved'); 4}); 5 6// even if the enableMainTopic is true, subscribe to 'my/topic' 7this.$mqtt.subscribe( 8 'my/topic', 9 (data: string) => { 10 console.log(data, 'recieved'); 11 }, 12 false, 13);
1import { $mqtt } from 'vue-paho-mqtt'; 2 3$mqtt.subscribe('my/topic', (data: string) => { 4 console.log(data, 'recieved'); 5});
Used to publish string data to the topic specified.
1const publish: ( 2 topic: string, 3 payload: string, 4 mode: MqttMode, 5 useMainTopic?: boolean, 6) => 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 |
1// if the enableMainTopic is true, publish to 'MAIN/my/topic' 2// 'Fnr' => Qos: 2 , retained: false 3this.$mqtt.publish('test/topic', 'Hello, world!', 'Fnr'); 4 5// even if the enableMainTopic is true, publish to 'my/topic' 6// 'B' => Qos: 0 , retained: false 7this.$mqtt.publish('test/topic', 'Hello, world!', 'B', false); 8 9// if the enableMainTopic is true, publish to 'MAIN/my/topic' 10// 'Qr' => Qos: 1 , retained: true 11this.$mqtt.publish('test/topic', 'Hello, world!', 'Qr'); 12 13// payload: "Hello, world!"
1import { $mqtt } from 'vue-paho-mqtt'; 2 3$mqtt.publish('test/topic', 'Hello, world!', 'Qr');
Get or set the host parameter from the MQTT Options.
1const host: (e?: string) => string;
1$mqtt.host(); // ie: "localhost"
1$mqtt.host('192.168.0.1');
1<template> 2 <label>MQTT host: {{ $mqtt.host() }}</label> 3</template>
1onMounted(() => { 2 console.log(this.$mqtt.host()); 3});
1import { onMounted } from 'vue'; 2import { $mqtt } from 'vue-paho-mqtt'; 3 4onMounted(() => { 5 console.log($mqtt.host()); 6});
Get or set the port parameter from the MQTT Options.
1const port: (e?: number) => number;
1$mqtt.port(); // ie: 9001
1$mqtt.port(1234);
1<template> 2 <label>MQTT port: {{ $mqtt.port() }}</label> 3</template>
1onMounted(() => { 2 console.log(this.$mqtt.port()); 3});
1import { onMounted } from 'vue'; 2import { $mqtt } from 'vue-paho-mqtt'; 3onMounted(() => { 4 console.log($mqtt.port()); 5});
Get or set the path parameter from the MQTT Options.
1const path: (e?: string) => string;
1$mqtt.path(); // ie: "/mqtt"
1$mqtt.path('/ws/mqtt');
1<template> 2 <label>MQTT path: {{ $mqtt.path() }}</label> 3</template>
1onMounted(() => { 2 console.log(this.$mqtt.path()); 3});
1import { onMounted } from 'vue'; 2import { $mqtt } from 'vue-paho-mqtt'; 3 4onMounted(() => { 5 console.log($mqtt.path()); 6});
Get or set the username parameter from the MQTT Options.
1const username: (e?: string) => string;
1$mqtt.username(); // ie: ""
1$mqtt.username('testUsername');
1<template> 2 <label>MQTT username: {{ $mqtt.username() }}</label> 3</template>
1onMounted(() => { 2 console.log(this.$mqtt.username()); 3});
1import { onMounted } from 'vue'; 2import { $mqtt } from 'vue-paho-mqtt'; 3 4onMounted(() => { 5 console.log($mqtt.username()); 6});
[!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.
1const password: (e?: string) => string;
1$mqtt.password(); // ie: ""
1$mqtt.password('secret');
1<template> 2 <label>MQTT password: {{ $mqtt.password() }}</label> 3</template>
1onMounted(() => { 2 console.log(this.$mqtt.password()); 3});
1import { onMounted } from 'vue'; 2import { $mqtt } from 'vue-paho-mqtt'; 3 4onMounted(() => { 5 console.log($mqtt.password()); 6});
Get or set the clientId parameter from the MQTT Options.
1const clientId: (e?: string) => string;
1$mqtt.clientId(); // ie: "MyID-234"
1$mqtt.clientId('MyNewClientId');
1<template> 2 <label>MQTT client id: {{ $mqtt.clientId() }}</label> 3</template>
1onMounted(() => { 2 console.log(this.$mqtt.clientId()); 3});
1import { onMounted } from 'vue'; 2import { $mqtt } from 'vue-paho-mqtt'; 3 4onMounted(() => { 5 console.log($mqtt.clientId()); 6});
Get or set the mainTopic parameter from the MQTT Options.
1const mainTopic: (e?: string) => string | undefined;
1$mqtt.mainTopic(); // ie: "MyID-234"
1$mqtt.mainTopic('MyNewClientId');
1<template> 2 <label>MQTT mainTopic: {{ $mqtt.mainTopic() }}</label> 3</template>
1onMounted(() => { 2 console.log(this.$mqtt.mainTopic()); 3});
1import { onMounted } from 'vue'; 2import { $mqtt } from 'vue-paho-mqtt'; 3 4onMounted(() => { 5 console.log($mqtt.mainTopic()); 6});
Used to unsubscribe from the topic specified
1const 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 |
1// if the enableMainTopic is true, unsubscribe from 'MAIN/my/topic' 2$mqtt.unsubscribe('test/topic'); 3 4// even if the enableMainTopic is true, unsubscribe from 'my/topic' 5$mqtt.unsubscribe('test/topic', false);
Used to unsubscribe from all the topics subscribed previously.
1const unsubscribeAll: () => void;
1$mqtt.unsubscribeAll();
Used to get the status of the mqtt connection.
1type MqttStatus = 2 | 'connected' 3 | 'disconnected' 4 | 'connecting' 5 | 'error' 6 | 'lost' 7 | null; 8 9const status: () => MqttStatus;
1$mqtt.status(); // ie: "connected"
1<template> 2 <label>MQTT Status: {{ $mqtt.status() }}</label> 3</template>
1onMounted(() => { 2 console.log($mqtt.status()); 3});
1mounted() { 2 // Connect to the mqtt broker 3 this.$mqtt.connect(); 4 5 // Subscribe to a topic 6 this.$mqtt.subscribe("test/topic", (message: string) => { 7 console.log("Received message:", message); 8 }); 9 10 // Publish a message 11 this.$mqtt.publish("test/topic", "Hello, world!", "F"); 12 13 // Disconnect from the broker 14 this.$mqtt.disconnect(); 15}
1<script setup lang="ts"> 2 3import { onMounted } from "vue"; 4import { $mqtt } from 'vue-paho-mqtt'; 5 6onMounted(() => { 7 // Connect to the mqtt broker 8 $mqtt.connect(); 9 10 // Subscribe to a topic 11 $mqtt.subscribe("test/topic", (message: string) => { 12 console.log("Received message:", message); 13 }); 14 15 // Publish a message 16 $mqtt.publish("test/topic", "Hello, world!", "F"); 17 18 // Disconnect from the broker 19 $mqtt.disconnect(); 20}); 21 22</script> 23
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.
This project is licensed under MIT License
if you want to see more, please check LICENSE for more information.
This project is created and actively maintained by kaandesu and EgeOnder
Maintainer | ||
---|---|---|
kaandesu | kaandesu00@gmail.com | - |
EgeOnder | 40398628+EgeOnder@users.noreply.github.com | @EgeOnder23 |
Please see CHANGELOG for more information on what has changed recently.
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.
No vulnerabilities found.
No security vulnerabilities found.