Getting Started
Questo contenuto non è ancora disponibile nella tua lingua.
-
Install the package
Terminal window npm i @capgo/capacitor-mqttTerminal window pnpm add @capgo/capacitor-mqttTerminal window yarn add @capgo/capacitor-mqttTerminal window bun add @capgo/capacitor-mqtt -
Sync with native projects
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window 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();