-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgustavsnode.js
390 lines (327 loc) · 10.2 KB
/
gustavsnode.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
const express = require('express')
const fetch = require("node-fetch");
const socket = require('socket.io');
//var http = require('http');
//var fs = require('fs');
const osc = require('osc-min');
const dgram = require('dgram');
// this is the raspberry pi's IP:
// var ip = '192.168.1.219';
// var ip = '0.0.0.0';
// var port = '3000';
// var port2 = '3001';
var app = express()
var dt = new Date();
dt.setHours(dt.getHours() + 2);
var timeIndex = 0;
// SMHIs api_url
const api_url = 'https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/18.102919/lat/59.336600/data.json';
const sun_url = 'https://api.sunrise-sunset.org/json?lat=59.336600&lng=18.102919'
//var socket;
var pcat;
var dtRise = new Date();
var dtSet = new Date();
var sunStatus;
var pcatIndex;
// Set up the server
var server = app.listen(process.env.PORT || 3000, listen);
// This call back just tells us that the server has started
function listen() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://' + host + ':' + port);
}
app.use(express.static(__dirname + '/public'));
console.log("Server up and running!");
/*
// not sure if this is doing anything... For the new http update this doesn't work.
var io = socket(server, {
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin,
"Access-Control-Allow-Credentials": true
};
res.writeHead(200, headers);
res.end();
}
});
*/
const io = socket(server);
// Register a callback function to run when we have an individual connection
// This is run for each individual user that connects
io.sockets.on('connection', newConnection);
async function getSun() {
try {
const response = await fetch(sun_url);
var hms = await response.json();
// Calculations for sunrise
var a = hms.results.sunrise.split(':');
var b = a[2].split(' ');
var hoursRise = parseInt(a[0]) + 1;
var minutesRise = parseInt(a[1]);
var secondsRise = parseInt(b[0]);
if (b[1] == 'PM') {
hoursRise = hoursRise + 12;
} else if (b[1] == 'AM') {}
dtRise.setHours(hoursRise);
dtRise.setMinutes(minutesRise);
dtRise.setSeconds(secondsRise);
console.log('Sun rises at: ' + dtRise);
var dt2 = new Date();
if (dtRise > dt2.getTime()) {
console.log('dtRise is bigger than current time, which means that the sun has not risen yet');
sunStatus = true;
} else {
console.log('dtRise is not bigger than current time, which means that the program was started after sunrine');
sunStatus = false;
}
// Calculations for sunset
var c = hms.results.sunset.split(':');
var d = c[2].split(' ');
var hoursSet = parseInt(c[0]) + 1;
var minutesSet = parseInt(c[1]);
var secondsSet = parseInt(d[0]);
if (d[1] == 'PM') {
hoursSet = hoursSet + 12;
} else if (d[1] == 'AM') {
// Do nothing
}
dtSet.setHours(hoursSet);
dtSet.setMinutes(minutesSet - 24);
// The -24 is 24 minutes from Pd's 2 minutes per fader movement * 12 faders.
// Because of this, The fade will be completed by the time the sun has set.
dtSet.setSeconds(secondsSet);
console.log('Sun sets at: ' + dtSet);
var hoursSet = dtSet.getHours();
var minutesSet = dtSet.getMinutes();
var sunData = {
hoursRise: hoursRise,
minutesRise: minutesRise,
hoursSet: hoursSet,
minutesSet: minutesSet,
sunStatus: sunStatus
};
sunData2(sunData);
} catch (err) {
console.log("getSun could not fetch data, check internet connection");
}
}
async function updatePcat() {
try {
const response = await fetch(api_url);
const data = await response.json();
var i;
for (i = 0; i < data.timeSeries[timeIndex].parameters.length; i++) {
const param = data.timeSeries[timeIndex].parameters[i];
if (param.name === 'pcat') {
pcatIndex = i;
}
}
// Updating pcat with the new updated pcatIndex.
pcat = data.timeSeries[timeIndex].parameters[pcatIndex].level;
console.log('pcat index is: ' + pcatIndex);
console.log('pcat value is: ' + pcat);
console.log('approved time: ' + data.approvedTime);
console.log('referenceTime: ' + data.referenceTime);
// If there's rain on startup, send rain on. Otherwise, do nothing.
if (pcat != 0) {
var smhiData = {
pcat: data.timeSeries[timeIndex].parameters[pcatIndex].level,
}
smhi(smhiData);
console.log('emitting to gustavsnode, pcat not equal to 0');
}
} catch (err) {
console.log("updatePcat could not fetch api data, check internet connection");
}
}
async function getISS() {
try {
const response = await fetch(api_url);
const data = await response.json();
var i;
for (i = 0; i < data.timeSeries[timeIndex].parameters.length; i++) {
const param = data.timeSeries[timeIndex].parameters[i];
if (param.name === 'pcat') {
pcatIndex = i;
}
}
// Updating pcat with the new updated pcatIndex.
pcat = data.timeSeries[timeIndex].parameters[pcatIndex].level;
console.log('Current time series is: ' + data.timeSeries[timeIndex].validTime);
console.log('pcatIndex = ' + pcatIndex);
if (pcat != data.timeSeries[timeIndex].parameters[pcatIndex].level) {
var smhiData = {
pcat: data.timeSeries[timeIndex].parameters[pcatIndex].level,
};
console.log('this should only be called if there is a change in pcat');
smhi(smhiData);
pcat = data.timeSeries[timeIndex].parameters[pcatIndex].level;
}
if (data.timeSeries[timeIndex].parameters[pcatIndex].level != 0) {
console.log('it is raining, call the socket.emit!');
// Does it ever start raining? getISS() is called once every hour,
// but this function should only be called on server startup,
// then if pcat changes. Need to write a new global function.
}
// '.' First, store pcat in a variable. Then, once every hour, call the API,
// compare the pcat value from the API with the one stored in the variable.
// If they do not equal, call the socket.emit.
} catch (err) {
console.log("getISS could not fetch data, check internet connection");
}
}
updatePcat();
getISS();
getSun();
//At first, getISS (that is, get the weather) and getSun is called.
//Then, getSun updates once every 24 hours.
//getISS should update once every hour, but it should only send data to Pd
//whenever it starts or stops raining.
setInterval(function () {
getSun();
}, 86400000);
setInterval(function () {
getISS();
}, 3600000)
async function sunData2(data) {
hoursRise = data.hoursRise;
minutesRise = data.minutesRise;
hoursSet = data.hoursSet;
minutesSet = data.minutesSet;
sunStatus = data.sunStatus;
console.log('sending sundata to pd')
var osc_msg = osc.toBuffer({
oscType: 'message',
address: '/sun',
args: [{
type: 'integer',
value: hoursRise
},
{
type: 'integer',
value: minutesRise
},
{
type: 'integer',
value: hoursSet
},
{
type: 'integer',
value: minutesSet
},
{
type: 'symbol',
value: sunStatus
}
]
});
udp_server.send(osc_msg, 0, osc_msg.length, 9999);
}
// This is for receiving OSC from Pd.
var udp_server = dgram.createSocket('udp4', function (msg, rinfo) {
var osc_message;
try {
osc_message = osc.fromBuffer(msg);
console.log(osc.fromBuffer(msg));
} catch (err) {
return console.log('Could not decode OSC message');
}
if (osc_message.address = '/mp3gate') {
//var x = parseInt(osc_message.args[0].value);
console.log("osc_messages is......" + x);
io.emit('osc', {
//value: parseInt(osc_message.args[0].value),
value: osc_message.args[0].value,
});
return console.log('Found an mp3gate adress. Returning.');
}
//ParseInt converts a string to an integer.
//Then it looks at the message.
var x = parseInt(osc_message.args[0].value);
console.log("osc_messages is......" + x);
remote_osc_ip = rinfo.address;
rinfo
io.emit('osc', { // this emits the change to sketch.js
x: parseInt(osc_message.args[0].value) || 0,
y: parseInt(osc_message.args[1].value) || 0
});
});
// We are given a websocket object in our function
function newConnection(socket) {
console.log('We have a new client: ' + socket.id);
// These functions are called on startup, then they're called with timed events.
socket.emit('getISS');
socket.emit('getRadar');
socket.emit('getZ');
let counter = 0;
setInterval(() => {
socket.emit('getISS', ++counter);
}, 3600000);
setInterval(() => {
socket.emit('getRadar', ++counter);
}, 60000);
socket.on('sunToPd', sunData2);
socket.on('checkboxToggle', mute);
socket.on('musicboxToggle', activateMusic);
socket.on('rainfall', sendRainfall);
async function sendRainfall(data) {
if (data > 45) { // Safety measure keeping installation from playing too loud
data = 45;
}
console.log('rainfall updated, z = ' + data);
let data_int = parseInt(data, 10);
var osc_msg = osc.toBuffer({
oscType: 'message',
address: '/z',
args: [{
type: 'integer',
value: data_int
}]
});
udp_server.send(osc_msg, 0, osc_msg.length, 9999);
}
async function mute(data) {
if (data) {
dt2 = new Date();
console.log('Weather installation was unmuted at ' + dt2.toLocaleDateString() + ' ' + dt2.toLocaleTimeString('en-US'));
} else {
dt2 = new Date();
console.log('Weather installation was muted at ' + dt2.toLocaleDateString() + ' ' + dt2.toLocaleTimeString('en-US'));
}
var osc_msg = osc.toBuffer({
oscType: 'message',
address: '/mute',
args: [{
type: 'symbol',
value: data
}]
});
udp_server.send(osc_msg, 0, osc_msg.length, 9999);
}
async function activateMusic(data) {
dt2 = new Date();
console.log('Music checkbox was set to ' + data + ' at ' + dt2.toLocaleDateString() + ' ' + dt2.toLocaleTimeString('en-US'));
var osc_msg = osc.toBuffer({
oscType: 'message',
address: '/musictoggle',
args: [{
type: 'symbol',
value: data
}]
});
udp_server.send(osc_msg, 0, osc_msg.length, 9999);
}
}
//tydligen behöver man en bind för att annars ändras porten dynamiskt.
udp_server.bind(9998);
console.log('Starting UDP server on UDP port 9998');
// function timeout(ms, promise) {
// return new Promise(function (resolve, reject) {
// setTimeout(function () {
// reject(new Error("timeout"))
// }, ms)
// promise.then(resolve, reject)
// })
// }