-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.js
3089 lines (2442 loc) · 123 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.
* Modified by Carsten on 12/06/15.
* Modified by Psomdecerff (PCS) on 12/21/15.
*
* 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....
*
* 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 - check if links 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 - Checksum for marker needs to be verified on the server side as well.
**
**********************************************************************************************************************
******************************************** constant settings *******************************************************
**********************************************************************************************************************/
// These variables are used for global status, such as if the server sends debugging messages and if the developer
// user interfaces should be accesable
var globalVariables = {
developer: true, // show developer web GUI
debug: false // debug messages to console
};
// ports used to define the server behaviour
/*
The server uses port 8080 to communicate with other servers and with the Reality Editor.
As such the Server reacts to http and web sockets on this port.
The beat port is used to send UDP broadcasting messages in a local network. The Reality Editor and other Objects
pick up these messages to identify the object.
*/
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 timeToLive = 2; // the amount of routers a UDP broadcast can jump. For a local network 2 is enough.
const beatInterval = 5000; // how often is the heartbeat sent
const socketUpdateInterval = 2000; // how often the system checks if the socket connections are still up and running.
const version = "1.7.6"; // the version of this server
const protocol = "R1"; // the version of this server
const netmask = "255.255.0.0"; // define the network scope from which this server is accessable.
// for a local network 255.255.0.0 allows a 16 bit block of local network addresses to reach the object.
// basically all your local devices can see the object, however the internet is unable to reach the object.
console.log(parseInt(version.replace(/\./g, "")));
// All objects are stored in this folder:
const objectPath = __dirname + "/objects";
// All visual UI representations for IO Points are stored in this folder:
const nodePath = __dirname + "/libraries/nodes";
// All visual UI representations for IO Points are stored in this folder:
const blockPath = __dirname + "/libraries/logicBlocks";
// All interfaces for different hardware such as Arduino Yun, PI, Philips Hue are stored in this folder.
const hardwarePath = __dirname + "/hardwareInterfaces";
// The web service level on which objects are accessable. http://<IP>:8080 <objectInterfaceFolder> <object>
const objectInterfaceFolder = "/";
/**********************************************************************************************************************
******************************************** Requirements ************************************************************
**********************************************************************************************************************/
var _ = require('lodash'); // JavaScript utility library
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'); // body parsing middleware
var express = require('express'); // Web Sever library
var exphbs = require('express-handlebars'); // View Template library
// constrution for the werbserver using express combined with socket.io
var webServer = express();
webServer.set('views', 'libraries/webInterface/views');
webServer.engine('handlebars', exphbs({
defaultLayout: 'main',
layoutsDir: 'libraries/webInterface/views/layouts',
partialsDir: 'libraries/webInterface/views/partials'
}));
webServer.set('view engine', 'handlebars');
var http = require('http').createServer(webServer).listen(serverPort, function () {
cout('webserver + socket.io is listening on port: ' + serverPort);
});
var io = require('socket.io')(http); // Websocket library
var socket = require('socket.io-client'); // websocket client source
var cors = require('cors'); // Library for HTTP Cross-Origin-Resource-Sharing
var formidable = require('formidable'); // Multiple file upload library
var cheerio = require('cheerio');
// additional files containing project code
// This file hosts all kinds of utilities programmed for the server
var utilities = require(__dirname + '/libraries/utilities');
// The web frontend a developer is able to see when creating new user interfaces.
var webFrontend = require(__dirname + '/libraries/webFrontend');
// Definition for a simple API for hardware interfaces talking to the server.
// This is used for the interfaces defined in the hardwareAPI folder.
var hardwareAPI = require(__dirname + '/libraries/hardwareInterfaces');
var util = require("util"); // node.js utility functionality
var events = require("events"); // node.js events used for the socket events.
// Set web frontend debug to inherit from global debug
webFrontend.debug = globalVariables.debug;
/**********************************************************************************************************************
******************************************** Constructors ************************************************************
**********************************************************************************************************************/
/**
* @desc This is the default constructor for the Hybrid Object.
* It contains information about how to render the UI and how to process the internal data.
**/
function Objects() {
// The ID for the object will be broadcasted along with the IP. It consists of the name with a 12 letter UUID added.
this.objectId = null;
// The name for the object used for interfaces.
this.name = "";
// The IP address for the object is relevant to point the Reality Editor to the right server.
// It will be used for the UDP broadcasts.
this.ip = ip.address();
// The version number of the Object.
this.version = version;
this.deactivated = false;
this.protocol = protocol;
// The (t)arget (C)eck(S)um is a sum of the checksum values for the target files.
this.tcs = null;
// Reality Editor: This is used to possition the UI element within its x axis in 3D Space. Relative to Marker origin.
this.x = 0;
// Reality Editor: This is used to possition the UI element within its y axis in 3D Space. Relative to Marker origin.
this.y = 0;
// Reality Editor: This is used to scale the UI element in 3D Space. Default scale is 1.
this.scale = 1;
// Unconstrained positioning in 3D space
this.matrix = [];
// Used internally from the reality editor to indicate if an object should be rendered or not.
this.visible = false;
// Used internally from the reality editor to trigger the visibility of naming UI elements.
this.visibleText = false;
// Used internally from the reality editor to indicate the editing status.
this.visibleEditing = false;
// every object holds the developer mode variable. It indicates if an object is editable in the Reality Editor.
this.developer = true;
// Intended future use is to keep a memory of the last matrix transformation when interacted.
// This data can be used for interacting with objects for when they are not visible.
this.memory = {}; // TODO use this to store UI interface for image later.
// Stores all the links that emerge from within the object. If a IOPoint has new data,
// the server looks through the Links to find if the data has influence on other IOPoints or Objects.
this.links = {};
// Stores all IOPoints. These points are used to keep the state of an object and process its data.
this.nodes = {};
// Store the frames. These embed content positioned relative to the object
this.frames = {};
}
/**
* @desc The Link constructor is used every time a new link is stored in the links object.
* The link does not need to keep its own ID since it is created with the link ID as Obejct name.
**/
function Link() {
// The origin object from where the link is sending data from
this.objectA = null;
// The origin IOPoint from where the link is taking its data from
this.nodeA = null;
// if origin location is a Logic Node then set to Logic Node output location (which is a number between 0 and 3) otherwise null
this.logicA = null;
// Defines the type of the link origin. Currently this function is not in use.
this.namesA = ["",""];
// The destination object to where the origin object is sending data to.
// At this point the destination object accepts all incoming data and routs the data according to the link data sent.
this.objectB = null;
// The destination IOPoint to where the link is sending data from the origin object.
// objectB and nodeB will be send with each data package.
this.nodeB = null;
// if destination location is a Logic Node then set to logic block input location (which is a number between 0 and 3) otherwise null
this.logicB = null;
// Defines the type of the link destination. Currently this function is not in use.
this.namesB = ["",""];
// check that there is no endless loop in the system
this.loop = false;
// Will be used to test if a link is still able to find its destination.
// It needs to be discussed what to do if a link is not able to find the destination and for what time span.
this.health = 0; // todo use this to test if link is still valid. If not able to send for some while, kill link.
}
/**
* @desc Constructor used to define every nodes generated in the Object. It does not need to contain its own ID
* since the object is created within the nodes with the ID as object name.
**/
function Node() {
// the name of each link. It is used in the Reality Editor to show the IO name.
this.name = "";
// the actual data of the node
this.data = new Data();
// Reality Editor: This is used to possition the UI element within its x axis in 3D Space. Relative to Marker origin.
this.x = 0;
// Reality Editor: This is used to possition the UI element within its y axis in 3D Space. Relative to Marker origin.
this.y = 0;
// Reality Editor: This is used to scale the UI element in 3D Space. Default scale is 1.
this.scale = 1;
// Unconstrained positioning in 3D space
this.matrix = [];
// defines the nodeInterface that is used to process data of this type. It also defines the visual representation
// in the Reality Editor. Such data points interfaces can be found in the nodeInterface folder.
this.type = "node";
// defines the origin Hardware interface of the IO Point. For example if this is arduinoYun the Server associates
// this IO Point with the Arduino Yun hardware interface.
//this.type = "arduinoYun"; // todo "arduinoYun", "virtual", "edison", ... make sure to define yours in your internal_module file
// indicates how much calls per second is happening on this node
this.stress = 0;
}
/**
* @desc Constructor used to define every logic node generated in the Object. It does not need to contain its own ID
* since the object is created within the nodes with the ID as object name.
**/
function Logic() {
this.name = "";
// data for logic blocks. depending on the blockSize which one is used.
this.data = new Data();
// Reality Editor: This is used to possition the UI element within its x axis in 3D Space. Relative to Marker origin.
this.x = 0;
// Reality Editor: This is used to possition the UI element within its y axis in 3D Space. Relative to Marker origin.
this.y = 0;
// Reality Editor: This is used to scale the UI element in 3D Space. Default scale is 1.
this.scale = 1;
// Unconstrained positioning in 3D space
this.matrix = [];
// if showLastSettingFirst is true then lastSetting is the name of the last block that was moved or set.
this.lastSetting = false;
this.lastSettingBlock = "";
// the iconImage is in png or jpg format and will be stored within the logicBlock folder. A reference is placed here.
this.iconImage = null;
// nameInput are the names given for each IO.
this.nameInput = ["", "", "", ""];
// nameOutput are the names given for each IO
this.nameOutput = ["", "", "", ""];
// the array of possible connections within the logicBlock.
// if a block is set, a new Node instance is coppied in to the spot.
this.type = "logic";
this.links = {};
this.blocks = {};
this.route = 0;
this.routeBuffer = [0,0,0,0];
}
/**
* @desc The Link constructor for Blocks is used every time a new logic Link is stored in the logic Node.
* The block link does not need to keep its own ID since it is created with the link ID as Object name.
**/
function BlockLink() {
// origin block UUID
this.nodeA = null;
// item in that block
this.logicA = 0;
// destination block UUID
this.nodeB = null;
// item in that block
this.logicB = 0;
// check if the links are looped.
this.loop = false;
// Will be used to test if a link is still able to find its destination.
// It needs to be discussed what to do if a link is not able to find the destination and for what time span.
this.health = 0; // todo use this to test if link is still valid. If not able to send for some while, kill link.
}
/**
* @desc Constructor used to define every block within the logicNode.
* The block does not need to keep its own ID since it is created with the link ID as Object name.
**/
function Block() {
// name of the block
this.name = "";
// local ID given to a used block.
this.id = null;
this.x = null;
this.y = null;
// amount of elements the IO point is created of. Single IO nodes have the size 1.
this.blockSize = 1;
// the category for the editor
this.category = 1;
// the global / world wide id of the actual reference block design. // checksum of the block??
this.globalId = null;
// the checksum should be identical with the checksum for the persistent package files of the reference block design.
this.checksum = null; // checksum of the files for the program
// data for logic blocks. depending on the blockSize which one is used.
this.data = [new Data(), new Data(), new Data(), new Data()];
// experimental. This are objects for data storage. Maybe it makes sense to store data in the general object
// this would allow the the packages to be persistent. // todo discuss usability with Ben.
this.privateData = {};
this.publicData = {};
// IO for logic
// define how many inputs are active.
this.activeInputs = [true, false, false, false];
// define how many outputs are active.
this.activeOutputs = [true, false, false, false];
// define the names of each active IO
this.nameInput = ["", "", "", ""];
this.nameOutput = ["", "", "", ""];
// A specific icon for the node, png or jpg.
this.iconImage = null;
// Text within the node, if no icon is available.
// indicates how much calls per second is happening on this block
this.stress = 0;
// this is just a compatibility with the original engine. Maybe its here to stay
this.type = "default";
}
/**
* @desc Constructor used to define special blocks that are connecting the logic crafting with the outside system.
**/
function EdgeBlock() {
// name of the block
this.name = "";
// data for logic blocks. depending on the blockSize which one is used.
this.data = [new Data(), new Data(), new Data(), new Data()];
// indicates how much calls per second is happening on this block
this.stress = 0;
this.type = "default";
}
/**
* @desc Definition for Values that are sent around.
**/
function Data() {
// storing the numerical content send between nodes. Range is between 0 and 1.
this.value = 0;
// Defines the kind of data send. At this point we have 3 active data modes and one future possibility.
// (f) defines floating point values between 0 and 1. This is the default value.
// (d) defines a digital value exactly 0 or 1.
// (+) defines a positive step with a floating point value for compatibility.
// (-) defines a negative step with a floating point value for compatibility.
this.mode = "f";
// string of the name for the unit used (for Example "C", "F", "cm"). Default is set to no unit.
this.unit = "";
// scale of the unit that is used. Usually the scale is between 0 and 1.
this.unitMin = 0;
this.unitMax = 1;
}
/**
* Embedded content positioned relative to an object
* @constructor
* @param {String} src - path to content
*/
function ObjectFrame(src) {
this.src = src;
this.x = 0;
this.y = 0;
this.scale = 1;
this.matrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
this.developer = true;
}
/**
* @desc This Constructor is used when a new socket connection is generated.
**/
function ObjectSockets(socketPort, ip) {
// keeps the own IP of an object
this.ip = ip;
// defines where to connect to
this.io = socket.connect('http://' + ip + ':' + socketPort, {
// defines the timeout for a connection between objects and the reality editor.
'connect timeout': 5000,
// try to reconnect
'reconnect': true,
// time between re-connections
'reconnection delay': 500,
// the amount of reconnection attempts. Once the connection failed, the server kicks in and tries to reconnect
// infinitely. This behaviour can be changed once discussed what the best model would be.
// At this point the invinit reconnection attempt keeps the system optimal running at all time.
'max reconnection attempts': 20,
// automatically connect a new conneciton.
'auto connect': true,
// fallbacks connection models for socket.io
'transports': [
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-multipart'
, 'xhr-polling'
, 'jsonp-polling']
});
}
function EditorSocket(socketID, object) {
// keeps the own IP of an object
this.id = socketID;
// defines where to connect to
this.obj = object;
}
function Protocols() {
this.R1 = {
send: function (object, node, data) {
return JSON.stringify({object: object, node: node, data: data})
},
receive: function (message) {
if (!message) return null;
var msgContent = JSON.parse(message);
if (!msgContent.object) return null;
if (!msgContent.node) return null;
if (!msgContent.data) return null;
if (msgContent.object in objects) {
if (msgContent.node in objects[msgContent.object].nodes) {
var objectData = objects[msgContent.object].nodes[msgContent.node].data;
for (var key in msgContent.data) {
objectData[key] = msgContent.data[key];
}
return {object:msgContent.object, node:msgContent.node, data: objectData};
}
}
return null
}
};
this.R0 = {
send: function (object, node, data) {
return JSON.stringify({obj: object, pos: node, value: data.value, mode: data.mode})},
receive: function (message) {
if (!message) return null;
var msgContent = JSON.parse(message);
if (!msgContent.obj) return null;
if (!msgContent.pos) return null;
if (!msgContent.value) msgContent.value = 0;
if (!msgContent.mode) return null;
if (msgContent.obj in objects) {
if (msgContent.pos in objects[msgContent.obj].nodes) {
var objectData = objects[msgContent.obj].nodes[msgContent.pos].data;
objectData.value = msgContent.value;
objectData.mode = msgContent.mode;
return {object:msgContent.obj, node:msgContent.pos, data: objectData};
}
}
return null
}
};
}
/**********************************************************************************************************************
******************************************** Variables and Objects ***************************************************
**********************************************************************************************************************/
// This variable will hold the entire tree of all objects and their sub objects.
var objects = {};
var nodeTypeModules = {}; // Will hold all available data point interfaces
var blockModules = {}; // Will hold all available data point interfaces
var hardwareInterfaceModules = {}; // Will hold all available hardware interfaces.
// A list of all objects known and their IPs in the network. The objects are found via the udp heart beat.
// If a new link is linking to another objects, this knownObjects list is used to establish the connection.
// This list is also used to keep track of the actual IP of an object. If the IP of an object in a network changes,
// It has no influance on the connectivity, as it is referenced by the object UUID through the entire time.
var protocols = new Protocols();
var knownObjects = {};
// A lookup table used to process faster through the objects.
var objectLookup = {};
// This list holds all the socket connections that are kept alive. Socket connections are kept alive if a link is
// associated with this object. Once there is no more link the socket connection is deleted.
var socketArray = {}; // all socket connections that are kept alive
var realityEditorSocketArray = {}; // all socket connections that are kept alive
var realityEditorBlockSocketArray = {}; // all socket connections that are kept alive
// counter for the socket connections
// this counter is used for the Web Developer Interface to reflect the state of the server socket connections.
var sockets = {
sockets: 0, // amount of created socket connections
connected: 0, // amount of connected socket connections
notConnected: 0, // not connected
socketsOld: 0, // used internally to react only on updates
connectedOld: 0, // used internally to react only on updates
notConnectedOld: 0 // used internally to react only on updates
};
/**********************************************************************************************************************
******************************************** Initialisations *********************************************************
**********************************************************************************************************************/
cout("Starting the Server");
// get a list with the names for all IO-Points, based on the folder names in the nodeInterfaces folder folder.
// Each folder represents on IO-Point.
var nodeFolderList = fs.readdirSync(nodePath).filter(function (file) {
return fs.statSync(nodePath + '/' + file).isDirectory();
});
// Remove eventually hidden files from the Hybrid Object list.
while (nodeFolderList[0][0] === ".") {
nodeFolderList.splice(0, 1);
}
// Create a objects list with all IO-Points code.
for (var i = 0; i < nodeFolderList.length; i++) {
nodeTypeModules[nodeFolderList[i]] = require(nodePath + '/' + nodeFolderList[i] + "/index.js");
}
// get a list with the names for all IO-Points, based on the folder names in the nodeInterfaces folder folder.
// Each folder represents on IO-Point.
var blockFolderList = fs.readdirSync(blockPath).filter(function (file) {
return fs.statSync(blockPath + '/' + file).isDirectory();
});
// Remove eventually hidden files from the Hybrid Object list.
while (blockFolderList[0][0] === ".") {
blockFolderList.splice(0, 1);
}
// Create a objects list with all IO-Points code.
for (var i = 0; i < blockFolderList.length; i++) {
blockModules[blockFolderList[i]] = require(blockPath + '/' + blockFolderList[i] + "/index.js");
}
cout("Initialize System: ");
cout("Loading Hardware interfaces");
// set all the initial states for the Hardware Interfaces in order to run with the Server.
hardwareAPI.setup(objects, objectLookup, globalVariables, __dirname, nodeTypeModules, blockModules, function (objectKey, nodeKey, data, objects, nodeTypeModules) {
//these are the calls that come from the objects before they get processed by the object engine.
// send the saved value before it is processed
sendMessagetoEditors({
object: objectKey,
node: nodeKey,
data: data
});
engine.trigger(objectKey, nodeKey, objects[objectKey].nodes[nodeKey]);
}, Node, function(thisAction){
actionSender(thisAction);
});
cout("Done");
cout("Loading Objects");
// This function will load all the Objects
loadObjects();
cout("Done");
startSystem();
cout("started");
// get the directory names of all available soutyperces for the 3D-UI
var hardwareAPIFolderList = fs.readdirSync(hardwarePath).filter(function (file) {
return fs.statSync(hardwarePath + '/' + file).isDirectory();
});
// remove hidden directories
while (hardwareAPIFolderList[0][0] === ".") {
hardwareAPIFolderList.splice(0, 1);
}
// add all types to the nodeTypeModules object. Iterate backwards because splice works inplace
for (var i = hardwareAPIFolderList.length - 1; i >= 0; i--) {
//check if hardwareInterface is enabled, if it is, add it to the hardwareInterfaceModules
if (require(hardwarePath + "/" + hardwareAPIFolderList[i] + "/index.js").enabled) {
hardwareInterfaceModules[hardwareAPIFolderList[i]] = require(hardwarePath + "/" + hardwareAPIFolderList[i] + "/index.js");
} else {
hardwareAPIFolderList.splice(i, 1);
}
}
cout("ready to start internal servers");
hardwareAPI.reset();
cout("found " + hardwareAPIFolderList.length + " internal server");
cout("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 loadObjects() {
cout("Enter loadObjects");
// check for objects in the objects folder by reading the objects directory content.
// get all directory names within the objects directory
var objectFolderList = fs.readdirSync(objectPath).filter(function (file) {
return fs.statSync(objectPath + '/' + file).isDirectory();
});
// remove hidden directories
try {
while (objectFolderList[0][0] === ".") {
objectFolderList.splice(0, 1);
}
} catch (e) {
cout("no hidden files");
}
for (var i = 0; i < objectFolderList.length; i++) {
var tempFolderName = utilities.getObjectIdFromTarget(objectFolderList[i], __dirname);
cout("TempFolderName: " + tempFolderName);
if (tempFolderName !== null) {
// fill objects with objects named by the folders in objects
objects[tempFolderName] = new Objects();
objects[tempFolderName].name = objectFolderList[i];
// add object to object lookup table
utilities.writeObject(objectLookup, objectFolderList[i], tempFolderName);
// try to read a saved previous state of the object
try {
objects[tempFolderName] = JSON.parse(fs.readFileSync(__dirname + "/objects/" + objectFolderList[i] + "/object.json", "utf8"));
objects[tempFolderName].ip = ip.address();
// this is for transforming old lists to new lists
if(typeof objects[tempFolderName].objectValues !== "undefined")
{
objects[tempFolderName].nodes = objects[tempFolderName].objectValues;
delete objects[tempFolderName].objectValues;
}
if(typeof objects[tempFolderName].objectLinks !== "undefined")
{
objects[tempFolderName].links = objects[tempFolderName].objectLinks;
delete objects[tempFolderName].objectLinks;
}
for (var nodeKey in objects[tempFolderName].nodes) {
if(typeof objects[tempFolderName].nodes[nodeKey].item !== "undefined"){
var tempItem = objects[tempFolderName].nodes[nodeKey].item;
objects[tempFolderName].nodes[nodeKey].data = tempItem[0];
}
}
cout("I found objects that I want to add");
} catch (e) {
objects[tempFolderName].ip = ip.address();
objects[tempFolderName].objectId = tempFolderName;
cout("No saved data for: " + tempFolderName);
}
} else {
cout(" object " + objectFolderList[i] + " has no marker yet");
}
}
hardwareAPI.reset();
}
/**********************************************************************************************************************
******************************************** 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 objects) {
if(!objects[key].deactivated) {
objectBeatSender(beatPort, key, objects[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();
// 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();
}
/**********************************************************************************************************************
******************************************** Stopping the System *****************************************************
**********************************************************************************************************************/
function exit() {
var mod;
hardwareAPI.shutdown();
process.exit();
}
process.on('SIGINT', exit);
/**********************************************************************************************************************
******************************************** Emitter/Client/Sender ***************************************************
**********************************************************************************************************************/
/**
* @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 {string} thisVersion The version of the Object
* @param {string} thisTcs The target checksum of the Object.
* @param {boolean} oneTimeOnly if true the beat will only be sent once.
**/
function objectBeatSender(PORT, thisId, thisIp, oneTimeOnly) {
if (typeof oneTimeOnly === "undefined") {
oneTimeOnly = false;
}
var HOST = '255.255.255.255';
cout("creating beat for object: " + thisId);
objects[thisId].version = version;
objects[thisId].protocol = protocol;
var thisVersionNumber = parseInt(objects[thisId].version.replace(/\./g, ""));
if (typeof objects[thisId].tcs === "undefined") {
objects[thisId].tcs = 0;
}
// Objects
cout("with version number: " + thisVersionNumber);
// json string to be send
var message = new Buffer(JSON.stringify({
id: thisId,
ip: thisIp,
vn: thisVersionNumber,
pr: protocol,
tcs: objects[thisId].tcs
}));
if (globalVariables.debug) console.log("UDP broadcasting on port: " + PORT);
if (globalVariables.debug) console.log("Sending beats... Content: " + JSON.stringify({
id: thisId,
ip: thisIp,
vn: thisVersionNumber,
pr: protocol,
tcs: objects[thisId].tcs
}));
cout("UDP broadcasting on port: " + PORT);
cout("Sending beats... Content: " + JSON.stringify({
id: thisId,
ip: thisIp,
vn: thisVersionNumber,
pr: protocol,
tcs: objects[thisId].tcs
}));
// creating the datagram
var client = dgram.createSocket('udp4');
client.bind(function () {
client.setBroadcast(true);
client.setTTL(timeToLive);
client.setMulticastTTL(timeToLive);
});
if (!oneTimeOnly) {
setInterval(function () {
// send the beat#
if (thisId in objects && !objects[thisId].deactivated) {
// cout("Sending beats... Content: " + JSON.stringify({ id: thisId, ip: thisIp, vn:thisVersionNumber, tcs: objects[thisId].tcs}));
var message = new Buffer(JSON.stringify({
id: thisId,
ip: thisIp,
vn: thisVersionNumber,
pr: protocol,
tcs: objects[thisId].tcs
}));
// this is an uglly trick to sync each object with being a developer object
if (globalVariables.developer) {
objects[thisId].developer = true;
} else {
objects[thisId].developer = false;
}
//console.log(globalVariables.developer);
client.send(message, 0, message.length, PORT, HOST, function (err) {
if (err) {
cout("error in beatSender");
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 objects && !objects[thisId].deactivated) {
var message = new Buffer(JSON.stringify({
id: thisId,
ip: thisIp,
vn: thisVersionNumber,
pr: protocol,
tcs: objects[thisId].tcs
}));
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) {
console.log(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(timeToLive);
client.setMulticastTTL(timeToLive);
});
// 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.
**/
var thisIP = ip.address();
function objectBeatServer() {
// creating the udp server
var udpServer = dgram.createSocket("udp4");
udpServer.on("error", function (err) {
cout("server error:\n" + err);
udpServer.close();
});
udpServer.on("message", function (msg) {
var msgContent;
// check if object ping
msgContent = JSON.parse(msg);
if (msgContent.id && msgContent.ip && !checkObjectActivation(msgContent.id) && !(msgContent.id in knownObjects)) {
if(!knownObjects[msgContent.id]){
knownObjects[msgContent.id] = {};
}
if(msgContent.vn)
knownObjects[msgContent.id].version = msgContent.vn;
if(msgContent.pr)
knownObjects[msgContent.id].protocol = msgContent.pr;
else
{
knownObjects[msgContent.id].protocol = "R0";
}
if(msgContent.ip)
knownObjects[msgContent.id].ip = msgContent.ip;