React and Mosquitto MQTT broker integration - githeim/windheim_archive GitHub Wiki

React and Mosquitto MQTT broker integration

Explain how to integrate Mosquitto MQTT & react framework.

If you want to know about mosquitto mqtt and C++ application integration, refer to the following document.

MQTT broker install and examples

Eclipse Mosquitto settings

Eclipse Mosquitto is an open source message broker that implements the MQTT protocol versions 5.0, 3.1.1 and 3.1.

This part is based on this following document.

enabling-websockets-over-mqtt-with-mosquitto

install eclipse mosquitto

$ sudo apt update
$ sudo apt install mosquitto mosquitto-clients libmosquitto-dev

setup websocket settings

create /etc/mosquitto/mosquitto.conf

vi /etc/mosquitto/mosquitto.conf
# Port to use for the default listener
listener 1885

listener 8885
protocol websockets
allow_anonymous true

connection_messages true
log_timestamp true

start mosquitto with configuration

$ mosquitto -c /etc/mosquitto/mosquitto.conf
1685400115: mosquitto version 2.0.11 starting
1685400115: Config loaded from /etc/mosquitto/conf.d/custom.conf.
1685400115: Opening ipv4 listen socket on port 1885.
1685400115: Opening ipv6 listen socket on port 1885.
1685400115: Opening websockets listen socket on port 8885.
1685400115: mosquitto version 2.0.11 running

In this case websocket uses port 8885.

react settings

setup for react.

This part is based on this following document.

getting-started-with-reactjs-and-mqtt-iot-dashboard

create react application

$ npx create-react-app react-mqtt
$ cd react-mqtt
$ npm install mqtt
$ npm install url

edit App.js file

import React, { useState, Fragment } from "react";
import "./App.css";
 
var mqtt = require("mqtt");
var options = {
  protocol: "ws",
//  username: "xxxxxxxxx",
//  password: "xxxxxxxx",
//  keepalive: 20,
// clientId uniquely identifies client
// choose any string you wish
  clientId: "mqttjs_" + Math.random().toString(16).substr(2, 8),
};

var client = mqtt.connect("mqtt://<your IP address>:<your websocket port>", options);
// ex) var client = mqtt.connect("mqtt://192.168.1.171:8885", options);
 
console.log(options.protocol);
console.log(options.clientId);
client.subscribe("publishtopic");
console.log("Client subscribed ");
 
function App() {
  var note;
  client.on("message", function (topic, message) {
    note = message.toString();
    // Updates React state with message
    setMsg(note);
    console.log(note);
    client.end();
  });
 
  // Sets default React state
  const [msg, setMsg] = useState(
    <Fragment>
      <em>...</em>
    </Fragment>
  );
 
  return (
    <div className="App">
      <header className="App-header">
        <h1>Hello MQTT in React</h1>
        <p>The message payload is: {msg}</p>
      </header>
    </div>
  );
}
export default App;

Settings for webpack5

with following command, there is an error "Buffer is not defined"

npm start

connect with the brower.

ex) http://192.168.0.100:3000

you can see the following error in your browser

constants.js:46 Uncaught ReferenceError: Buffer is not defined
    at ./node_modules/mqtt-packet/constants.js (constants.js:46:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./node_modules/mqtt-packet/parser.js (parser.js:4:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./node_modules/mqtt-packet/mqtt.js (mqtt.js:1:1)
    at options.factory (react refresh:6:1)

to suppress this error, create the file webpack.config.js in node_modules/mqtt

const webpack = require('webpack')
module.exports = {
    entry: "./lib/connect/index.js",
    //mode: "development",
    output: {
        library:  {
            type: "commonjs2"
        },
        filename: "mqtt.browser.js"
    },
    plugins: [
        // fix "process is not defined" error:
        // (do "npm install process" before running the build)
        new webpack.ProvidePlugin({
          process: 'process/browser',
        }),
        new webpack.ProvidePlugin({
            Buffer: [ 'buffer', 'Buffer' ],
        }),
    ],
    resolve: {
        fallback: {
            assert: require.resolve('assert'),
            buffer: require.resolve('buffer'),
            console: require.resolve('console-browserify'),
            constants: require.resolve('constants-browserify'),
            crypto: require.resolve('crypto-browserify'),
            domain: require.resolve('domain-browser'),
            events: require.resolve('events'),
            http: require.resolve('stream-http'),
            https: require.resolve('https-browserify'),
            os: require.resolve('os-browserify/browser'),
            path: require.resolve('path-browserify'),
            punycode: require.resolve('punycode'),
            process: require.resolve('process/browser'),
            querystring: require.resolve('querystring-es3'),
            stream: require.resolve('stream-browserify'),
            string_decoder: require.resolve('string_decoder'),
            sys: require.resolve('util'),
            timers: require.resolve('timers-browserify'),
            tty: require.resolve('tty-browserify'),
            url: require.resolve('url'),
            util: require.resolve('util'),
            vm: require.resolve('vm-browserify'),
            zlib: require.resolve('browserify-zlib'),
        }
    }
}

and then edit the file node_modules/mqtt/package.json

{
  ...
  "type": "commonjs",
  "browser": {
    "./mqtt.js": "./dist/mqtt.browser.js"
    ...
  }
  ...
}

in the directory node_modules/mqtt , execute the followings

$ npm i 
$ npm i buffer process
$ npm i webpack webpack-cli
$ npx webpack

clean npm cache

$ cd react-mqtt
$ rm -rf node_modules/.cache

then rebuild and start application

$ npm start

Test Application

open your webpage with browser

ex) http://192.168.0.100:3000/

send the message to topic "publishtopic" with mosquitto client

remember the port of mqtt is 1885 in this settings. it is different from websocket port 8885 that the web application is using.

mosquitto_pub -h localhost -p 1885 -t publishtopic -m "Hell Wolrd" -q 1

And then you can see the message "Hell World" in your browser.

⚠️ **GitHub.com Fallback** ⚠️