forked from TheThingSystem/node-flower-power-cloud
/
FlowerPowerCloud.js
252 lines (219 loc) · 6.47 KB
/
FlowerPowerCloud.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
var ApiError = require('./ApiError');
var async = require('async');
var request = require('request');
var qs = require('querystring');
var schedule = require('node-schedule');
const DEBUG = false;
function FlowerPowerCloud() {
this._token = {};
this._isLogged = false;
this.credentials = {};
this.autoRefresh = false;
var self = this;
var api = {
// Profile
'getProfile': {method: 'GET/json', path: '/user/v4/profile', auth: true},
'getUserVersions': {method: 'GET/json', path: '/user/v1/versions', auth: true},
'verify': {method: 'GET/json', path: '/user/v1/verify', auth: true},
// Garden
'getSyncGarden': {method: 'GET/json', path: '/sensor_data/v4/garden_locations_status', auth: true},
'sendSamples': {method: 'PUT/json', path: '/sensor_data/v5/sample', auth: true},
'getSyncData': {method: 'GET/json', path: '/sensor_data/v3/sync', auth: true},
'getFirmwareUpdate': {method: 'GET/json', path: '/sensor_data/v1/firmware_update', auth: true},
'getLocationSamples': {method: 'GET/json', path: '/sensor_data/v2/sample/location/:location_identifier', auth: true},
'getStatistics': {method: 'GET/json', path: '/sensor_data/v1/statistics/:location_identifier', auth: true},
// Images
'getImageLocation': {method: 'GET/json', path: '/image/v3/location/user_images/:location_identifier', auth: true},
};
for (var item in api) {
self.makeReqFunction(item, api[item]);
}
return this;
};
FlowerPowerCloud.url = 'https://apiflowerpower.parrot.com';
FlowerPowerCloud.prototype.makeReqFunction = function(name, req) {
var self = this;
FlowerPowerCloud.prototype[name] = function(data, callback) {
self.invoke(req, data, callback);
};
};
FlowerPowerCloud.prototype.makeHeader = function(req, data) {
var options = {headers: {}};
var verb = req.method.split('/')[0];
var type = req.method.split('/')[1];
switch (type) {
case 'urlencoded':
options.body = qs.stringify(data);
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
break;
case 'json':
options.body = JSON.stringify(data);
options.headers['Content-Type'] = 'application/json';
break;
default:
options.body = data;
options.headers['Content-Type'] = 'text/plain';
break;
}
options.url = FlowerPowerCloud.url + req.path;
options.method = verb;
options.headers['Authorization'] = (req.auth) ? "Bearer " + this._token.access_token : "";
return options;
};
FlowerPowerCloud.prototype.makeUrl = function(req, data) {
var self = this;
if (data) {
for (var item in data.url) {
req.path = req.path.replace(':' + item, data.url[item]);
}
delete data.url;
}
if (DEBUG) self.loggerReq(req, data);
return req;
};
FlowerPowerCloud.prototype.loggerReq = function(req, data) {
console.log(req.method, req.path);
for (var key in data) {
console.log(key + ":", data[key]);
}
};
FlowerPowerCloud.prototype.invoke = function(req, data, callback) {
var options = {};
var self = this;
if (typeof data == 'function') {
callback = data;
data = null;
}
if (data && typeof data !== 'object') {
return callback(new Error('Data is not a json'));
}
req = self.makeUrl(req, data);
options = self.makeHeader(req, data);
if (DEBUG) console.log(options);
request(options, function(err, res, body) {
if (typeof body == 'string') {
try {
body = JSON.parse(body);
} catch (e) {};
}
if (err) callback(err, null);
else if (res.statusCode != 200 || (body.errors && body.errors.length > 0)) {
return callback(new ApiError(res.statusCode, body), null);
}
else if (callback) {
var results = body;
if (results.sensors) {
var sensors = {};
for (var sensor of results.sensors) {
if (sensor.sensor_serial) {
sensors[sensor.sensor_serial] = sensor;
}
}
results.sensors = sensors;
}
if (results.locations) {
var locations = {};
for (var location of results.locations) {
if (location.sensor_serial) {
locations[location.sensor_serial] = location;
}
}
results.locations = locations;
}
if (results.sensors && results.locations) {
results.sensors = self.concatJson(results.sensors, results.locations);
delete results.locations;
}
return callback(null, results);
}
else throw "Give me a callback";
});
};
FlowerPowerCloud.prototype.login = function(data, callback) {
var req = {method: 'POST/urlencoded', path: '/user/v2/authenticate'};
var self = this;
if (typeof data['auto-refresh'] != 'undefined') {
self.autoRefresh = data['auto-refresh'];
delete data['auto-refresh'];
}
self.credentials = data;
data['grant_type'] = 'password';
self.invoke(req, data, function(err, res) {
if (err) callback(err);
else self.setToken(res, callback);
});
};
FlowerPowerCloud.prototype.setToken = function(token, callback) {
var self = this;
self._token = token;
self._isLogged = true;
if (self.autoRefresh) {
var job = new schedule.Job(function() {
self.refresh(token);
});
job.schedule(new Date(Date.now() + (token['expires_in'] - 1440) * 1000));
}
if (typeof callback == 'function') callback(null, token);
}
FlowerPowerCloud.prototype.refresh = function(token) {
var req = {method: 'POST/urlencoded', path: '/user/v2/authenticate'};
var self = this;
var data = {
'client_id': self.credentials['client_id'],
'client_secret': self.credentials['client_secret'],
'refresh_token': token.refresh_token,
'grant_type': 'refresh_token'
};
self.invoke(req, data, function(err, res) {
if (err) callback(err);
else self.setToken(res);
});
};
FlowerPowerCloud.prototype.getGarden = function(callback) {
var self = this;
async.parallel({
syncGarden: function(callback) {
self.getSyncGarden(callback);
},
syncData: function(callback) {
self.getSyncData(callback);
}
}, function(err, res) {
if (err) callback(err);
else callback(null, self.concatJson(res.syncData, res.syncGarden));
});
};
FlowerPowerCloud.prototype.concatJson = function(json1, json2) {
var dest = json1;
var self = this;
for (var key in json2) {
if (typeof json1[key] == 'object' && typeof json2[key] == 'object') {
dest[key] = self.concatJson(json1[key], json2[key]);
}
else {
dest[key] = json2[key];
}
}
return dest;
}
// 'url1': {
// 'getProfile',
// 'getUserVersions',
// 'getSyncGarden',
// 'sendSamples',
// 'getSyncData',
// 'getFirmwareUpdate',
// 'getLocationSamples',
// 'getStatistics',
// },
// 'url2': {
// 'searchName',
// 'suggest',
// 'suggestLocation'
// },
// 'url3': {
// 'infoPlant',
// 'plantdataVersion',
// 'listPopularityPlant',
// }
module.exports = FlowerPowerCloud;