Skip to content

Commit

Permalink
paho-mqtt websocket nodejs example
Browse files Browse the repository at this point in the history
  • Loading branch information
dexif committed Jan 23, 2024
1 parent 9971b74 commit 65d6f5e
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 1 deletion.
2 changes: 1 addition & 1 deletion mqtt-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ That may be a **Standard** token, a **Master** token (although using it in the e

## nodejs

Example source code is located at [./nodejs/](./nodejs/)
Example source code is located at [./nodejs/](./nodejs/) and [./nodejs-paho/](./nodejs-paho/)

To run the example you need to install the dependencies ([mqtt](https://github.com/mqttjs/MQTT.js) package):

Expand Down
2 changes: 2 additions & 0 deletions mqtt-client/nodejs-paho-ws/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
package-lock.json
3 changes: 3 additions & 0 deletions mqtt-client/nodejs-paho-ws/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# nodejs Paho MQTT Client example

Please [refer here](../#nodejs) for complete README
31 changes: 31 additions & 0 deletions mqtt-client/nodejs-paho-ws/example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Paho from "paho-mqtt";

// for nodejs
import WebSocket from 'ws';
global.WebSocket = WebSocket

const uri = "mqtt.flespi.io";
const username = `FlespiToken ${process.env.FlespiToken}`;
const clientId = `mqtt-async-test-${parseInt(Math.random() * 100)}`;
const client = new Paho.Client(uri, 443, clientId);
function onConnect() {
console.log("Success");
client.subscribe("test/test");
}

function onFailure(error) {
console.log("Failed", error);
}

function onMessageArrived(message) {
console.log("Message: " + message.payloadString);
}

client.onMessageArrived = onMessageArrived;

client.connect({
userName: username,
useSSL: true,
onSuccess: onConnect,
onFailure: onFailure,
});
27 changes: 27 additions & 0 deletions mqtt-client/nodejs-paho-ws/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "mqtt-client-example-nodejs-paho-ws",
"version": "1.0.0",
"description": "",
"scripts": {
"example": "node ./example.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/flespi-software/examples.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/flespi-software/examples/issues"
},
"homepage": "https://github.com/flespi-software/examples#readme",
"dependencies": {
"paho-mqtt": "^1.1.0",
"ws": "^8.16.0"
}
}





0 comments on commit 65d6f5e

Please sign in to comment.