@arkyutao/react-native-mqtt
v0.1.2
Published
The Mqtt client for react native
Downloads
4
Readme
Enhancement of Quito
source repository: https://github.com/6d7a/quito
- upgrade react-native to 0.73
- upgrade CocoaMQTT to 2.1.6
- use MqttCocoaAsyncSocket instead of CocoaAsyncSocket
- fix exapmle project bug
- fix typescript type export error
Quito
A TCP-capable MQTT client for React Native. The module provides a Typescript API for native MQTT clients on iOS and Android.
The module provides both promise- and callback-based methods to interact with the native clients.
This libraries owes a lot to davesters' and SudoPlz' respective libraries, so thank you :100:
Installation
npm install @arkyutao/react-native-mqtt
To make an unencrypted connection to an MQTT broker, make sure a consuming android application allows cleartext traffic, either generally by setting the android:usesCleartextTraffic flag in the application field of the AndroidManifest.xml, or by adding a security configuration.
Usage
The module provides promise- and callback-based methods to interact with the native clients.
Callback-based usage
import { MqttClient, MqttOptionsBuilder } from '@arkyutao/react-native-mqtt';
// build a config using the MqttOptionsBuilder
const config = new MqttOptionsBuilder()
.uri('tcp://test.mosquitto.org:1883')
.clientId('quito-test-client')
.build();
const client = new MqttClient(config);
client.init() // call init() to create native client and set up native event listeners
.then(() => {
// Subscribing to event callbacks
client.on(MqttEvent.CONNECTING, () => {
// called when client is connecting
});
client.on(MqttEvent.CONNECTED, () => {
// called when client is connected
});
client.on(MqttEvent.SUBSCRIBED, (topic: string) => {
// called when client has subscribed to a topic
});
client.on(MqttEvent.UNSUBSCRIBED, (topic: string) => {
// called when client has unsubscribed from a topic
});
client.on(
MqttEvent.MESSAGE_RECEIVED,
(topic: string, payload: Uint8Array) => {
// called when client has received a message
}
);
client.on(
MqttEvent.MESSAGE_PUBLISHED,
(topic: string, payload: Uint8Array) => {
// called when client has sent a message
}
);
client.on(MqttEvent.DISCONNECTED, () => {
// called when client has disconnected
});
client.on(MqttEvent.CONNECTION_LOST, (error?: Error) => {
// called when client has unexpectedly lost its connection to the broker
});
client.on(MqttEvent.EXCEPTION, (error: Error) => {
// called when client encountered an error
});
client.on(MqttEvent.CLOSED, (error?: Error) => {
// called when client was closed
});
// connecting to the MQTT broker
client.connect();
// subscribing to a message topic
// both a single topic or an array of topics are supported
client.subscribe([
{
topic: 'first/topic',
qos: 2, // Quality of Service
},
{
topic: 'second/topic',
qos: 1,
},
]);
// unsubscribing from a message topic
// both a single topic string or an array of topic strings are supported
client.unsubscribe('first/topic');
// publishing a message
client.publish(
'first/topic',
Buffer.from('This is a test message!'),
0, // Quality of service
false // whether the message should be retained
);
// checking client connection
client.isConnected().then((isConnected: Boolean) => {
// process connection state
});
// shutting down client
client.end();
});
Promise-based usage
import { MqttCliet, MqttOptionsBuilder } from 'react-native-mqtt';
// build a config using the MqttOptionsBuilder
const config = new MqttOptionsBuilder()
.uri('tcp://test.mosquitto.org:1883')
.clientId('quito-test-client')
.build();
const client = new MqttClient(config);
await client.init(); // call init() to create native client and set up native event listeners
// Most message callbacks are redundant
// when using the Promise-based API
client.on(
MqttEvent.MESSAGE_RECEIVED,
(topic: string, payload: Uint8Array) => {
// called when client has received a message
}
);
client.on(MqttEvent.CONNECTION_LOST, (error?: Error) => {
// called when client has unexpectedly lost its connection to the broker
});
client.on(MqttEvent.EXCEPTION, (error: Error) => {
// called when client encountered an error
});
// connecting to the MQTT broker
try {
await client.connectAsync();
} catch (e: any) {
// handle error
}
// subscribing to a message topic
// both a single topic or an array of topics are supported
try {
await client.subscribeAsync([
{
topic: 'first/topic',
qos: 2, // Quality of Service
},
{
topic: 'second/topic',
qos: 1,
},
]);
} catch (e: any) {
// handle error
}
// unsubscribing from a message topic
// both a single topic string or an array of topic strings are supported
try {
await client.unsubscribeAsync('first/topic');
} catch (e: any) {
// handle error
}
// publishing a message
try {
await client.publishAsync(
'first/topic',
Buffer.from('This is a test message!'),
0, // Quality of service
false // whether the message should be retained
);
} catch (e: any) {
// handle error
}
// checking client connection
const isConnected = await client.isConnected();
// shutting down client
try {
await client.endAsync();
} catch (e: any) {
// handle error
}
Mqtt Options
Use the MqttOptionsBuilder to generate a config for the MQTT client. The following options for configuring the MQTT client are available:
clientId
: string - Identifier used in the communication with the MQTT bromkerusername
: string - Username used to authenticate the client against the brokerpassword
: string - Password used to authenticate the client against the brokerkeepaliveSec
: number - Maximum time interval in seconds between control packetsconnectTimeoutMs
: number - Maximum time interval the client will wait for the network connection to the MQTT broker to be establishedwill
: Will - MQTT message that the broker will send, should the client connect ungracefully.topic
: string - Topic the will will be published topayload
: string - Message of the will Base64-encodedqos
: QoS - quality of service of the willretain
: boolean - Indicates whether the will should be retained
tls
: boolean - Whether the client will secure the connection to the broker using TLS. Depending on the host platform, the options vary.- On Android: If
tls == true
, at least the broker's CA certificateandroid_caBase64
is required. If the broker expects the client to present a certificate as well, the sharedandroid_caBase64
plusandroid_certificateBase64
,keyStoreKey
, andkeyStorePassword
options become mandatory - On iOS: If
tls == true
and noios_certKeyP12Base64
is provided, broker certificates will not be validated. Iftls == true
andios_certKeyP12Base64
is provided, the client wil authenticate using the contained crypto.
- On Android: If
ios_certKeyP12Base64
: String - Base64-encoded PKCS12 archive containing client certificate and keyandroid_caBase64
: String - Base64-encoded CA certificate (DER) used by the MQTT brokerandroid_certificateBase64
: String - Base64-encoded self-signed X509 certificate (DER) of the clientandroid_privateKeyBase64
: string - Base64-encoded RSA private key of the clientkeyStorePassword
: string - Password used in creating the client's keystorecleanSession
: boolean - When set totrue
, the broker will open a non-persistent connection, during which it will not store any subscription information or undelivered messages for the clientprotocol
: Protocol - Identifies the protocol used in the connection to the brokerprotocolVersion
: number - Identies the MQTT version used in the connection to the brokerreconnectPeriod
: number - Time interval to elapse before a client will attempt to reconnect an unexpectedly disconnected clienthost
: string - Host name of the MQTT broker to connect toport
: number - Port number of the MQTT broker to connect to