forked from openhybrid/object
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1595 lines (1286 loc) · 67.1 KB
/
server.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @preserve
*
* .,,,;;,'''..
* .'','... ..',,,.
* .,,,,,,',,',;;:;,. .,l,
* .,',. ... ,;, :l.
* ':;. .'.:do;;. .c ol;'.
* ';;' ;.; ', .dkl';, .c :; .'.',::,,'''.
* ',,;;;,. ; .,' .'''. .'. .d;''.''''.
* .oxddl;::,,. ', .'''. .... .'. ,:;..
* .'cOX0OOkdoc. .,'. .. ..... 'lc.
* .:;,,::co0XOko' ....''..'.'''''''.
* .dxk0KKdc:cdOXKl............. .. ..,c....
* .',lxOOxl:'':xkl,',......'.... ,'.
* .';:oo:... .
* .cd, ╔═╗┌─┐┬─┐┬ ┬┌─┐┬─┐ .
* .l; ╚═╗├┤ ├┬┘└┐┌┘├┤ ├┬┘ '
* 'l. ╚═╝└─┘┴└─ └┘ └─┘┴└─ '.
* .o. ...
* .''''','.;:''.........
* .' .l
* .:. l'
* .:. .l.
* .x: :k;,.
* cxlc; cdc,,;;.
* 'l :.. .c ,
* o.
* .,
*
* ╦ ╦┬ ┬┌┐ ┬─┐┬┌┬┐ ╔═╗┌┐ ┬┌─┐┌─┐┌┬┐┌─┐
* ╠═╣└┬┘├┴┐├┬┘│ ││ ║ ║├┴┐ │├┤ │ │ └─┐
* ╩ ╩ ┴ └─┘┴└─┴─┴┘ ╚═╝└─┘└┘└─┘└─┘ ┴ └─┘
*
* Created by Valentin on 10/22/14.
*
* Copyright (c) 2015 Valentin Heun
*
* All ascii characters above must be included in any redistribution.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*********************************************************************************************************************
******************************************** TODOS *******************************************************************
**********************************************************************************************************************
**
* TODO - Only allow upload backups and not any other data....
*
* something to remember: hexString = yourNumber.toString(16); and reverse the process with: yourNumber = parseInt(hexString, 16);
*
* TODO - check any collision with knownObjects -> Show collision with other object....
* TODO - Check if Targets are double somehwere. And iff Target has more than one target in the file...
*
* TODO - Check the socket connections
* TODO - stream of values for the user device
* TODO - Plugin Structure - check how good it works
* TODO - check if objectlinks are pointing to values that actually exist. - (happens in browser at the moment)
* TODO - Test self linking from internal to internal value (endless loop) - (happens in browser at the moment)
*
*
* TODO - mark object functional only if: if(thisId in objectExp && thisId.length>12)
**
**********************************************************************************************************************
******************************************** constant settings *******************************************************
**********************************************************************************************************************/
var globalVariables = {
clear: false, // stops or starts the system
developer: true, // show developer UI
debug: true // debug messages to console
};
// ports used to define the server behaviour
const serverPort = 8080;
const socketPort = serverPort; // server and socket port are always identical
const beatPort = 52316; // this is the port for UDP broadcasting so that the objects find each other.
const beatInterval = 3000; // how often is the heartbeat sent
const socketUpdateInterval = 2000; // how often the system checks if the socket connections are still up and running.
//origins
const objectPath = __dirname + "/objects"; // where all the objects are stored.
const modulePath = __dirname + "/dataPointInterfaces"; // all the visual UI interfaces are stored here.
const internalPath = __dirname + "/hardwareInterfaces"; // all the visual UI interfaces are stored here.
const objectInterfaceFolder = "/"; // the level on which the webservice is accessible
/**********************************************************************************************************************
******************************************** Requirements ************************************************************
**********************************************************************************************************************/
var _ = require('lodash');
var fs = require('fs'); // Filesystem library
var dgram = require('dgram'); // UDP Broadcasting library
var ip = require("ip"); // get the device IP address library
var bodyParser = require('body-parser');
var express = require('express');
var webServer = express();
var http = require('http').createServer(webServer).listen(serverPort, function () {
if (globalVariables.debug) console.log('webserver + socket.io is listening on port: ' + serverPort);
});
var io = require('socket.io')(http);
var socket = require('socket.io-client');
var cors = require('cors'); // Library for HTTP Cross-Origin-Resource-Sharing
var formidable = require('formidable'); // Multiple file upload library
//var xml2js = require('xml2js');
// additional required code
var HybridObjectsUtilities = require(__dirname + '/libraries/HybridObjectsUtilities');
var HybridObjectsWebFrontend = require(__dirname + '/libraries/HybridObjectsWebFrontend');
var templateModule = require(__dirname + '/libraries/templateModule');
// Set web frontend debug to inherit from global debug
HybridObjectsWebFrontend.debug = globalVariables.debug;
/**********************************************************************************************************************
******************************************** Constructors ************************************************************
**********************************************************************************************************************/
/**
* @desc Constructor for the the object
**/
function ObjectExp() {
this.objectId = null;
this.ip = ip.address();
this.version = "0.3.2";
this.rotation = 0;
this.x = 0;
this.y = 0;
this.scale = 1;
this.visible = false;
this.visibleText = false;
this.visibleEditing = false;
this.developer = false;
this.matrix3dMemory = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // TODO use this to store UI interface for image later.
this.objectLinks = {}; // Array of ObjectLink()
this.objectValues = {}; // Array of ObjectValue()
}
/**
* @desc Constructor for each link
**/
function ObjectLink() {
this.ObjectA = null;
this.locationInA = 0;
this.typeA = "";
this.ObjectB = null;
this.locationInB = 0;
this.typeB = "";
this.countLinkExistance = 0; // todo use this to test if link is still valid. If not able to send for some while, kill link.
}
/**
* @desc Constructor for each object value
**/
function ObjectValue() {
this.name = "";
this.value = null;
this.mode = "f"; // this is for (f) floating point, (d) digital or (s) step and finally (m) media
this.rotation = 0;
this.x = 0;
this.y = 0;
this.scale = 1;
this.plugin = "default";
this.pluginParameter = null;
this.index = null;
this.type = "arduinoYun"; // todo "arduinoYun", "virtual", "edison", ... make sure to define yours in your internal_module file
}
/**
* @desc Constructor for the socket.io web sockets
**/
function ObjectSockets(socketPort, ip) {
this.ip = ip;
this.io = socket.connect('http://' + ip + ':' + socketPort, {
'connect timeout': 5000,
'reconnect': true,
'reconnection delay': 500,
'max reconnection attempts': 20,
'auto connect': true,
'transports': [
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-multipart'
, 'xhr-polling'
, 'jsonp-polling']
});
}
/**********************************************************************************************************************
******************************************** Initialisations *********************************************************
**********************************************************************************************************************/
// Initializing the object tree
var objectExp = {};
var pluginModules = {}; // the pluginModule, that will hold all available plugins
var internalModules = {}; // the modules that will hold all internal connectors
var knownObjects = {}; // list of ids linked with ips of all objects found via udp heartbeats
var objectLookup = {}; // objectID lookup table
var socketArray = {}; // all socket connections that are kept alive
// counter for the socket connections
var sockets = {
sockets: 0,
connected: 0,
notConnected: 0,
socketsOld: 0,
connectedOld: 0,
notConnectedOld: 0
};
if (globalVariables.debug) console.log("got it started");
// get the directory names of all available plugins for the 3D-UI
var tempFiles = fs.readdirSync(modulePath).filter(function (file) {
return fs.statSync(modulePath + '/' + file).isDirectory();
});
// remove hidden directories
while (tempFiles[0][0] === ".") {
tempFiles.splice(0, 1);
}
// add all plugins to the pluginModules object.
for (var i = 0; i < tempFiles.length; i++) {
pluginModules[tempFiles[i]] = require(__dirname + "/dataPointInterfaces/" + tempFiles[i] + "/index.js").render;
}
var modulesList = ['base',
'documentation',
'header',
'home-object',
'home-object-add',
'interface',
'interface-rowitem',
'monitor',
'sidebar',
'target'];
templateModule.loadAllModules(modulesList, function () {
// start system
});
loadHybridObjects();
startSystem();
// add all modules for internal communication
// get the directory names of all available plugins for the 3D-UI
var tempFilesInternal = fs.readdirSync(internalPath).filter(function (file) {
return fs.statSync(internalPath + '/' + file).isDirectory();
});
// remove hidden directories
while (tempFilesInternal[0][0] === ".") {
tempFilesInternal.splice(0, 1);
}
// add all plugins to the pluginModules object.
for (var i = 0; i < tempFilesInternal.length; i++) {
internalModules[tempFilesInternal[i]] = require(internalPath + "/" + tempFilesInternal[i] + "/index.js");
}
/*
for (var i = 0; i < tempFilesInternal.length; i++) {
internalModules[tempFilesInternal[i]].debug(globalVariables.debug);
}*/
// starting the internal servers (receive)
for (var i = 0; i < tempFilesInternal.length; i++) {
internalModules[tempFilesInternal[i]].receive(objectExp, objectLookup, globalVariables, __dirname, pluginModules, function (objKey2, valueKey, objectExp, pluginModules) {
objectEngine(objKey2, valueKey, objectExp, pluginModules);
});
}
if (globalVariables.debug) console.log("found " + tempFilesInternal.length + " internal server");
if (globalVariables.debug) console.log("starting internal Server.");
/**
* Returns the file extension (portion after the last dot) of the given filename.
* If a file name starts with a dot, returns an empty string.
*
* @author VisioN @ StackOverflow
* @param {string} fileName - The name of the file, such as foo.zip
* @return {string} The lowercase extension of the file, such has "zip"
*/
function getFileExtension(fileName) {
return fileName.substr((~-fileName.lastIndexOf(".") >>> 0) + 2).toLowerCase();
}
/**
* @desc Add objects from the objects folder to the system
**/
function loadHybridObjects() {
// check for objects in the objects folder by reading the objects directory content.
// get all directory names within the objects directory
var tempFiles = fs.readdirSync(objectPath).filter(function (file) {
return fs.statSync(objectPath + '/' + file).isDirectory();
});
// remove hidden directories
try {
while (tempFiles[0][0] === ".") {
tempFiles.splice(0, 1);
}
} catch (e) {
if (globalVariables.debug) console.log("no hidden files");
}
for (var i = 0; i < tempFiles.length; i++) {
var tempFolderName = HybridObjectsUtilities.getObjectIdFromTarget(tempFiles[i], __dirname);
if (tempFolderName !== null) {
// fill objectExp with objects named by the folders in objects
objectExp[tempFolderName] = new ObjectExp();
objectExp[tempFolderName].folder = tempFiles[i];
// add object to object lookup table
HybridObjectsUtilities.writeObject(objectLookup, tempFiles[i], tempFolderName);
// try to read a saved previous state of the object
try {
objectExp[tempFolderName] = JSON.parse(fs.readFileSync(__dirname + "/objects/" + tempFiles[i] + "/object.json", "utf8"));
objectExp[tempFolderName].ip = ip.address();
// adding the values to the arduino lookup table so that the serial connection can take place.
// todo this is maybe obsolete.
for (var tempkey in objectExp[tempFolderName].objectValues) {
ArduinoLookupTable.push({obj: tempFiles[i], pos: tempkey});
}
// todo the sizes do not really save...
// todo new Data points are never writen in to the file. So this full code produces no value
// todo Instead keep the board clear=false forces to read the data points from the arduino every time.
// todo this is not true the datapoints are writen in to the object. the sizes are wrong
// if not uncommented the code does not connect to the arduino side.
// data comes always from the arduino....
// clear = true;
if (globalVariables.debug) {
console.log("I found objects that I want to add");
console.log("---");
console.log(ArduinoLookupTable);
console.log("---");
}
} catch (e) {
objectExp[tempFolderName].ip = ip.address();
objectExp[tempFolderName].objectId = tempFolderName;
if (globalVariables.debug) console.log("No saved data for: " + tempFolderName);
}
} else {
if (globalVariables.debug) console.log(" object " + tempFolderName + " has no marker yet");
}
}
for (var keyint in internalModules) {
internalModules[keyint].init();
}
}
/**********************************************************************************************************************
******************************************** Starting the System ******************************************************
**********************************************************************************************************************/
/**
* @desc starting the system
**/
function startSystem() {
// generating a udp heartbeat signal for every object that is hosted in this device
for (var key in objectExp) {
objectBeatSender(beatPort, key, objectExp[key].ip);
}
// receiving heartbeat messages and adding new objects to the knownObjects Array
objectBeatServer();
// serving the visual frontend with web content as well serving the REST API for add/remove links and changing
// object sizes and positions
objectWebServer();
// receives all socket connections and processes the data
socketServer();
// receives all serial calls and processes the data
// initializes the first sockets to be opened to other objects
socketUpdater();
// keeps sockets to other objects alive based on the links found in the local objects
// removes socket connections to objects that are no longer linked.
socketUpdaterInterval();
// blink the LED at the arduino board
}
/**********************************************************************************************************************
******************************************** Emitter/Client/Sender Objects *******************************************
**********************************************************************************************************************/
/**
* @desc Sends out a Heartbeat broadcast via UDP in the local network.
* @param {Number} PORT The port where to start the Beat
* @param {string} thisId The name of the Object
* @param {string} thisIp The IP of the Object
* @param {boolean} oneTimeOnly if true the beat will only be sent once.
**/
function objectBeatSender(PORT, thisId, thisIp, oneTimeOnly) {
if (_.isUndefined(oneTimeOnly)) {
oneTimeOnly = false;
}
var HOST = '255.255.255.255';
// json string to be send
var message = new Buffer(JSON.stringify({id: thisId, ip: thisIp}));
if (globalVariables.debug) console.log("UDP broadcasting on port: " + PORT);
if (globalVariables.debug) console.log("Sending beats... Content: " + JSON.stringify({id: thisId, ip: thisIp}));
// creating the datagram
var client = dgram.createSocket('udp4');
client.bind(function () {
client.setBroadcast(true);
client.setTTL(2);
client.setMulticastTTL(2);
});
if (!oneTimeOnly) {
setInterval(function () {
// send the beat#
// if(thisId in objectLookup)
//console.log(JSON.stringify(thisId));
// console.log(JSON.stringify( objectExp));
if (thisId in objectExp && thisId.length > 12) {
// if (globalVariables.debug) console.log("Sending beats... Content: " + JSON.stringify({id: thisId, ip: thisIp}));
// this is an ugly hack to sync each object with being a developer object
objectExp[thisId].developer = globalVariables.developer;
client.send(message, 0, message.length, PORT, HOST, function (err) {
if (err) {
console.log("error ");
throw err;
}
// client is not being closed, as the beat is send ongoing
});
}
}, beatInterval + _.random(-250, 250));
}
else {
// Single-shot, one-time heartbeat
// delay the signal with timeout so that not all objects send the beat in the same time.
setTimeout(function () {
// send the beat
if (thisId in objectExp) {
client.send(message, 0, message.length, PORT, HOST, function (err) {
if (err) throw err;
// close the socket as the function is only called once.
client.close();
});
}
}, _.random(1, 250));
}
}
/**
* @desc sends out an action json object via udp. Actions are used to cause actions in all objects and devices within the network.
* @param {Object} action string of the action to be send to the system. this can be a jason object
**/
function actionSender(action) {
var HOST = '255.255.255.255';
var message;
message = new Buffer(JSON.stringify({action: action}));
// creating the datagram
var client = dgram.createSocket('udp4');
client.bind(function () {
client.setBroadcast(true);
client.setTTL(64);
client.setMulticastTTL(64);
});
// send the datagram
client.send(message, 0, message.length, beatPort, HOST, function (err) {
if (err) {
throw err;
}
client.close();
});
}
/**********************************************************************************************************************
******************************************** Server Objects **********************************************************
**********************************************************************************************************************/
/**
* @desc Receives a Heartbeat broadcast via UDP in the local network and updates the knownObjects Array in case of a
* new object
* @note if action "ping" is received, the object calls a heartbeat that is send one time.
**/
function objectBeatServer() {
// creating the udp server
var udpServer = dgram.createSocket("udp4");
udpServer.on("error", function (err) {
console.log("server error:\n" + err);
udpServer.close();
});
udpServer.on("message", function (msg) {
var msgContent;
// check if object ping
// if (globalVariables.debug) console.log("I found new Objects: " + msg);
msgContent = JSON.parse(msg);
if (msgContent.hasOwnProperty("id") && msgContent.hasOwnProperty("ip") && !(msgContent.id in objectExp) && !(msgContent.id in knownObjects)) {
knownObjects[msgContent.id] = msgContent.ip;
if (globalVariables.debug) console.log("I found new Objects: " + JSON.stringify({
id: msgContent.id,
ip: msgContent.ip
}));
if (globalVariables.debug) console.log("knownObjectfound:" + knownObjects + "this message: ");
}
// check if action 'ping'
if (msgContent.action === "ping") {
if (globalVariables.debug) console.log(msgContent.action);
for (var key in objectExp) {
objectBeatSender(beatPort, key, objectExp[key].ip, true);
}
}
});
udpServer.on("listening", function () {
var address = udpServer.address();
if (globalVariables.debug) console.log("UDP listening on port: " + address.port);
});
// bind the udp server to the udp beatPort
udpServer.bind(beatPort);
}
/**
* @desc A static Server that serves the user, handles the links and
* additional provides active modification for objectDefinition.
**/
function objectWebServer() {
// define the body parser
webServer.use(bodyParser.urlencoded({
extended: true
}));
webServer.use(bodyParser.json());
// devine a couple of static directory routs
webServer.use("/obj", express.static(__dirname + '/objects/'));
if (globalVariables.developer === true) {
webServer.use("/public", express.static(__dirname + '/libraries/webInterface/'));
webServer.use(express.static(__dirname + '/libraries/webInterface/'));
}
// use the cors cross origin REST model
webServer.use(cors());
// allow requests from all origins with '*'. TODO make it dependent on the local network. this is important for security
webServer.options('*', cors());
// adding a new link to an object. *1 is the object *2 is the link id
// ****************************************************************************************************************
webServer.post('/object/*/link/*/', function (req, res) {
// if(globalVariables.debug) console.log("post 1");
var updateStatus = "nothing happened";
if (objectExp.hasOwnProperty(req.params[0])) {
objectExp[req.params[0]].objectLinks[req.params[1]] = req.body;
// call an action that asks all devices to reload their links, once the links are changed.
actionSender(JSON.stringify({reloadLink: {id: req.params[0], ip: objectExp[req.params[0]].ip}}));
updateStatus = "added";
// check if there are new connections associated with the new link.
socketUpdater();
// write the object state to the permanent storage.
HybridObjectsUtilities.writeObjectToFile(objectExp, req.params[0], __dirname);
res.send(updateStatus);
}
});
// changing the size and possition of an item. *1 is the object *2 is the datapoint id
// ****************************************************************************************************************
webServer.post('/object/*/size/*/', function (req, res) {
// if(globalVariables.debug) console.log("post 2");
var updateStatus = "nothing happened";
var thisObject = req.params[0];
var thisValue = req.params[1];
// check that the numbers are valid numbers..
if (typeof req.body.x === "number" && typeof req.body.y === "number" && typeof req.body.scale === "number") {
// if the object is equal the datapoint id, the item is actually the object it self.
if (thisObject === thisValue) {
objectExp[thisObject].x = req.body.x;
objectExp[thisObject].y = req.body.y;
objectExp[thisObject].scale = req.body.scale;
}
else {
objectExp[thisObject].objectValues[thisValue].x = req.body.x;
objectExp[thisObject].objectValues[thisValue].y = req.body.y;
objectExp[thisObject].objectValues[thisValue].scale = req.body.scale;
}
// console.log(req.body);
// ask the devices to reload the objects
actionSender(JSON.stringify({reloadObject: {id: thisObject, ip: objectExp[thisObject].ip}}));
updateStatus = "added";
// write the object state to the permanent storage.
HybridObjectsUtilities.writeObjectToFile(objectExp, req.params[0], __dirname);
}
res.send(updateStatus);
});
// delete a link. *1 is the object *2 is the link id
// ****************************************************************************************************************
webServer.delete('/object/*/link/*/', function (req, res) {
if (globalVariables.debug) console.log("delete 1");
if (globalVariables.debug) console.log("i got a delete message");
var thisLinkId = req.params[1];
var fullEntry = objectExp[req.params[0]].objectLinks[thisLinkId];
var destinationIp = knownObjects[fullEntry.ObjectB];
delete objectExp[req.params[0]].objectLinks[thisLinkId];
if (globalVariables.debug) console.log(objectExp[req.params[0]].objectLinks);
actionSender(JSON.stringify({reloadLink: {id: req.params[0], ip: objectExp[req.params[0]].ip}}));
HybridObjectsUtilities.writeObjectToFile(objectExp, req.params[0], __dirname);
res.send("deleted: " + thisLinkId + " in object: " + req.params[0]);
var checkIfIpIsUsed = false;
var checkerKey, subCheckerKey;
for (checkerKey in objectExp) {
for (subCheckerKey in objectExp[checkerKey].objectLinks) {
if (objectExp[checkerKey].objectLinks[subCheckerKey].ObjectB === fullEntry.ObjectB) {
checkIfIpIsUsed = true;
}
}
}
if (fullEntry.ObjectB !== fullEntry.ObjectA && !checkIfIpIsUsed) {
// socketArray.splice(destinationIp, 1);
delete socketArray[destinationIp];
}
});
// request a link. *1 is the object *2 is the link id
// ****************************************************************************************************************
webServer.get('/object/*/link/:id', function (req, res) {
// if(globalVariables.debug) console.log("get 1");
res.send(objectExp[req.params[0]].objectLinks[req.params.id]);
});
// request all link. *1 is the object
// ****************************************************************************************************************
webServer.get('/object/*/link', function (req, res) {
// if(globalVariables.debug) console.log("get 2");
res.send(objectExp[req.params[0]].objectLinks);
});
// request a zip-file with the object stored inside. *1 is the object
// ****************************************************************************************************************
webServer.get('/object/*/zipBackup/', function (req, res) {
// if(globalVariables.debug) console.log("get 3");
res.writeHead(200, {
'Content-Type': 'application/zip',
'Content-disposition': 'attachment; filename=HybridObjectBackup.zip'
});
var Archiver = require('archiver');
var zip = Archiver('zip', false);
zip.pipe(res);
zip.directory(__dirname + "/objects/" + req.params[0], req.params[0] + "/");
zip.finalize();
});
// Send the programming interface static web content
// ****************************************************************************************************************
webServer.get('/obj/dataPointInterfaces/*/*/', function (req, res) { // watch out that you need to make a "/" behind request.
res.sendFile(__dirname + "/dataPointInterfaces/" + req.params[0] + '/www/' + req.params[1]);
});
// general overview of all the hybrid objects - html response
// ****************************************************************************************************************
webServer.get('/object/*/html', function (req, res) {
var msg = [];
var hoVals, hoLinks, subKey;
var objectName = req.params[0];
var hybridObject = objectExp[objectName];
msg.push("<html><head><meta http-equiv='refresh' content='3.3' /><title>", objectName, "</title></head>\n<body>\n");
msg.push("<table border='0' cellpadding='10'>\n<tr>\n<td align='left' valign='top'>\n");
msg.push("Values for ", objectName, ":<br>\n\n<table border='1'>\n<tr><td>ID</td><td>Value</td></tr>\n");
if (!_.isUndefined(hybridObject)) {
hoVals = hybridObject.objectValues;
for (subKey in hoVals) {
msg.push("<tr><td>", subKey, "</td><td>", hoVals[subKey].value, "</td></tr>\n");
}
}
msg.push("</table>\n</td>\n<td align='left' valign='top'>\n\n");
msg.push("Links:<br>\n\n<table border='1'>\n<tr><td>ID</td><td>ObjectA</td><td>locationInA</td><td>ObjectB</td><td>locationInB</td></tr>\n");
if (!_.isUndefined(hybridObject)) {
hoLinks = hybridObject.objectLinks;
for (subKey in hoLinks) {
msg.push(" <tr><td>", subKey, "</td><td>", hoLinks[subKey].ObjectA, "</td><td>", hoLinks[subKey].locationInA, "</td>");
msg.push("<td>", hoLinks[subKey].ObjectB, "</td><td>", hoLinks[subKey].locationInB, "</td></tr>\n");
}
}
msg.push("</table>\n</td></tr>\n</table>\n");
msg.push("<table border='0' cellpadding='10'>\n<tr><td align='left' valign='top'>\n");
msg.push("Interface:<br>\n\n<table border='1'>\n");
for (subKey in hybridObject) {
msg.push(" <tr><td>", subKey, "</td><td>", hybridObject[subKey], "</td></tr>\n");
}
msg.push("</table>\n</td>\n<td align='left' valign='top'>");
msg.push("Known Objects:<br>\n\n<table border='1'>\n");
for (subKey in knownObjects) {
msg.push(" <tr><td>", subKey, "</td><td>", knownObjects[subKey], "</td></tr>\n");
}
msg.push("</table>\n</td><td align='left' valign='top'>");
socketIndicator();
msg.push("Socket Activity:<br>\n<table border='1'>\n");
for (subKey in sockets) {
if (subKey !== "socketsOld" && subKey !== "connectedOld" && subKey !== "notConnectedOld")
msg.push(" <tr><td>", subKey, "</td><td>", sockets[subKey], "</td></tr>\n");
}
msg.push("</table>\n</td></tr>\n</table>\n");
msg.push("</body></html>");
res.send(msg.join(""));
});
// sends json object for a specific hybrid object. * is the object name
// ****************************************************************************************************************
webServer.get('/object/*/', function (req, res) {
// if(globalVariables.debug) console.log("get 7");
res.json(objectExp[req.params[0]]);
});
webServer.get('/object/*/thisObject', function (req, res) {
// if(globalVariables.debug) console.log("get 8");
res.json(objectExp[req.params[0]]);
});
// sends all json object values for a specific hybrid object. * is the object name
// ****************************************************************************************************************
webServer.get('/object/*/value', function (req, res) {
// if(globalVariables.debug) console.log("get 9");
res.json(objectExp[req.params[0]].objectValues);
});
// sends a specific value for a specific hybrid object. * is the object name :id is the value name
// ****************************************************************************************************************
webServer.get('/object/*/value/:id', function (req, res) {
// if(globalVariables.debug) console.log("get 10");
res.send({value: objectExp[req.params[0]].objectValues[req.params.id].value});
});
// sends a specific json object value for a specific hybrid object. * is the object name :id is the value name
// ****************************************************************************************************************
webServer.get('/object/*/value/full/:id', function (req, res) {
// if(globalVariables.debug) console.log("get 11");
res.json(objectExp[req.params[0]].objectValues[req.params.id]);
});
// ****************************************************************************************************************
// frontend interface
// ****************************************************************************************************************
if (globalVariables.developer === true) {
// sends the info page for the object :id
// ****************************************************************************************************************
webServer.get(objectInterfaceFolder + 'info/:id', function (req, res) {
// if(globalVariables.debug) console.log("get 12");
res.send(HybridObjectsWebFrontend.uploadInfoText(req.params.id, objectLookup, objectExp, knownObjects, io, sockets));
});
// sends the content page for the object :id
// ****************************************************************************************************************
webServer.get(objectInterfaceFolder + 'content/:id', function (req, res) {
// if(globalVariables.debug) console.log("get 13");
res.send(HybridObjectsWebFrontend.uploadTargetContent(req.params.id, __dirname, objectInterfaceFolder));
});
// sends the target page for the object :id
// ****************************************************************************************************************
webServer.get(objectInterfaceFolder + 'target/:id', function (req, res) {
// if(globalVariables.debug) console.log("get 14");
res.send(HybridObjectsWebFrontend.uploadTargetText(req.params.id, objectLookup, objectExp, globalVariables.debug));
// res.sendFile(__dirname + '/'+ "index2.html");
});
webServer.get(objectInterfaceFolder + 'target/*/*/', function (req, res) {
// if(globalVariables.debug) console.log("get 15");
res.sendFile(__dirname + '/' + req.params[0] + '/' + req.params[1]);
});
// sends the object folder?? //todo what is this for?
// ****************************************************************************************************************
webServer.get(objectInterfaceFolder, function (req, res) {
// if(globalVariables.debug) console.log("get 16");
res.send(HybridObjectsWebFrontend.printFolder(objectExp, __dirname, globalVariables.debug, objectInterfaceFolder, objectLookup));
});
// ****************************************************************************************************************
// post interfaces
// ****************************************************************************************************************
webServer.post(objectInterfaceFolder + "contentDelete/:id", function (req, res) {
// if(globalVariables.debug) console.log("post 21");
if (req.body.action === "delete") {
var folderDel = __dirname + '/objects/' + req.body.folder;
if (fs.lstatSync(folderDel).isDirectory()) {
var deleteFolderRecursive = function (folderDel) {
if (fs.existsSync(folderDel)) {
fs.readdirSync(folderDel).forEach(function (file, index) {
var curPath = folderDel + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(folderDel);
}
};
deleteFolderRecursive(folderDel);
}
else {
fs.unlinkSync(folderDel);
}
res.send(HybridObjectsWebFrontend.uploadTargetContent(req.params.id, __dirname, objectInterfaceFolder));
}
});
//*****************************************************************************************
webServer.post(objectInterfaceFolder, function (req, res) {
// if(globalVariables.debug) console.log("post 22");
if (req.body.action === "new") {
// console.log(req.body);
if (req.body.folder !== "") {
HybridObjectsUtilities.createFolder(req.body.folder, __dirname, globalVariables.debug);
}
res.send(HybridObjectsWebFrontend.printFolder(objectExp, __dirname, globalVariables.debug, objectInterfaceFolder, objectLookup));
}
if (req.body.action === "delete") {
var folderDel = __dirname + '/objects/' + req.body.folder;
var deleteFolderRecursive = function (folderDel) {
if (fs.existsSync(folderDel)) {
fs.readdirSync(folderDel).forEach(function (file, index) {
var curPath = folderDel + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(folderDel);
}
};
deleteFolderRecursive(folderDel);
var tempFolderName2 = HybridObjectsUtilities.readObject(objectLookup, req.body.folder);// req.body.folder + thisMacAddress;
if (tempFolderName2 !== null) {
if (tempFolderName2 in objectExp) {
if (globalVariables.debug) console.log("ist noch da");
} else {
if (globalVariables.debug) console.log("ist weg");
}
if (tempFolderName2 in knownObjects) {
if (globalVariables.debug) console.log("ist noch da");
} else {
if (globalVariables.debug) console.log("ist weg");
}
// remove object from tree
delete objectExp[tempFolderName2];
delete knownObjects[tempFolderName2];
delete objectLookup[req.body.folder];
if (tempFolderName2 in objectExp) {
if (globalVariables.debug) console.log("ist noch da");
} else {
if (globalVariables.debug) console.log("ist weg");
}
if (tempFolderName2 in knownObjects) {
if (globalVariables.debug) console.log("ist noch da");
} else {
if (globalVariables.debug) console.log("ist weg");
}
}
if (globalVariables.debug) console.log("i deleted: " + tempFolderName2);
res.send(HybridObjectsWebFrontend.printFolder(objectExp, __dirname, globalVariables.debug, objectInterfaceFolder, objectLookup));
}
});
var tmpFolderFile = "";
// this is all used just for the backup folder
//*************************************************************************************
webServer.post(objectInterfaceFolder + 'backup/',
function (req, res) {
// if(globalVariables.debug) console.log("post 23");
if (globalVariables.debug)console.log("komm ich hier hin?");
var form = new formidable.IncomingForm({
uploadDir: __dirname + '/objects', // don't forget the __dirname here
keepExtensions: true
});
var filename = "";
form.on('error', function (err) {
throw err;
});
form.on('fileBegin', function (name, file) {
filename = file.name;
//rename the incoming file to the file's name
file.path = form.uploadDir + "/" + file.name;
});
form.parse(req, function (err, fields, files) {
var old_path = files.file.path,
file_size = files.file.size;
});
form.on('end', function () {
var folderD = form.uploadDir;
if (globalVariables.debug) console.log("------------" + form.uploadDir + " " + filename);
if (getFileExtension(filename) === "zip") {