Giter Site home page Giter Site logo

return764 / react-native-mqtt Goto Github PK

View Code? Open in Web Editor NEW

This project forked from 6d7a/quito

3.0 0.0 1.0 2.19 MB

TCP-capable MQTT client for react native

License: MIT License

JavaScript 3.47% Ruby 3.99% C 0.11% Objective-C 2.56% Kotlin 27.67% TypeScript 38.38% Swift 20.80% Objective-C++ 3.03%

react-native-mqtt's Introduction

Enhancement of Quito

source repository: https://github.com/6d7a/quito

  1. upgrade react-native to 0.73
  2. upgrade CocoaMQTT to 2.1.6
  3. use MqttCocoaAsyncSocket instead of CocoaAsyncSocket
  4. fix exapmle project bug

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.

This libraries owes a lot to davesters' and SudoPlz' respective libraries, so thank you ๐Ÿ’ฏ

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 MqttClient = new MqttClient(config);

MqttClient.init() // call init() to create native client and set up native event listeners
  .then(() => {
    // Subscribing to event callbacks
    MqttClient.on(MqttEvent.CONNECTING, () => {
      // called when client is connecting
    });
    MqttClient.on(MqttEvent.CONNECTED, () => {
      // called when client is connected
    });
    MqttClient.on(MqttEvent.SUBSCRIBED, (topic: string) => {
      // called when client has subscribed to a topic
    });
    MqttClient.on(MqttEvent.UNSUBSCRIBED, (topic: string) => {
      // called when client has unsubscribed from a topic
    });
    MqttClient.on(
      MqttEvent.MESSAGE_RECEIVED,
      (topic: string, payload: Uint8Array) => {
        // called when client has received a message
      }
    );
    MqttClient.on(
      MqttEvent.MESSAGE_PUBLISHED,
      (topic: string, payload: Uint8Array) => {
        // called when client has sent a message
      }
    );
    MqttClient.on(MqttEvent.DISCONNECTED, () => {
      // called when client has disconnected
    });
    MqttClient.on(MqttEvent.CONNECTION_LOST, (error?: Error) => {
      // called when client has unexpectedly lost its connection to the broker
    });
    MqttClient.on(MqttEvent.EXCEPTION, (error: Error) => {
      // called when client encountered an error
    });
    MqttClient.on(MqttEvent.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.unsubscribe('first/topic');

    // publishing a message
    MqttClient.publish(
      'first/topic',
      Buffer.from('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 { 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 MqttClient = new MqttClient(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(
  MqttEvent.MESSAGE_RECEIVED,
  (topic: string, payload: Uint8Array) => {
    // called when client has received a message
  }
);
MqttClient.on(MqttEvent.CONNECTION_LOST, (error?: Error) => {
  // called when client has unexpectedly lost its connection to the broker
});
MqttClient.on(MqttEvent.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',
    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 MqttClient.isConnected();

// shutting down client
try {
  await MqttClient.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 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. Depending on the host platform, the options vary.
    • On Android: If tls == true, at least the broker's CA certificate android_caBase64 is required. If the broker expects the client to present a certificate as well, the shared android_caBase64 plus android_certificateBase64, keyStoreKey, and keyStorePassword options become mandatory
    • On iOS: If tls == true and no ios_certKeyP12Base64 is provided, broker certificates will not be validated. If tls == true and ios_certKeyP12Base64 is provided, the client wil authenticate using the contained crypto.
  • ios_certKeyP12Base64: String - Base64-encoded PKCS12 archive containing client certificate and key
  • android_caBase64: String - Base64-encoded CA certificate (DER) used by the MQTT broker
  • android_certificateBase64: String - Base64-encoded self-signed X509 certificate (DER) of the client
  • android_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

react-native-mqtt's People

Contributors

6d7a avatar return764 avatar

Stargazers

Ghyath avatar Felipe Valenzuela avatar Kyrie avatar

Forkers

hiroenzo

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.