-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
114 lines (94 loc) · 2.8 KB
/
app.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
const mqtt = require('mqtt');
const Omx = require('node-omxplayer'); // https://github.com/Ap0c/node-omxplayer
const schedule = require('node-schedule');
let { controllerUrl, actAsController, video, totalNodes, volume } = require('./config.json');
console.log('--- STARTING NETWORK PLAYER ---');
console.log('controllerUrl:', controllerUrl);
console.log('video:', video);
console.log('totalNodes:', totalNodes);
try {
let nodesConnected = 1;
let nodesDone = 0;
let player = createPlayer();
if (actAsController) {
startServer();
// if we are the server, listen to our ip
controllerUrl = 'mqtt://0.0.0.0';
}
const client = mqtt.connect(controllerUrl);
client.on('connect', onConnect);
client.on('message', onMessage);
function onConnect() {
client.subscribe(['/ready', '/play', '/done'], function (err) {
if (!err) {
console.log(`connected to ${controllerUrl}`);
if (!actAsController) {
client.publish('/ready'); // first argument is the topic, second is the message
}
}
});
}
function onMessage(topic, message) {
const msg = message.toString();
console.log('received a message topic: %s with message: %s', topic, msg);
if (topic === '/ready' && actAsController) {
nodesConnected++;
if (nodesConnected === totalNodes) {
playVideo();
}
}
if (topic === '/done' && actAsController) {
nodesDone++;
if (nodesDone === totalNodes) {
nodesDone = 0;
playVideo();
}
}
if (topic === '/play') {
onPlay(msg);
}
}
function playVideo() {
const startTime = new Date();
startTime.setSeconds(0);
startTime.setMinutes(startTime.getMinutes() + 1);
client.publish('/play', `${startTime.getTime()}`);
}
function onPlay(msg) {
const startTime = new Date();
startTime.setTime(msg);
console.log('Going to play video at ', startTime);
schedule.scheduleJob(startTime, function() {
console.log('Playing video at ', startTime);
player.play();
player.on('close', function() {
console.log('player done');
player = createPlayer();
client.publish('/done', 'video complete');
});
});
}
function startServer() {
console.log('\n+++ STARTING CONTROLLER SERVER +++');
const aedes = require('aedes')();
const net = require('net');
const port = 1883;
const server = net.createServer(aedes.handle)
server.listen(port, function () {
console.log('server started and listening on port ', port)
});
}
function createPlayer() {
const player = Omx(
video, // video file
'both', // audio output
false, // loop
volume // initial volume
);
player.pause();
return player;
}
} catch (e) {
console.log(e.stack);
process.exit();
}