-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
67 lines (56 loc) · 1.58 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
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const moment = require('moment');
const path = require('path');
const iotHubClient = require('./IoTHub/iot-hub.js');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res/*, next*/) {
res.redirect('/');
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
try {
console.log('sending data ' + data);
client.send(data);
} catch (e) {
console.error(e);
}
}
});
};
var iotHubReader = new iotHubClient(process.env['Azure.IoT.IoTHub.ConnectionString'], process.env['Azure.IoT.IoTHub.ConsumerGroup']);
iotHubReader.startReadMessage(function (obj, date) {
try {
console.log(date);
date = date || Date.now()
wss.broadcast(JSON.stringify(Object.assign(obj, { time: moment.utc(date).format('YYYY:MM:DD[T]hh:mm:ss') })));
} catch (err) {
console.log(obj);
console.error(err);
}
});
var port = normalizePort(process.env.PORT || '3000');
server.listen(port, function listening() {
console.log('Listening on %d', server.address().port);
});
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}