TCP-capable MQTT client for react native

Overview

Quito Logo

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.

Installation

npm install quito

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 { Quito, QuitoOptionsBuilder } from 'quito';

// build a config using the QuitoOptionsBuilder
const config = new QuitoOptionsBuilder()
  .uri('tcp://test.mosquitto.org:1883')
  .clientId('quito-test-client')
  .build();

const MqttClient = new Quito(config);

MqttClient.init() // call init() to create native client and set up native event listeners
  .then(() => {
    // Subscribing to event callbacks
    MqttClient.on(QuitoEvent.CONNECTING, () => {
      // called when client is connecting
    });
    MqttClient.on(QuitoEvent.CONNECTED, () => {
      // called when client is connected
    });
    MqttClient.on(QuitoEvent.SUBSCRIBED, (topic: string) => {
      // called when client has subscribed to a topic
    });
    MqttClient.on(QuitoEvent.UNSUBSCRIBED, (topic: string) => {
      // called when client has unsubscribed from a topic
    });
    MqttClient.on(QuitoEvent.MESSAGE_RECEIVED, (topic: string, payload: Buffer) => {
      // called when client has received a message
    });
    MqttClient.on(QuitoEvent.MESSAGE_PUBLISHED, () => {
      // called when client has sent a message
    });
    MqttClient.on(QuitoEvent.DISCONNECTED, () => {
      // called when client has disconnected
    });
    MqttClient.on(QuitoEvent.CONNECTION_LOST, (error?: Error) => {
      // called when client has unexpectedly lost its connection to the broker
    });
    MqttClient.on(QuitoEvent.EXCEPTION, (error: Error) => {
      // called when client encountered an error
    });
    MqttClient.on(QuitoEvent.CLOSED, (error?: Error) => {
      // called when client was closed
    });

    // connecting to the MQTT broker
    MqttClient.connect();

    // subscribing to a message topic
    // both a single topic or an array of topics are supported
    MqttClient.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
    MqttClient.unsubsctibe('first/topic');

    // publishing a message
    MqttClient.publish(
      'first/topic',
      'This is a test message',
      0, // Quality of service
      false // whether the message should be retained
    );

    // checking client connection
    MqttClient.isConnected().then((isConnected: Boolean) => {
      // process connection state
    });

    // shutting down client
    MqttClient.end();
  });

Promise-based usage

import { Quito, QuitoOptionsBuilder } from 'quito';

// build a config using the QuitoOptionsBuilder
const config = new QuitoOptionsBuilder()
  .uri('tcp://test.mosquitto.org:1883')
  .clientId('quito-test-client')
  .build();

const MqttClient = new Quito(config);


await MqttClient.init(); // call init() to create native client and set up native event listeners

// Most message callbacks are redundant 
// when using the Promise-based API
MqttClient.on(QuitoEvent.MESSAGE_RECEIVED, (topic: string, payload: Buffer) => {
  // called when client has received a message
});
MqttClient.on(QuitoEvent.CONNECTION_LOST, (error?: Error) => {
  // called when client has unexpectedly lost its connection to the broker
});
MqttClient.on(QuitoEvent.EXCEPTION, (error: Error) => {
  // called when client encountered an error
});

// connecting to the MQTT broker
try {
  await MqttClient.connectAsync();
} catch (e: any) {
  // handle error
}

// subscribing to a message topic
// both a single topic or an array of topics are supported
try {
  await MqttClient.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 MqttClient.unsubscribeAsync('first/topic');
} catch (e: any) {
  // handle error
}

// publishing a message
try {
  await MqttClient.publishAsync(
    'first/topic',
    '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 MqttClient.isConnected()

// shutting down client
try {
  await MqttClient.endAsync();
} catch (e: any) {
  // handle error
}

Quito Options

Use the QuitoOptionsBuilder to generate a config for the Quito MQTT client. The following options for configuring the Quito MQTT client are available:

  • clientId: string - Identifier used in the communication with the MQTT bromker
  • username: string - Username used to authenticate the client against the broker
  • password: string - Password used to authenticate the client against the broker
  • keepaliveSec: number - Maximum time interval in seconds between control packets
  • connectTimeoutMs: number - Maximum time interval the client will wait for the network connection to the MQTT broker to be established
  • will: Will - MQTT message that the broker will send, should the client connect ungracefully.
    • topic: string - Topic the will will be published to
    • payload: string - Message of the will Base64-encoded
    • qos: QoS - quality of service of the will
    • retain: boolean - Indicates whether the will should be retained
  • tls: boolean - Whether the client will secure the connection to the broker using TLS. If true, at least the broker's CA certificate caBase64 is required. If the broker expects the client to present a certificate as well, the shared caBase64 plus certificateBase64, keyStoreKey, and keyStorePassword options become mandatory
  • caBase64: String - Base64-encoded CA certificate (DER) used by the MQTT broker
  • certificateBase64: String - Base64-encoded self-signed certificate (DER) of the client
  • privateKeyBase64: string - Base64-encoded RSA private key of the client
  • keyStorePassword: string - Password used in creating the client's keystore
  • cleanSession: boolean - When set to true, the broker will open a non-persistent connection, during which it will not store any subscription information or undelivered messages for the client
  • protocol: Protocol - Identifies the protocol used in the connection to the broker
  • protocolVersion: number - Identies the MQTT version used in the connection to the broker
  • reconnectPeriod: number - Time interval to elapse before a client will attempt to reconnect an unexpectedly disconnected client
  • host: string - Host name of the MQTT broker to connect to
  • port: number - Port number of the MQTT broker to connect to

The QuitoOptionsBuilder provides a number of convenience methods for configurating:

const config = new QuitoOptionsBuilder()
  // uri(uri: string)
  // parses uri and sets host, port, 
  // protocol, and tls (if applicable)
  .uri('ssl://test.mosquitto.org:8883')
  .ca(/* takes a Buffer of the DER-encoded CA */)
  // clientCertificate(certificateDer: Buffer, keyRsaDer: Buffer, keyStorePassword: string)
  // sets all necessary options for self-signed client authentication
  .clientCertificate(cert, key, pass)
  .build();
You might also like...
Kotlin DSL http client
Kotlin DSL http client

Introduction Kotlin DSL http client Features 🔹 Developers Experience-driven library without verbosity. 🔹 Native way to use http client in Kotlin. 🔹

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

AndroidAsync AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request li

Unirest in Java: Simplified, lightweight HTTP client library.

Unirest for Java Install With Maven: !-- Pull in as a traditional dependency -- dependency groupIdcom.konghq/groupId artifactIdunire

An android asynchronous http client built on top of HttpURLConnection.

Versions 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 Version 1.0.6 Description An android asynchronous http client based on HttpURLConnection. Updates U

Unirest in Java: Simplified, lightweight HTTP client library.

Unirest for Java Install With Maven: !-- Pull in as a traditional dependency -- dependency groupIdcom.konghq/groupId artifactIdunire

Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects

Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects

A gRPC Kotlin based server and client starter that builds with Gradle and runs on the JVM
A gRPC Kotlin based server and client starter that builds with Gradle and runs on the JVM

gRPC Kotlin starter Overview This directory contains a simple bar service written as a Kotlin gRPC example. You can find detailed instructions for bui

A Kotlin client for the gRPC based Bar Service
A Kotlin client for the gRPC based Bar Service

Bar Service Kotlin Client Overview This directory contains a simple bar service client written in Kotlin against generated models (protos) You can fin

Kotlin-REST-Retrofit - Simple client to consume a REST API with Retrofit using Kotlin
Kotlin-REST-Retrofit - Simple client to consume a REST API with Retrofit using Kotlin

Kotlin REST Retrofit Sencillo cliente para consumir una API REST con Retrofit us

Owner
Kevin
Kevin
MQTT, publisher-subscriber, Applicazione android per il monitoraggio dello stato vitale dell'utente e dell'ambiente circostante.

MQTT, publisher-subscriber, Applicazione android per il monitoraggio dello stato vitale dell'utente e dell'ambiente circostante.

Andrea Castronovo 2 Jan 12, 2022
Ktor-Client this is the client part that uses the Ktor server

Ktor-Client this is the client part that uses the Ktor server Previews Tech stack & Open source libraries Minimum SDK level 21. Kotlin+ Coroutines + F

Mohamed Emad 4 Dec 23, 2022
Simple kafka client for monitoring topic events. Client has UI powered by Darklaf

kafka-client Simple kafka client for monitoring topic values. How to start $ java -jar kafka-client-1.0.jar How to use specify kafka hosts in config.y

Salavat 0 Jun 3, 2022
Kotlin-echo-client - Echo client using Kotlin with Ktor networking library

Overview This repository contains an echo server implemented with Kotlin and kto

Elliot Barlas 2 Sep 1, 2022
Support for Spring's RestTemplate within native Android applications

Spring for Android Spring for Android is a library that is designed to provide components of the Spring Framework family of projects for use in native

Spring 710 Dec 20, 2022
Asynchronous Http and WebSocket Client library for Java

Async Http Client Follow @AsyncHttpClient on Twitter. The AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and a

AsyncHttpClient 6k Jan 8, 2023
Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

OkHttp See the project website for documentation and APIs. HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP

Square 43.4k Jan 5, 2023
A type-safe HTTP client for Android and the JVM

Retrofit A type-safe HTTP client for Android and Java. For more information please see the website. Download Download the latest JAR or grab from Mave

Square 41k Jan 5, 2023
Android client for ProjectRTC - a WebRTC demo

AndroidRTC WebRTC Live Streaming An Android client for ProjectRTC. It is designed to demonstrate WebRTC video calls between androids and/or desktop br

Chabardes 1.5k Jan 6, 2023
Multiplatform coroutine-based HTTP client wrapper for Kotlin

networkinkt This is a lightweight HTTP client for Kotlin. It relies on coroutines on both JS & JVM platforms. Here is a simple GET request: val text =

Egor Zhdan 31 Jul 27, 2022