forked from circuitpython/web-editor
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathble.js
307 lines (270 loc) · 11.4 KB
/
ble.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
/*
* This class will encapsulate all of the workflow functions specific to BLE
*/
import {FileTransferClient} from '../common/ble-file-transfer.js';
import {CONNTYPE} from '../constants.js';
import {Workflow} from './workflow.js';
import {GenericModal, DeviceInfoModal} from '../common/dialogs.js';
import {sleep} from '../common/utilities.js';
const bleNusServiceUUID = 'adaf0001-4369-7263-7569-74507974686e';
const bleNusCharRXUUID = 'adaf0002-4369-7263-7569-74507974686e';
const bleNusCharTXUUID = 'adaf0003-4369-7263-7569-74507974686e';
const BYTES_PER_WRITE = 20;
let btnRequestBluetoothDevice, btnBond, btnReconnect;
class BLEWorkflow extends Workflow {
constructor() {
super();
this.rxCharacteristic = null;
this.txCharacteristic = null;
this.serialService = null;
this.bleServer = null;
this.bleDevice = null;
this.decoder = new TextDecoder();
this.connectDialog = new GenericModal("ble-connect");
this.infoDialog = new DeviceInfoModal("device-info");
this.partialWrites = true;
this.type = CONNTYPE.Ble;
this.buttonStates = [
{reconnect: false, request: false, bond: false},
{reconnect: false, request: true, bond: false},
{reconnect: true, request: true, bond: false},
{reconnect: false, request: false, bond: true},
];
}
// This is called when a user clicks the main disconnect button
async disconnectButtonHandler(e) {
await super.disconnectButtonHandler(e);
if (this.connectionStatus()) {
// Disconnect BlueTooth and Reset things
if (this.bleDevice !== undefined && this.bleDevice.gatt.connected) {
this.bleDevice.gatt.disconnect();
}
await this.onDisconnected(e, false);
}
}
async showConnect(documentState) {
let p = this.connectDialog.open();
let modal = this.connectDialog.getModal();
btnRequestBluetoothDevice = modal.querySelector('#requestBluetoothDevice');
btnBond = modal.querySelector('#promptBond');
btnReconnect = modal.querySelector('#bleReconnect');
// Map the button states to the buttons
this.connectButtons = {
reconnect: btnReconnect,
request: btnRequestBluetoothDevice,
bond: btnBond
};
btnRequestBluetoothDevice.addEventListener('click', this.onRequestBluetoothDeviceButtonClick.bind(this));
btnBond.addEventListener('click', this.onBond.bind(this));
btnReconnect.addEventListener('click', this.reconnectButtonHandler.bind(this));
// Check if Web Bluetooth is available
if (!(await this.available() instanceof Error)) {
let stepOne;
if (stepOne = modal.querySelector('.step:first-of-type')) {
stepOne.classList.add("hidden");
}
try {
const devices = await navigator.bluetooth.getDevices();
console.log(devices);
this.connectionStep(devices.length > 0 ? 2 : 1);
} catch (e) {
console.log("New Permissions backend for Web Bluetooth not enabled. Go to chrome://flags/#enable-web-bluetooth-new-permissions-backend to enable.", e);
}
} else {
modal.querySelectorAll('.step:not(:first-of-type)').forEach((stepItem) => {
stepItem.classList.add("hidden");
});
this.connectionStep(0);
}
return await p;
}
async onSerialReceive(e) {;
// TODO: Make use of super.onSerialReceive() so that title can be extracted
let output = this.decoder.decode(e.target.value.buffer, {stream: true});
console.log(output);
this.writeToTerminal(output);
}
async connectToSerial() {
try {
this.serialService = await this.bleServer.getPrimaryService(bleNusServiceUUID);
// TODO: create a terminal for each serial service (maybe?)
this.txCharacteristic = await this.serialService.getCharacteristic(bleNusCharTXUUID);
this.rxCharacteristic = await this.serialService.getCharacteristic(bleNusCharRXUUID);
// Remove any existing event listeners to prevent multiple reads
this.txCharacteristic.removeEventListener('characteristicvaluechanged', this.onSerialReceive.bind(this));
this.txCharacteristic.addEventListener('characteristicvaluechanged', this.onSerialReceive.bind(this));
await this.txCharacteristic.startNotifications();
return true;
} catch (e) {
console.log(e, e.stack);
return e;
}
}
// Reconnect
async reconnectButtonHandler(e) {
if (!this.connectionStatus()) {
try {
console.log('Getting existing permitted Bluetooth devices...');
const devices = await navigator.bluetooth.getDevices();
console.log('> Found ' + devices.length + ' Bluetooth device(s).');
// These devices may not be powered on or in range, so scan for
// advertisement packets from them before connecting.
for (const device of devices) {
await this.connectToBluetoothDevice(device);
}
}
catch (error) {
console.error(error);
await this._showMessage(error);
}
}
}
// Bring up a dialog to request a device
async requestDevice() {
return navigator.bluetooth.requestDevice({
filters: [{services: [0xfebb]},], // <- Prefer filters to save energy & show relevant devices.
optionalServices: [0xfebb, bleNusServiceUUID]
});
}
async connectToBluetoothDevice(device) {
const abortController = new AbortController();
async function onAdvertisementReceived(event) {
console.log('> Received advertisement from "' + device.name + '"...');
// Stop watching advertisements to conserve battery life.
abortController.abort();
console.log('Connecting to GATT Server from "' + device.name + '"...');
try {
await device.gatt.connect();
} catch (error) {
await this._showMessage("Failed to connect to device. Try forgetting device from OS bluetooth devices and try again.");
}
if (device.gatt.connected) {
console.log('> Bluetooth device "' + device.name + ' connected.');
await this.switchToDevice(device);
} else {
console.log('Unable to connect to bluetooth device "' + device.name + '.');
}
}
device.removeEventListener('advertisementreceived', onAdvertisementReceived.bind(this));
device.addEventListener('advertisementreceived', onAdvertisementReceived.bind(this));
this.debugLog("connecting to " + device.name);
try {
console.log('Watching advertisements from "' + device.name + '"...');
await device.watchAdvertisements({signal: abortController.signal});
}
catch (error) {
console.error(error);
await this._showMessage(error);
}
}
// Request Bluetooth Device
async onRequestBluetoothDeviceButtonClick(e) {
//try {
console.log('Requesting any Bluetooth device...');
this.debugLog("Requesting device. Cancel if empty and try existing");
let device = await this.requestDevice();
console.log('> Requested ' + device.name);
await device.gatt.connect();
await this.switchToDevice(device);
/*}
catch (error) {
console.error(error);
await this._showMessage(error);
this.debugLog('No device selected. Try to connect to existing.');
}*/
}
async switchToDevice(device) {
console.log(device);
this.bleDevice = device;
this.bleDevice.removeEventListener("gattserverdisconnected", this.onDisconnected.bind(this));
this.bleDevice.addEventListener("gattserverdisconnected", this.onDisconnected.bind(this));
this.bleServer = this.bleDevice.gatt;
console.log("connected", this.bleServer);
let services;
console.log(device.gatt.connected);
//try {
services = await this.bleServer.getPrimaryServices();
/*} catch (e) {
console.log(e, e.stack);
}*/
console.log(services);
console.log('Initializing File Transfer Client...');
this.initFileClient(new FileTransferClient(this.bleDevice, 65536));
await this.fileHelper.bond();
await this.connectToSerial();
// Enable/Disable UI buttons
this.connectionStep(3);
await this.onConnected();
this.connectDialog.close();
await this.loadEditor();
}
// Bond
async onBond(e) {
try {
console.log("bond");
await this.fileHelper.bond();
console.log("bond done");
} catch (e) {
console.log(e, e.stack);
}
await this.loadEditor();
}
async serialTransmit(msg) {
if (this.rxCharacteristic) {
let encoder = new TextEncoder();
let value = encoder.encode(msg);
try {
if (value.byteLength < BYTES_PER_WRITE) {
await this.rxCharacteristic.writeValueWithoutResponse(value);
return;
}
var offset = 0;
while (offset < value.byteLength) {
let len = Math.min(value.byteLength - offset, BYTES_PER_WRITE);
let chunk_contents = value.slice(offset, offset + len);
console.log("write subarray", offset, chunk_contents);
// Delay to ensure the last value was written to the device.
await sleep(100);
await this.rxCharacteristic.writeValueWithoutResponse(chunk_contents);
offset += len;
}
} catch (e) {
console.log("caught write error", e, e.stack);
}
}
}
async connect() {
let result;
if (result = await super.connect() instanceof Error) {
return result;
}
// Is this a new connection?
if (!this.bleDevice) {
let devices = await navigator.bluetooth.getDevices();
for (const device of devices) {
await this.connectToBluetoothDevice(device);
}
}
// Do we have a connection now but still need to connect serial?
if (this.bleDevice && !this.bleServer) {
await this.showBusy(this.bleDevice.gatt.connect());
this.switchToDevice(this.bleDevice);
}
}
updateConnected(connectionState) {
super.updateConnected(connectionState);
this.connectionStep(2);
}
async available() {
if (!('bluetooth' in navigator)) {
return Error("Web Bluetooth is not enabled in this browser");
} else if (!(await navigator.bluetooth.getAvailability())) {
return Error("No bluetooth adapter found");
}
return true;
}
async showInfo(documentState) {
return await this.infoDialog.open(this, documentState);
}
}
export {BLEWorkflow};