forked from vpctorr/broadlink-rm-http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice.js
94 lines (68 loc) · 2.21 KB
/
device.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
// from: https://raw.githubusercontent.com/lprhodes/homebridge-broadlink-rm/master/helpers/getDevice.js
const BroadlinkJS = require('broadlinkjs-rm');
const broadlink = new BroadlinkJS()
const discoveredDevices = {};
const limit = 5;
let discovering = false;
const discoverDevices = (count = 0) => {
discovering = true;
if (count >= 5) {
discovering = false;
return;
}
broadlink.discover();
count++;
setTimeout(() => {
discoverDevices(count);
}, 5 * 1000)
}
discoverDevices();
broadlink.on('deviceReady', (device) => {
const macAddressParts = device.mac.toString('hex').match(/[\s\S]{1,2}/g) || []
const macAddress = macAddressParts.join(':')
device.host.macAddress = macAddress
if (discoveredDevices[device.host.address] || discoveredDevices[device.host.macAddress]) return;
console.log(`Discovered Broadlink RM device at ${device.host.macAddress} (${device.host.address})`)
discoveredDevices[device.host.address] = device;
discoveredDevices[device.host.macAddress] = device;
})
const getDevice = ({ host, log, learnOnly }) => {
let device;
if (host) {
device = discoveredDevices[host];
} else { // use the first one of no host is provided
const hosts = Object.keys(discoveredDevices);
if (hosts.length === 0) {
log(`Send data (no devices found)`);
if (!discovering) {
log(`Attempting to discover RM devices for 5s`);
discoverDevices()
}
return
}
// Only return device that can Learn Code codes
if (learnOnly) {
for (let i = 0; i < hosts.length; i++) {
let currentDevice = discoveredDevices[hosts[i]];
if (currentDevice.enterLearning) {
device = currentDevice
break;
}
}
if (!device) log(`Learn Code (no device found at ${host})`)
if (!device && !discovering) {
log(`Attempting to discover RM devices for 5s`);
discoverDevices()
}
} else {
device = discoveredDevices[hosts[0]];
if (!device) log(`Send data (no device found at ${host})`);
if (!device && !discovering) {
log(`Attempting to discover RM devices for 5s`);
discoverDevices()
}
}
}
return device;
}
module.exports = getDevice;