forked from csdhku/csdosc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoscServer.js
393 lines (337 loc) · 10.3 KB
/
oscServer.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
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').Server(app);
const io = require('socket.io')(server);
const osc = require('node-osc');
const readline = require('readline');
const fs = require('fs');
const http = require('http');
const https = require('https');
const _ = require('lodash');
const midi = require('midi');
const midiIn = new midi.Input();
const midiOut = new midi.Output();
const {SerialPort} = require('serialport');
let sendSocket = [];
let oscServer = [];
let oscClient = [];
let clients = {};
let serial;
/*--------------osc-----------------/
*-----------functions--------------/
*///-------------------------------/
//check if a server is already running on the desired port, if so: kill it first
function serverExist(port,id,callback) {
let found = 0;
for (let i in oscServer) {
if (oscServer[i] && oscServer[i].port == port) {
found = 1;
oscServer[i].close();
oscServer[i] = null;
callback();
}
}
if (!found) {
callback();
}
}
/*--------user-interaction----------/
*----------exit-program------------/
*///-------------------------------/
//handle ctrl+c
process.on('SIGINT', function(){
killOsc();
process.exit (0);
});
//get user input from the terminal
const rl = readline.createInterface({
input: process.stdin
});
//check the code that is given by the user.
rl.on('line', (input) => {
//quit the program when one of these words is used.
if (input == "quit" || input == "stop" || input == "hou op!") {
killOsc();
process.exit(0);
}
//start the update process
if (input == "update") {
requestUpdate();
}
});
async function requestUpdate() {
await downloadFile('https://csd.hku.nl/sysbas/csdoscHelper/updateState.txt','./.updateState.txt')
.then(getUpdateState)
.then(downloadFile('https://csd.hku.nl/sysbas/csdoscHelper/filesToUpdate.txt','./.filesToUpdate.txt'))
.then(startUpdate)
.then(doUpdate)
.then(updateSucces).catch(error => {
console.log(error);
});
}
// close any of the available OSC instances, client and servers.
function killOsc() {
oscServer.forEach(s => {
if (s)s.close();
});
oscClient.forEach(s => {
if (s)s.close();
});
}
/*-----------http-server------------/
*----------------------------------/
*///-------------------------------/
//start the server listening on port 8001
server.listen(8001,function() {
console.log("De server staat aan! Je kunt deze via localhost:8001 bereiken.\nJe kunt dit programma afsluiten door stop+enter te typen");
});
//zorg dat de server alle paths kan bereiken.
app.use(express.static(path.join(__dirname,'/')));
//genereer errormessage als de pagina niet bestaat
app.use(function(req,res,next) {
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
res.status(400).send("De pagina <b>"+fullUrl+"</b> bestaat niet, heb je het goede adres ingevuld?");
});
/*----------web-socket--------------/
*----------------------------------/
*///-------------------------------/
io.on('connection', function (socket) {
clients[socket.id] = socket;
//initialize socket, make a connection with the webpage
socket.on('oscLib',function(data) {
sendSocket[data] = clients[data];
let returnMessage = setTimeout(function() {
sendSocket[data].emit("connected",data);
},100);
//what to do on disconnecting
sendSocket[data].on('disconnect',function() {
//close the open serial port, if available
if (serial) {
if (serial.isOpen) {
serial.close()
}
}
//close the midiPort, if available
if (midiIn._events) {
midiIn.closePort();
}
if (midiOut._events) {
midiOut.closePort();
}
//close the OSC-port.
if (data && oscServer[data]) {
oscServer[data].close();
oscServer[data] = null;
}
});
});
//on receiving start message for server
socket.on('startServer',function(data) {
serverExist(data.port,data.id,function() {
oscServer[data.id] = new osc.Server(data.port,'0.0.0.0');
sendSocket[data.id].emit("serverRunning",{"port":data.port});
oscServer[data.id].on("message",function([...msg],rinfo) {
let address = msg.shift();
let message = msg;
let sendData = {"add":address,"msg":message};
sendSocket[data.id].emit('getMessage',sendData);
});
});
});
//on receiving kill message for server
socket.on('killServer',function() {
oscServer.close();
});
//on receiving start message for client
socket.on('startClient',function(data) {
oscClient[data.id] = new osc.Client(data.ip, data.port);
sendSocket[data.id].emit("clientRunning",{"ip":data.ip,"port":data.port,"active":1});
});
//on receiving kill message for client
socket.on('killClient',function() {
oscClient.close();
});
//on receiving message to send
socket.on('sendMessage',function(data) {
if (oscClient[data.id]) {
oscClient[data.id].send(data.address, data.message, function () {
});
}
});
//serial
//get serial ports
socket.on('getSerialPorts',function(data) {
let sendData = [];
SerialPort.list().then(ports => {
for (let i in ports) {
sendData[i] = {"path":ports[i].path,"manufacturer":ports[i].manufacturer,"serialNumber":ports[i].serialNumber};
}
sendSocket[data.id].emit("serialPorts",sendData);
});
});
//open Serial port by path (default)
socket.on('openSerialPort',function(data) {
serial = new SerialPort({
path: data.path,
baudRate: data.baudRate
}, function(err) {
serial.on('data', function(rcvdata) {
let sendData = {"message":rcvdata.toString()};
sendSocket[data.id].emit("serialData",sendData);
})
});
});
socket.on('sendSerialData',function(data) {
serial.write(data.message, err => {
if (err) {
console.log(`serial message ${data.message} cannot be sent.`)
}
});
});
socket.on('closeSerialPort',function(data) {
if (serial) {
if (serial.isOpen) {
serial.close();
}
}
});
//midi
//get midi-in-ports
socket.on('getInPorts',function(data) {
let sendData = [];
for (let i = 0; i < midiIn.getPortCount(); i++) {
sendData[i] = midiIn.getPortName(i);
}
sendSocket[data.id].emit("midiInPorts",sendData);
});
//get midi-out-ports
socket.on('getOutPorts',function(data) {
let sendData = [];
for (let i = 0; i < midiOut.getPortCount(); i++) {
sendData[i] = midiOut.getPortName(i);
}
sendSocket[data.id].emit("midiOutPorts",sendData);
});
//open port for incoming data
socket.on('openInPort',function(data) {
midiIn.openPort(data.port);
midiIn.on('message',(dTime,message) => {
let sendData = {"message":message};
sendSocket[data.id].emit("getMidi",sendData);
});
});
//open port for outgoing data
socket.on('openOutPort',function(data) {
midiOut.openPort(data.port);
});
//send midi data
socket.on('sendMidiData',function(data) {
if (data.chan >= 144 && data.chan < 192) {
midiOut.sendMessage([data.chan,data.note,data.vel]);
}
else {
midiOut.sendMessage([data.chan,data.note]);
}
});
});
//all the functions for updating this code.
async function downloadFile(url, filePath) {
const proto = !url.charAt(4).localeCompare('s') ? https : http;
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filePath);
let fileInfo = null;
const request = proto.get(url, response => {
if (response.statusCode !== 200) {
reject(`Failed to get '${url}' (${response.statusCode})`);
return;
}
fileInfo = {
mime: response.headers['content-type'],
size: parseInt(response.headers['content-length'], 10),
};
response.pipe(file);
});
// The destination stream is ended by the time it's called
file.on('finish', () => resolve(fileInfo));
request.on('error', err => {
fs.unlink(filePath, () => reject(err));
});
file.on('error', err => {
fs.unlink(filePath, () => reject(err));
});
request.end();
});
}
async function getUpdateState() {
return new Promise((resolve, reject) => {
fs.readFile('./.lastUpdate.txt','utf8', (err,lastDay) => {
if (err)reject ("er ging iets fout...");
let lastUpdate = new Date(lastDay);
fs.readFile('./.updateState.txt', 'utf8', (err,data) => {
if (err) {
reject(`can't read update file`);
}
else {
newestUpdate = new Date(data.replace(/(\r\n|\n|\r)/gm,""));
if (lastUpdate < newestUpdate) {
resolve();
}
else {
reject("Er is op dit moment geen update beschikbaar");
}
}
});
})
})
}
async function startUpdate() {
return new Promise((resolve,reject) => {
fs.readFile('./.filesToUpdate.txt','utf8',(err,data) => {
if (err) {
reject(`no files found to update`)
} else {
let updateList = data.split("\n")
resolve(updateList);
}
})
});
}
async function doUpdate(list) {
return new Promise(async (resolve, reject) => {
for (let i = 0; i < list.length; i++) {
if (list[i] !== '') {
//check if this file is in a folder, if it does not exist yet, make it
let folder = list[i].split("/")[0]; //get the folder
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
await downloadFile('https://csd.hku.nl/sysbas/csdoscHelper/csdosc/'+list[i],list[i])
.catch( error => {
reject(error);
})
}
}
resolve("De update is geslaagd! Dit programma zal nu worden afgesloten, start het daarna opnieuw op door npm start te typen");
});
}
async function updateSucces(result) {
let today = formatDate();
fs.writeFile('./.lastUpdate.txt',today,'utf8',error => {
if (error)console.log(error);
console.log(result);
killOsc()
process.exit(0);
});
}
function formatDate() {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}