forked from aholstenson/miio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnectToDevice.js
50 lines (41 loc) · 1.11 KB
/
connectToDevice.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
'use strict';
const network = require('./network');
const Device = require('./device');
const Placeholder = require('./placeholder');
const models = require('./models');
module.exports = function(options) {
let handle = network.ref();
// Connecting to a device via IP, ask the network if it knows about it
return network.findDeviceViaAddress(options)
.then(device => {
const deviceHandle = {
ref: network.ref(),
api: device
};
// Try to resolve the correct model, otherwise use the generic device
const d = models[device.model];
if(! d) {
return new Device(deviceHandle);
} else {
return new d(deviceHandle);
}
})
.catch(e => {
if((e.code === 'missing-token' || e.code === 'connection-failure') && options.withPlaceholder) {
const deviceHandle = {
ref: network.ref(),
api: e.device
};
return new Placeholder(deviceHandle);
}
// Error handling - make sure to always release the handle
handle.release();
e.device = null;
throw e;
})
.then(device => {
// Make sure to release the handle
handle.release();
return device.init();
});
};