forked from kwnevarez/particle-device-locator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
249 lines (224 loc) · 8.73 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
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
// Copyright 2015-2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Sample of web sockets for Google App Engine
// https://github.com/GoogleCloudPlatform/nodejs-docs-samples/tree/master/appengine/websockets
'use strict';
const http = require('http');
const request = require('request');
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
const session = require('express-session');
const bodyParser = require('body-parser');
const Particle = require('particle-api-js');
const fs = require('fs');
const particle = new Particle();
const urlencodedParser = bodyParser.urlencoded({
extended: false
})
var websocket;
const ws_port = '50051'; // https://cloud.google.com/shell/docs/limitations#outgoing_connections
const ws_route = '/ws';
var config = require("./config.json");
// In order to use websockets on App Engine, you need to connect directly to
// application instance using the instance's public external IP. This IP can
// be obtained from the metadata server.
const METADATA_NETWORK_INTERFACE_URL = 'http://metadata/computeMetadata/v1/' +
'/instance/network-interfaces/0/access-configs/0/external-ip';
function get_external_ip(cb) {
const options = {
url: METADATA_NETWORK_INTERFACE_URL,
headers: {
'Metadata-Flavor': 'Google'
}
};
request(options, (err, resp, body) => {
if (err || resp.statusCode !== 200) {
console.log('Error while talking to metadata server, assuming localhost');
cb('localhost');
return;
}
cb(body);
});
}
// session middleware
// Warning The default server-side session storage, MemoryStore, is purposely not
// designed for a production environment. It will leak memory under most conditions,
// does not scale past a single process, and is meant for debugging and developing.
// for a list of compatible, production read stores, see:
// https://github.com/expressjs/session#compatible-session-stores
// or https://cloud.google.com/appengine/docs/flexible/nodejs/using-redislabs-memcache
app.use(session({
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'shhhh, very very secret',
}));
// session persisted message middleware
app.use(function(req, res, next) {
var msg = req.session.message;
delete req.session.message;
res.locals.message = '';
if (msg) res.locals.message = '<p class="msg">' + msg + '</p>';
next();
});
// our websocket setup
app.ws(ws_route, (ws) => {
// simply grab the websocket and store so we can call it at a later time
// no need for event handling since the client should never be sending
// messages our way
websocket = ws;
ws.on('open', function(msg) {
console.log('websocket open');
});
ws.on('close', function(msg) {
console.log('websocket close');
});
ws.on('err', function(msg) {
console.log('websocket error');
});
ws.on('message', function(msg) {
console.log('websocket msg: ' + JSON.stringify(msg));
});
});
// default page leads you to login
app.get('/', (req, res) => {
res.redirect('/login');
});
app.get('/login', (req, res) => {
res.render("login.ejs");
});
// logs into particle then set up the event listener
app.post('/login', urlencodedParser, function(req, res) {
console.log('Logging in');
particle.login({
username: req.body.username,
password: req.body.password
}).then(function(data) {
console.log('logged in. Getting event stream');
req.session.token = data.body.access_token;
//Get your devices events
particle.getEventStream({
deviceId: 'mine',
auth: req.session.token
}).then(function(stream) {
console.log('Got event stream.');
stream.on('event', function(data) {
console.log('Event: ' + JSON.stringify(data));
// this is the event handler for particle events
// make sure we are only looking at the deviceLocator events
if (data.name.startsWith('hook-response/'+ config.event_name)) {
var device_id = data.name.split("/")[2];
var published_at = data.published_at;
data = JSON.parse(data.data);
var msg = JSON.stringify({
id: device_id,
pub: published_at,
pos: {
lat: data.location.lat,
lng: data.location.lng,
},
acc: data.accuracy
});
websocket.send(msg);
}
});
res.redirect('/map');
},
function(err) {
req.session.message = 'Get stream failed, please try again.' + err.shortErrorDescription;
res.redirect('/logout');
}
);
},
function(err) {
req.session.message = 'Login failed, please try again. ' + err.shortErrorDescription;
res.redirect('/login');
}
);
})
app.get('/logout', function(req, res) {
// destroy the user's session to log them out
// will be re-created next request
req.session.destroy(function() {
res.redirect('/');
});
});
// you have to be logged in to get the map page
function restrict(req, res, next) {
if (req.session.token) {
next();
} else {
req.session.message = 'Access denied! Login required.';
res.redirect('/login');
}
}
// render the map page with relevent ip and websocket information
app.get('/map', restrict, (req, res) => {
// render the map page
get_external_ip((external_ip) => {
console.log('External IP: ' + external_ip);
res.render("map.ejs", {
external_ip: external_ip,
ws_port: ws_port,
ws_route: ws_route,
map_api_key: config.map_api_key
});
});
});
function random_float(min, max) {
return Math.random() * (max - min) + min;
}
function random_int(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// fake the placement of a device, for testing
// ex: http://localhost:8080/send_event?id=123ABC&pub=2017-03-30T05:00:46.167Z&lat=39.043756699999996&lng=-77.4874416&acc=50
// for fully random use: http://localhost:8080/send_event
app.get('/send_event', restrict, (req, res) => {
console.log('params: '+ JSON.stringify(req.query));
websocket.send(JSON.stringify({
id: req.query.id || Math.floor(Math.random()*16777215).toString(16), // if no id is given create a random one
pub: req.query.pub || new Date().toISOString(), // 2017-03-30T05:00:46.167Z
pos: {
lat: parseFloat(req.query.lat) || random_float( -50.0, 70.0), // random lat and lng if none given
lng: parseFloat(req.query.lng) || random_float(-180.0, 180.0)
},
acc: parseInt(req.query.acc) || random_int(300, 3000) // if no accuracy is given create a random one
}));
res.send('Event!!');
});
// see what the external ip address is
app.get('/ip', (req, res) => {
get_external_ip((external_ip) => {
console.log('External IP: ' + external_ip);
res.send(externalIp);
});
});
// lauch our servers
if (module === require.main) {
// Start the websocket server
const wsServer = app.listen(ws_port, () => {
console.log('Websocket server listening on port %s', wsServer.address().port);
});
// Additionally listen for non-websocket connections on the default App Engine
// port 8080. Using http.createServer will skip express-ws's logic to upgrade
// websocket connections.
const PORT = process.env.PORT || 8080;
http.createServer(app).listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
}
module.exports = app;