-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoja_mqtt2020.js
56 lines (38 loc) · 1.21 KB
/
moja_mqtt2020.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// SETUP MQTT ------------------------------------------
const broker = "test.mosquitto.org";
const port = 8081 ;
const secured = false;
const topic="mojaitu";
const myID = "id" + parseInt(Math.random() * 100000, 10);
// CONNECT ----------------------------------------------
let mqttClient = new Paho.MQTT.Client( broker, port, myID);
mqttClient.connect({onSuccess: onConnect, useSSL:secured});
mqttClient.onConnectionLost = conLost;
mqttClient.onMessageArrived = receiveMessage;
// MQTT Handler functions--------------------------------
function onConnect()
{
console.log("Connected");
mqttClient.subscribe(topic);
};
function sendMQTT(message)
{
console.log("sending");
let mOBJ = {deviceID:myID, content:message};
let mSend = new Paho.MQTT.Message(JSON.stringify(mOBJ));
mSend.destinationName = topic;
mqttClient.send(mSend);
};
function receiveMessage(message)
{
console.log("message received");
let mUnpack = JSON.parse(message.payloadString);
let senderID = mUnpack.deviceID;
let receivedMessage = mUnpack.content;
//do stuff with the message
console.log(receivedMessage);
}
function conLost()
{
console.log("Lost connection");
}