/
serial_noble.js
275 lines (246 loc) · 8.77 KB
/
serial_noble.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
(function () {
/* On Linux, BLE normally needs admin right to be able to access BLE
*
* sudo apt-get install libcap2-bin
* sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
*/
if (typeof require === 'undefined') return;
var noble = undefined;
var NORDIC_SERVICE = "6e400001b5a3f393e0a9e50e24dcca9e";
var NORDIC_TX = "6e400002b5a3f393e0a9e50e24dcca9e";
var NORDIC_RX = "6e400003b5a3f393e0a9e50e24dcca9e";
var NORDIC_TX_MAX_LENGTH = 20;
var initialised = false;
var errored = false;
function findByUUID(list, uuid) {
for (var i=0;i<list.length;i++)
if (list[i].uuid.replace(/-/g,"")==uuid) return list[i];
// normal noble returns UUIDs without dashes, but noble-winrt returns them with dashes in!
return undefined;
}
// map of bluetooth devices found by getPorts
var btDevices = {};
var newDevices = [];
var lastDevices = [];
var btDevice;
var txCharacteristic;
var rxCharacteristic;
var txInProgress = false;
var scanStopTimeout = undefined;
function init() {
Espruino.Core.Config.add("BLUETOOTH_LOW_ENERGY", {
section: "Communications",
name: "Connect over Bluetooth Smart (BTLE) via 'noble'",
descriptionHTML: 'Allow connection to Espruino via BLE with the Nordic UART implementation',
type: "boolean",
defaultValue: true
});
}
/* Needed because Noble just throws a global exception if
it tries to start and no device is there! */
function nobleExceptionHandler(err) {
if (err.toString().includes("ENODEV")) {
process.removeListener('uncaughtException', nobleExceptionHandler);
console.log("Noble: "+err.toString()+" - disabling.");
errored = true;
} else throw err;
}
function startNoble() {
try {
process.on('uncaughtException', nobleExceptionHandler);
try {
noble = require('noble-winrt'); // for windows 10+ compat. noble-uwp should work too
} catch (e) {
try {
noble = require('@abandonware/noble'); // this would be our preference on other platforms
} catch (e) {
noble = require('noble'); // else try the standard noble
}
}
} catch (e) {
console.log("Noble: module couldn't be loaded, no node.js Bluetooth Low Energy\n", e);
// super nasty workaround for https://github.com/sandeepmistry/noble/issues/502
process.removeAllListeners('exit');
errored = true;
return false;
}
noble.on('stateChange', function(state) {
process.removeListener('uncaughtException', nobleExceptionHandler);
console.log("Noble: stateChange -> "+state);
if (state=="poweredOn") {
if (Espruino.Config.WEB_BLUETOOTH) {
// Everything has already initialised, so we must disable
// web bluetooth this way instead
console.log("Noble: Disable Web Bluetooth as we have Noble instead");
Espruino.Config.WEB_BLUETOOTH = false;
}
initialised = true;
startScan();
}
if (state=="poweredOff") {
initialised = false;
}
});
noble.on('discover', function(dev) {
if (!scanStopTimeout) {
// we should already have stopped!
noble.stopScanning();
return;
}
if (!dev.advertisement) return;
for (var i in newDevices)
if (newDevices[i].path == dev.address) return; // already seen it
var name = dev.advertisement.localName || dev.address;
var hasUartService = dev.advertisement.serviceUuids &&
dev.advertisement.serviceUuids.map(s => s.replaceAll('-', '')).indexOf(NORDIC_SERVICE)>=0;
if (hasUartService ||
Espruino.Core.Utils.isRecognisedBluetoothDevice(name, dev.address)) {
console.log("Noble: Found UART device:", name, dev.address);
newDevices.push({ path: dev.address, description: name, type: "bluetooth", rssi: dev.rssi });
btDevices[dev.address] = dev;
} else console.log("Noble: Found device:", name, dev.address);
});
// if we didn't initialise for whatever reason, keep going anyway
setTimeout(function() {
if (initialised) return;
console.log("Noble: Didn't initialise in 10 seconds, disabling.");
errored = true;
}, 10000);
return true;
}
function startScan() {
if (scanStopTimeout) {
clearTimeout(scanStopTimeout);
scanStopTimeout = undefined;
} else {
console.log("Noble: Starting scan");
lastDevices = [];
newDevices = [];
noble.startScanning([], true);
}
scanStopTimeout = setTimeout(function () {
scanStopTimeout = undefined;
console.log("Noble: Stopping scan");
noble.stopScanning();
}, 3000);
}
var getPorts = function (callback) {
if (errored || !Espruino.Config.BLUETOOTH_LOW_ENERGY) {
console.log("Noble: getPorts - disabled");
callback([], true/*instantPorts*/);
} else if (!initialised) {
console.log("Noble: getPorts - initialising...");
if (!noble)
if (!startNoble())
return callback([], true/*instantPorts*/);
callback(reportedDevices, false/*instantPorts*/);
} else { // all ok - let's go!
// Ensure we're scanning
startScan();
// report back device list from both the last scan and this one...
var reportedDevices = [];
newDevices.forEach(function (d) {
reportedDevices.push(d);
});
lastDevices.forEach(function (d) {
var found = false;
reportedDevices.forEach(function (dv) {
if (dv.path == d.path) found = true;
});
if (!found) reportedDevices.push(d);
});
reportedDevices.sort(function (a, b) { return a.path.localeCompare(b.path); });
lastDevices = newDevices;
newDevices = [];
//console.log("Noble: reportedDevices",reportedDevices);
callback(reportedDevices, false/*instantPorts*/);
}
};
var openSerial = function (serialPort, openCallback, receiveCallback, disconnectCallback) {
btDevice = btDevices[serialPort];
if (btDevice === undefined) throw "BT device not found"
if (scanStopTimeout) {
clearTimeout(scanStopTimeout);
scanStopTimeout = undefined;
console.log("Noble: Stopping scan (openSerial)");
noble.stopScanning();
}
txInProgress = false;
console.log("BT> Connecting");
btDevice.on('disconnect', function() {
txCharacteristic = undefined;
rxCharacteristic = undefined;
btDevice = undefined;
txInProgress = false;
disconnectCallback();
});
btDevice.connect(function (error) {
if (error) {
console.log("BT> ERROR Connecting");
btDevice = undefined;
return openCallback();
}
console.log("BT> Connected");
btDevice.discoverAllServicesAndCharacteristics(function(error, services, characteristics) {
var btUARTService = findByUUID(services, NORDIC_SERVICE);
txCharacteristic = findByUUID(characteristics, NORDIC_TX);
rxCharacteristic = findByUUID(characteristics, NORDIC_RX);
if (error || !btUARTService || !txCharacteristic || !rxCharacteristic) {
console.log("BT> ERROR getting services/characteristics");
console.log("Service "+btUARTService);
console.log("TX "+txCharacteristic);
console.log("RX "+rxCharacteristic);
btDevice.disconnect();
txCharacteristic = undefined;
rxCharacteristic = undefined;
btDevice = undefined;
return openCallback();
}
rxCharacteristic.on('data', function (data) {
receiveCallback(new Uint8Array(data).buffer);
});
rxCharacteristic.subscribe(function() {
openCallback({});
});
});
});
};
var closeSerial = function () {
if (btDevice) {
btDevice.disconnect(); // should call disconnect callback?
}
};
// Throttled serial write
var writeSerial = function (data, callback) {
if (txCharacteristic === undefined) return;
if (data.length>NORDIC_TX_MAX_LENGTH) {
console.error("BT> TX length >"+NORDIC_TX_MAX_LENGTH);
return callback();
}
if (txInProgress) {
console.error("BT> already sending!");
return callback();
}
console.log("BT> send "+JSON.stringify(data));
txInProgress = true;
try {
txCharacteristic.write(Espruino.Core.Utils.stringToBuffer(data), false, function() {
txInProgress = false;
return callback();
});
} catch (e) {
console.log("BT> SEND ERROR " + e);
closeSerial();
}
};
// ----------------------------------------------------------
Espruino.Core.Serial.devices.push({
"name" : "Noble Bluetooth LE",
"init": init,
"getPorts": getPorts,
"open": openSerial,
"write": writeSerial,
"close": closeSerial,
"maxWriteLength" : NORDIC_TX_MAX_LENGTH,
});
})();