Đọc dữ liệu từ MQTT bằng JavaScript

Step 1:

Download file JS từ CDN sau:
mqttws31.js

Step 2: demo.js để test thử như sau:

var websocket=”m15.cloudmqtt.com”;
var port=36113;
var user=”hlexxxxx”;
var pass=”wOWkJOtyyyy”;

clientID = “clientID-” + parseInt(Math.random() * 100);

// Create a client instance
client = new Paho.MQTT.Client(websocket, port,clientID);

// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;

var options = {
useSSL: true,
userName: user,
password: pass,
onSuccess:onConnect,
onFailure:doFail
}

// connect the client
client.connect(options);

// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log(“onConnect”);
client.subscribe(“light”);
message = new Paho.MQTT.Message(“Hello CloudMQTT”);
message.destinationName = “light”;
client.send(message);
}

function doFail(e){
console.log(e);
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log(“onConnectionLost:”+responseObject.errorMessage);
}
}

// called when a message arrives
function onMessageArrived(message) {
console.log(“onMessageArrived:”+message.payloadString);
}

Step 3: chèn js vào phần head của trang html

<head>

http://mqttws31.js
http://demo.js
</head>

Step 4: chạy trang html và mở Console ra để test

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s