-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1983 lines (1718 loc) · 64 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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable linebreak-style */
/* eslint-disable no-param-reassign */
/* eslint-disable dot-notation */
/* eslint-disable no-console */
/**
* FordConnect API Simulator.
*
* This simulator is only intended for use by someone that is already authorized by Ford to use
* the FordConnect API, for example [Ford Smart Vehicle Connectivity Challenge]
* (https://fordsmart.devpost.com/). Please ensure you also test your application against the
* FordConnect API provided by Ford; using a test VIN if needed.
*
* The purpose of this project is to simulate the API from FordConnect, while enabling the user
* to test various scenarios without having to have a vehicle to perform the test scenarios. For
* example, you can change the location of the vehicle, change fuel level, etc. This simulator
* is intented to run on your local development environment. If your application cannot access
* your local development environment, you make need to use ngrok.com to expose it on the internet.
*
* Error descriptions/messages are not idential to FordConnect server, but status codes should
* match.
*
* The oauth2 route is slightly different than the FordConnect route, and it uses the server
* provided value for the 'code' variable (not the one from the oauth2 redirect).
*
* Tokens expire after 20 minutes.
*
* Supported Environment Variables:
* FORDSIM_HTTPPORT = 80 (The HTTP port that the service will listen on. Default = 80)
* FORDSIM_CODE = SomeCode (Any special access code. Default = auto-generated code.)
* FORDSIM_TOKEN = SomeToken (Any special access token. Default = auto-generated token.)
* FORDSIM_TIMEOUT = 1200 (Number of seconds before code + access token expire. Default = 1200)
* FORDSIM_CMDTIMEOUT = 120 (Number of seconds before commandId values expire. Default = 120)
*
* If you have a new mock vehicle, update vehicles.js with an additional export.
*
*/
// Contributors to the simulator, please search for "TEST:", "REVIEW:", "TODO:" and "SECURITY:"
// comments & also look at issues at https://github.com/jamisonderek/ford-connect-sim/issues.
const express = require('express');
const http = require('http');
const https = require('https');
const formidable = require('express-formidable');
const path = require('path');
const fs = require('fs');
const { createWriteStream } = require('fs');
const timestamp = require('./timestamp');
const mockVehicles = require('./vehicles');
const { toBoolean, toFloat } = require('./convert');
const { toDoor, toRole, toState } = require('./convert');
const { toDirection } = require('./convert');
const { makeGuid } = require('./guid');
const { getAccessTokenTimeout, getCodeTimeout } = require('./timeout');
const { getTokenFromRequest, isTokenExpired, isValidRefreshToken } = require('./token');
const { generateToken, isValidApplicationId } = require('./token');
const { isValidMake, isValidYear } = require('./validate');
const { isValidClientId, isValidClientSecret, isValidRedirectUri } = require('./validate');
const { commands, createCommand, getCommand } = require('./command');
const {
updateTokenFromCode,
refreshToken,
getVehicles,
getDetails,
imageFull,
imageThumbnail,
getDepartureTimes,
getChargeSchedule,
} = require('./fordConnect/fordConnect');
const app = express();
/**
* This is a wrapper for all of the async app calls, so exceptions get forwared on to the next
* handler.
*
* @param {*} fn the async function to wrap.
* @returns a wrapped function.
*/
function asyncAppWrapper(fn) {
if (process.env.NODE_ENV !== 'test') {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
}
return (req, res, next) => { fn(req, res, next); };
}
/**
* Returns an object with extra properties about the vehicle. Most of the properties can be
* used to determine the current state of the vehicle.
*
* @param {*} full Name of large image image.
* @param {*} thumbnail Name of thumbnail image.
* @returns The extra property for the vehicle, or undefined.
*/
function makeExtra(full, thumbnail) {
return {
doorsLocked: true,
doorsLockedTimestamp: timestamp.now(),
alarmEnabled: false,
alarmTriggered: false,
alarmTimestamp: timestamp.now(),
lastStarted: 0, // These are Date.now() values.
lastStopped: 0,
lastWake: 0,
lastStartCharge: 0,
lastStopCharge: 0,
image: full === undefined ? 'full-image.png' : full,
imageThumbnail: thumbnail === undefined ? 'thumbnail.png' : thumbnail,
};
}
const vehicles = [];
vehicles.push({
vehicle: mockVehicles.ice1,
info: mockVehicles.ice1_info,
extra: makeExtra('full-image.png', 'thumbnail.png'),
});
// IMPORTANT: Put your list of test vehicles here. See the README.md file for directions.
vehicles.push({
vehicle: mockVehicles.ice2,
info: undefined,
extra: makeExtra('full-image.png', 'thumbnail.png'),
});
vehicles.push({
vehicle: mockVehicles.ev1,
info: mockVehicles.ev1_info,
extra: makeExtra('full-image.png', 'thumbnail.png'),
evdata: mockVehicles.ev1_evdata,
});
// This code is here just to enforce that the above code added at least 1 vehicle.
if (vehicles.length < 1) {
console.error('ERROR: Please add at least 1 vehicle.');
process.exit(1);
} else {
console.log(vehicles);
}
const httpPort = parseInt(process.env.FORDSIM_HTTPPORT, 10) || 80;
const httpServer = http.createServer(app);
if (process.env.NODE_ENV !== 'test') {
console.log(`Listening on port ${httpPort}`);
httpServer.listen(httpPort);
} else {
console.log('WARNING: Environment set to "test" so not enabling listener.');
}
// We have POST data for our OAuth2 routes. Use express-formidable middleware to parse.
app.use(formidable());
// The code is only good until the codeExpireTimestamp.
let code = process.env.FORDSIM_CODE || `Code${makeGuid()}`;
let codeExpireTimestamp = Date.now() + getCodeTimeout() * 1000;
console.log(`Code is: ${code}`);
/**
* Returns user controlled data for use in a JSON response. In general, returning user controlled
* data in your response is a bad idea from security perspective. Always use this method when
* returning user controlled data, so that the security review is easier.
*
* @param {*} value User controlled data.
* @returns User controlled data.
*/
function reflectedUserInput(value) {
// TEST: Does the FordConnect server escape the data?
return value;
}
/**
* Returns a deep copy of the item specified, so that any modifications will not impact the
* original object. NOTE: This does not handle copying properties that are set to undefined.
*
* @param {*} item The item to make a copy of.
* @returns A copy of the item.
*/
function DeepCopy(item) {
return JSON.parse(JSON.stringify(item));
}
/**
* Sends an HTTP 400 response that the vehicleId parameter was not the proper length.
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The res.json result.
*/
function sendBadVehicleIdLength(req, res) {
res.statusCode = 400;
// No Vehicleid header is sent back.
return res.json({
errorCode: '400',
errorMessage: 'getVehicleV3.vehicleId: Invalid vehicleId, getVehicleV3.vehicleId: size must be between 32 and 32',
});
}
/**
* Sends an HTTP 400 response that the make parameter was not a valid value.
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The res.json result.
*/
function sendBadMakeParameter(req, res) {
// REVIEW: FordConnect server currently returns 500 status code, but we are returning 400.
res.statusCode = 400;
// No Vehicleid header is sent back.
return res.json({
errorCode: '400',
errorMessage: 'Invalid make parameter. Must be one of: "F", "Ford", "L", "Lincoln".',
});
}
/**
* Sends an HTTP 400 response that the year parameter was not a valid value.
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The res.json result.
*/
function sendBadYearParameter(req, res) {
// REVIEW: FordConnect currently returns 500 status code, but we are returning 400.
res.statusCode = 400;
// No Vehicleid header is sent back.
return res.json({
errorCode: '400',
errorMessage: 'Invalid year parameter. Must be four digit format (like 2019).',
});
}
/**
* Sends an HTTP 401 response that the applicationId is not valid.
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The res.json result.
*/
function sendInvalidApplicationId(req, res) {
const appId = req.headers['application-id'];
res.statusCode = 401;
// No Vehicleid header is sent back.
const message = `Access denied due to ${appId === undefined ? 'missing' : 'invalid'} subscription key.`;
return res.json({
statusCode: 401,
message,
});
}
/**
* Sends an HTTP 401 response that the access token is expired.
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The res.json result.
*/
function sendTokenExpiredJson(req, res) {
res.statusCode = 401;
// No Vehicleid header is sent back.
return res.json({
error: 'invalid_token',
error_description: `Access token expired: ${reflectedUserInput(getTokenFromRequest(req))}`,
});
}
/**
* Sends an HTTP 401 response that the user is not authorized.
* @param {*} req The request object.
* @param {*} res The response object.
* @param {*} commandId The commandId the user specified or undefined.
* @param {*} vehicleId The vehicleId the user specified or undefined.
*
* @returns The res.json result.
*/
function sendUnauthorizedUser(req, res, commandId, vehicleId) {
res.statusCode = 401;
const response = {
error: {
code: 3000,
title: 'Unauthorized user',
details: 'The user is unauthorized.',
statusCode: 'UNAUTHORIZED',
},
status: 'FAILED',
commandStatus: 'FAILED',
};
if (commandId !== undefined) {
response.commandId = reflectedUserInput(commandId);
}
if (vehicleId) {
res.setHeader('Vehicleid', vehicleId);
}
return res.json(response);
}
/**
* Sends an HTTP 404 response that the resource was not found.
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The res.json result.
*/
function sendNotFound(req, res) {
const { vehicleId } = req.params;
res.statusCode = 404;
if (vehicleId) {
res.setHeader('Vehicleid', reflectedUserInput(vehicleId));
}
const response = {
error: {
code: 4002,
title: 'Resource not found',
details: 'The resource was not found.',
statusCode: 'NOT_FOUND',
},
status: 'FAILED',
};
if (req.method === 'POST') {
if (req.originalUrl.indexOf('Charge') > 0) {
response.commandStatus = 'FAILED';
} else {
response.commandStatus = 'EMPTY';
}
} else {
// eslint-disable-next-line no-lonely-if
if (req.originalUrl.indexOf('/chargeSchedules') > 0) {
response.chargeSchedules = null;
} else if (req.originalUrl.indexOf('/departureTimes') > 0) {
response.departureTimes = null;
} else if (
(req.originalUrl.indexOf('/unlock') > 0)
|| (req.originalUrl.indexOf('/lock') > 0)
|| (req.originalUrl.indexOf('/startEngine') > 0)
|| (req.originalUrl.indexOf('/stopEngine') > 0)) {
response.commandStatus = 'EMPTY';
}
}
return res.json(response);
}
/**
* Sends an HTTP 401/406 response that the vehicle is not authorized.
* @param {*} req The request object.
* @param {*} res The response object.
* @param {*} isPost Boolean. true if request is POST, false if GET.
* @param {*} vehicleId The vehicleId the user specified or undefined.
* @param {*} addNullDepartureTimes If set, then a null depatureTimes will be added.
* @returns The res.json result.
*/
function sendVehicleNotAuthorized(req, res, isPost, vehicleId, addNullDepartureTimes) {
if (isPost) {
return sendUnauthorizedUser(req, res, undefined, vehicleId);
}
res.statusCode = 406;
const response = {
error: {
code: 4006,
title: 'Not Acceptable',
details: 'Not acceptable',
statusCode: 'NOT_ACCEPTABLE',
},
status: 'FAILED',
};
if (addNullDepartureTimes) {
response.departureTimes = null;
}
if (vehicleId) {
res.setHeader('Vehicleid', vehicleId);
}
return res.json(response);
}
/**
* Sends an HTTP 406 response when a vehicleId does not have feature (like when issuing an
* EV command to an ICE vehicle.)
*
* @param {*} req The request object.
* @param {*} res The response ojbect.
* @returns The res.json result.
*/
function sendUnsupportedVehicle(req, res) {
const { vehicleId } = req.params;
res.statusCode = 406;
res.setHeader('Vehicleid', reflectedUserInput(vehicleId));
return res.json({
error: {
code: 4006,
title: 'Vehicle not supported for this command',
details: 'Vehicle not supported for this command',
statusCode: 'NOT_ACCEPTABLE',
},
status: 'FAILED',
commandStatus: 'FAILED',
});
}
/**
* Updates the access token and refresh token. Sends a response with the new tokens.
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The res.json result.
*/
function sendRefreshTokenResponse(req, res) {
const now = Date.now();
console.log('Updating token');
const token = generateToken();
const simRefreshToken = generateToken(undefined, true);
return res.json({
access_token: token.key,
id_token: 'eyJAAA==', // Stub - we don't use this.
token_type: 'Bearer',
not_before: Math.trunc(now / 1000),
expires_in: getAccessTokenTimeout(),
expires_on: Math.trunc(token.expires / 1000),
resource: 'c1e4c1a0-2878-4e6f-a308-836b34474ea9',
id_token_expires_in: getAccessTokenTimeout(),
profile_info: 'ejyAAA==', // Stub - we don't use this.
scope: 'https://simulated-environment.onmicrosoft.com/fordconnect/access openid offline_access',
refresh_token: simRefreshToken.key,
refresh_token_expires_in: 7776000, // 90 days.
});
}
/**
* Returns the vehicle object that has a vehicleId matching the vehicleId query parameter. If no
* matching vehicle is found, a JSON response will be sent using the response object and undefined
* will be returned.
*
* @param {*} req The request object.
* @param {*} res The response object.
* @returns The matching vehicle object from the glocal vehicles variable, or undefined if no match.
*/
function getVehicleOrSendError(req, res) {
// TODO: Refactor this method so the caller doesn't need to return undefined.
const { vehicleId } = req.params;
if (!vehicleId || vehicleId.length !== 32) {
sendBadVehicleIdLength(req, res);
return undefined;
}
const matches = vehicles.filter((v) => v.vehicle.vehicleId === vehicleId);
if (!matches || matches.length === 0) {
sendNotFound(req, res);
return undefined;
}
if (!matches[0].vehicle.vehicleAuthorizationIndicator) {
sendVehicleNotAuthorized(req, res, true, reflectedUserInput(vehicleId));
return undefined;
}
return matches[0];
}
/**
* Internal method for sending the oauth response.
* @param {*} req The client request object.
* @param {*} res The response object.
* @returns res.json A response will be sent.
*/
function oauth(req, res) {
let msg = '';
if (!isValidClientId(req.fields['client_id'])) {
msg = 'ERROR: Client_id not expected value.';
} else if (!isValidClientSecret(req.fields['client_secret'])) {
msg = 'ERROR: client_secret not expected value.';
} else if (req.fields['grant_type'] === 'refresh_token') {
if (isValidRefreshToken(req.fields['refresh_token'])) {
return sendRefreshTokenResponse(req, res);
}
msg = 'ERROR: Refresh token not expected value.';
} else if (req.fields['grant_type'] === 'authorization_code') {
if (!isValidRedirectUri(req.fields['redirect_uri'])) {
msg = 'ERROR: invalid redirect_url.';
} else if (req.fields['code'] === code || (code === '*' && req.fields['code'])) {
if (Date.now() < codeExpireTimestamp) {
return sendRefreshTokenResponse(req, res);
}
// REVIEW: We are exposing the fact the code *was* valid by giving different error.
msg = 'ERROR: invalid code parameter (Only good for 20 minutes. Restart server.)';
} else {
msg = 'ERROR: invalid code parameter. (See server startup output, don\'t use real OAUTH code.)';
}
} else {
msg = 'ERROR: grant_type not expected value.';
}
console.error(msg);
return res.json({ error: 'invalid request', error_description: msg });
}
app.post('/oauth2/v2.0/token', asyncAppWrapper((req, res) => oauth(req, res)));
app.post('/:guid/oauth2/v2.0/token', asyncAppWrapper((req, res) => oauth(req, res)));
app.get('/api/fordconnect/vehicles/v1', asyncAppWrapper((req, res) => {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);
}
return res.json({ status: 'SUCCESS', vehicles: vehicles.map((v) => v.vehicle) });
}));
/**
* Checks if a vehicle supports EV functions.
*
* @param {*} engineType The engine type.
* @returns Boolean. true if the vehicle supports EV functions.
*/
function isEV(engineType) {
// PHEV (Plug-in Hybrid Electric Vehicle) and BEV (Battery Electric Vehicle) are EVs.
// ICE (Internal Combustion Engine) is NOT an EV.
return engineType && engineType.toUpperCase().indexOf('EV') >= 0;
}
/**
* Processes a POST message for a vehicleId and invokes the callback method with the vehicle
* and command object.
*
* @param {*} req The request object.
* @param {*} res The response object.
* @param {*} requiresEv Boolean. Set to true if the API requires EV vehicle.
* @param {*} fn Callback function(req, res, matchedVehicle, commandObject).
* @returns The res.json result, or undefined in some error cases.
*/
function vehicleIdPostMethod(req, res, requiresEv, fn) {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);
}
const match = getVehicleOrSendError(req, res);
if (match) {
if (requiresEv && match.info && !isEV(match.info.engineType)) {
return sendUnsupportedVehicle(req, res);
}
const command = createCommand(match.vehicle.vehicleId);
// Invoke the callback function, with the matching vehicle and command object.
fn(req, res, match, command);
const response = {
status: 'SUCCESS',
commandStatus: 'COMPLETED',
commandId: command.commandId,
};
res.statusCode = 202;
res.setHeader('Vehicleid', match.vehicle.vehicleId);
return res.json(response);
}
return undefined; // getVehicleOrSendError send response.
}
/**
* Processes a GET message for a vehicleId and invokes the callback method with the vehicle
* and command object.
* @param {*} req The request object.
* @param {*} res THe response object.
* @param {*} commandArray An array of command objects, or undefinded to use all command objects.
* @param {*} fn Callback function(req, res, matchedVehicle, commandObject).
* @param {*} successCode The HTTP code to return on success.
* @returns The res.json result, or undefined in some error cases.
*/
function vehicleIdGetCommandStatus(req, res, commandArray, fn, successCode) {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);
}
const match = getVehicleOrSendError(req, res);
if (match) {
const command = getCommand(req, commandArray);
if (command === undefined) {
const { commandId } = req.params;
return sendUnauthorizedUser(res, res, reflectedUserInput(commandId), match.vehicle.vehicleId);
}
// Change the commandStatus based on how long ago the original POST request was.
const statuses = command.commandStatuses.split(';');
for (let i = 0; i < statuses.length; i += 1) {
const s = statuses[i].split(',');
const deltaTime = parseInt(s[0], 10);
const status = s[1];
if (deltaTime === -1 || (Date.now() < command.timestamp + deltaTime)) {
command.commandStatus = status;
break;
}
}
const response = {
status: 'SUCCESS',
commandStatus: command.commandStatus,
commandId: command.commandId,
};
// Invoke the callback function, with the matching vehicle and command object.
fn(req, res, match, command, response);
res.statusCode = (successCode === undefined) ? 200 : successCode;
res.setHeader('Vehicleid', match.vehicle.vehicleId);
return res.json(response);
}
return undefined; // getVehicleOrSendError send response.
}
/**
* Processes a GET request for a vehicle image (full or thumbnail).
* @param {*} req The request object.
* @param {*} res THe response object.
* @param {*} fn Callback function(matchedVehicle).
* @returns The res.json result, or undefined in some error cases.
*/
function vehicleIdGetImage(req, res, fn) {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);
}
const { make } = req.query;
if (make === undefined) {
res.statusCode = 404;
return res.json({ statusCode: 404, message: 'Resource not found' });
}
if (!isValidMake(make)) {
return sendBadMakeParameter(req, res);
}
const { model } = req.query;
if (model === undefined) {
res.statusCode = 404;
return res.json({ statusCode: 404, message: 'Resource not found' });
}
const { year } = req.query;
if (year === undefined) {
res.statusCode = 404;
return res.json({ statusCode: 404, message: 'Resource not found' });
}
if (!isValidYear(year)) {
return sendBadYearParameter(req, res);
}
const match = getVehicleOrSendError(req, res);
if (match) {
const options = {
root: path.join(__dirname, 'images'),
cacheControl: false,
};
const imageName = fn(match);
// TODO: Send same cache headers as FordConnect server.
res.setHeader('Vehicleid', match.vehicle.vehicleId);
return res.sendFile(imageName, options);
}
return undefined; // getVehicleOrSendError send response.
}
app.post('/api/fordconnect/vehicles/v1/:vehicleId/unlock', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, false, (_req, _res, match, command) => {
commands.unlock.push(command);
match.extra.doorsLocked = false;
match.extra.doorsLockedTimestamp = timestamp.now();
});
}));
app.get('/api/fordconnect/vehicles/v1/:vehicleId/unlock/:commandId', asyncAppWrapper((req, res) => {
vehicleIdGetCommandStatus(req, res, commands.unlock, () => { });
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/lock', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, false, (_req, _res, match, command) => {
commands.lock.push(command);
match.extra.doorsLocked = true;
match.extra.doorsLockedTimestamp = timestamp.now();
});
}));
app.get('/api/fordconnect/vehicles/v1/:vehicleId/lock/:commandId', asyncAppWrapper((req, res) => {
vehicleIdGetCommandStatus(req, res, commands.lock, () => { });
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/startEngine', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, false, (_req, _res, match, command) => {
commands.startEngine.push(command);
match.extra.lastStarted = Date.now();
match.info.vehicleStatus.remoteStartStatus = {
status: 'ENGINE_RUNNING',
duration: 0, // #10 - TODO: Does this need to change over time?
timeStamp: timestamp.now(),
};
match.info.vehicleStatus.ignitionStatus.value = 'ON';
});
}));
app.get('/api/fordconnect/vehicles/v1/:vehicleId/startEngine/:commandId', asyncAppWrapper((req, res) => {
vehicleIdGetCommandStatus(req, res, commands.startEngine, () => { });
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/stopEngine', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, false, (_req, _res, match, command) => {
commands.stopEngine.push(command);
match.extra.lastStarted = Date.now();
match.info.vehicleStatus.remoteStartStatus = {
status: 'ENGINE_STOPPED',
duration: 0, // #10 - TODO: Does this need to change over time (minutes)?
timeStamp: timestamp.now(),
};
match.info.vehicleStatus.ignitionStatus.value = 'OFF';
});
}));
app.get('/api/fordconnect/vehicles/v1/:vehicleId/stopEngine/:commandId', asyncAppWrapper((req, res) => {
vehicleIdGetCommandStatus(req, res, commands.stopEngine, () => { });
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/wake', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, false, (_req, _res, match, command) => {
commands.wake.push(command);
match.extra.lastWake = Date.now();
});
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/startCharge', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, true, (_req, _res, match, command) => {
commands.startCharge.push(command);
match.extra.lastStartCharge = Date.now();
});
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/stopCharge', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, true, (_req, _res, match, command) => {
commands.stopCharge.push(command);
match.extra.lastStopCharge = Date.now();
});
}));
/**
* Compares two coordinates (lat, long) to see if they are 'near' each other.
* @param {*} lat1 Latitude for coordinate 1
* @param {*} long1 Longitude for coordinate 1
* @param {*} lat2 Latitude for coordinate 2
* @param {*} long2 Longitude for coordinate 2
* @returns Boolean. true is coordinate 1 and coordinate 2 are near each other.
*/
function near(lat1, long1, lat2, long2) {
// For latitude a delta of 0.001 is about 360 feet
// For longitude a delta of 0.001 depends on your latitude. (It is about 360 feet
// near the equator & only about 200 feet near northern Canada.)
return Math.abs(lat1 - lat2) < 0.001 && Math.abs(long1 - long2) < 0.001;
}
app.get('/api/fordconnect/vehicles/v1/:vehicleId/chargeSchedules', asyncAppWrapper((req, res) => {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);
}
const match = getVehicleOrSendError(req, res);
if (match) {
let nearbySchedule;
if (match.evdata && (match.info && isEV(match.info.engineType))) {
const matchLat = parseFloat(match.info.vehicleLocation.latitude);
const matchLong = parseFloat(match.info.vehicleLocation.longitude);
for (let i = 0; i < match.evdata.chargeSchedules.length; i += 1) {
const s = match.evdata.chargeSchedules[i];
const sLat = parseFloat(s.latitude);
const sLong = parseFloat(s.longitude);
if (near(matchLat, matchLong, sLat, sLong)) {
nearbySchedule = s;
}
}
}
const response = {
status: 'SUCCESS',
// TEST: #23 - What is FordConnect API response if we aren't near any chargers?
// For now we just return an empty array.
chargeSchedules: (nearbySchedule !== undefined) ? nearbySchedule.schedule : [],
};
if (nearbySchedule && response.chargeSchedules) {
for (let i = 0; i < response.chargeSchedules.length; i += 1) {
response.chargeSchedules[i].desiredChargeLevel = nearbySchedule.desiredChargeLevel;
}
}
res.statusCode = 200;
res.setHeader('Vehicleid', match.vehicle.vehicleId);
return res.json(response);
}
return undefined; // getVehicleOrSendError send response.
}));
const DAYS = {
MONDAY: 1,
TUESDAY: 2,
WEDNESDAY: 3,
THURSDAY: 4,
FRIDAY: 5,
SATURDAY: 6,
SUNDAY: 7,
};
// NOTE: This is a simulated day, not actual day.
const today = {
hour: 16,
minutes: 10,
dayOfWeek: DAYS.THURSDAY,
};
/**
* The number of milliseconds until the departureTime event.
*
* @param {*} departureTime an evdata.departureTimes[x] object.
* @returns The number of milliseconds from today (simulated time) until the departureTime.
*/
function msUntilDepartureTime(departureTime) {
const dow = DAYS[departureTime.dayOfWeek];
// Create a timestamp (1-Mar-2021 was a Monday, 5-Mar-2021 was a Friday, etc.)
const dt = Date.parse(`${dow} Mar 2021 ${departureTime.time}`);
const nt = Date.parse(`${today.dayOfWeek} Mar 2021 ${today.hour}:${today.minutes}`);
let diff = dt - nt;
if (diff < 0) {
// The time was in the past, so add 7 days to find the next occurance.
diff += 7 * 24 * 60 * 60 * 1000;
}
return diff;
}
// Returns the next departure time.
app.get('/api/fordconnect/vehicles/v1/:vehicleId/departureTimes', asyncAppWrapper((req, res) => {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);
}
const match = getVehicleOrSendError(req, res);
if (match) {
if (match.info && !isEV(match.info.engineType)) {
return sendVehicleNotAuthorized(req, res, false, match.vehicle.vehicleId, true);
}
let response;
if (match.evdata && match.evdata.departureTimes && match.evdata.departureTimes.length > 0) {
let minIndex = 0;
let minValue = msUntilDepartureTime(match.evdata.departureTimes[0]);
for (let i = 0; i < match.evdata.departureTimes.length; i += 1) {
const v = msUntilDepartureTime(match.evdata.departureTimes[i]);
if (v < minValue) {
minValue = v;
minIndex = i;
}
}
response = {
status: 'SUCCESS',
departureTimes: {
dayOfWeek: match.evdata.departureTimes[minIndex].dayOfWeek,
enabled: true,
hour: parseInt(match.evdata.departureTimes[minIndex].time.split(':')[0], 10),
minutes: parseInt(match.evdata.departureTimes[minIndex].time.split(':')[1], 10),
preConditioningSetting: match.evdata.departureTimes[minIndex].preConditioningSetting,
},
};
} else {
response = {
status: 'SUCCESS',
departureTimes: {
dayOfWeek: 'MONDAY',
enabled: false,
hour: 0,
minutes: 0,
preConditioningSetting: 'OFF',
},
};
}
res.statusCode = 200;
res.json(response);
}
return undefined; // getVehicleOrSendError send response.
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/status', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, false, (_req, _res, match, command) => {
commands.status.push(command);
});
}));
app.get('/api/fordconnect/vehicles/v1/:vehicleId/statusrefresh/:commandId', asyncAppWrapper((req, res) => {
vehicleIdGetCommandStatus(req, res, commands.status, (_, __, match, command, response) => {
if (command.commandStatus === 'COMPLETED') {
let doorsLocked = match.extra.doorsLocked ? 'LOCKED' : 'UNLOCKED';
if (match.extra.doorsLocked === undefined) {
doorsLocked = 'ERROR';
}
const alarmEnabled = match.extra.alarmEnabled ? 'SET' : 'NOTSET';
let alarmValue = match.extra.alarmTriggered ? 'ACTIVE' : alarmEnabled;
if (match.extra.alarmTriggered === undefined) {
alarmValue = 'ERROR';
}
response.vehiclestatus = {
lockStatus: {
timestamp: match.extra.doorsLockedTimestamp,
value: doorsLocked,
},
alarm: {
timestamp: match.extra.alarmTimestamp,
value: alarmValue,
},
};
}
}, 202);
}));
app.get('/api/fordconnect/vehicles/v1/:vehicleId', asyncAppWrapper((req, res) => {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);
}
const match = getVehicleOrSendError(req, res);
if (match) {
const vehicleDetails = {
status: 'SUCCESS',
vehicle: (match.info === undefined) ? {
...DeepCopy(match.vehicle),
} : {
...DeepCopy(match.vehicle),
...DeepCopy(match.info),
},
};
return res.json(vehicleDetails);
}
return undefined; // getVehicleOrSendError send response.
}));
app.post('/api/fordconnect/vehicles/v1/:vehicleId/location', asyncAppWrapper((req, res) => {
vehicleIdPostMethod(req, res, false, (_req, _res, match, command) => {
// NOTE: This commandId isn't used for anything by FordConnect API.
commands.location.push(command);
});
}));
app.get('/api/fordconnect/vehicles/v1/:vehicleId/location', asyncAppWrapper((req, res) => {
if (!isValidApplicationId(req)) {
return sendInvalidApplicationId(req, res);
}
if (isTokenExpired(req)) {
return sendTokenExpiredJson(req, res);