-
Notifications
You must be signed in to change notification settings - Fork 8
/
web-bluetooth-example.html
403 lines (328 loc) · 16.1 KB
/
web-bluetooth-example.html
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
---
feature_name: Web Bluetooth / Battery Level (Async Await)
chrome_version: 55
check_min_version: true
feature_id: 5264933985976320
icon_url: icon.png
index: index.html
---
<img class="pageIcon" src="icon.png">
<h1>Web Bluetooth / Coyote Sample</h1>
<p class="availability">
Available in <a target="_blank" href="https://www.chromestatus.com/feature/5264933985976320">Chrome 55+</a> |
<a target="_blank" href="https://github.com/rezreal/pavlow3/web-bluetooth-example.html">View on GitHub</a>
</p>
<p>The <a href="https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web">Web Bluetooth
API</a> lets websites discover and communicate with devices over the
Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT). It is
currently partially implemented in Android M, Chrome OS, Linux, and Mac.</p>
<p>This sample illustrates the use of the Web Bluetooth API to interact with the Coyote device alert service.</p>
<p><em>Note: During operation, the tab must stay in the foreground in order to keep sending the power levels. Otherwise the device will stutter (background tabs can only "tick" once a second). This problem can be addressed using web-workers.</em></p>
<button id="pair">Pair with Coyote</button>
<form>
<fieldset>
<legend>Status</legend>
<label for="battery_level">Battery Level</label>
<progress id="battery_level" value="0" max="100"></progress>
<input id="battery_level_text" disabled/>
<label for="max_power">Max Power</label>
<input id="max_power" disabled value="?"/>
<label for="power_step">Power Step</label>
<input id="power_step" disabled value="?"/>
<br/>
<label for="power_level_a">Power Level A</label>
<input id="power_level_a" min="0" value="0" max="2000" step="7" type="number"/>
<progress id="power_level_a_progress" value="0" max="2000"></progress>
<br/>
<label for="power_level_b">Power Level B</label>
<input id="power_level_b" min="0" value="0" max="2000" step="7" type="number"/>
<progress id="power_level_b_progress" value="0" max="2000"></progress>
<br/>
<button type="button" id="start" disabled="disabled">Start</button>
<button type="button" id="stop" disabled="disabled">Stop</button>
</fieldset>
<fieldset>
<legend>Pattern A</legend>
<label for="ax">Pulse Length (0-31 ms)</label>
<input id="ax" type="number" min="0" max="31" value="" placeholder="?"/>
<label for="ay">Pause Length (0-1023 ms)</label>
<input id="ay" type="number" min="0" max="1024" step="10" value="" placeholder="?"/>
<label for="az">Amplitude (0-31)</label>
<input id="az" type="number" min="0" max="31" value="" placeholder="?"/>
</fieldset>
<fieldset>
<legend>Pattern B</legend>
<label for="bx">Pulse Length (0-31)</label>
<input id="bx" type="number" min="0" max="31" value="" placeholder="?"/>
<label for="by">Pause Length (0-1023)</label>
<input id="by" type="number" min="0" max="1024" step="10" value="" placeholder="?"/>
<label for="bz">Amplitude (0-31)</label>
<input id="bz" type="number" min="0" max="31" value="" placeholder="?"/>
</fieldset>
</form>
<script>
var ChromeSamples = {
log: function () {
var line = Array.prototype.slice.call(arguments).map(function (argument) {
return typeof argument === 'string' ? argument : JSON.stringify(argument);
}).join(' ');
document.querySelector('#log').textContent += line + '\n';
const elem = document.getElementById('log');
elem.scrollTop = elem.scrollHeight;
},
clearLog: function () {
document.querySelector('#log').textContent = '';
},
setStatus: function (status) {
document.querySelector('#status').textContent = status;
},
setContent: function (newContent) {
var content = document.querySelector('#content');
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
content.appendChild(newContent);
}
};
</script>
<h3>Live Output</h3>
<div id="output" class="output">
<div id="content"></div>
<div id="status"></div>
<pre id="log"></pre>
</div>
<script>
if (/Chrome\/(\d+\.\d+.\d+.\d+)/.test(navigator.userAgent)) {
// Let's log a warning if the sample is not supposed to execute on this
// version of Chrome.
if (55 > parseInt(RegExp.$1)) {
ChromeSamples.setStatus('Warning! Keep in mind this sample has been tested with Chrome ' + 55 + '.');
}
}
</script>
<script>
const coyoteService = "955a180b-0fe2-f5aa-a094-84b8d4f3e8ad";
const configCharacteristic = "955a1507-0fe2-f5aa-a094-84b8d4f3e8ad";
const powerCharacteristic = "955a1504-0fe2-f5aa-a094-84b8d4f3e8ad";
const patternACharacteristic = "955a1506-0fe2-f5aa-a094-84b8d4f3e8ad";
const patternBCharacteristic = "955a1505-0fe2-f5aa-a094-84b8d4f3e8ad";
const batteryService = "955a180a-0fe2-f5aa-a094-84b8d4f3e8ad";
const batteryCharacteristic = "955a1500-0fe2-f5aa-a094-84b8d4f3e8ad";
let hasAcceptedWarning = false;
document.querySelector('button#pair').addEventListener('click', () => {
if (isWebBluetoothEnabled()) {
ChromeSamples.clearLog();
onButtonClick();
}
});
/***
* @param {ArrayBuffer} buffer
* @return {void}
*/
function flipFirstAndThirdByte(buffer) {
const bufferBytes = new Uint8Array(buffer);
const b = bufferBytes[0];
bufferBytes[0] = bufferBytes[2];
bufferBytes[2] = b;
}
/**
* @param {number} powerA
* @param {number} powerB
* @return {ArrayBuffer}
*/
function encodePower(powerA, powerB) {
/**
* notify/write: 3 bytes: zero(2) ~ uint(11).as("powerLevelB") ~uint(11).as("powerLevelA")
* 0 0 a a a a a a | a a a a a b b b | b b b b b b b b
* Power levels must likely be a multiple of "powerStep" and between 0 and "maxPower" (as obtained through config attribute.)
*/
const buffer = new ArrayBuffer(3);
const view = new DataView(buffer);
view.setUint8(0, (powerA >>> 5) & 0b00111111)
view.setUint8(1, ((powerA & 0b00011111) << 3) | ((powerB & 0b11111111111) >>> 8))
view.setUint8(2, powerB & 0b11111111)
flipFirstAndThirdByte(buffer);
return buffer;
}
/**
* @param {DataView} dataView
* @return {[number, number]} powerA and powerB
*/
function parsePower(dataView) {
flipFirstAndThirdByte(dataView.buffer);
// notify/write: 3 bytes: flipFirstAndThirdByte(zero(2) ~ uint(11).as("powerLevelB") ~uint(11).as("powerLevelA")
const powerA = dataView.getUint16(0) >> 3 // push the remainder of B out of the first 2 bytes
const powerB = dataView.getUint16(1) & 0b0000011111111111 // push the remainder A out of the last 2 bytes
return [powerA, powerB]
}
/**
* @param {DataView} dataView
* @return {[number, number, number]} ax ay az
*/
function parsePattern(dataView) {
flipFirstAndThirdByte(dataView.buffer);
// flipFirstAndThirdByte(zero(4) ~ uint(5).as("az") ~ uint(10).as("ay") ~ uint(5).as("ax"))
// 0000zzzz | zyyyyyyy | yyyxxxxx
const az = (dataView.getUint16(0) & 0b00001111_10000000) >>> 7;
const ay = ((dataView.getUint16(0) & 0b00000000_01111111)) << 3 | ((dataView.getUint8(2) & 0b11100000) >>> 5);
const ax = (dataView.getUint8(2) & 0b00011111)
return [ax, ay, az]
}
/**
* @param {number} ax
* @param {number} ay
* @param {number} az
* @return {ArrayBuffer}
*/
function encodePattern(ax, ay, az) {
const buffer = new ArrayBuffer(3);
// flipFirstAndThirdByte(zero(4) ~ uint(5).as("az") ~ uint(10).as("ay") ~ uint(5).as("ax"))
// 0000zzzz | zyyyyyyy | yyyxxxxx
const view = new DataView(buffer);
view.setUint8(0, ((az & 0b00011110) >>> 1))
view.setUint16(1, ((az & 0b00000001) << 15) | ((ay & 0b00000011_11111111) << 5) | (ax & 0b00011111));
flipFirstAndThirdByte(buffer);
return buffer;
}
async function onButtonClick() {
try {
log('Requesting Bluetooth Device...');
const device = await navigator.bluetooth.requestDevice({
filters: [{
namePrefix: 'D-LAB',
}],
//acceptAllDevices: true,
optionalServices: [coyoteService, batteryService]
});
log('Connecting to GATT Server...');
const server = await device.gatt.connect();
log('Getting Coyote Service...');
const service = await server.getPrimaryService(coyoteService);
log('Getting Config Characteristic...');
const config = await service.getCharacteristic(configCharacteristic);
log('Reading Config Characteristic...');
// read: 3 bytes: flipFirstAndThirdByte(skip(5) ~ uint(11).as("maxPower") ~ uint8.as("powerStep"))
const configValue = await config.readValue();
flipFirstAndThirdByte(configValue.buffer);
const maxPower = configValue.getUint16(0);
const powerStep = configValue.getUint8(2);
const powerLevelAInput = document.getElementById('power_level_a');
const powerLevelBInput = document.getElementById('power_level_b');
document.getElementById('max_power').value = maxPower;
document.getElementById('power_step').value = powerStep;
powerLevelAInput.max = maxPower;
powerLevelAInput.step = powerStep;
powerLevelBInput.max = maxPower;
powerLevelBInput.step = powerStep;
document.getElementById('power_level_a_progress').max = maxPower;
document.getElementById('power_level_b_progress').max = maxPower;
log('Getting Power Characteristic...');
const power = await service.getCharacteristic(powerCharacteristic);
log('Read Power value...');
const powerValue = await power.readValue();
let [devicePowerA, devicePowerB] = parsePower(powerValue);
const powerLevelAProgress = document.querySelector('#power_level_a_progress');
const powerLevelBProgress = document.querySelector('#power_level_b_progress');
powerLevelAInput.value = devicePowerA;
powerLevelBInput.value = devicePowerB;
powerLevelAProgress.value = devicePowerA;
powerLevelBProgress.value = devicePowerB;
log(`> Power Level is at a:${devicePowerA} b:${devicePowerB}`);
log('Subscribing to Power value...');
power.addEventListener('characteristicvaluechanged',
(event) => {
[devicePowerA, devicePowerB] = parsePower(event.target.value);
powerLevelAProgress.value = devicePowerA;
powerLevelBProgress.value = devicePowerB;
log(`> Power Level is at a:${devicePowerA} b:${devicePowerB}`);
});
await power.startNotifications();
log('Getting Pattern Characteristics...');
const patternA = await service.getCharacteristic(patternACharacteristic);
const patternB = await service.getCharacteristic(patternBCharacteristic);
log('Reading Pattern Characteristics...');
const patternAValue = await patternA.readValue();
const [ax, ay, az] = parsePattern(patternAValue);
document.querySelector('#ax').value = ax;
document.querySelector('#ay').value = ay;
document.querySelector('#az').value = az;
log(`> Pattern A is at ax:${ax} ${ay} az:${az}`);
const patternBValue = await patternB.readValue();
const [bx, by, bz] = parsePattern(patternBValue);
document.querySelector('#bx').value = bx;
document.querySelector('#by').value = by;
document.querySelector('#bz').value = bz;
log(`> Pattern B is at bx:${bx} ${by} bz:${bz}`);
log('Getting Battery Service...');
const battery = await server.getPrimaryService(batteryService);
{
log('Getting Battery Level Characteristic...');
const batteryLevelCharacteristic = await battery.getCharacteristic(batteryCharacteristic);
log('Starting Battery Level Notifications...');
await batteryLevelCharacteristic.startNotifications();
log('Reading Battery Level...');
const value = await batteryLevelCharacteristic.readValue();
document.querySelector('progress#battery_level').value = value.getUint8(0);
document.querySelector('input#battery_level_text').value = value.getUint8(0) + "%";
log('> Battery Level is ' + value.getUint8(0) + '%');
batteryLevelCharacteristic.addEventListener('characteristicvaluechanged',
(event) => {
let batteryLevel = event.target.value.getUint8(0);
log('> Battery Level is ' + batteryLevel + '%');
document.querySelector('progress#battery_level').value = Math.round(batteryLevel);
document.querySelector('input#battery_level_text').value = batteryLevel + "%";
});
}
const startButton = document.querySelector("button#start");
const stopButton = document.querySelector("button#stop");
startButton.disabled = false;
startButton.addEventListener('click', () => {
if (hasAcceptedWarning || window.confirm("This can hurt! Are you sure you want to continue (on your responsibility)?")) {
hasAcceptedWarning = true;
}
startButton.disabled = true;
const timer = window.setInterval(()=> {
const ax = parseInt(document.querySelector('#ax').value);
const ay = parseInt(document.querySelector('#ay').value);
const az = parseInt(document.querySelector('#az').value);
patternA.writeValue(encodePattern(ax, ay, az));
const bx = parseInt(document.querySelector('#bx').value);
const by = parseInt(document.querySelector('#by').value);
const bz = parseInt(document.querySelector('#bz').value);
patternB.writeValue(encodePattern(bx, by, bz));
const selectedPowerA = parseInt(powerLevelAInput.value);
const selectedPowerB = parseInt(powerLevelBInput.value);
if (selectedPowerA !== devicePowerA || selectedPowerB !== devicePowerB) {
power.writeValue(encodePower(selectedPowerA, selectedPowerB));
log(`> Writing Power with with: a:${selectedPowerA} ${selectedPowerB}`);
}
}, 100);
const stopClickListener = stopButton.addEventListener('click', () => {
stopButton.removeEventListener('click', stopClickListener);
clearInterval(timer);
power.writeValue(encodePower(0,0));
powerLevelAInput.value = 0;
powerLevelBInput.value = 0;
startButton.disabled = false;
stopButton.disabled = true;
});
stopButton.disabled = false;
});
} catch (error) {
log('Argh! ' + error);
throw error;
}
}
</script>
<script>
log = ChromeSamples.log;
function isWebBluetoothEnabled() {
if (navigator.bluetooth) {
return true;
} else {
ChromeSamples.setStatus('Web Bluetooth API is not available.\n' +
'Please make sure the "Experimental Web Platform features" flag is enabled.');
return false;
}
}
</script>