-
Notifications
You must be signed in to change notification settings - Fork 0
/
bleManager.js
245 lines (209 loc) · 7.34 KB
/
bleManager.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
"use strict";
var log = require('./logging.js');
var Promise = require('bluebird')
var Candle = require('./candle.js')
var Tools = require("./tools.js");
const colorsCharacteristicUUID = "fffc"
const batteryCharacteristicUUID = "2a19"
const batteryServiceUUID = "180f"
const playbulbServiceUUID = "ff02"
const operationsDelayMilliseconds = 2000
const disconnectDelayMilliseconds = 10000
const scanningForPeripheralsTime = 20000
const performBLEActionTimeout = 10000
class BLEManager {
constructor() {
this.noble = Promise.promisifyAll(require('noble'))
this.knownCandles = {}
this.defaultColor
}
candleForPeripheral(peripheral) {
if (peripheral.id in this.knownCandles) {
return this.knownCandles[peripheral.id]
}
var newCandle = new Candle()
newCandle.id = peripheral.id
newCandle.desiredColor = this.defaultColor
newCandle.name = peripheral.advertisement.localName
this.knownCandles[peripheral.id] = newCandle
return newCandle
}
performSingleCandlesLoop(updateColors, turnOn) {
if (updateColors && Object.keys(this.knownCandles).length > 0 && this.areAllCandlesSatisfied(turnOn)) {
return Promise.reject(new Error())
}
var thisManager = this;
return new Promise((resolve, reject) => {
var foundPeripherals = 0
var timeoutOccured = false
var finishFunc = function () {
if (foundPeripherals == 0 && timeoutOccured) {
resolve(thisManager.knownCandles)
}
}
var processSinglePeripheralFunc = function (peripheral) {
var candle = thisManager.candleForPeripheral(peripheral)
return peripheral.connectAsync()
.timeout(performBLEActionTimeout)
.delay(operationsDelayMilliseconds)
.then(function () {
log.debug("Connected to " + peripheral.advertisement.localName)
return thisManager.readBatteryForPeripheral(peripheral)
})
.then(function (battery) {
if (battery) {
candle.battery = battery.readInt8()
var utc = new Date().toLocaleString("en-US", { hour12: false })
candle.updateDate = utc
}
})
.catch(function () { })
.then(function () {
if (updateColors) {
var colorToSet = turnOn ? candle.desiredColor : BLEManager.TurnedOffColor
return thisManager.setColorForPeripheral(peripheral, colorToSet)
}
})
.then(function () {
return thisManager.readColorForPeripheral(peripheral)
})
.then(function (color) {
if (color) {
candle.currentColor = color
var utc = new Date().toLocaleString("en-US", { hour12: false })
candle.updateDate = utc
}
})
.delay(disconnectDelayMilliseconds)
.then(function () {
log.debug("Will disconnect from " + peripheral.advertisement.localName)
return peripheral.disconnectAsync()
})
.timeout(performBLEActionTimeout)
.catch(function () { })
.finally(function () {
foundPeripherals -= 1
finishFunc()
peripheral.disconnectAsync()
.then(function () {
log.debug("Disconnected")
})
})
}
var foundPeripheralsPromisesArray = []
var handleDiscovery = function (peripheral) {
var peripheral = Promise.promisifyAll(peripheral)
log.debug('Found device with local name: ' + peripheral.advertisement.localName);
log.debug('advertising the following service uuid\'s: ' + peripheral.advertisement.serviceUuids);
foundPeripherals += 1
foundPeripheralsPromisesArray.push(peripheral)
}
thisManager.noble.on('discover', handleDiscovery)
thisManager.noble.startScanning([playbulbServiceUUID], false)
setTimeout(function () {
log.debug("Stopping scanning")
timeoutOccured = true
thisManager.noble.stopScanning()
thisManager.noble.removeListener("discover", handleDiscovery)
Promise.each(foundPeripheralsPromisesArray, function (peripheral) {
log.debug("Started processing " + peripheral)
return processSinglePeripheralFunc(peripheral)
})
.catch(function () { })
finishFunc()
}, scanningForPeripheralsTime);
})
}
areAllCandlesSatisfied(shouldBeTurnedOn) {
for (var key in this.knownCandles) {
let candle = this.knownCandles[key];
var desiredColor = shouldBeTurnedOn ? candle.desiredColor : BLEManager.TurnedOffColor
if (candle.currentColor != desiredColor) {
return false
}
}
return true
}
isPoweredOnAsync() {
var thisManager = this;
return new Promise((resolve, reject) => {
if (thisManager.noble.state == "poweredOn") {
resolve()
}
thisManager.noble.on('stateChange', function (state) {
if (thisManager.noble.state == "poweredOn") {
resolve()
}
})
})
}
// Candles operations
readBatteryForPeripheral(peripheral) {
return this.readValueForCharacteristic(peripheral, batteryServiceUUID, batteryCharacteristicUUID)
.then(function (value) {
log.debug("Battery for " + peripheral.advertisement.localName + " = " + value)
return value
})
.catch(function () { })
}
readColorForPeripheral(peripheral) {
return this.readValueForCharacteristic(peripheral, playbulbServiceUUID, colorsCharacteristicUUID)
.then(function (value) {
var colorHex = Tools.bytesToHex(value)
log.debug("Color for " + peripheral.advertisement.localName + " = " + value)
return colorHex
})
.catch(function () { })
}
setColorForPeripheral(peripheral, color) {
var colorBytes = Tools.hexToBytes(color)
return this.setValueForCharacteristic(peripheral, playbulbServiceUUID, colorsCharacteristicUUID, colorBytes)
.catch(function () { })
}
// Generic
readValueForCharacteristic(peripheral, serviceUUID, characteristicUUID) {
var returnValue = null
return this.performActionWithColorCharacteristic(peripheral, serviceUUID, characteristicUUID,
function (characteristic) {
return characteristic[0].readAsync()
.timeout(performBLEActionTimeout)
.then(function (value) {
log.debug("Read value: '" + value + "' for characteristic: '" + characteristicUUID + "' for: " + peripheral.advertisement.localName)
returnValue = value
return returnValue
})
}
)
.then(function () {
return returnValue
})
}
setValueForCharacteristic(peripheral, serviceUUID, characteristicUUID, value) {
return this.performActionWithColorCharacteristic(peripheral, serviceUUID, characteristicUUID,
function (characteristic) {
log.debug("Will set value: '" + value + "' to characteristic: '" + characteristicUUID + "' for: " + peripheral.advertisement.localName)
return characteristic[0].writeAsync(new Buffer(value), true)
.timeout(performBLEActionTimeout)
.then(function () {
log.debug("Did set value: '" + value + "' to characteristic: '" + characteristicUUID + "' for: " + peripheral.advertisement.localName)
})
}
)
}
performActionWithColorCharacteristic(peripheral, serviceUUID, characteristicUUID, action) {
return peripheral.discoverSomeServicesAndCharacteristicsAsync([serviceUUID], [characteristicUUID])
.timeout(performBLEActionTimeout)
.delay(operationsDelayMilliseconds)
.map(function (services, characteristics) {
log.debug("Discovered services and characteristics for " + peripheral.advertisement.localName)
for (let characteristic of services.characteristics) {
if (characteristic.uuid == characteristicUUID) {
return Promise.promisifyAll(characteristic)
}
}
})
.then(action)
}
}
BLEManager.TurnedOffColor = "00000000"
module.exports = BLEManager;