Getting Started
Este contenido aún no está disponible en tu idioma.
-
Install the package
Ventana de terminal npm i @capgo/capacitor-mqttVentana de terminal pnpm add @capgo/capacitor-mqttVentana de terminal yarn add @capgo/capacitor-mqttVentana de terminal bun add @capgo/capacitor-mqtt -
Sync with native projects
Ventana de terminal npx cap syncVentana de terminal pnpm cap syncVentana de terminal yarn cap syncVentana de terminal bunx cap sync
Import the plugin and connect to an MQTT broker:
import { CapacitorMqtt } from '@capgo/capacitor-mqtt';
await CapacitorMqtt.connect({ brokerUrl: 'wss://broker.hivemq.com:8884/mqtt', clientId: `device-${Date.now()}`,});
await CapacitorMqtt.subscribe({ topic: 'myapp/events', qos: 1 });
await CapacitorMqtt.publish({ topic: 'myapp/events', message: 'hello from app', qos: 1,});API Reference
Section titled “API Reference”connect(options)
Section titled “connect(options)”Connect to an MQTT broker.
interface ConnectOptions { brokerUrl: string; clientId: string; username?: string; password?: string; cleanSession?: boolean; keepAliveInterval?: number;}
await CapacitorMqtt.connect({ brokerUrl: 'wss://broker.hivemq.com:8884/mqtt', clientId: 'my-client-id',});subscribe(options)
Section titled “subscribe(options)”Subscribe to a topic.
await CapacitorMqtt.subscribe({ topic: 'myapp/events', qos: 1,});publish(options)
Section titled “publish(options)”Publish to a topic.
await CapacitorMqtt.publish({ topic: 'myapp/commands', message: JSON.stringify({ command: 'ping' }), qos: 1,});addListener()
Section titled “addListener()”Listen for incoming messages.
const listener = await CapacitorMqtt.addListener('onMessage', (payload) => { console.log(payload.topic, payload.message);});disconnect()
Section titled “disconnect()”Disconnect from the broker.
await CapacitorMqtt.disconnect();