-
Notifications
You must be signed in to change notification settings - Fork 0
/
particle-calls.js
363 lines (327 loc) · 10.9 KB
/
particle-calls.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
var accessToken = "";
var functionName = "command";
var storage = require("./storage.js");
var base64js = require("./b64.js");
var http = require("http");
var utils = require("./utils.js");
var coap = require("coap");
coap.parameters.maxRetransmit = 0;
var URL = require("url");
// Local IP, get from OS
var os = require('os');
var location;
var ifaces = os.networkInterfaces();
// local IP address
var mcastServer;
var COAP_PORT = 5683;
Object.keys(ifaces).forEach(function (ifname) {
var alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
// 00:50:56 and 0a:00:27 are virtual mac addresses assigned by VMWare and VirtualBox respectively
if (iface.mac != null && iface.mac.indexOf("00:50:56") == -1 && iface.mac.indexOf("0a:00:27") == -1) {
if (mcastServer != null) {
throw "CONFLICTING LOCAL IP ADDRESSES!";
} else {
// create the server now that we know the interface it should be created on
// we will still run this loop to make sure there is no conflict, throw exception if that occurs
createMcastServer(iface.address);
}
}
});
});
function createMcastServer(IP) {
// build CoAP mcast server
mcastServer = coap.createServer({ multicastAddress: "234.234.234.234", multicastInterface: IP });
mcastServer.on('request', function(req, res) {
/* cannot respond to mcast */
console.log("LOCAL AREA COMMS - " + req.url);
var urlParts = req.url.split("/");
handleRequest({data:req.payload.toString('utf-8'), coreid: urlParts[1], name:urlParts[2]}, true);
res.end();
});
mcastServer.listen(COAP_PORT, function() {
console.log("MCAST SERVER LISTENING");
});
}
/*******************
* RUN QUEUE *
*******************/
// commands to be sent more slowly
var queue = [];
// whole commands that could not be sent
var notConnectedQueue = [];
setTimeout(queueOnInterval, 500);
function queueOnInterval() {
if (queue.length != 0) {
var object = queue[0];
queue.splice(0, 1);
module.exports.particlePost(object.id, object.cmd, object.data);
}
var deviceArray = module.exports.deviceArray;
if (deviceArray != null && deviceArray != undefined) {
for (var i = 0; i < deviceArray.length; i++) {
var device = deviceArray[i];
if (module.exports.isRobotIDAvailable(device.id) && notConnectedQueue[device.id] != null) {
for (var j = 0; j < notConnectedQueue[device.id].length; j++) {
var object = notConnectedQueue[device.id][j];
module.exports.loadToQueue(device.id, object);
}
// empty the queue for the device
notConnectedQueue[device.id] = [];
}
}
}
setTimeout(queueOnInterval, 500);
}
/*******************
* INIT PARTICLE *
*******************/
var Particle = require("particle-api-js");
var particle = new Particle();
updateDevices();
openEventStream();
/********************
* PARTICLE EVENTS *
********************/
function openEventStream() {
particle.getEventStream({deviceId: "mine", auth: accessToken}).then(function(stream) {
stream.on("event", function(data) {
console.log("EVENT - " + data.name + " - " + data.published_at);
handleRequest(data, false);
});
stream.on("end", function() {
console.log("ended! re-opening in 3 seconds...");
setTimeout(openEventStream, 3 * 1000);
});
});
}
function handleRequest(data, isLocal) {
var name = module.exports.getDeviceNameFromID(data.coreid);
// if this came over the local then we only handle certain events
if (isLocal) {
if (data.name == storage.EventEnum.MOVE_STATUS) {
var move = base64js.toByteArray(data.data);
location.moveStatus(name, move);
}
return;
}
switch (data.name) {
case storage.EventEnum.COMPLETE:
storage.storeEvent(name, storage.EventEnum.COMPLETE);
break;
case storage.EventEnum.STOPPED:
storage.storeEvent(name, storage.EventEnum.STOPPED);
location.robotShouldBeStopped(name);
break;
case storage.EventEnum.CALIBRATION_VALUES:
var temp = base64js.toByteArray(data.data);
storage.storeCalibration(name, temp);
break;
case storage.EventEnum.ULTRASONIC_VALUES:
var temp = base64js.toByteArray(data.data);
storage.storeDistances(name, temp);
break;
case storage.EventEnum.GYRO_READING_VALUES:
var temp = base64js.toByteArray(data.data);
storage.storeGyroReadings(name, temp);
break;
case storage.EventEnum.STATUS:
updateDevices();
break;
case storage.EventEnum.FAILED:
storage.storeEvent(name, storage.EventEnum.FAILED);
storage.setRobotAsDead(name);
location.robotShouldBeStopped(name);
break;
case storage.EventEnum.HAS_FAILED:
storage.storeEvent(name, storage.EventEnum.HAS_FAILED);
storage.setRobotAsDead(name);
location.robotShouldBeStopped(name);
break;
case storage.EventEnum.LOCAL_IP:
var temp = base64js.toByteArray(data.data);
storage.storeLocalIP(name, temp);
break;
default:
console.log("EVENT UNHANDLED! : " + data.name);
}
}
function updateDevices() {
var deviceList = particle.listDevices({auth: accessToken});
deviceList.then(doneDeviceList, errorDeviceList);
}
function doneDeviceList (devices) {
module.exports.deviceArray = devices.body;
console.log("GOT DEVICES");
module.exports.updateCalibrationValues("all");
if (location == null) location = require("./location.js");
location.devicesReady(devices.body);
}
function errorDeviceList (err) {
console.log("FAILED TO GET DEVICES - " + err.description);
process.exit();
}
function getDeviceByID(ID) {
var deviceArray = module.exports.deviceArray;
for (var i = 0; i < deviceArray.length; i++) {
if (deviceArray[i].id == ID) {
return deviceArray[i];
}
}
return null;
}
function postData(ID, string) {
if (!module.exports.isRobotIDAvailable(ID)) {
if (notConnectedQueue[ID] == null || notConnectedQueue[ID] == undefined) {
notConnectedQueue[ID] = [];
}
notConnectedQueue[ID][notConnectedQueue[ID].length] = string;
} else {
var postCall = particle.callFunction({
deviceId: ID, name: functionName,
argument: string, auth: accessToken
});
postCall.then(function (data) {
console.log("COMPLETED POST - " + data.statusCode);
res.setEncoding("utf8");
res.on("data", function (chunk) {
console.log("Response: " + chunk);
});
}, function (err) {
console.log("FAILED TO POST - " + string + " - " + err.errorDescription + " - " + err.info);
});
}
}
function localPostData(deviceName, data) {
var localIP = storage.getLocalIP(deviceName);
var ID = module.exports.getDeviceIDFromName(deviceName);
if (localIP == null || localIP == undefined || !module.exports.isRobotAvailable(deviceName)) {
if (notConnectedQueue[ID] == null || notConnectedQueue[ID] == undefined) {
notConnectedQueue[ID] = [];
}
notConnectedQueue[ID][notConnectedQueue[ID].length] = data;
} else {
var url = URL.parse("coap://" + localIP + "/" + functionName);
url.port = COAP_PORT;
url.confirmable = true;
url.observable = false;
url.method = "POST";
var request = coap.request(url);
request.on("error", function(err) {
// No error as we cannot handle retransmission with IoT
});
request.write(data);
request.end();
}
}
module.exports = {
storage: storage,
isRobotAvailable: function(deviceName) {
return getDeviceByID(this.getDeviceIDFromName(deviceName)).connected;
},
isRobotIDAvailable: function(deviceID) {
return getDeviceByID(deviceID).connected;
},
loadToQueue: function(deviceID, cmd) {
/* don't repeat some specific commands */
for (var i = 0; i < queue.length; i++) {
if (utils.isNoRepeatEndpoint(queue[i].cmd)) {
return;
}
}
var object = {};
object.id = deviceID;
object.cmd = cmd;
object.data = [];
if (arguments.length > 2 && cmd != null) {
var dataCount = 0;
for (var arg = 2; arg < arguments.length; arg++) {
if (arguments[arg] == null) continue;
object.data[dataCount++] = arguments[arg];
}
}
queue[queue.length] = object;
},
particlePost: function particlePost(deviceID, cmd) {
var dataString = cmd;
var isUsingLocal = storage.isDeviceUsingLocal(module.exports.getDeviceNameFromID(deviceID));
var isLocal = utils.isLocalCommunication(cmd) && isUsingLocal;
if (arguments.length > 2 && cmd != null) {
for (var arg = 2; arg < arguments.length; arg++) {
if (arguments[arg] == null || arguments[arg].length == 0) continue;
dataString += "," + arguments[arg];
}
}
if (deviceID != "all") {
if (isLocal) {
localPostData(module.exports.getDeviceNameFromID(deviceID), dataString);
} else {
postData(deviceID, dataString);
}
} else {
var deviceArray = module.exports.deviceArray;
for (var i = 0; i < deviceArray.length; i++) {
if (isLocal) {
localPostData(module.exports.getDeviceNameFromID(deviceArray[i].id), dataString);
} else {
postData(deviceArray[i].id, dataString);
}
}
}
},
getDeviceIDFromName: function getDeviceIDFromName(name) {
var deviceArray = module.exports.deviceArray;
if (deviceArray == null) {
return "";
}
for (var i = 0; i < deviceArray.length; i++) {
if (deviceArray[i].name == name) {
return deviceArray[i].id;
}
}
return "";
},
getDeviceNameFromID: function getDeviceNameFromID(ID) {
var deviceArray = module.exports.deviceArray;
if (deviceArray == null) {
return "";
}
for (var i = 0; i < deviceArray.length; i++) {
if (deviceArray[i].id == ID) {
return deviceArray[i].name;
}
}
return "";
},
getAllDeviceData: function getAllDeviceNames() {
var array = [];
var deviceArray = module.exports.deviceArray;
if (deviceArray == null) return;
for (var i = 0; i < deviceArray.length; i++) {
var online = this.isRobotAvailable(deviceArray[i].name);
var obj = {attributes: {deviceName: deviceArray[i].name, id: deviceArray[i].id, online: online}};
array.push(obj);
}
return array;
},
updateCalibrationValues: function updateCalibrationValues(ID) {
if (ID == "all") {
var deviceArray = module.exports.deviceArray;
for (var i = 0; i < deviceArray.length; i++) {
var device = deviceArray[i];
this.particlePost(device.id, utils.OtherEndpointsEnum.GET_CALIBRATION);
}
} else {
this.particlePost(ID, utils.OtherEndpointsEnum.GET_CALIBRATION);
}
},
changeLedState: function(deviceName, state) {
var trueState = state ? 1 : 0;
var ID = this.getDeviceIDFromName(deviceName);
this.particlePost(ID, utils.OtherEndpointsEnum.LED_OFF, trueState);
}
};