-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (69 loc) · 1.93 KB
/
index.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
var AIRTRIK_KEY = ""
var AIRTRIK_apiEndPoint = "https://airtrik.com/iot/";
var AIRTRIK_lastMsgEndPoint = "https://airtrik.com/api/lastmsg/";
var AIRTRIK_mqttEndPoint = "airtrik.com";
var AIRTRIK_clientId = Math.random().toString(36).substring(2);
var AIRTRIK_portNumber = 8083
var AIRTRIK_client = new Paho.MQTT.Client(AIRTRIK_mqttEndPoint, AIRTRIK_portNumber, AIRTRIK_clientId)
function onReceive(msg, deviceId){
console.log("Data : "+ msg)
console.log("deviceId : "+ deviceId)
}
function onConnectionLost(responseObject){
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
function onMessageArrived(message){
let msg = message.payloadString
let deviceId = message.destinationName.split("/")[1]
onReceive(msg, deviceId)
}
function subscribe(deviceId){
AIRTRIK_client.subscribe(AIRTRIK_KEY+"/"+deviceId)
}
function onConnect(){
console.log("Connected")
}
function AIRTRIK_connect(key){
AIRTRIK_KEY = key
var username = ""
var password = ""
let tosend = new FormData();
tosend.append('key', key)
fetch(AIRTRIK_apiEndPoint, {
method: 'POST',
body: tosend
})
.then(res => res.json())
.then((data)=>{
username = data.username
password = data.password
AIRTRIK_client.connect({onSuccess:onConnect, userName: username, password: password, useSSL: true});
AIRTRIK_client.onConnectionLost = onConnectionLost;
AIRTRIK_client.onMessageArrived = onMessageArrived;
})
}
function lastmsg(key=0){
if(key == 0){
key = AIRTRIK_KEY
}
let myPromise = new Promise((resolve, reject)=>{
let tosend = new FormData();
tosend.append('key', key)
fetch(AIRTRIK_lastMsgEndPoint, {
method: 'POST',
body: tosend
})
.then(res => res.json())
.then((data)=>{
resolve(data)
});
})
return myPromise;
}
function send(deviceId, msg){
message = new Paho.MQTT.Message(msg);
message.destinationName = AIRTRIK_KEY+"/"+deviceId;
AIRTRIK_client.send(message);
}