-
Notifications
You must be signed in to change notification settings - Fork 1
/
homie.js
450 lines (372 loc) · 12 KB
/
homie.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
Homie = {
Utils: {},
/**
* Synchronous Sleep/Timeout `await this.timeout()`
* Default delay is 2s, specify delay in ms in call to `this.timeout(2000)` for custom delays
*/
sleep( customDelay ) {
let delay = customDelay ? parseInt( customDelay ) : 2000;
return new Promise(function(resolve, reject) {
setTimeout(resolve, delay);
});
}
};
/**
* Homie API Constructor
* @param options
* @constructor
*/
Homie.API = function(options) {
this.options = Object.assign({
url: '192.168.123.1',
userAgent: 'Meteor Homie',
requestTimeout: 2000,
}, options);
if (this.options.url.substring(0,7) !== 'http://') {
this.options.url = 'http://' + this.options.url;
}
this.defaults = {
timeout: this.options.requestTimeout,
};
};
/**
* Get Device Heartbeat
* @param options
* @returns {Promise<void>}
*/
Homie.API.prototype.getHeartBeat = function( options ) {
/**
* GET /heart
Response
204 No Content
*/
return this.Query( 'GET', '/heart', options, 204 );
};
/**
* Get Device Info
* @param options
* @returns {Promise<void>}
*/
Homie.API.prototype.getDeviceInfo = function(options) {
/**
* GET /device-info
Response
200 OK (application/json)
{
"hardware_device_id": "52a8fa5d",
"homie_esp8266_version": "2.0.0",
"firmware": {
"name": "awesome-device",
"version": "1.0.0"
},
"nodes": [
{
"id": "light",
"type": "light"
}
],
"settings": [
{
"name": "timeout",
"description": "Timeout in seconds",
"type": "ulong",
"required": false,
"default": 10
}
]
}
*/
return this.Query( 'GET', '/device-info', options );
};
/**
* Get WiFi Networks from Device
* @param options
* @returns {Promise<void>}
*/
Homie.API.prototype.getNetworks = function(options) {
/**
* GET /networks
Response
In case of success:
200 OK (application/json)
{
"networks": [
{ "ssid": "Network_2", "rssi": -82, "encryption": "wep" },
{ "ssid": "Network_1", "rssi": -57, "encryption": "wpa" },
{ "ssid": "Network_3", "rssi": -65, "encryption": "wpa2" },
{ "ssid": "Network_5", "rssi": -94, "encryption": "none" },
{ "ssid": "Network_4", "rssi": -89, "encryption": "auto" }
]
}
In case the initial Wi-Fi scan is not finished on the device:
503 Service Unavailable (application/json)
{"error": "Initial Wi-Fi scan not finished yet"}
*/
return this.Query( 'GET', '/networks', options, 200, 'networks' );
};
/**
* Generate Device Configuration JSON
* @param device_name
* @param device_id
* @param wifi_ssid
* @param wifi_password
* @param mqtt_host
* @param custom_settings
* @param wifi_options
* @param mqtt_options
* @param ota
* @returns {{name: *, device_id: *, wifi: {ssid: *, password: *, bssid: null, channel: *, ip: null, mask: null, gw: null, dns1: null, dns2: null}, mqtt: {host: *, port: number, base_topic: string, auth: boolean, username: null, password: null}, ota: {enabled: boolean}}}
*/
Homie.API.prototype.generateConfig = function(device_name, device_id, wifi_ssid, wifi_password, mqtt_host, custom_settings, wifi_options, mqtt_options, ota ) {
if (!wifi_password) throw new Error('wifi_password is empty');
if (!mqtt_host) throw new Error('mqtt_host is empty');
if (!wifi_ssid) throw new Error('wifi_ssid is empty');
let config = {
"name": device_name,
"device_id": device_id,
"wifi": {
"ssid": wifi_ssid,
"password": wifi_password,
"bssid": wifi_options && wifi_options.bssid ? wifi_options.bssid : null,
"channel": wifi_options && wifi_options.bssid ? wifi_options.bssid : null,
"ip": wifi_options && wifi_options.ip ? wifi_options.ip : null,
"mask": wifi_options && wifi_options.mask ? wifi_options.mask : null,
"gw": wifi_options && wifi_options.gw ? wifi_options.gw : null,
"dns1": wifi_options && wifi_options.dns1 ? wifi_options.dns1 : null,
"dns2": wifi_options && wifi_options.dns2 ? wifi_options.dns2 : null
},
"mqtt": {
"host": mqtt_host,
"port": mqtt_options && mqtt_options.port ? mqtt_options.port : 1883,
// "mdns": mqtt_options && mqtt_options.mdns ? mqtt_options.mdns : null,
"base_topic": mqtt_options && mqtt_options.base_topic ? mqtt_options.base_topic : 'devices/',
"auth": mqtt_options && mqtt_options.auth ? mqtt_options.auth : false,
"username": mqtt_options && mqtt_options.username ? mqtt_options.username : null,
"password": mqtt_options && mqtt_options.password ? mqtt_options.password : null,
// "ssl": mqtt_options && mqtt_options.ssl ? mqtt_options.ssl : false,
// "fingerprint": mqtt_options && mqtt_options.fingerprint ? mqtt_options.fingerprint : null
},
"ota": {
"enabled": ota && ota.enabled ? ota.enabled : false,
}
};
if( custom_settings ){
config.settings = custom_settings;
}
this.Utils.remNullProps(config, true);
if (!config.hasOwnProperty('name')) {
config.device_name = 'Homie Device';
}
if (!config.hasOwnProperty('device_id')) {
config.device_id = 'Homie-' + Homie.Utils.randomID(8, 'a0');
}
return config;
};
/**
* Send HTTP API Query Call to Homie Device
*
* @param {String} method Method to use for HTTP call (GET, POST, PUT, etc)
* @param {String} endpoint Endpoint on API to call (with prepended /), example: /device-info
* @param {Object} options Options object for HTTP call. To POST/PUT data, set data key in object to value to use for data
* @param {Integer} successCode HTTP status code to consider a successful HTTP call (optional - default 200)
* @param {String} dataKey Specific key to return from data response (optional)
* @returns {Promise<void>}
*/
Homie.API.prototype.Query = function( method, endpoint, options, successCode, dataKey ){
let httpSuccessCode = successCode ? successCode : 200;
let mergedOptions = Object.assign( {}, this.defaults, options );
return new Promise( (resolve, reject) => {
HTTP.call( method, this.options.url + endpoint, mergedOptions, (error, response) => {
let hasError = this.parseError( error, response, httpSuccessCode );
let successData = this.parseResponse( response, httpSuccessCode, dataKey );
if( hasError ) {
let responseError = hasError.statusCode ? '(' + hasError.statusCode + ') ' : '';
responseError += hasError.data && hasError.data.error ? hasError.data.error : hasError.content ? hasError.content : hasError;
console.log( 'Homie.API.Query reject hasError', hasError, responseError );
// throw new Error( responseError );
reject( new Error( responseError ) );
} else if ( successData ){
resolve(successData);
} else {
console.log( 'Unkown errorsz');
reject( new Error( 'Unknown error!' ) );
}
});
});
};
/**
* Parse Query Errors
* @param error
* @param response
* @param successCode
* @returns {*}
*/
Homie.API.prototype.parseError = function( error, response, successCode ){
if( error ){
if( error.response && error.response.statusCode ){
return error.response;
}
console.log( 'Non response code error', error );
return error;
} else if ( response && response.statusCode && response.statusCode !== successCode ){
return response;
}
return false;
};
/**
* Parse Successful Response (and check if should return error)
* @param response
* @param successCode
* @param dataKey
* @returns {boolean}
*/
Homie.API.prototype.parseResponse = function( response, successCode, dataKey ){
if( response && response.statusCode && response.statusCode === successCode ){
// Initially set return response to data object (or true if doesn't exist)
let returnResponse = response.data ? response.data : true;
// If we want a specific data key to be returned, and it exists, return that instead
if( dataKey && response.data && response.data.hasOwnProperty( dataKey ) ){
returnResponse = response.data[dataKey];
}
return returnResponse;
}
return false;
};
/**
* Save configuration to Device
* @param config
* @param options
* @returns {*}
*/
Homie.API.prototype.saveConfig = function(config, options) {
if( ! config ) return new Error( 'Config is missing!' );
if( ! options ) options = {};
/**
* PUT /config
Request body
(application/json)
See JSON configuration file.
Response
In case of success:
200 OK (application/json)
{ "success": true }
In case of error in the payload:
400 Bad Request (application/json)
{ "success": false, "error": "Reason why the payload is invalid" }
In case the device already received a valid configuration and is waiting for reboot:
403 Forbidden (application/json)
{ "success": false, "error": "Device already configured" }
*/
// Set data object in options to JSON to configure device with
let callOptions = { data: config };
// Merge passed options, if any
if( options ){
callOptions = Object.assign( {}, callOptions, options );
}
return this.Query( 'PUT', '/config', callOptions );
};
/**
* Connect device to WiFi
* @param ssid
* @param password
* @param options
* @returns {*}
*/
Homie.API.prototype.connectToWifi = function(ssid, password,options) {
if( ! ssid ) return new Error( 'ssid is missing!' );
if( ! options ) options = {};
/**
* PUT /wifi/connect
v2.1 - POST /wifi/connect
Request params
ssid - wifi ssid network name
password - wifi password
Response
In case of success:
202 Accepted (application/json)
{ "success": true }
In case of error in the payload:
400 Bad Request (application/json)
{ "success": false, "error": "[Reason why the payload is invalid]" }
*/
// Set data object in options to JSON to configure device with
let callOptions = { data: { ssid: ssid, password: password } };
// Merge passed options, if any
if( options ){
callOptions = Object.assign( {}, callOptions, options );
}
return this.Query( 'POST', '/wifi/connect', callOptions, 202 );
};
/**
* Get WiFi Status
* @param options
* @returns {Promise<void>}
*/
Homie.API.prototype.getWifiStatus = function(options) {
/**
* GET /wifi/status
Possible status values
idle
connect_failed
connection_lost
no_ssid_available
connected (along with a local_ip field)
disconnected
Response
In case of success:
200 OK (application/json)
{ "status": "[status of wifi connection]" }
*/
return this.Query( 'GET', '/wifi/status', options );
};
/**
* Get Device Configuration
* @param options
* @returns {Promise<void>}
*/
Homie.API.prototype.getConfig = function(options) {
/**
* GET /config
*
In case of success:
200 OK (application/json)
*/
return this.Query( 'GET', '/config', options );
};
/**
* Enable/disable the device to act as a transparent proxy between AP and Station networks.
*
* All requests that don't collide with existing api paths will be bridged to the destination according to the "Host" header in http. The destination host is called using the existing Wifi connection (Station Mode established after ssid/password is configured in "/wifi-connect") and all contents are bridged back to the connection made to the AP side.
*
* This feature can be used to help captive portals to perform cloud api calls during device enrollment using the esp wifi ap connection without having to patch the Homie firmware. By using the transparent proxy, all operations can be performed by the custom javascript running on the browser (/data/homie/ui_bundle.gz)
* https is not supported.
*
* Important: The http request and responses must be kept as small as possible because all contents are transported using ram memory, which is very limited.
*
* @param enabled
* @returns {Promise<void>}
*/
Homie.API.prototype.setProxy = function(enabled) {
/**
* PUT /proxy/control
v2.1 POST /proxy/control
Request params
enable - true or false indicating if the device has to bridge all unknown requests to the Internet (transparent proxy activated) or not.
Response
In case of success:
200 OK (application/json)
{
"success": true
}
400 Bad Request (application/json)
{
"success": false,
"error": "Reason why the payload is invalid"
}
*/
let callOptions = { data: { enabled: enabled } };
if( options ){
callOptions = Object.assign( {}, callOptions, options );
}
return this.Query( 'POST', '/proxy/control', callOptions );
};