This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 435
/
server.js
65 lines (56 loc) · 1.89 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
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const EventHubReader = require('./scripts/event-hub-reader.js');
const iotHubConnectionString = process.env.IotHubConnectionString;
if (!iotHubConnectionString) {
console.error(`Environment variable IotHubConnectionString must be specified.`);
return;
}
console.log(`Using IoT Hub connection string [${iotHubConnectionString}]`);
const eventHubConsumerGroup = process.env.EventHubConsumerGroup;
console.log(eventHubConsumerGroup);
if (!eventHubConsumerGroup) {
console.error(`Environment variable EventHubConsumerGroup must be specified.`);
return;
}
console.log(`Using event hub consumer group [${eventHubConsumerGroup}]`);
// Redirect requests to the public subdirectory to the root
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res /* , next */) => {
res.redirect('/');
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.broadcast = (data) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
try {
console.log(`Broadcasting data ${data}`);
client.send(data);
} catch (e) {
console.error(e);
}
}
});
};
server.listen(process.env.PORT || '3000', () => {
console.log('Listening on %d.', server.address().port);
});
const eventHubReader = new EventHubReader(iotHubConnectionString, eventHubConsumerGroup);
(async () => {
await eventHubReader.startReadMessage((message, date, deviceId) => {
try {
const payload = {
IotData: message,
MessageDate: date || Date.now().toISOString(),
DeviceId: deviceId,
};
wss.broadcast(JSON.stringify(payload));
} catch (err) {
console.error('Error broadcasting: [%s] from [%s].', err, message);
}
});
})().catch();