├── .gitattributes ├── img ├── light-broker.png ├── NanoLedPushbutton.fzz ├── NanoLedPushbutton_bb.png ├── NanoLedPushbutton_schem.png └── web-midi-mqtt.svg ├── _config.yml ├── browser-clients ├── eclipse-pahojs │ ├── EclipsePahoWithQRCode │ │ ├── style.css │ │ ├── index.html │ │ └── sketch.js │ ├── mqtt-midi-controller │ │ ├── style.css │ │ └── index.html │ ├── EclipsePahoP5Client │ │ ├── index.html │ │ └── sketch.js │ ├── mousePressed-client │ │ ├── index.html │ │ └── sketch.js │ ├── EclipsePahoHueLightControl │ │ ├── index.html │ │ └── sketch.js │ ├── p5Serial-client │ │ ├── index.html │ │ ├── ArduinoJoystick │ │ │ └── ArduinoJoystick.ino │ │ └── sketch.js │ ├── mqtt-midi-client │ │ └── index.html │ ├── EclipsePahoSensorReceiverJSON │ │ ├── index.html │ │ └── script.js │ ├── EclipsePahoClientSimple │ │ ├── index.html │ │ └── script.js │ └── readme.md └── mqttjs │ ├── mqtt-midi-controller │ ├── style.css │ └── index.html │ ├── mqttjs-p5js-mousepressed-client │ ├── index.html │ └── sketch.js │ ├── mqttjsHueLightControl │ ├── index.html │ └── sketch.js │ ├── mqttjs-client-simple │ ├── index.html │ └── script.js │ └── readme.md ├── node-clients ├── MqttNodeClientFileWriter │ ├── package.json │ └── client.js ├── MqttNodeClient │ ├── package.json │ └── mqtt-client.js ├── readme.md └── MqttNodeClientSerial │ ├── package.json │ ├── SerialInOut │ └── SerialInOut.ino │ └── mqtt-client-serial.js ├── .gitignore ├── _includes └── nav.html ├── _layouts └── default.html ├── arduino-clients ├── MqttClientMIDIPlayer │ └── MqttClientMIDIPlayer.ino ├── MqttClientNeoPixel │ └── MqttClientNeoPixel.ino ├── ArduinoMqttClient-SHTC3Sender │ └── ArduinoMqttClient-SHTC3Sender.ino ├── MqttClient_SensorENS160Sender │ └── MqttClient_SensorENS160Sender.ino ├── ArduinoMqttClientLamp │ └── ArduinoMqttClientLamp.ino ├── ArduinoMqttClient │ └── ArduinoMqttClient.ino ├── ArduinoMqttClientTouchReadESP32 │ └── ArduinoMqttClientTouchReadESP32.ino ├── MqttClientHueControl │ └── MqttClientHueControl.ino ├── ArduinoMqttClientESP32_Eduroam │ └── ArduinoMqttClientESP32_Eduroam.ino ├── MqttClient_SensorTCS34725Sender │ └── MqttClient_SensorTCS34725Sender.ino ├── MqttClientMIDIController │ └── MqttClientMIDIController.ino ├── MqttClient_SensorCombinedAQISender │ └── MqttClient_SensorCombinedAQISender.ino ├── MqttClientAS7343 │ └── MqttClientAS7343.ino ├── MqttClientSubTopics │ └── MqttClientSubTopics.ino ├── ArduinoMqttClientWithWill │ └── ArduinoMqttClientWithWill.ino └── readme.md ├── mqtt-vs-websockets.md └── readme.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /img/light-broker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tigoe/mqtt-examples/HEAD/img/light-broker.png -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal 2 | codeurl: https://github.com/tigoe/mqtt-examples/tree/main -------------------------------------------------------------------------------- /img/NanoLedPushbutton.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tigoe/mqtt-examples/HEAD/img/NanoLedPushbutton.fzz -------------------------------------------------------------------------------- /img/NanoLedPushbutton_bb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tigoe/mqtt-examples/HEAD/img/NanoLedPushbutton_bb.png -------------------------------------------------------------------------------- /img/NanoLedPushbutton_schem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tigoe/mqtt-examples/HEAD/img/NanoLedPushbutton_schem.png -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/EclipsePahoWithQRCode/style.css: -------------------------------------------------------------------------------- 1 | /* adapted from https://css-tricks.com/simplified-fluid-typography/ */ 2 | 3 | html { 4 | font-size: min(max(1rem, 4vmax), 22px); 5 | } 6 | -------------------------------------------------------------------------------- /browser-clients/mqttjs/mqtt-midi-controller/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial, Helvetica, sans-serif; 3 | } 4 | #black-keys { 5 | font-size: 24px; 6 | letter-spacing: 5px; 7 | } 8 | 9 | #white-keys { 10 | font-size: 24px; 11 | letter-spacing: 5px; 12 | } 13 | 14 | #notes { 15 | font-size: 12px; 16 | word-spacing: 14px; 17 | } -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/mqtt-midi-controller/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial, Helvetica, sans-serif; 3 | } 4 | #black-keys { 5 | font-size: 24px; 6 | letter-spacing: 5px; 7 | } 8 | 9 | #white-keys { 10 | font-size: 24px; 11 | letter-spacing: 5px; 12 | } 13 | 14 | #notes { 15 | font-size: 12px; 16 | word-spacing: 14px; 17 | } -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/EclipsePahoP5Client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/mousePressed-client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /browser-clients/mqttjs/mqttjs-p5js-mousepressed-client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /browser-clients/mqttjs/mqttjsHueLightControl/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | public 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/EclipsePahoHueLightControl/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | public 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /node-clients/MqttNodeClientFileWriter/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mqttnodeclientfilewriter", 3 | "version": "0.0.3", 4 | "description": "A node mqtt client that writes to the filesystem", 5 | "main": "client.js", 6 | "dependencies": { 7 | "mqtt": "^4.3.7" 8 | }, 9 | "devDependencies": {}, 10 | "scripts": { 11 | "test": "echo \"Error: no test specified\" && exit 1" 12 | }, 13 | "keywords": [ 14 | "mqtt" 15 | ], 16 | "author": "Tom Igoe", 17 | "license": "ISC" 18 | } 19 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/p5Serial-client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/mqtt-midi-client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/EclipsePahoSensorReceiverJSON/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | 10 |

MQTT Sensor Reader with JSON

11 | Topic:
12 |
local messages go here
13 |
remote messages go here
14 | 15 | 16 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/EclipsePahoWithQRCode/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | public 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *arduino_secrets.h 2 | *.DS_Store 3 | MqttClientButtonLed/arduino_secrets.h 4 | MqttClientMIDIPlayer/arduino_secrets.h 5 | MqttClientReceiver/arduino_secrets.h 6 | MqttClientSender/arduino_secrets.h 7 | MqttClientButtonLed/arduino_secrets.h 8 | */arduino_secrets.h 9 | MqttClientSender/arduino_secrets.h 10 | MqttClientMIDIPlayer/arduino_secrets.h 11 | MqttClientButtonLed/arduino_secrets.h 12 | */node_modules/* 13 | MqttClientButtonLed/arduino_secrets.h 14 | */arduino_secrets.h 15 | MqttClientButtonLed/arduino_secrets.h 16 | MqttClientSender/arduino_secrets.h 17 | MqttClientSender/arduino_secrets.h 18 | MqttNodeClientFileWriter/data.txt 19 | MqttClientSender/arduino_secrets.h 20 | *node_modules 21 | -------------------------------------------------------------------------------- /node-clients/MqttNodeClient/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "mqtt": "^1.14.0" 4 | }, 5 | "name": "mqtt-node-client", 6 | "version": "0.0.2", 7 | "description": "a simple node mqtt client", 8 | "main": "mqtt-client.js", 9 | "devDependencies": {}, 10 | "scripts": { 11 | "test": "echo \"Error: no test specified\" && exit 1" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/tigoe/mqtt-examples.git" 16 | }, 17 | "keywords": [ 18 | "mqtt" 19 | ], 20 | "author": "Tom Igoe", 21 | "license": "ISC", 22 | "bugs": { 23 | "url": "https://github.com/tigoe/mqtt-examples/issues" 24 | }, 25 | "homepage": "https://github.com/tigoe/mqtt-examples#readme" 26 | } 27 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/EclipsePahoClientSimple/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | public 6 | 7 | 8 | 9 | 10 |

Eclipse Paho JS basic example

11 | 12 | Click here for the source code 13 |
14 |
15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /node-clients/readme.md: -------------------------------------------------------------------------------- 1 | # Node.js Clients 2 | 3 | There are three clients built in node.js in this repository 4 | * [MqttNodeClient]({{site.codeurl}}/node-clients/MqttNodeClient/) which is a basic example of how to make a client with the [node.js MQTT library](https://www.npmjs.com/package/mqtt). It sends a reading every few seconds, and subscribes to a topic called `lights`. It will work with the light control examples above. 5 | * [MqttNodeClientSerial]({{site.codeurl}}/node-clients/MqttNodeClientSerial/) is similar, but it uses the node serialport library from [serialport.io](https://serialport.io/docs) to connect MQTT to serial in and out. 6 | * [MqttNodeClientFileWriter]({{site.codeurl}}/node-clients/MqttNodeClientFileWriter/) reads messages from a topic and writes them to a text file. 7 | -------------------------------------------------------------------------------- /node-clients/MqttNodeClientSerial/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mqtt-node-client-serial", 3 | "version": "0.0.2", 4 | "description": "An MQTT to Serialport client", 5 | "main": "mqtt-client-serial.js", 6 | "dependencies": { 7 | "mqtt": "^1.14.0", 8 | "serialport": "^9.2.0" 9 | }, 10 | "scripts": { 11 | "test": "echo \"Error: no test specified\" && exit 1" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/tigoe/mqtt-examples.git" 16 | }, 17 | "keywords": [ 18 | "mqtt", 19 | "serialport" 20 | ], 21 | "author": "Tom Igoe", 22 | "license": "ISC", 23 | "bugs": { 24 | "url": "https://github.com/tigoe/mqtt-examples/issues" 25 | }, 26 | "homepage": "https://github.com/tigoe/mqtt-examples#readme" 27 | } 28 | -------------------------------------------------------------------------------- /browser-clients/mqttjs/mqttjs-client-simple/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | MQTT Client 9 | 10 | 11 |

mqtt.js basic example

12 | 13 | Click here for the source code 14 | 15 |
16 |
17 | 18 | -------------------------------------------------------------------------------- /node-clients/MqttNodeClientSerial/SerialInOut/SerialInOut.ino: -------------------------------------------------------------------------------- 1 | int lastSensorReading = 0; 2 | int threshold = 5; 3 | 4 | void setup() { 5 | // open serial port and set timeout for reading to 10ms: 6 | Serial.begin(9600); 7 | Serial.setTimeout(10); 8 | // init pin 9 as output: 9 | pinMode(9, OUTPUT); 10 | } 11 | 12 | void loop() { 13 | // read a sensor, get a range from 0-255: 14 | int sensor = analogRead(A0) / 4; 15 | 16 | // if it's changed enough, send it: 17 | if (abs(sensor - lastSensorReading) > threshold) { 18 | Serial.println(sensor); 19 | } 20 | // if there's serial to be read, read and parse 21 | // for an integer: 22 | if (Serial.available() > 0) { 23 | int intensity = Serial.parseInt(); 24 | // if the result is > 0, 25 | // set the LED on pin 9 with it: 26 | if (intensity > 0) { 27 | analogWrite(9, intensity); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /_includes/nav.html: -------------------------------------------------------------------------------- 1 |

2 | tigoe.github.io
3 | MQTT Examples Home
4 | MQTT and WebSockets Compared
5 | Arduino Clients
6 | mqtt.js Browser Clients
7 | mqtt.js node.js Clients
8 | Eclipse PAHO Browser Clients (library no longer supported)
9 | Desktop and Mobile Client Apps
10 | MQTT Brokers
11 | Client Settings by Broker
12 |

-------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/p5Serial-client/ArduinoJoystick/ArduinoJoystick.ino: -------------------------------------------------------------------------------- 1 | /* 2 | A Joystick client 3 | Reads a joystick whose two potentiometers are connected 4 | to analog 0 and analog 1. 5 | */ 6 | 7 | void setup() { 8 | Serial.begin(9600); 9 | pinMode(2, INPUT_PULLUP); 10 | } 11 | 12 | void loop() { 13 | int buttonState = digitalRead(2); 14 | // read analog 0, convert to a byte: 15 | int x = analogRead(A0) / 4; 16 | // 1ms delay to stabilize ADC: 17 | delay(1); 18 | // read analog 1, convert to a byte: 19 | int y = analogRead(A1) / 4; 20 | // send values out serial port as a JSON string: 21 | String jsonString = "{\"x\":XPOS,\"y\":YPOS,\"button\":BUTTON}"; 22 | // replace the placeholders in the String with the actual values: 23 | jsonString.replace("XPOS", String(x)); 24 | jsonString.replace("YPOS", String(y)); 25 | jsonString.replace("BUTTON", String(buttonState)); 26 | // send the string: 27 | Serial.println(jsonString); 28 | } 29 | -------------------------------------------------------------------------------- /browser-clients/mqttjs/mqtt-midi-controller/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Document 11 | 12 | 13 |

MIDI MQTT Message Sender and Receiver

14 |

This page connects to an MQTT broker, and uses WebMIDI to connect to any MIDI inputs or outputs on your system. It will auto-detect new MIDI devices as they are connected or disconnected from your system.

15 |

When a MIDI message is received, it is converted to an MQTT message on a topic called Midi, and sent out to the MQTT broker. Likewise, when an MQTT message is received, it is converted to a MIDI message and sent to the selected MIDI output device.

16 |

You can also generate MIDI messages (and MQTT messages) by typing the keys below.

17 |

The Local Echo checkbox selects whether the MIDI output takes messages from local sources, or just from MQTT.

18 | 19 |
20 |
21 |
22 |
local messages will go here
23 |
waiting for messages
24 |
messages will go here
25 | 26 |

Keyboard Input:

27 |  W E    T Y U   O
28 | A S D F G H J K L
29 | C3 D3 E3 F3 G3 A4 B4 C4 D4 30 | 31 | -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/mqtt-midi-controller/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Document 11 | 12 | 13 |

MIDI MQTT Message Sender and Receiver

14 |

This page connects to an MQTT broker, and uses WebMIDI to connect to any MIDI inputs or outputs on your system. It will auto-detect new MIDI devices as they are connected or disconnected from your system.

15 |

When a MIDI message is received, it is converted to an MQTT message on a topic called Midi, and sent out to the MQTT broker. Likewise, when an MQTT message is received, it is converted to a MIDI message and sent to the selected MIDI output device.

16 |

You can also generate MIDI messages (and MQTT messages) by typing the keys below.

17 |

The Local Echo checkbox selects whether the MIDI output takes messages from local sources, or just from MQTT.

18 | 19 |
20 |
21 |
22 |
local messages will go here
23 |
waiting for messages
24 |
messages will go here
25 | 26 |

Keyboard Input:

27 |  W E    T Y U   O
28 | A S D F G H J K L
29 | C3 D3 E3 F3 G3 A4 B4 C4 D4 30 | 31 | -------------------------------------------------------------------------------- /node-clients/MqttNodeClient/mqtt-client.js: -------------------------------------------------------------------------------- 1 | /* 2 | Simple MQTT Node.js client. 3 | Connects to shiftr.io's public broker, and sends 4 | a message to a topic called lights every two 5 | seconds. 6 | 7 | created 10 Apr 2021 8 | by Tom Igoe 9 | */ 10 | 11 | // include the MQTT library: 12 | const mqtt = require('mqtt'); 13 | // the broker you plan to connect to. 14 | // transport options: 15 | // 'mqtt', 'mqtts', 'tcp', 'tls', 'ws', or 'wss': 16 | //const broker = 'mqtt://test.mosquitto.org'; 17 | const broker = 'mqtt://public.cloud.shiftr.io'; 18 | 19 | // client options: 20 | const options = { 21 | // add a random number for a unique clientId: 22 | clientId: 'nodeClient-' + Math.floor(Math.random()*1000000), 23 | username: 'public', 24 | password: 'public', 25 | clean: true, 26 | connectTimeout: 4000, 27 | reconnectPeriod: 1000 28 | } 29 | // topic and message payload: 30 | let myTopic = 'aardvarks'; 31 | let payload; 32 | 33 | // connect handler: 34 | function setupClient() { 35 | console.log('setup'); 36 | client.subscribe(myTopic); 37 | client.on('message', readMqttMessage); 38 | } 39 | 40 | // new message handler: 41 | function readMqttMessage(topic, message) { 42 | // message is a Buffer, so convert to a string: 43 | let msgString = message.toString(); 44 | console.log(topic); 45 | console.log(msgString); 46 | } 47 | 48 | // message sender: 49 | function sendMqttMessage(topic, msg) { 50 | if (client.connected) { 51 | let msgString = JSON.stringify(msg); 52 | client.publish(topic, msgString); 53 | console.log('update'); 54 | } 55 | } 56 | 57 | // setInterval handler: 58 | function update() { 59 | payload = Math.round(Math.random(254) * 254); 60 | sendMqttMessage(myTopic, payload); 61 | } 62 | 63 | // make a client and connect: 64 | let client = mqtt.connect(broker, options); 65 | client.on('connect', setupClient); 66 | 67 | // // send a message every two seconds: 68 | setInterval(update, 100); -------------------------------------------------------------------------------- /_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | {% seo %} 8 | 9 | 10 | 11 | 14 | 15 | 16 |
17 |
18 |

{{ site.title | default: site.github.repository_name }}

19 |

{{ site.description | default: site.github.project_tagline }} 20 |

21 | {% include nav.html %} 22 | 23 | 30 | 31 | {% if site.github.is_project_page %} 32 |

This project is maintained by {{ site.github.owner_name }}

33 | {% endif %} 34 | 35 | {% if site.github.is_user_page %} 36 | 39 | {% endif %} 40 |
41 | 42 |
43 | {{ content }} 44 |
45 | 46 | 49 |
50 | 51 | {% if site.google_analytics %} 52 | 60 | {% endif %} 61 | 62 | -------------------------------------------------------------------------------- /node-clients/MqttNodeClientSerial/mqtt-client-serial.js: -------------------------------------------------------------------------------- 1 | /* 2 | Simple MQTT Node.js client with serial port. 3 | Connects to shiftr.io's public broker. Reads from serial 4 | port and sends to broker; reads from broker and sends to 5 | serial port. 6 | 7 | To launch this, give the portname like so: 8 | node mqtt-client-seial.js portname 9 | 10 | Arduino sketch SerialInOut.ino works with this script. 11 | 12 | created 10 Apr 2021 13 | modified 21 Jun 2021 14 | by Tom Igoe 15 | */ 16 | 17 | // include the MQTT library: 18 | const mqtt = require('mqtt'); 19 | // include serialport libraries 20 | const SerialPort = require('serialport'); // include the serialport library 21 | const Readline = require('@serialport/parser-readline'); 22 | 23 | // the broker you plan to connect to. 24 | // transport options: 25 | // 'mqtt', 'mqtts', 'tcp', 'tls', 'ws', or 'wss': 26 | const broker = 'mqtt://public.cloud.shiftr.io'; 27 | 28 | // client options: 29 | const options = { 30 | // add a random number for a unique client ID: 31 | clientId: 'nodeClient-' + Math.floor(Math.random()*1000000), 32 | username: 'public', 33 | password: 'public', 34 | clean: true, 35 | connectTimeout: 4000, 36 | reconnectPeriod: 1000 37 | } 38 | // topic and message payload: 39 | let myTopic = 'lights'; 40 | let payload; 41 | 42 | // connect handler: 43 | function setupClient() { 44 | client.subscribe(myTopic); 45 | client.on('message', readMqttMessage); 46 | } 47 | 48 | // new message handler: 49 | function readMqttMessage(topic, message) { 50 | // message is a Buffer, so convert to a string: 51 | let msgString = message.toString(); 52 | console.log(topic + ': ' + msgString); 53 | // send it out the serial port: 54 | myPort.write(msgString); 55 | } 56 | 57 | // message sender: 58 | function sendMqttMessage(topic, msg) { 59 | if (client.connected) { 60 | client.publish(topic, msg); 61 | } 62 | } 63 | 64 | ///////////////////////// Serial functions 65 | // make a readline parser: 66 | const parser = new Readline({ delimiter: '\r\n' }); 67 | // get the port name from the command line: 68 | var portName = process.argv[2]; 69 | // serial port config: 70 | var portConfig = { 71 | baudRate: 9600, 72 | }; 73 | 74 | function openPort() { 75 | console.log('port open'); 76 | console.log('baud rate: ' + myPort.baudRate); 77 | } 78 | 79 | function serialEvent(data) { 80 | sendMqttMessage(myTopic, data); 81 | console.log(data); 82 | } 83 | 84 | // open the serial port: 85 | var myPort = new SerialPort(portName, portConfig); 86 | // set up a line reading parser: 87 | myPort.pipe(parser); 88 | // open the port: 89 | myPort.on('open', openPort); 90 | // set up a listener for new lines: 91 | parser.on('data', serialEvent); 92 | 93 | // make a client and connect: 94 | let client = mqtt.connect(broker, options); 95 | client.on('connect', setupClient); -------------------------------------------------------------------------------- /browser-clients/mqttjs/readme.md: -------------------------------------------------------------------------------- 1 | # mqtt.js Browser Client Examples 2 | 3 | These examples are based on the [mqtt.js](https://github.com/mqttjs/MQTT.js) client library. 4 | 5 | ## mqttjs-client-simple 6 | * [See the example running](mqttjs-client-simple) 7 | * [See the source code]({{site.codeurl}}/browser-clients/mqttjs/mqttjs-client-simple) 8 | 9 | This is a bare minimum client example for mqtt.js. On document load, the script for this page gets two divs from the HTML document for local and remote messages.Then it attempts to connect to the broker. Once it does, it sends the local time if it's connected every two seconds. The publish button allows you to turn on and off publishing status, in case you're testing with a second client that's sending to the same topic. 10 | 11 | The [ArduinoMqttClient example]({{site.codeurl}}/arduino-clients/ArduinoMqttClient) uses the same topic and sends the same range of numeric values if you want to test against another client. 12 | 13 | ## mqttjs-p5js-mousepressed-client 14 | * [See the example running](mqttjs-p5js-mousepressed-client) 15 | * [See the source code]({{site.codeurl}}/browser-clients/mqttjs/mqttjs-p5js-mousepressed-client) 16 | 17 | This example uses [p5.js](https://p5js.org/) and the [mqtt.js client library](https://www.npmjs.com/package/mqtt) to create an MQTT client that sends and receives MQTT messages. The client is set up for use on the [shiftr.io](https://www.shiftr.io/try/) test MQTT broker, but other options listed will work. 18 | 19 | ## mqtt-midi-controller 20 | * [See the example running](mqtt-midi-controller) 21 | * [See the source code]({{site.codeurl}}/browser-clients/mqttjs/mqtt-midi-controller) 22 | 23 | This example uses the [mqtt.js library](https://www.npmjs.com/package/mqtt) and the [Web MIDI API](https://www.w3.org/TR/webmidi/) to create an MQTT client that sends and receives MQTT messages that are MIDI messages. You can use keyboard input as well, as shown in the HTML. 24 | The client is set up for use on the [shiftr.io test MQTT broker](https://www.shiftr.io/try/), but has also been tested on other brokers. 25 | 26 | This [Arduino MQTT-to-MIDI Player Client]({{site.codeurl}}/arduino-clients/MqttClientMIDIPlayer/MqttClientMIDIPlayer.ino) can receive MIDI messages from the same broker and send MIDI to your operating system or MIDI system. This [Arduino MIDI-to-MQTT Controller Client]({{site.codeurl}}/arduino-clients/MqttClientMIDIController/MqttClientMIDIController.ino) can send noteon and noteoff messages via MQTT at the push of a button. 27 | 28 | ## mqttjsHueLightControl 29 | * [See the example running](mqttjsHueLightControl) 30 | * [See the source code]({{site.codeurl}}/browser-clients/mqttjs/mqttjsHueLightControl) 31 | 32 | This example will change the brightness of a light on a local [Philips Hue Hub](https://tigoe.github.io/hue-control/) when you change the slider, and will send an MQTT message with the value of the slider when you press the button. If it receives an MQTT message on the `lights` topic, it uses that value to change the brightness of the light. So you can use this to change the brightness of a local hub, or of a friend's hub on a remote network if you are both connected to the same broker. -------------------------------------------------------------------------------- /node-clients/MqttNodeClientFileWriter/client.js: -------------------------------------------------------------------------------- 1 | /* 2 | MQTT Node.js client writes to filesystem. 3 | Connects to a broker, subscribes to a broad range of topics, 4 | and writes any messages received to a local file called 5 | data.json 6 | 7 | created 10 Apr 2021 8 | modified 3 Nov 2024 9 | by Tom Igoe 10 | */ 11 | 12 | // include the libraries: 13 | const mqtt = require('mqtt'); 14 | const fs = require('fs'); 15 | 16 | // All these brokers work with this code. 17 | // Uncomment the one you want to use. 18 | 19 | ////// emqx. Works in both basic WS and TLS WS: 20 | // const broker = 'wss://broker.emqx.io:8084/mqtt' 21 | // const broker = 'ws://broker.emqx.io:8083/mqtt' 22 | 23 | //////// shiftr.io desktop client. 24 | // Fill in your desktop IP address for localhost: 25 | // const broker = 'ws://localhost:1884'; 26 | 27 | //////// shiftr.io, using username and password 28 | // (see options variable below): 29 | // const broker = 'wss://public.cloud.shiftr.io'; 30 | 31 | //////// test.mosquitto.org, uses no username and password: 32 | // const broker = 'wss://test.mosquitto.org:8081'; 33 | 34 | // or use your own: 35 | const broker = 'mqtt://mysite.com'; 36 | 37 | // the path to the data file: 38 | let filePath = __dirname + '/data.json'; 39 | 40 | // client options: 41 | const options = { 42 | // add the current epoch time for a unique clientId: 43 | clientId: 'nodeClient-' + Date.now(), 44 | username: 'user', 45 | password: 'password!', 46 | clean: true, 47 | connectTimeout: 4000, 48 | reconnectPeriod: 1000 49 | } 50 | // topic: 51 | let myTopic = '#'; 52 | 53 | // connect handler: 54 | function setupClient() { 55 | console.log('client connected'); 56 | client.subscribe(myTopic); 57 | } 58 | 59 | // new message handler: 60 | function readMqttMessage(topic, message, packet) { 61 | // // make a timestamp string: 62 | let now = new Date(); 63 | // create a new record from the topic and subtopics: 64 | let record = {}; 65 | let subTopics = topic.split('/'); 66 | // assume first subTopic is the creator name: 67 | record.creator = subTopics[0]; 68 | // if there's a second subTopic, assume that's the data label: 69 | let dataLabel = subTopics[1]; 70 | // if it's empty, use the label 'data': 71 | if (!dataLabel) dataLabel = 'data'; 72 | // make a timestamp: 73 | record.timeStamp = now.toISOString(); 74 | 75 | // see if the message parses as valid JSON: 76 | try { 77 | let data = JSON.parse(message.toString()); 78 | // if it parses, it's JSON or a valid number or array. 79 | // if it's not, just put it in the data category as is: 80 | if (typeof data != 'object') { 81 | record[dataLabel] = data; 82 | } else { 83 | // if JSON, Extract the object properties 84 | // and put each in the record as its own property: 85 | for (i in data) { 86 | record[i] = data[i]; 87 | } 88 | } 89 | } catch (err) { 90 | // if it fails parsing, just put the string in the dataLabel property: 91 | record[dataLabel] = message.toString(); 92 | } 93 | // save to the file: 94 | saveData(record); 95 | } 96 | 97 | 98 | function saveData(data) { 99 | // this function is called by the writeFile and appendFile functions 100 | // below: 101 | function fileWriteResponse() { 102 | console.log("wrote to file at: " + data.timeStamp); 103 | } 104 | /* 105 | write to the file asynchronously. The third parameter of 106 | writeFile is the callback function that's called when 107 | you've had a successful write. 108 | */ 109 | fs.exists(filePath, function (exists) { 110 | if (exists) { 111 | fs.appendFile(filePath, JSON.stringify(data) + '\n', fileWriteResponse); 112 | } else { 113 | fs.writeFile(filePath, JSON.stringify(data) + '\n', fileWriteResponse); 114 | } 115 | }); 116 | } 117 | 118 | // make a client and connect: 119 | let client = mqtt.connect(broker, options); 120 | client.on('connect', setupClient); 121 | client.on('message', readMqttMessage); -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/mousePressed-client/sketch.js: -------------------------------------------------------------------------------- 1 | /* 2 | p5.js MQTT Client example 3 | This example uses p5.js: https://p5js.org/ 4 | and the Eclipse Paho MQTT client library: https://www.eclipse.org/paho/clients/js/ 5 | to create an MQTT client that sends and receives MQTT messages. 6 | The client is set up for use on the shiftr.io test MQTT broker, 7 | but other options listed will work. 8 | 9 | created 12 June 2020 10 | modified 31 Dec 2022 11 | by Tom Igoe 12 | */ 13 | 14 | // All these brokers work with this code. 15 | // Uncomment the one you want to use. 16 | 17 | ////// emqx. Works in both basic WS and SSL WS: 18 | // const broker = 'broker.emqx.io' 19 | // const port = 8083; // no SSL 20 | // const broker = 'broker.emqx.io' 21 | // const port = 8084; // SSL 22 | 23 | //////// shiftr.io desktop client. 24 | // Fill in your desktop URL for localhost: 25 | // const broker = 'localhost'; 26 | // const port = 1884; // no SSL 27 | 28 | //////// shiftr.io, requires username and password 29 | // (see options variable below): 30 | const broker = 'public.cloud.shiftr.io'; 31 | const port = 443; 32 | 33 | //////// test.mosquitto.org, uses no username and password: 34 | // const broker = 'test.mosquitto.org'; 35 | // const port = 8081; 36 | 37 | // MQTT client: 38 | let client; 39 | // client credentials (add random number for unique ID): 40 | let clientID = 'EclipsePahoClient-' + Math.floor(Math.random()*1000000); 41 | 42 | let options = { 43 | // Clean session 44 | cleanSession: true, 45 | // connect timeout in seconds: 46 | timeout: 10, 47 | // callback function for when you connect: 48 | onSuccess: onConnect, 49 | // username & password: 50 | userName: 'public', 51 | password: 'public', 52 | // use SSL 53 | useSSL: true 54 | }; 55 | 56 | // topic to subscribe to when you connect: 57 | let topic = 'monkey'; 58 | // divs to show messages: 59 | let localDiv, remoteDiv; 60 | 61 | // position of the circle 62 | let xPos, yPos; 63 | 64 | function setup() { 65 | createCanvas(400, 400); 66 | // Create an MQTT client: 67 | client = new Paho.MQTT.Client(broker, port, clientID); 68 | // set callback handlers for the client: 69 | client.onConnectionLost = onDisconnect; 70 | client.onMessageArrived = onMessage; 71 | // connect to the MQTT broker: 72 | client.connect(options); 73 | // create a div for local messages: 74 | localDiv = createDiv('local messages will go here'); 75 | localDiv.position(20, 50); 76 | // create a div for the response: 77 | remoteDiv = createDiv('waiting for messages'); 78 | remoteDiv.position(20, 80); 79 | } 80 | 81 | function draw() { 82 | background(255); 83 | noStroke(); 84 | // draw a circle when a message is received: 85 | fill('#2398CE'); 86 | // circle moves with the message: 87 | circle(xPos, yPos, 30); 88 | } 89 | 90 | function mousePressed() { 91 | sendMqttMessage(mouseX + ',' + mouseY); 92 | } 93 | // called when the client connects 94 | function onConnect() { 95 | localDiv.html('client is connected'); 96 | client.subscribe(topic); 97 | } 98 | 99 | // called when the client loses its connection 100 | function onDisconnect(response) { 101 | if (response.errorCode !== 0) { 102 | localDiv.html('disconnect:' + response.errorMessage); 103 | } 104 | } 105 | 106 | // called when a message arrives 107 | function onMessage(message) { 108 | remoteDiv.html('I got a message:' + message.payloadString); 109 | // assume the message is two numbers, mouseX and mouseY. 110 | // Split it into an array: 111 | let values = split(message.payloadString, ','); 112 | // convert the array values into numbers: 113 | xPos = Number(values[0]); 114 | yPos = Number(values[1]); 115 | } 116 | 117 | // called when you want to send a message: 118 | function sendMqttMessage(msg) { 119 | // if the client is connected to the MQTT broker: 120 | if (client.isConnected()) { 121 | // start an MQTT message: 122 | message = new Paho.MQTT.Message(msg); 123 | // choose the destination topic: 124 | message.destinationName = topic; 125 | // send it: 126 | client.send(message); 127 | // print what you sent: 128 | localDiv.html('I sent: ' + message.payloadString); 129 | } 130 | } -------------------------------------------------------------------------------- /browser-clients/mqttjs/mqttjs-p5js-mousepressed-client/sketch.js: -------------------------------------------------------------------------------- 1 | /* 2 | p5.js MQTT Client example 3 | This example uses p5.js: https://p5js.org/ 4 | and the mqtt.js client library: https://www.npmjs.com/package/mqtt 5 | to create an MQTT client that sends and receives MQTT messages. 6 | The client is set up for use on the shiftr.io test MQTT broker, 7 | but other options listed will work. 8 | 9 | created 12 June 2020 10 | modified 19 Feb 2025 11 | by Tom Igoe 12 | */ 13 | 14 | // All these brokers work with this code. 15 | // Uncomment the one you want to use. 16 | 17 | ////// emqx. Works in both basic WS and TLS WS: 18 | // const broker = 'wss://broker.emqx.io:8084/mqtt' 19 | // const broker = 'ws://broker.emqx.io:8083/mqtt' 20 | 21 | //////// shiftr.io desktop client. 22 | // Fill in your desktop IP address for localhost: 23 | // const broker = 'ws://localhost:1884'; 24 | 25 | //////// shiftr.io, requires username and password 26 | // (see options variable below): 27 | const broker = 'wss://public.cloud.shiftr.io'; 28 | 29 | //////// test.mosquitto.org, uses no username and password: 30 | // const broker = 'wss://test.mosquitto.org:8081'; 31 | 32 | // MQTT client: 33 | let client; 34 | // connection options: 35 | let options = { 36 | // Clean session 37 | clean: true, 38 | // connect timeout in ms: 39 | connectTimeout: 10000, 40 | // Authentication 41 | // add a random number for a unique client ID: 42 | clientId: 'mqttJsClient-' + Math.floor(Math.random()*1000000) , 43 | // add these in for public.cloud.shiftr.io: 44 | username: 'public', 45 | password: 'public' 46 | } 47 | 48 | 49 | // topic to subscribe to when you connect: 50 | let topic = 'monkey'; 51 | // divs to show messages: 52 | let localDiv, remoteDiv; 53 | 54 | // position of the circle 55 | let xPos, yPos; 56 | 57 | function setup() { 58 | createCanvas(400, 400); 59 | // Create an MQTT client: 60 | // attempt to connect: 61 | client = mqtt.connect(broker, options); 62 | // set listeners: 63 | client.on('connect', onConnect); 64 | client.on('close', onDisconnect); 65 | client.on('message', onMessage); 66 | client.on('error', onError); 67 | 68 | // create a div for local messages: 69 | localDiv = createDiv('local messages will go here'); 70 | localDiv.position(20, 50); 71 | // create a div for the response: 72 | remoteDiv = createDiv('waiting for messages'); 73 | remoteDiv.position(20, 80); 74 | } 75 | 76 | function draw() { 77 | background(255); 78 | noStroke(); 79 | // draw a circle when a message is received: 80 | fill('#2398CE'); 81 | // circle moves with the message: 82 | circle(xPos, yPos, 30); 83 | } 84 | 85 | function mousePressed() { 86 | sendMqttMessage(mouseX + ',' + mouseY); 87 | } 88 | 89 | // called when the client connects 90 | function onConnect() { 91 | localDiv.html('client is connected'); 92 | client.subscribe(topic); 93 | } 94 | // handler for mqtt disconnect event: 95 | function onDisconnect() { 96 | // update localDiv text: 97 | localDiv.html('disconnected from broker.'); 98 | } 99 | 100 | // handler for mqtt error event: 101 | function onError(error) { 102 | // update localDiv text: 103 | localDiv.html(error); 104 | } 105 | 106 | // handler for mqtt subscribe event: 107 | function onSubscribe(response, error) { 108 | if (!error) { 109 | // update localDiv text: 110 | localDiv.html('Subscribed to broker.'); 111 | } else { 112 | // update localDiv text with the error: 113 | localDiv.html(error); 114 | } 115 | } 116 | 117 | // called when a message arrives 118 | function onMessage(topic, payload, packet) { 119 | let message = payload.toString(); 120 | remoteDiv.html('I got a message:' + message); 121 | // assume the message is two numbers, mouseX and mouseY. 122 | // Split it into an array: 123 | let values = message.split(','); 124 | // convert the array values into numbers: 125 | xPos = Number(values[0]); 126 | yPos = Number(values[1]); 127 | } 128 | 129 | // called when you want to send a message: 130 | function sendMqttMessage(msg) { 131 | // if the client is connected to the MQTT broker: 132 | if (client.connected) { 133 | client.publish(topic, msg); 134 | // update localDiv text 135 | localDiv.html('I sent: ' + msg); 136 | } 137 | } -------------------------------------------------------------------------------- /browser-clients/eclipse-pahojs/EclipsePahoSensorReceiverJSON/script.js: -------------------------------------------------------------------------------- 1 | /* 2 | MQTT Client example with JSON parsing 3 | This example uses p5.js: https://p5js.org/ 4 | and the Eclipse Paho MQTT client library: https://www.eclipse.org/paho/clients/js/ 5 | to create an MQTT client that receives MQTT messages. 6 | The client is set up for use on the shiftr.io test MQTT broker, 7 | but other options listed will work. 8 | 9 | There's no loop here: all the functions are event-driven. 10 | 11 | created 12 June 2020 12 | modified 31 Dec 2022 13 | by Tom Igoe 14 | */ 15 | 16 | // All these brokers work with this code. 17 | // Uncomment the one you want to use. 18 | 19 | ////// emqx. Works in both basic WS and SSL WS: 20 | // const broker = 'broker.emqx.io' 21 | // const port = 8083; // no SSL 22 | // const broker = 'broker.emqx.io' 23 | // const port = 8084; // SSL 24 | 25 | //////// shiftr.io desktop client. 26 | // Fill in your desktop URL for localhost: 27 | // const broker = 'localhost'; 28 | // const port = 1884; // no SSL 29 | 30 | //////// shiftr.io, requires username and password 31 | // (see options variable below): 32 | const broker = 'public.cloud.shiftr.io'; 33 | const port = 443; 34 | 35 | //////// test.mosquitto.org, uses no username and password: 36 | // const broker = 'test.mosquitto.org'; 37 | // const port = 8081; 38 | 39 | // MQTT client: 40 | let client; 41 | // client credentials: 42 | let clientID = 'EclipsePahoClient'; 43 | 44 | let options = { 45 | // Clean session 46 | cleanSession: true, 47 | // connect timeout in seconds: 48 | timeout: 10, 49 | // callback function for when you connect: 50 | onSuccess: onConnect, 51 | // username & password: 52 | userName: 'public', 53 | password: 'public', 54 | // use SSL 55 | useSSL: true 56 | }; 57 | 58 | // topic to subscribe to when you connect: 59 | let topic = 'AQISensor'; 60 | // divs to show messages: 61 | let localDiv, remoteDiv; 62 | 63 | // incoming data: 64 | let data; 65 | 66 | function setup() { 67 | // put the divs in variables for ease of use: 68 | localDiv = document.getElementById('local'); 69 | remoteDiv = document.getElementById('remote'); 70 | 71 | // set text of localDiv: 72 | localDiv.innerHTML = 'trying to connect'; 73 | // Create an MQTT client: 74 | client = new Paho.MQTT.Client(broker, port, clientID); 75 | // set callback handlers for the client: 76 | client.onConnectionLost = onDisconnect; 77 | client.onMessageArrived = onMessage; 78 | // connect to the MQTT broker: 79 | client.connect(options); 80 | } 81 | 82 | // handler for mqtt connect event: 83 | function onConnect() { 84 | // update localDiv text: 85 | localDiv.innerHTML = 'connected to broker.' 86 | // subscribe to the topic: 87 | client.subscribe(topic, {onSuccess:onSubscribe}); 88 | } 89 | 90 | // handler for mqtt disconnect event: 91 | function onDisconnect(response) { 92 | // update localDiv text: 93 | if (response.errorCode !== 0) { 94 | localDiv.innerHTML = 'disconnected from broker: ' + response.errorMessage; 95 | } 96 | } 97 | 98 | // handler for mqtt error event: 99 | function onError(error) { 100 | // update localDiv text: 101 | localDiv.innerHTML = error; 102 | } 103 | 104 | // handler for mqtt subscribe event: 105 | function onSubscribe(response) { 106 | // update localDiv text: 107 | localDiv.innerHTML = JSON.stringify(response) 108 | +'
Subscribed to ' + topic; 109 | } 110 | 111 | function subscribeToTopic(target) { 112 | client.unsubscribe(topic); 113 | localDiv.innerHTML = "unsubscribed from " + topic; 114 | topic = target.value; 115 | if (client.isConnected()) { 116 | client.subscribe(topic, {onSuccess:onSubscribe}); 117 | } 118 | } 119 | 120 | // handler for mqtt message received event: 121 | function onMessage(message) { 122 | // variable to hold the incoming result: 123 | let result; 124 | // get the JSON string from the incoming message and parse it: 125 | try { 126 | data = JSON.parse(message.payloadString); 127 | } catch (error) { 128 | // if it's not JSON, report that 129 | result = "message is not JSON: " + message.payloadString; 130 | remoteDiv.innerHTML = result; 131 | return; 132 | } 133 | // assuming you got good JSON: 134 | result = "Incoming data:
\n