-
Notifications
You must be signed in to change notification settings - Fork 0
/
device.js
112 lines (97 loc) · 3.13 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
'use strict';
/**
* A Device object manages an edge device and its bluetooth communication
*/
class Device {
constructor(bleDevice) {
this.id = bleDevice.address.replace(/:/g, '');
this.bleDevice = bleDevice;
this.fwVersion = null;
this.timer = null;
}
resetState() {
this.fwVersion = null;
this.timer = null;
}
/**
* Returns a Promise that will resolve with the ble device's firmware revision,
* or reject with an error
*/
readFirmware() {
return new Promise((resolve, reject) => {
console.log(`${this.id}: readFirmwareRevision`);
this.bleDevice.readFirmwareRevision((error, firmwareRevision) => {
if (error) {
reject(error);
return;
}
console.log(`${this.id}: firmware revision = ${firmwareRevision}`);
this.fwVersion = firmwareRevision;
resolve();
});
});
}
/**
* Returns a Promise that will connect and set up the ble device with noble.
* Once set up, it will read the device's firmware and enable its luxometer.
*/
setUp() {
return new Promise((resolve, reject) => {
this.timer = setTimeout(() => {
this.bleDevice.disconnect();
reject("connection timeout")
}, 10000)
this.bleDevice.connectAndSetUp((setupError) => {
if (setupError) {
reject(new Error(setupError));
}
if(this.timer == null) {
this.bleDevice.disconnect();
reject("connection timeout")
} else {
clearTimeout(this.timer)
this.timer = null
}
this.readFirmware()
.then(this.enableLuxometer.bind(this))
.then(() => {
resolve(this);
})
.catch((err) => {
console.log(`DEVICE SETUP ERROR: ${err}`);
reject(err)
});
});
});
}
/**
* Returns a Promise that will enable the device's luxometer
*/
enableLuxometer() {
return new Promise((resolve) => {
console.log(`${this.id}: enableLuxometer`);
this.bleDevice.enableLuxometer(resolve);
});
}
/**
* Returns a Promise that will notify the device's luxometer
*/
notifyLuxometer() {
return new Promise((resolve) => {
console.log(`${this.id}: notifyLuxometer`);
this.bleDevice.notifyLuxometer(resolve);
});
}
/**
* This function will bind its given callback to run when the ble device
* triggers a 'luxometerChange' event.
*/
onLuxometerChange(callback) {
console.log(`${this.id}: set up onluxchange`);
this.bleDevice.on('luxometerChange', (lux) => {
callback(this, lux);
});
return this.notifyLuxometer();
}
}
module.exports = Device;