This is a simple example of how to use MQTT.js in a React Native project. This example also is using Expo to make it easier to run the project.
- Getting Started
- Environment Variables
- Config MQTT.js in React Native
- About important files
- Contributing
- Clone this repository
- Install the dependencies with
npm install
- Copy the
.env.example
file to.env
and configure the MQTT broker settings - Run the project with
npm start
- Open the project in your device using the Expo Go APP reading the QR code that will appear in the terminal.
- Publish a message from your MQTT Broker
Variable | Type | Description | Example |
---|---|---|---|
EXPO_PUBLIC_TZ |
string | Timezone will be used to format the date | UTC | America/Santo_Domingo |
EXPO_PUBLIC_EMIT_CONSOLE_LOGS |
boolean | Show in console all error logs | true | false |
EXPO_PUBLIC_MQTT_HOST |
string | MQTT Broker Host | localhost | domain.com |
EXPO_PUBLIC_MQTT_PORT |
number | MQTT Broker Port | 1883 |
EXPO_PUBLIC_MQTT_PORT_SSL |
number | MQTT Broker SSL Port | 8883 |
EXPO_PUBLIC_MQTT_SSL |
boolean | Enable connection via SSL | true | false |
EXPO_PUBLIC_MQTT_VERSION |
number | MQTT Protocol Version |
3 = 3.1
4 = 3.1.1
5 = 5
|
EXPO_PUBLIC_MQTT_QOS |
number | MQTT Broker Quality of Service | 0 | 1 | 2 |
EXPO_PUBLIC_MQTT_USERNAME |
string | MQTT Broker Username | producer | consumer |
EXPO_PUBLIC_MQTT_PASSWORD |
string | MQTT Broker Password | 123 | 456 |
EXPO_PUBLIC_MQTT_TOPICS |
string | MQTT Broker Topics separated by comma , |
topic/1 | topic/1,topic/2 | topic/# |
Mosquitto Test Server Configuration
# APP
EXPO_PUBLIC_TZ = "UTC"
EXPO_PUBLIC_EMIT_CONSOLE_LOGS = true
# MQTT
EXPO_PUBLIC_MQTT_HOST = "test.mosquitto.org"
EXPO_PUBLIC_MQTT_PORT = 8080
EXPO_PUBLIC_MQTT_PORT_SSL = 8081
EXPO_PUBLIC_MQTT_SSL = true
EXPO_PUBLIC_MQTT_VERSION = 4
EXPO_PUBLIC_MQTT_QOS = 0
EXPO_PUBLIC_MQTT_USERNAME = ""
EXPO_PUBLIC_MQTT_PASSWORD = ""
EXPO_PUBLIC_MQTT_TOPICS = "#"
React Native (RN) doesn't support some technologies as web browsers does, in RN the mqtt client always will be established from a WebSocket
instance, for that reason you need some extra packages to make it work. Here is a list of the packages that you need to install to make it work:
File | Description |
---|---|
/App.js |
Main entry point of the application |
/src/screen/Mttq.jsx |
The screen that will show the MQTT logs |
I was looking for a simple example of how to use MQTT.js in a React Native project, but I couldn't find any. So I decided to create this example to help others that are looking for the same thing. In the process I found a issue with the mqtt
package that I had to fix, the PR is in (#1840) if you want to check it out.
Feel free to make a PR if you find any issue or if you want to improve this example. Also, if you have any other issue with the mqtt
package, feel free to open an issue in the MQTT.js repository.
- Juan Carlos: author of this example
- Máximo Liberata: author of the PR that fixed the issue with the
mqtt
package