-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.js
80 lines (69 loc) · 2.36 KB
/
command.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
/* eslint-disable linebreak-style */
/* eslint-disable no-param-reassign */
/* eslint-disable dot-notation */
/* eslint-disable no-console */
const { toLower } = require('./convert');
const { makeGuid } = require('./guid');
const { getCommandTimeout } = require('./timeout');
// Track all of the commandId that were created via POST calls.
const commands = {
unlock: [],
lock: [],
startEngine: [],
stopEngine: [],
wake: [],
status: [],
location: [],
startCharge: [],
stopCharge: [],
};
/**
* Returns the command object that matches the request, or undefined if not found.
* @param {*} req The request object.
* @param {*} commandArray An array of command objects.
* @returns The command object that matches the query parameters (commandId, vehicleId).
*/
function getCommand(req, commandArray) {
let { commandId } = req.params;
let { vehicleId } = req.params;
commandId = toLower(commandId); // FordConnect server is case-insensitive.
vehicleId = toLower(vehicleId);
let searchLists = (commandArray !== undefined) ? { data: commandArray } : commands;
// BUGFIX: FordConnect API returns matching commandId regardless of the route used.
searchLists = commands;
let match;
Object.keys(searchLists).forEach((searchList) => {
const matches = searchLists[searchList].filter(
(c) => c.commandId === commandId && c.vehicleId === vehicleId,
);
if (matches && matches.length > 0) {
// eslint-disable-next-line prefer-destructuring
match = matches[0];
if (Date.now() - match.timestamp > getCommandTimeout() * 1000) {
match = undefined;
}
}
});
return match;
}
/**
* Returns a new command object (4 seconds of "PENDINGRESPONSE", then "COMPLETED")
* @param {*} vehicleId The vehicleId for the command.
* @param {*} duration The duration for pending response. Use undefined for default time.
* @returns A command object with a random commandId.
*/
function createCommand(vehicleId, duration) {
if (duration === undefined) {
duration = 4000;
}
return {
commandId: makeGuid(),
vehicleId: toLower(vehicleId),
timestamp: Date.now(),
commandStatuses: `${duration},PENDINGRESPONSE;-1,COMPLETED`,
commandStatus: 'PENDINGRESPONSE', // possible values: PENDINGRESPONSE, COMPLETED, FAILED
};
}
exports.commands = commands;
exports.createCommand = createCommand;
exports.getCommand = getCommand;