-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdevices.js
307 lines (247 loc) · 7.18 KB
/
devices.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
'use strict'
const util = require('./util/util')
const BleServices = require('./services/services')
const async = require('async')
const logger = require('./util/logs').logger
// Device types
const DEVICE_TYPE_LIGHT_BLUE = 'DEVICE_TYPE_LIGHT_BLUE'
const DEVICE_TYPE_BLE = 'DEVICE_TYPE_BLE'
const BEAN_UUID = util.normalizeUUID('a495ff10c5b14b44b5121370f02d74de');
class PeripheralMixin {
constructor(peripheral) {
this._peripheral = peripheral
}
update(peripheral) {
this._peripheral = peripheral
return true
}
getPeripheral() {
return this._peripheral
}
getName() {
let adv = this._peripheral.advertisement
return adv.localName ? adv.localName : ''
}
getAddress() {
return this._peripheral.uuid
}
}
class ScannedDevice extends PeripheralMixin {
constructor(peripheral) {
super(peripheral)
this._advertisedServices = []
this._reportAtLeastOnce = false
}
print() {
let out = `${this.getType()}:\n`
out += ` Name: ${this.getName()}\n`
out += ` Address: ${this.getAddress()}\n`
out += ` Advertised Services:\n`
if (this._advertisedServices.length > 0) {
for (let i in this._advertisedServices) {
out += ` ${this._advertisedServices[i]}\n`
}
} else {
out += ` None\n`
}
return out
}
update(peripheral) {
this._peripheral = peripheral
let newServices = peripheral.advertisement.serviceUuids
let updated = false
for (let i in newServices) {
let sUUID = newServices[i]
if (this._advertisedServices.indexOf(sUUID) === -1) {
updated = true
this._advertisedServices.push(sUUID)
}
}
if (!this._reportAtLeastOnce) {
this._reportAtLeastOnce = true
updated = true
}
return updated
}
getType() {
if (this._advertisedServices.indexOf(BEAN_UUID) < 0) {
return DEVICE_TYPE_BLE
} else {
return DEVICE_TYPE_LIGHT_BLUE
}
}
}
class BleDevice extends PeripheralMixin {
constructor(peripheral) {
super(peripheral)
// State
this._services = {}
}
_lookupService(serviceKey) {
/**
* Helper function to look up a service based on a key, with error logging
*/
let s = this._services[serviceKey]
if (s)
return s
logger.info(`No such service: ${serviceKey}`)
return null
}
getType() {
return DEVICE_TYPE_BLE
}
getServices() {
return this._services
}
getDeviceInformationService() {
return this._lookupService(BleServices.deviceInformation.UUID)
}
getBatteryService() {
return this._lookupService(BleServices.battery.UUID)
}
getOADService() {
return this._lookupService(BleServices.oad.UUID)
}
getSerialTransportService() {
return this._lookupService(BleServices.serialTransport.UUID)
}
getScratchService() {
return this._lookupService(BleServices.scratch.UUID)
}
toString() {
return `${this.getName()}(${this.getAddress()})`
}
serialize() {
return {
name: this.getName(),
address: this.getAddress(),
device_type: this.getType()
}
}
isConnected() {
return this._peripheral.state === 'connected'
}
isConnectedOrConnecting() {
return this._peripheral.state === 'connected' || this._peripheral.state === 'connecting'
}
connect(callback) {
/**
* Connect to the device
*
* @param callback Callback function that takes an error argument
*/
logger.info(`Connecting to device: ${this.getName()}`)
if (this.isConnected()) {
logger.info('Already connected.')
callback(null, this)
} else {
this._peripheral.connect((err)=> {
callback(err, this)
})
}
}
disconnect(callback) {
if (this.isConnected()) {
this._peripheral.disconnect((error)=> {
if (error) {
logger.error(`Device disconnect ERROR (${this.toString()}: ${error}`)
} else {
logger.info(`Device disconnect success (${this.toString()})`)
}
callback(error)
})
} else {
callback(null)
}
}
lookupServices(callback) {
logger.info(`Looking up services for device: ${this.getName()}`)
this._services = [] // Clear services
this._peripheral.discoverAllServicesAndCharacteristics((err, services) => {
if (err) {
logger.info(`There was an error getting services: ${err}`)
callback(err)
} else {
let setupFns = []
for (let nobleService of services) {
let sUUID = util.normalizeUUID(nobleService.uuid)
let service = null
if (this._services[sUUID]) {
// Service exists
service = BleServices.fromExistingService(this._services[sUUID], nobleService)
} else {
// New service
service = BleServices.fromNobleService(nobleService)
}
logger.info(`Found service: ${service.getName()} / ${nobleService.uuid}`)
this._services[sUUID] = service
}
for (let i in this._services) {
let s = this._services[i]
setupFns.push((setupCallback)=> {
s.setup((setupError)=> {
logger.info(`Service setup successfully: ${s.getName()}`)
setupCallback(setupError)
})
})
}
async.parallel(setupFns, function (error, results) {
logger.info('All services have been setup!')
callback(error)
})
}
})
}
}
class LightBlueDevice extends BleDevice {
constructor(peripheral) {
super(peripheral)
}
getType() {
return DEVICE_TYPE_LIGHT_BLUE
}
setLed(red, green, blue, callback) {
let cmd = BleServices.serialTransport.commandIds.CC_LED_WRITE_ALL
this.getSerialTransportService().sendCommand(cmd, [red, green, blue], callback)
}
readAccelerometer(callback) {
let cmd = BleServices.serialTransport.commandIds.CC_ACCEL_READ
this.getSerialTransportService().sendCommand(cmd, [], null, callback)
}
readSketchInfo(callback) {
let cmd = BleServices.serialTransport.commandIds.BL_GET_META
this.getSerialTransportService().sendCommand(cmd, [], null, callback)
}
readBleConfig(callback) {
let cmd = BleServices.serialTransport.commandIds.BT_GET_CONFIG
this.getSerialTransportService().sendCommand(cmd, [], null, callback)
}
sendSerial(dataBuffer, callback) {
let cmd = BleServices.serialTransport.commandIds.SERIAL_DATA
this.getSerialTransportService().sendCommand(cmd, [dataBuffer], callback)
}
rename(newName, callback) {
this.readBleConfig((err, existingCfg)=> {
let cmd = BleServices.serialTransport.commandIds.BT_SET_CONFIG
let args = [
existingCfg.advertising_interval,
existingCfg.connection_interval,
existingCfg.tx_power,
existingCfg.advertising_mode,
existingCfg.ibeacon_uuid,
existingCfg.ibeacon_major_id,
existingCfg.ibeacon_minor_id,
newName,
newName.length
]
this.getSerialTransportService().sendCommand(cmd, args, callback)
})
}
}
module.exports = {
ScannedDevice: ScannedDevice,
BleDevice: BleDevice,
LightBlueDevice: LightBlueDevice,
DEVICE_TYPE_LIGHT_BLUE: DEVICE_TYPE_LIGHT_BLUE,
DEVICE_TYPE_BLE: DEVICE_TYPE_BLE
}