-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraspberryApp.js
More file actions
459 lines (379 loc) · 15.6 KB
/
Copy pathraspberryApp.js
File metadata and controls
459 lines (379 loc) · 15.6 KB
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
// load file module
var fs = require('fs');
// load Render Module
var Renderer = require('./node_modules/renderModule.js');
// module for synchronization of user content
var gitsync = require('gitsync');
// load DMX serial communication module
var DMX = require('dmxhost');
//-----------OPTIONS--------------------------------
gitsync.directory = 'savedAnimations/';
gitsync.remote = 'git://neuesvomlicht.de:4880/sync.git';
gitsync.branch = 'animations';
DMX.log = true;
DMX.relayPath = './node_modules/dmxhost/dmxhost-serial-relay.py';
DMX.relayResponseTimeout = 10000;
// enable or disable simulation interface with express io
var enableWebInterface = false;
// time between checks for changed scenes [ms]
var sceneCheckInterval = 30 * 1000;
//default blending scene 4s black
var defaultBlendingScene=[{"duration":4000,"type":1,"windows":[{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1},{"color":[0,0,0],"active":1}]}];
var scenePath="savedAnimations/";
// player speed
var fps = 30;
//----------------------------------------------------
var DMXManager = function() {
//initialize and configure DMX Module
this.initialize = function() {
DMX.spawn(null, function(error) {
if (error) {
console.log("--------DMX BRIDGE COULD NOT BE INITIALIZED -----------");
console.log("Error:", error);
console.log("-------------------------------------------------------");
} else {
console.log("Relay spawned.");
}
});
};
//data should be array with 4*16 bytes
var rgbw = new Array(16*4);
var frameCounter = 0;
this.send = function(frame) {
//fill rgb array
frame.map( function( rgbWindow, index )
{
rgbw[ 4*index + 0 ] = rgbWindow[0];
rgbw[ 4*index + 1 ] = rgbWindow[1];
rgbw[ 4*index + 2 ] = rgbWindow[2];
rgbw[ 4*index + 3 ] = 0;
});
//update web interface every 3 frames
frameCounter++;
frameCounter=frameCounter % 3;
if(enableWebInterface && frameCounter == 0){
//broadcast to all connected clients
app.io.broadcast('newFrame', rgbw);
}
DMX.ready() && DMX.send( {data: rgbw} );
};
};
var SceneManagerObj =function(fileManager){
var that = this;
var sceneRankingData,scheduleData;
var sceneRankingFilename="_schedule";
var scheduleFileName="_schedule";
//next sheduled file data
var nextScheduledTime, nextScheduledSceneName;
var setScheneRankingData=function(data){
sceneRankingData=data;
}
var setscheduleData=function(data){
scheduleData=data;
}
//load blending, sceneranking and shedule
this.initialize = function(){
}
//returns blendingscene, if param frame is set function returns blending scene with correct framecount
this.getBlendingScene = function(frameCount) {
if (!frameCount){
//return default length
return blendingScene;
}
else {
//return a custom scene
newBlendingScene = new Array(frameCount);;
var defaultLength=blendingScene.length;
for (var i = 0; i < frameCount; i++) {
newBlendingScene[i]=blendingScene[i % defaultLength];
}
return newBlendingScene;
}
};
this.getNextSceneNameByRanking = function() {
var highestRanking = 0;
var highestRankedScene;
for (var i = 0; i < sceneRanking.length; i++) {
//check if dynamicRating is below staticRating
if (sceneRanking[i].dynamicRating < sceneRanking[i].staticRating)
sceneRanking[i].dynamicRating = sceneRanking[i].staticRating;
//add or increase current rating
if (!sceneRanking[i].currentRating)
sceneRanking[i].currentRating = sceneRanking[i].dynamicRating;
else {
sceneRanking[i].currentRating += sceneRanking[i].dynamicRating;
}
//find scene with highest current rating value
if (parseInt(sceneRanking[i].currentRating) >= highestRanking) {
highestRanking = sceneRanking[i].currentRating;
highestRankedScene = sceneRanking[i];
}
}
if (highestRankedScene) {
//reset currentrating of highest ranked scene
highestRankedScene.currentRating = 0;
highestRankedScene.dynamicRating = highestRankedScene.dynamicRating > highestRankedScene.staticRating ? (highestRankedScene.dynamicRating - 1) : highestRankedScene.staticRating;
console.log("next Scene: --<<" + highestRankedScene.sceneName + ">>--, rating values d/s:" + highestRankedScene.dynamicRating + "/" + highestRankedScene.staticRating);
return highestRankedScene.sceneName;
}
};
this.getNextScheduledScene = function() {
var current = (new Date()).getTime();
var closestTime = current;
//for each schedule entry
for (var i = 0; i < schedule.length; i++) {
// check if it is currently before the endDate
if (current < schedule[i].endDate) {
//find the closest start time to now
var tmp = schedule[i].startDate;
while (tmp < current) {
tmp += schedule[i].repeatEach;
}
//found new closest Schedule
if ((tmp - current) < closestTime) {
closestTime = (tmp - current);
nextScheduledTime = tmp;
nextScheduledSceneName = schedule[i].sceneName;
return {
"nextScheduledTime": nextScheduledTime,
"nextScheduledSceneName": nextScheduledSceneName
};
}
}
}
};
}
var FileManagerObj = function(scenePath) {
var that = this;
//keepPreviouslyCachedObjects
var rawCache=[];
this.loadFileAndStartWatch(filename, callback){
that.loadAndParseFile(fileName,function(data){
callback(data);
that.watchFileForChanges(fileName,function(data){
callback(data);
})
})
}
this.watchFileForChanges(filename, callback){
fs.watch(fileName, {
persistent: true
}, function(event, filename,callback) {
console.log(event + " event occurred on " + filename);
that.loadAndParseFile(filename,callback);
});
}
this.loadAndParseFile(fileName,callback){
fs.readFile(scenePath+fileName, "utf-8", function(err, result, callback) {
if (err){
console.log(fileName+" corrupt or not existent")
console.log(err);
}
else {
var data;
try{
data = JSON.parse(result);
}catch(e){
console.log("Error while parsing shedule file contents");
console.log(e);
}
if(data){
callback(data)
}
else{
console.log("no data could be loaded")
}
}
})
this.loadSceneData = function(sceneName, callback) {
//load file
fs.readFile(scenePath + sceneName, "utf-8", function(err, result) {
if (err) {
console.log("Can not load scene "+sceneName+", get default-blendingscene instead");
console.log("error: " + err);
//todo: add errorscene
sceneData = blendingScene;
} else {
//transform scene from fronted json format to simple array with all frames
try{
sceneData = myRenderer.parse(JSON.parse(result));
}catch(e){
console.log("Can not load scene "+sceneName+", load blendingscene instead");
console.log("error: " + e);
sceneData = blendingScene;
}
callback(sceneData);
}
});
};
};
var PlayerObj = function(fps, fileManager) {
var that = this;
var currentScene = [];
var nextRankedScene = [];
var nextScheduledScene = [];
var nextSceneType = "";
var blendingScene = [];
var currentSceneFrameNumber = 0;
var nextScheduledSceneInfo;
var currentsceneType = "";
var nextSceneName = "";
this.start = function() {
//load the blending scene data
fileManager.loadBlendingScene(that.setBlendingScene);
//refresh Schedule and Scenelist
setInterval(that.checkForNewScenes, sceneCheckInterval);
// fileManager.loadSceneRanking();
// fileManager.loadSchedule(that.setNextScheduledSceneInfo);
//interval to send frames to arduino
setInterval(that.playerTick, 1000 / fps);
};
//callback function to set Blendingscene
this.setBlendingScene = function(sceneData) {
blendingScene = sceneData;
};
this.setCurrentScene = function(sceneData) {
console.log("loading new scene, duration: " + sceneData.length / fps);
currentSceneFrameNumber = 0;
currentScene = sceneData;
};
//callback function to set NextScheduledSceneInfo
this.setNextScheduledSceneInfo = function() {
//load next sheduled scene information (name and time)
nextScheduledSceneInfo = fileManager.getNextScheduledScene();
};
//refresh Schedule and Scenelist every 5 seconds
this.checkForNewScenes = function() {
//console.log("checkForNewScenes")
// update files from remote repository
gitsync.pull({
init: true
}, function(error) {
if (!error) {
// log success
console.log("Pulled scenes from remote.");
} else {
// log error
console.log("Error pulling scenes from remote:", error);
}
// load scenes from files - TODO: move to if ( !error ) bracket in final version
fileManager.loadSceneRanking();
fileManager.loadSchedule(that.setNextScheduledSceneInfo);
});
};
this.setNextScene = function(sceneData) {
//set next scene type to rankedScene as default
nextRankedScene = sceneData;
nextSceneType = "rankedScene";
var nextSheduledInSeconds=99999;
//check if there is a time conflict with the next sheduled scene
//get timespan till next sheduled scene begins
if (nextScheduledSceneInfo){
if (nextScheduledSceneInfo.nextScheduledTime){
nextSheduledInSeconds = (nextScheduledSceneInfo.nextScheduledTime - (new Date()).getTime()) / 1000;
console.log("the next scheduled scene " + nextScheduledSceneInfo.nextScheduledSceneName + " should start in " + nextSheduledInSeconds + " seconds. Precisely at " + new Date(nextScheduledSceneInfo.nextScheduledTime));
}
else
console.log("nextScheduledTime is not set for sceneinfo");
}
if (nextSheduledInSeconds < ((nextRankedScene.length / fps) + (blendingScene.length / fps))) {
console.log("nextscene: " + nextRankedScene.length / fps + " s |" + " blending: " + blendingScene.length / fps + " s are to long");
console.log("create a fitting blendingScene with " + (Math.floor(nextSheduledInSeconds) * fps) + " frames");
//if there is a conflict create a fitting blending scene to wait for the scheduled scene
var fittingBlendingScene = fileManager.getBlendingScene(Math.floor(nextSheduledInSeconds) * fps);
currentsceneType = "blendingScene";
that.setCurrentScene(fittingBlendingScene);
if (enableWebInterface)
app.io.broadcast('newSceneInfo', "blendingscene (" + fittingBlendingScene.length / fps + "s)");
//and load the next sheduled scene
fileManager.loadSceneData(nextScheduledSceneInfo.nextScheduledSceneName, that.setNextScheduledScene);
} else {
//set a normal blending scene
console.log("set currentscene to blendingScene");
currentsceneType = "blendingScene";
that.setCurrentScene(blendingScene);
if (enableWebInterface)
app.io.broadcast('newSceneInfo', "blendingscene (" + blendingScene.length / fps + "s)");
}
};
this.setNextScheduledScene = function(sceneData) {
nextSceneType = "scheduledScene";
nextScheduledScene = sceneData;
//search for next sheduled scene
that.setNextScheduledSceneInfo();
};
this.loadNewScene = function() {
//if the current scene endet and was of type blendingscene load a sheduled or a ranked scene
if (currentsceneType == "blendingScene") {
if (nextSceneType == "scheduledScene") {
console.log("set currentscene to scheduledScene");
currentsceneType = "scheduledScene";
that.setCurrentScene(nextScheduledScene);
if (enableWebInterface)
app.io.broadcast('newSceneInfo', "scene " + nextSceneName + " (" + nextScheduledScene.length/fps + "s)");
}
if (nextSceneType == "rankedScene") {
console.log("set currentscene to rankedScene");
currentsceneType = "rankedScene";
that.setCurrentScene(nextRankedScene);
if (enableWebInterface)
app.io.broadcast('newSceneInfo', "scene " + nextSceneName + " (" + nextRankedScene.length/fps + "s)");
}
}
//if the current scene endet and was of type rankedScene, sheduledscene or undefined then try to find the next scene and add a blendingscene until loading is done
else if (currentsceneType == "rankedScene" || currentsceneType == "scheduledScene" || currentsceneType === "") {
//get next ranked scene name if sceneranking was loaded
nextSceneName = fileManager.getNextSceneNameByRanking();
//load the next ranked scene and check if there is a time conflict with a scheduled scene
if (nextSceneName) {
fileManager.loadSceneData(nextSceneName, that.setNextScene);
}
}
};
this.playerTick = function() {
if (currentScene.length > 0) {
//if last frame of scene
if (currentSceneFrameNumber == currentScene.length) {
that.loadNewScene();
currentSceneFrameNumber = 0;
} else {
if (currentScene[currentSceneFrameNumber]) {
dmxManager.send(currentScene[currentSceneFrameNumber]);
} else
console.log("framerror, possibly with blending scene generation");
currentSceneFrameNumber++;
}
} else {
that.loadNewScene();
}
};
};
//create new Renderer with 24 Frames
var myRenderer = new Renderer(fps);
//initialize dmx serial manager
var dmxManager = new DMXManager();
dmxManager.initialize();
console.log("Wait for dmx bridge for "+DMX.relayResponseTimeout+" ms");
setTimeout( function()
{
//initialize filemanager
var fileManager = new FileManagerObj();
var scenemanager = new SceneManager(fileManager);
//initialize player
var player = new PlayerObj(fps, fileManager);
player.start();
//create simulation interface
if (enableWebInterface) {
//socket io for debugging and testing interface (tower simulation)
var express = require('express.io');
var app = express();
//open socket
app.http().io();
app.use(express.static(__dirname + '/towerSimulation'));
var server = app.listen(3001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('tower app listening at http://%s:%s', host, port);
});
}
}, DMX.relayResponseTimeout );