forked from ThingLabsIo/ThingLabs-IoT-Dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
78 lines (67 loc) · 2.81 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
var express = require('express.io')
var uuid = require('uuid');
var EventHubClient = require('azure-event-hubs').Client;
var IotHubClient = require('azure-iothub').Client;
var Message = require('azure-iot-common').Message;
app = express().http().io()
var iotHubConnectionString = process.env.THINGLABS_IOTHUB_CONNSTRING || ''
var eventHubConnectionString = process.env.THINGLABS_EVENTHUB_CONNSTRING || ''
var client = EventHubClient.fromConnectionString(eventHubConnectionString, 'thinglabseventhub')
// Setup your sessions, just like normal.
app.use(express.cookieParser())
app.use(express.session({secret: 'thinglabs'}))
// Session is automatically setup on initial request.
app.get('/', function(req, res) {
req.session.loginDate = new Date().toString()
res.sendfile(__dirname + '/index.html')
});
app.post('/:deviceId/led/:state', function (req, res) {
var deviceId = req.params.deviceId;
var ledState = req.params.state;
var messageData = '{"ledState":' + ledState + '}';
var client = IotHubClient.fromConnectionString(iotHubConnectionString);
client.open(function (err) {
if (err) {
console.Log('Could not open the connection to the service: ' + err.message);
} else {
client.send(deviceId, messageData, function (err) {
if (err) {
console.Log('Could not send the message to the service: ' + err.message);
} else {
client.close(function (err) {
if (err) {
console.Log('Could not close the connection to the service: ' + err.message);
}
});
}
});
}
});
res.status(200).end();
});
app.use(express.static(__dirname + '/static'));
// Instantiate an eventhub client
app.io.route('ready', function(req) {
// For each partition, register a callback function
client.getPartitionIds().then(function(ids) {
ids.forEach(function(id) {
var minutesAgo = 5;
var before = (minutesAgo*60*1000);
client.createReceiver('$Default', id, { startAfterTime: Date.now() - before })
.then(function(rx) {
rx.on('errorReceived', function(err) { console.log(err); });
rx.on('message', function(message) {
console.log(message.body);
var body = message.body;
try {
app.io.broadcast('data', body);
} catch (err) {
console.log("Error sending: " + body);
console.log(typeof(body));
}
});
});
});
});
});
app.listen(process.env.port || 7076)