Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
359 lines (321 loc) · 14.8 KB
/
Copy pathserver.js
File metadata and controls
359 lines (321 loc) · 14.8 KB
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
//NODE SERVER START
var express = require('express');
var app = express();
var config = require('./settings');
var faceRoutes = require('./routes/faceRoutes');
const fileUpload = require('express-fileupload');
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var logger = require('./logger/index').logger;
var logStr = 'CloudComputeEngine';
//var serial = require('node-serial-key');
var ip = require("ip");
var request = require('request');
var bodyParser = require('body-parser');
var azure = require('azure-storage');
var iothub = require('azure-iothub');
var eventHub = require('./communication/eventHub');
var port = config.port;
if (process.env && process.env.PORT) { port = process.env.PORT }
var blobStorage = azure.createBlobService(config.blobStorageAccountName, config.blobStorageAccessKey);
app.use(bodyParser.json());
app.use(fileUpload());
app.use(express.static(path.join(__dirname, 'Cameras')));
//ping mechanism
var topicSubscribe = require('./communication/IOTHub').topicSubscribe;
//computeId assigned by backend
var connectionString = config.iotHub.connectionString;
var registry = iothub.Registry.fromConnectionString(connectionString);
/**
* Invoking routes
*/
faceRoutes(app);
app.listen(port);
//Compute Engine's ping Mechanism
registerOnJetson();
//setInterval(registerOnJetson, config.pingInterval); // 15 mins
function registerOnJetson() {
console.log('\n\n _________________________________ CLOUD COMPUTE ENGINE STARTED ____________________________________\n\n');
logger.debug(' -----------------------------------------------------------------------------------------------');
logger.debug("Registering JETSON on Server....");
var jetsonDetails = {
"name": config.name,
"deviceType": config.deviceType,
"macId": config.serialKey,
"ipAddress": ip.address(),
"detectionAlgoritms": config.detectionAlgoritms,
"cameraSupported": config.cameraSupported,
"location": config.location,
"supportedShapes": config.supportedShapes,
"jetsonCamFolderLocation": config.camFolder,
"wayToCommunicate": config.wayToCommunicate,
"isCloudCompute": true
};
var options = {
rejectUnauthorized: false,
url: config.JetsonRegistrationURL,
method: 'POST',
json: jetsonDetails
};
request(options, function (error, response, body) {
if (error) {
logger.error("Error Registering the device");
}
else {
var computeEngineId = response.body._id;
logger.debug("Success in Registering!::computeEngineId ::", computeEngineId);
config.tier = response.body.tier;
// Setting default tier value
if (config.tier == 0) {
config.endPoint = config.endPointFree;
config.textEndpoint = config.textEndpointFree;
config.faceApiSubscriptionKey = config.faceApiSubscriptionKeyFree;
config.textSubscriptionKey = config.textSubscriptionKeyFree;
logger.debug(" ***** PRICING TIER UPDATED TO FREE ******");
}
else if (config.tier == 1) {
config.endPoint = config.endPointStandard;
config.textEndpoint = config.textEndpointStandard;
config.faceApiSubscriptionKey = config.faceApiSubscriptionKeyStandard;
config.textSubscriptionKey = config.textSubscriptionKeyStandard;
logger.debug(" ***** PRICING TIER UPDATED TO STANDARD ******");
}
//Face Detection
config.faceDetectionUrl = config.endPoint + "detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,emotion";
config.addFacesUrl = config.endPoint + "facelists/" + config.faceListId + "/persistedFaces?userData=";
config.findSimilarUrl = config.endPoint + "findsimilars";
config.getUserlistUrl = config.endPoint + "facelists/";
//Face Recognition
config.endpointRecognition = config.endPoint;
config.faceDetectionUrlRecognition = config.faceDetectionUrl;
config.addFacesUrlRecognition = config.endPoint + "facelists/" + config.faceListId + "/persistedFaces?userData=";
config.findSimilarUrlRecognition = config.endPoint + "findsimilars";
config.getUserlistUrlRecognition = config.endPoint + "facelists/";
//Text Recognition
config.textRecognitionUrl = config.textEndpoint + "ocr?language=en&detectOrientation=true";
config.textRecognize = config.textEndpoint + "recognizeText?mode=Printed"; //mode = Printed or Handwritten : By default it is set to Printed in controller
/**
* Algorithm Registration
*/
var algorithmDetails = {
"computeEngineId": computeEngineId,
"detectionAlgorithms": config.detectionAlgorithms,
}
var optionsAlgo = {
rejectUnauthorized: false,
url: config.registerAlgorithm,
method: 'POST',
json: algorithmDetails
};
request(optionsAlgo, function (error, response, body) {
if (error) {
logger.error("Error Registering the device");
logger.debug(' -----------------------------------------------------------------------------------------------');
} else {
logger.debug("Success in Registering Algorithms!");
//____________________IOTHub registration____________________
// Create a new device
var device = {
deviceId: computeEngineId
};
registry.create(device, function (err, deviceInfo, res) {
if (err) {
logger.error('error: ' + err.toString());
//if device already registered
registry.get(device.deviceId, function (err, deviceInfo, res) {
logger.debug("Got the device info\n");
var deviceConnectionString =
config.iotHub.connectionString.split(';')[0] + ";DeviceId=" + deviceInfo.deviceId + ";SharedAccessKey=" + deviceInfo.authentication.symmetricKey.primaryKey;
topicSubscribe(deviceConnectionString);
pingMechanismInterval(config.serialKey);
});
}
if (res)
console.log(' status: ' + res.statusCode + ' ' + res.statusMessage);
if (deviceInfo) {
var deviceConnectionString = config.iotHub.connectionString.split(';')[0] + ";DeviceId=" + deviceInfo.deviceId + ";SharedAccessKey=" + deviceInfo.authentication.symmetricKey.primaryKey;
topicSubscribe(deviceConnectionString);
pingMechanismInterval(config.serialKey);
}
});
logger.debug(' -----------------------------------------------------------------------------------------------');
}
});
}
});
}
/**
* Ping mechanism
* @param {*} serialNo
*/
var pingMechanismInterval = function (serialNo) {
setInterval(function () {
console.log('\n\n _________________________________ CLOUD COMPUTE ENGINE STARTED ____________________________________\n\n');
logger.debug(' -----------------------------------------------------------------------------------------------');
logger.debug("Registering JETSON on Server....");
var jetsonDetails = {
"name": config.name,
"deviceType": config.deviceType,
"macId": config.serialKey,
"ipAddress": ip.address(),
"detectionAlgoritms": config.detectionAlgoritms,
"cameraSupported": config.cameraSupported,
"location": config.location,
"supportedShapes": config.supportedShapes,
"jetsonCamFolderLocation": config.camFolder,
"wayToCommunicate": config.wayToCommunicate,
"isCloudCompute": true
};
var options = {
rejectUnauthorized: false,
url: config.JetsonRegistrationURL,
method: 'POST',
json: jetsonDetails
};
request(options, function (error, response, body) {
if (error) {
logger.error("Error Registering the device");
}
else {
var computeEngineId = response.body._id;
logger.debug("Success in Registering!::computeEngineId ::", computeEngineId);
config.tier = response.body.tier;
// Setting default tier value
if (config.tier == 0) {
config.endPoint = config.endPointFree;
config.textEndpoint = config.textEndpointFree;
config.faceApiSubscriptionKey = config.faceApiSubscriptionKeyFree;
config.textSubscriptionKey = config.textSubscriptionKeyFree;
logger.debug(" ***** PRICING TIER UPDATED TO FREE ******");
}
else if (config.tier == 1) {
config.endPoint = config.endPointStandard;
config.textEndpoint = config.textEndpointStandard;
config.faceApiSubscriptionKey = config.faceApiSubscriptionKeyStandard;
config.textSubscriptionKey = config.textSubscriptionKeyStandard;
logger.debug(" ***** PRICING TIER UPDATED TO STANDARD ******");
}
//Face Detection
config.faceDetectionUrl = config.endPoint + "detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,emotion";
config.addFacesUrl = config.endPoint + "facelists/" + config.faceListId + "/persistedFaces?userData=";
config.findSimilarUrl = config.endPoint + "findsimilars";
config.getUserlistUrl = config.endPoint + "facelists/";
//Face Recognition
config.endpointRecognition = config.endPoint;
config.faceDetectionUrlRecognition = config.faceDetectionUrl;
config.addFacesUrlRecognition = config.endPoint + "facelists/" + config.faceListId + "/persistedFaces?userData=";
config.findSimilarUrlRecognition = config.endPoint + "findsimilars";
config.getUserlistUrlRecognition = config.endPoint + "facelists/";
//Text Recognition
config.textRecognitionUrl = config.textEndpoint + "ocr?language=en&detectOrientation=true";
config.textRecognize = config.textEndpoint + "recognizeText?mode=Printed"; //mode = Printed or Handwritten : By default it is set to Printed in controller
/**
* Algorithm Registration
*/
var algorithmDetails = {
"computeEngineId": computeEngineId,
"detectionAlgorithms": config.detectionAlgorithms,
}
var optionsAlgo = {
rejectUnauthorized: false,
url: config.registerAlgorithm,
method: 'POST',
json: algorithmDetails
};
request(optionsAlgo, function (error, response, body) {
if (error) {
logger.error("Error Registering the device");
logger.debug(' -----------------------------------------------------------------------------------------------');
} else {
logger.debug("Success in Registering Algorithms!");
logger.debug(' -----------------------------------------------------------------------------------------------');
}
});
}
});
}, config.pingInterval);
}
//Create a new facelist if does not exists - Free
var reqBody = {
"name": config.faceListName,
"userData": config.faceListUserData
}
var headers =
{
'Ocp-Apim-Subscription-Key': config.faceApiSubscriptionKeyFree,
'Content-Type': 'application/json'
}
var optionsCreateApi =
{
url: config.createFacelistRecognitionFree,
method: 'PUT',
headers: headers,
json: reqBody
}
request(optionsCreateApi, function (error, response, body) {
if (!error) {
if (!body) {
logger.debug('FaceList created in FREE TIER ');
}
else {
if (body.error.code == 'FaceListExists') {
logger.error('FaceList already Exists - FREE TIER ');
}
}
}
else {
logger.error("Error in creating FaceList in FREE TIER : ", error);
}
})
//Create a new facelist if does not exists - Standard
var reqBodyStandard = {
"name": config.faceListName,
"userData": config.faceListUserData
}
var headersStandard =
{
'Ocp-Apim-Subscription-Key': config.faceApiSubscriptionKeyStandard,
'Content-Type': 'application/json'
}
var optionsCreateApiStandard =
{
url: config.createFacelistRecognitionStandard,
method: 'PUT',
headers: headersStandard,
json: reqBodyStandard
}
request(optionsCreateApiStandard, function (error, response, body) {
if (!error) {
if (!body) {
logger.debug('FaceList created in STANDARD TIER ');
}
else {
if (body.error.code == 'FaceListExists') {
logger.error('FaceList already Exists - STANDARD TIER ');
}
}
}
else {
logger.error("Error in creating FaceList in STANDARD TIER : ", error);
}
})
//Create new container for BLOB if does not exists
blobStorage.createContainerIfNotExists(config.blobContainerName, {
publicAccessLevel: 'container'
},
function (error, result, response) {
if (error) {
logger.error('Error : ', error);
// logger.debug(' -----------------------------------------------------------------------------------------------');
//process.exit();
}
else if (result.created == true) {
logger.debug('Container Created for Storing BLOB.');
// logger.debug(' -----------------------------------------------------------------------------------------------');
}
else {
logger.error('Container already Exists !!!');
// logger.debug(' -----------------------------------------------------------------------------------------------');
}
});