npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

capacitorv6-mqtt-native-plugin

v2.1.2

Published

⚡️This is an easy-to-use CapacitorJS plugin library that enables your CapacitorJS-powered Android mobile app to connect to an MQTT broker and send/receive messages. With this plugin, you can easily implement MQTT v5 based communication in your Android Cap

Downloads

9

Readme

CapacitorJS MQTT Native Plugin

⚡️ This plugin enables CapacitorJS-powered Android mobile apps to connect to an MQTT broker and send/receive messages natively using TCP protocol.

⚠️ Note: Supports only for android for now.

Installation

To install the plugin, run:

npm install capacitor-mqtt-native-plugin
npx cap sync

Examples

Here are some examples of how to use the plugin in your capacitorJS project using Typescript:

Connect to an MQTT Broker :

To connect to an MQTT broker, you can use the connect() method provided by the plugin. The following code demonstrates how to connect to an MQTT broker:

import { MqttBridge } from 'capacitor-mqtt-native-plugin';

// Set the MQTT server connection options
const connectionOptions = {
  serverURI: 'tcp://', // MQTT broker URI
  port: 1883, // MQTT broker default port
  clientId: 'your_mqtt_clientId', // client ID for connection
  username: 'your_mqtt_broker_username', // MQTT broker username
  password: 'your_mqtt_broker_password', // MQTT broker password
  setCleanSession: true, // clean session option
  connectionTimeout: 30, // connection timeout in seconds
  keepAliveInterval: 60, // keep alive interval in seconds
  setAutomaticReconnect: true, // automatic reconnect option
};

// connect to MQTT broker with options
MqttBridge.connect(connectionOptions)
  .then(() => {
    // connection successful
    console.log('Connect Success');
  })
  .catch((error: any) => {
    // connection failed with error message
    console.log('Connect Failed:', error);
  });

you can also add optional connect options parameter: lastWill to the connectOptions:

  setLastWill: {
    willTopic: "your_last_will_topic",
    willPayload: "your_last_will_message",
    willQoS: "your_last_will_QoS",
    setRetained: true,
  }

Disconnecting from the MQTT Broker :

To disconnect from the MQTT broker, you can use the disconnect() method provided by the plugin. The following code demonstrates how to disconnect from an MQTT broker:

import { MqttBridge } from 'capacitor-mqtt-native-plugin';

// Disconnect from the MQTT broker
MqttBridge.disconnect()
  .then(() => {
    // The disconnection is successful
    console.log('Successfully disconnected from the MQTT broker');
  })
  .catch((errorMessage: any) => {
    // The disconnection fails
    console.log(
      'Failed to disconnect from the MQTT broker. Error:',
      errorMessage,
    );
  });

Subscribing to an MQTT Topic :

To subscribe to an MQTT topic, you can use the subscribe() method provided by the plugin. The following code demonstrates how to subscribe to an MQTT topic:

import { MqttBridge } from 'capacitor-mqtt-native-plugin';

// Define the topic, qos
const topic = 'your_mqtt_topic';
const qos = 0;

// Subscribe to an MQTT topic
MqttBridge.subscribe({ topic, qos })
  // The subscription is successful
  .then((result: any) => {
    console.log('Successfully subscribed to topic:');
    console.log('Topic:', result.topic);
    console.log('QoS:', result.qos);
  })
  // The subscription fails
  .catch((errorMessage: any) => {
    console.log('Failed to subscribe to topic. Error:', errorMessage);
  });

Publishing a Message to an MQTT Topic :

To publish a message to an MQTT topic, you can use the publish() method provided by the plugin. The following code demonstrates how to publish a message to an MQTT topic:

import { MqttBridge } from 'capacitor-mqtt-native-plugin';

// Define the topic, payload, qos, and retained properties for the message
const topic = 'your_mqtt_topic';
const payload = 'your_mqtt_message';
const qos = 0;
const retained = false;

// Publish the message
MqttBridge.publish({ topic, payload, qos, retained })
  .then((result: any) => {
    // The message is published successfully
    console.log('Successfully published message:');
    console.log('Topic:', result.topic);
    console.log('QoS:', result.qos);
    console.log('Payload:', result.payload);
    console.log('Retained:', result.retained);
    console.log('Message ID:', result.messageId);
  })
  .catch((errorMessage: any) => {
    // The message fails to publish
    console.log('Failed to publish message. Error:', errorMessage);
  });

Listen to Incoming Messages :

To listen to incoming messages, you can add a CapacitorJS listener with this event name : onMessageArrived. The following code demonstrates how to publish a message to an MQTT topic:

import { MqttBridge } from 'capacitor-mqtt-native-plugin';

// Listen to incoming MQTT messages
MqttBridge.addListener('onMessageArrived', (result: any) => {
  console.log('Received a new message:');
  console.log('Topic:', result.topic);
  console.log('Message:', result.message);
});

When a message arrives, the listener will be triggered and you can access the message topic and payload in the result parameter. You can modify the code to suit your use case and do something more interesting with the incoming messages.

Listen to ConnectComplete Event :

This event is triggered only when the connection to the MQTT broker is successfully completed. It also triggers when the client was reconnected after a connection loss. To implement this, you can add a CapacitorJS listener with the event name : onConnectComplete. The following code demonstrates how to listen to the ConnectComplete event:

import { MqttBridge } from 'capacitor-mqtt-native-plugin';

// Listen for the 'onConnectComplete' event
MqttBridge.addListener('onConnectComplete', (result: any) => {
  console.log('Successfully connected to MQTT broker:');
  console.log('Reconnected:', result.reconnected);
  console.log('Server URI:', result.serverURI);
});

Listen to ConnectionLost Event :

This event is triggered only when the client loses the connection to the MQTT broker. To handle this event, you can add a CapacitorJS listener with the event name : onConnectionLost. The following code demonstrates how to listen to ConnectionLost event:

import { MqttBridge } from 'capacitor-mqtt-native-plugin';

// Add a listener for when the connection is lost
MqttBridge.addListener('onConnectionLost', (result: any) => {
  console.log('Connection lost:');
  console.log('Connection status:', result.connectionStatus);
  console.log('Reason code:', result.reasonCode);
  console.log('Message:', result.message);
});

The event listener function receives an object result as an argument with the following properties:

  • connectionStatus: The status of the connection at the time the event was triggered.
  • reasonCode: The MQTT reason code for the connection loss.
  • message: Additional information about the connection loss.

API

connect(...)

connect(options: { serverURI: string; port: number; clientId: string; username: string; password: string; setCleanSession: boolean; connectionTimeout: number; keepAliveInterval: number; setAutomaticReconnect: boolean; setLastWill?: { willTopic: string; willPayload: string; willQoS: number; setRetained: boolean; }; }) => Promise<void>

| Param | Type | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | options | { serverURI: string; port: number; clientId: string; username: string; password: string; setCleanSession: boolean; connectionTimeout: number; keepAliveInterval: number; setAutomaticReconnect: boolean; setLastWill?: { willTopic: string; willPayload: string; willQoS: number; setRetained: boolean; }; } |


disconnect()

disconnect() => Promise<void>

subscribe(...)

subscribe(options: { topic: string; qos: number; }) => Promise<{ topic: string; qos: number; }>

| Param | Type | | ------------- | -------------------------------------------- | | options | { topic: string; qos: number; } |

Returns: Promise<{ topic: string; qos: number; }>


publish(...)

publish(options: { topic: string; payload: string; qos: number; retained: boolean; correlationData?: string; }) => Promise<{ topic: string; payload: string; qos: number; retained: boolean; messageId: string; }>

| Param | Type | | ------------- | ---------------------------------------------------------------------------------------------------------- | | options | { topic: string; payload: string; qos: number; retained: boolean; correlationData?: string; } |

Returns: Promise<{ topic: string; payload: string; qos: number; retained: boolean; messageId: string; }>


addListener('onConnectionLost', ...)

addListener(eventName: 'onConnectionLost', listener: onConnectionLostListener) => Promise<PluginListenerHandle> & Partial<PluginListenerHandle>

| Param | Type | | --------------- | ----------------------------------------------------------------------------- | | eventName | 'onConnectionLost' | | listener | onConnectionLostListener |

Returns: Promise<PluginListenerHandle> & Partial<PluginListenerHandle>


addListener('onConnectComplete', ...)

addListener(eventName: 'onConnectComplete', listener: onConnectCompleteListener) => Promise<PluginListenerHandle> & Partial<PluginListenerHandle>

| Param | Type | | --------------- | ------------------------------------------------------------------------------- | | eventName | 'onConnectComplete' | | listener | onConnectCompleteListener |

Returns: Promise<PluginListenerHandle> & Partial<PluginListenerHandle>


addListener('onMessageArrived', ...)

addListener(eventName: 'onMessageArrived', listener: onMessageArrivedListener) => Promise<PluginListenerHandle> & Partial<PluginListenerHandle>

| Param | Type | | --------------- | ----------------------------------------------------------------------------- | | eventName | 'onMessageArrived' | | listener | onMessageArrivedListener |

Returns: Promise<PluginListenerHandle> & Partial<PluginListenerHandle>


Interfaces

PluginListenerHandle

| Prop | Type | | ------------ | ----------------------------------------- | | remove | () => Promise<void> |

Type Aliases

Partial

Make all properties in T optional

{ [P in keyof T]?: T[P]; }

onConnectionLostListener

(x: { connectionStatus: string; reasonCode: number; message: string; }): void

onConnectCompleteListener

(x: { reconnected: boolean; serverURI: string; }): void

onMessageArrivedListener

(x: { topic: string; message: string; correlationData?: string; responseTopic?: string; }): void