forked from mozilla-b2g/gaia
/
bluetooth.js
638 lines (561 loc) · 20 KB
/
bluetooth.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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
/**
* gDeviceList is defined here because the child window created for pairing
* requests needs to access its method via window.opener
*/
var gDeviceList = null;
// handle Bluetooth settings
onLocalized(function bluetoothSettings() {
var _ = navigator.mozL10n.get;
var settings = window.navigator.mozSettings;
var bluetooth = window.navigator.mozBluetooth;
var defaultAdapter = null;
if (!settings || !bluetooth) {
return;
}
var gBluetoothInfoBlock = document.getElementById('bluetooth-desc');
var gBluetoothCheckBox = document.querySelector('#bluetooth-status input');
var gBluetoothRename = document.getElementById('bluetooth-rename');
var gBluetoothSearch = document.getElementById('bluetooth-search');
// display Bluetooth power state
function updateBluetoothState(value) {
gBluetoothInfoBlock.textContent =
value ? _('bt-status-nopaired') : _('bt-status-turnoff');
gBluetoothCheckBox.checked = value;
gBluetoothRename.hidden = !value;
gBluetoothSearch.hidden = !value;
}
// activate main button
gBluetoothCheckBox.onchange = function changeBluetooth() {
settings.createLock().set({'bluetooth.enabled': this.checked});
};
function initialDefaultAdapter() {
if (!bluetooth.enabled)
return;
var req = bluetooth.getDefaultAdapter();
req.onsuccess = function bt_getAdapterSuccess() {
defaultAdapter = req.result;
if (defaultAdapter == null) {
// we can do nothing without DefaultAdapter, so set bluetooth disabled
settings.createLock().set({'bluetooth.enabled': false});
return;
}
defaultAdapter.ondevicefound = gDeviceList.onDeviceFound;
// initial related components that need defaultAdapter.
gMyDeviceInfo.initWithAdapter();
gDeviceList.initWithAdapter();
};
req.onerror = function bt_getAdapterFailed() {
// we can do nothing without DefaultAdapter, so set bluetooth disabled
settings.createLock().set({'bluetooth.enabled': false});
};
}
// device information
var gMyDeviceInfo = (function deviceInfo() {
var visibleItem = document.getElementById('device-visible');
var visibleName = document.getElementById('bluetooth-device-name');
var visibleCheckBox = document.querySelector('#device-visible input');
var renameButton = document.getElementById('rename-device');
var visibleTimeout = null;
var myName = '';
visibleCheckBox.onchange = function changeDiscoverable() {
setDiscoverable(this.checked);
};
renameButton.onclick = function renameBtnClicked() {
if (myName === '') {
myName = visibleName.textContent = defaultAdapter.name;
}
var nameEntered = window.prompt(_('change-phone-name'), myName);
if (!nameEntered || nameEntered === '' || nameEntered === myName)
return;
var req = defaultAdapter.setName(nameEntered);
req.onsuccess = function bt_renameSuccess() {
myName = visibleName.textContent = defaultAdapter.name;
}
};
// immediatly UI update, DOM element manipulation.
function updateDeviceInfo(show) {
if (show) {
visibleItem.hidden = false;
// get last user setting for device visible
var req = settings.createLock().get('bluetooth.visible');
req.onsuccess = function bt_getVisibleSuccess() {
var visible = req.result['bluetooth.visible'];
if (typeof visible === 'undefined') {
visible = true;
}
setDiscoverable(visible);
};
req.onerror = function bt_getVisibleError() {
visibleCheckBox.checked = true;
};
} else {
visibleItem.hidden = true;
renameButton.disabled = true;
if (visibleTimeout) {
clearTimeout(visibleTimeout);
visibleTimeout = null;
}
}
}
// initial this device information and do default actions
// when DefaultAdapter is ready.
function initial() {
setDiscoverable(visibleCheckBox.checked);
// we can't get device name immediately, wait a while
setTimeout(function() {
myName = visibleName.textContent = defaultAdapter.name;
renameButton.disabled = false;
}, 1000);
}
function setDiscoverable(visible) {
settings.createLock().set({'bluetooth.visible': visible});
if (!defaultAdapter)
return;
defaultAdapter.setDiscoverable(visible);
// Visibility will time out after 2 mins.
if (visible) {
if (!visibleTimeout) {
visibleTimeout = setTimeout(function() {
setDiscoverable(false);
}, 120000);
}
} else {
if (visibleTimeout) {
clearTimeout(visibleTimeout);
visibleTimeout = null;
}
}
visibleCheckBox.checked = visible;
}
// API
return {
update: updateDeviceInfo,
initWithAdapter: initial
};
})();
// device list
gDeviceList = (function deviceList() {
var pairList = {
title: document.getElementById('bluetooth-paired-title'),
list: document.getElementById('bluetooth-paired-devices'),
index: [],
clear: function emptyList() {
while (this.list.hasChildNodes()) {
this.list.removeChild(this.list.lastChild);
}
this.index = [];
},
show: function showArea(isShown) {
if (!isShown) {
this.clear();
}
this.title.hidden = !isShown;
this.list.hidden = !isShown;
}
};
var openList = {
title: document.getElementById('bluetooth-found-title'),
list: document.getElementById('bluetooth-devices'),
index: [],
clear: function emptyList() {
while (this.list.hasChildNodes()) {
this.list.removeChild(this.list.lastChild);
}
this.index = [];
},
show: function showArea(isShown) {
if (!isShown) {
this.clear();
}
this.title.hidden = !isShown;
this.list.hidden = !isShown;
}
};
var optionMenu = {
menu: document.getElementById('paired-device-option'),
connectOpt: document.getElementById('connect-option'),
disconnectOpt: document.getElementById('disconnect-option'),
unpairOpt: document.getElementById('unpair-option'),
show: function showMenu(device) {
var self = this;
// we only support audio-card device to connect atm
if (device.icon === 'audio-card') {
if (connectedAddress && device.address === connectedAddress) {
this.connectOpt.style.display = 'none';
this.disconnectOpt.style.display = 'block';
this.disconnectOpt.onclick = function() {
setDeviceDisconnect(device);
};
} else {
this.connectOpt.style.display = 'block';
this.disconnectOpt.style.display = 'none';
this.connectOpt.onclick = function() {
setDeviceConnect(device);
stopDiscovery();
};
}
} else {
this.connectOpt.style.display = 'none';
this.disconnectOpt.style.display = 'none';
}
this.unpairOpt.onclick = function() {
setDeviceUnpair(device);
};
this.menu.onsubmit = function closeMenu() {
return self.close();
}
this.menu.hidden = false;
},
close: function closeMenu() {
this.menu.hidden = true;
return false;
}
};
var searchAgainBtn = document.getElementById('search-device');
var searchingItem = document.getElementById('bluetooth-searching');
var enableMsg = document.getElementById('bluetooth-enable-msg');
var childWindow = null;
var pairingMode = 'active';
var pairingAddress = null;
var connectingAddress = null;
var connectedAddress = null;
var discoverTimeout = null;
searchAgainBtn.onclick = function searchAgainClicked() {
updateDeviceList(true); // reset network list
openList.clear();
startDiscovery();
};
// private DOM helper: create a device list item
function newListItem(device, desc) {
var deviceName = document.createElement('a');
var aName = (device.name === '') ? _('unnamed-device') : device.name;
deviceName.textContent = aName;
var deviceDesc = document.createElement('small');
deviceDesc.textContent = desc;
var li = document.createElement('li');
li.classList.add('bluetooth-device');
li.classList.add('bluetooth-type-' + device.icon);
li.appendChild(deviceDesc); // should append this first
li.appendChild(deviceName);
return li;
}
// immediatly UI update, DOM element manipulation.
function updateDeviceList(show) {
if (show) {
enableMsg.hidden = true;
openList.show(true);
searchingItem.hidden = false;
} else {
openList.show(false);
pairList.show(false);
enableMsg.hidden = false;
searchingItem.hidden = true;
optionMenu.close();
// clear discoverTimeout
clearTimeout(discoverTimeout);
discoverTimeout = null;
}
}
// do default actions (start discover avaliable devices)
// when DefaultAdapter is ready.
function initial() {
// Bind message handler for incoming pairing requests
navigator.mozSetMessageHandler('bluetooth-requestconfirmation',
function bt_gotConfirmationMessage(message) {
onRequestPairing(message, 'confirmation');
}
);
navigator.mozSetMessageHandler('bluetooth-requestpincode',
function bt_gotPincodeMessage(message) {
onRequestPairing(message, 'pincode');
}
);
navigator.mozSetMessageHandler('bluetooth-requestpasskey',
function bt_gotPasskeyMessage(message) {
onRequestPairing(message, 'passkey');
}
);
navigator.mozSetMessageHandler('bluetooth-cancel',
function bt_gotCancelMessage(message) {
showDevicePaired(false);
}
);
navigator.mozSetMessageHandler('bluetooth-pairedstatuschanged',
function bt_getPairedMessage(message) {
showDevicePaired(message.paired);
}
);
navigator.mozSetMessageHandler('bluetooth-hfp-status-changed',
function bt_getConnectedMessage(message) {
showDeviceConnected(message.address, message.connected);
}
);
getPairedDevice();
startDiscovery();
}
function getPairedDevice() {
var req = defaultAdapter.getPairedDevices();
req.onsuccess = function bt_getPairedSuccess() {
// copy for sorting
var paired = req.result.slice();
var length = paired.length;
if (length == 0) {
gBluetoothInfoBlock.textContent = _('bt-status-nopaired');
pairList.show(false);
return;
}
pairList.clear();
paired.sort(function(a, b) {
return a.name > b.name;
});
for (var i = 0; i < length; i++) {
(function(device) {
var state = (device.address === connectedAddress) ?
_('device-status-connected') : '';
var aItem = newListItem(device, state);
aItem.onclick = function() {
optionMenu.show(device);
};
pairList.list.appendChild(aItem);
pairList.index[device.address] = [device, aItem];
// if the device has to be connected when it just paired
// wait for a while so they can have time to communicate
// their connection protocol
if (device.address === connectingAddress &&
device.icon === 'audio-card') {
aItem.querySelector('small').textContent =
_('device-status-connecting');
setTimeout(function() {
setDeviceConnect(device);
}, 5000);
}
})(paired[i]);
}
var text = _('bt-status-paired', {
name: paired[0].name,
n: length - 1
});
gBluetoothInfoBlock.textContent = text;
pairList.show(true);
};
}
// callback function when an avaliable device found
function onDeviceFound(evt) {
var device = evt.device;
// ignore duplicate and paired device
if (openList.index[device.address] || pairList.index[device.address])
return;
var aItem = newListItem(device, _('device-status-tap-connect'));
// bind paired callback
aItem.onclick = function() {
aItem.querySelector('small').textContent = _('device-status-pairing');
var req = defaultAdapter.pair(device);
pairingMode = 'active';
pairingAddress = device.address;
stopDiscovery();
req.onerror = function bt_pairError() {
showDevicePaired(false);
};
};
openList.list.appendChild(aItem);
openList.index[device.address] = [device, aItem];
}
function showDevicePaired(paired) {
// if we are in a pairing process, update found device list
// or do error handling.
if (pairingAddress) {
if (paired) {
// if the device is on the list, remove it.
// it will show on paired list later.
if (openList.index[pairingAddress]) {
var device = openList.index[pairingAddress][0];
var item = openList.index[pairingAddress][1];
openList.list.removeChild(item);
connectingAddress = pairingAddress;
}
} else {
// if the attention screen still open, close it
if (childWindow)
childWindow.close();
// show pair process fail.
var msg = _('error-pair-title') + '\n' + _('error-pair-pincode');
// display failure only when active request
if (pairingMode === 'active')
window.alert(msg);
// rollback device status
if (openList.index[pairingAddress]) {
var item = openList.index[pairingAddress][1];
item.querySelector('small').textContent =
_('device-status-tap-connect');
}
}
pairingAddress = null;
}
// acquire a new paired list no matter paired or unpaired
getPairedDevice();
}
function setDeviceUnpair(device) {
if (device.address === connectedAddress) {
var msg = _('unpair-title') + '\n' + _('unpair-msg');
if (!window.confirm(msg))
return;
connectedAddress = null;
}
// backend takes responsibility to disconnect first.
var req = defaultAdapter.unpair(device);
req.onerror = function bt_pairError() {
showDevicePaired(true);
};
}
function setDeviceDisconnect(device) {
if (device.address !== connectedAddress)
return;
// '0x111E' is a service id to distigush connection type.
// https://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
var req = defaultAdapter.disconnect(0x111E);
req.onerror = function() {
showDeviceConnected(device.address, true);
};
}
function setDeviceConnect(device) {
// we only support audio-card device to connect now
if (!defaultAdapter || device.icon !== 'audio-card') {
connectingAddress = null;
return;
}
// disconnect current connected device first
if (connectedAddress && device.address !== connectedAddress) {
setDeviceDisconnect(pairList.index[connectedAddress][0]);
}
// '0x111E' is a service id to distigush connection type.
// https://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
var req = defaultAdapter.connect(device.address, 0x111E);
req.onerror = function() {
window.alert(_('error-connect-msg'));
showDeviceConnected(connectingAddress, false);
connectingAddress = null;
};
connectingAddress = device.address;
var item = pairList.index[connectingAddress][1];
item.querySelector('small').textContent = _('device-status-connecting');
}
function showDeviceConnected(deviceAddress, connected) {
if (connected) {
connectedAddress = deviceAddress;
} else {
if (connectedAddress === deviceAddress)
connectedAddress = null;
}
var item = pairList.index[deviceAddress][1];
item.querySelector('small').textContent = (connected) ?
_('device-status-connected') : '';
}
function onRequestPairing(evt, method) {
var device = {
address: evt.address,
name: evt.name || _('unnamed-device'),
icon: evt.icon || 'bluetooth-default'
};
if (device.address !== pairingAddress) {
pairingAddress = device.address;
pairingMode = 'passive';
}
var passkey = evt.passkey || null;
var protocol = window.location.protocol;
var host = window.location.host;
childWindow = window.open(protocol + '//' + host + '/onpair.html',
'pair_screen', 'attention');
childWindow.onload = function childWindowLoaded() {
childWindow.PairView.init(pairingMode, method, device, passkey);
};
}
function startDiscovery() {
if (!defaultAdapter)
return;
var req = defaultAdapter.startDiscovery();
req.onsuccess = function bt_discoveryStart() {
searchAgainBtn.disabled = true;
if (!discoverTimeout)
discoverTimeout = setTimeout(stopDiscovery, 60000);
};
req.onerror = function bt_discoveryFailed() {
searchingItem.hidden = true;
searchAgainBtn.disabled = false;
};
}
function stopDiscovery() {
if (!defaultAdapter || !bluetooth.enabled)
return;
var req = defaultAdapter.stopDiscovery();
req.onsuccess = function bt_discoveryStopped() {
searchAgainBtn.disabled = false;
searchingItem.hidden = true;
};
req.onerror = function bt_discoveryStopFailed() {
searchAgainBtn.disabled = true;
searchingItem.hidden = false;
};
clearTimeout(discoverTimeout);
discoverTimeout = null;
}
function setConfirmation(address) {
if (!defaultAdapter)
return;
var req = defaultAdapter.setPairingConfirmation(address, true);
}
function setPinCode(address, pincode) {
if (!defaultAdapter)
return;
defaultAdapter.setPinCode(address, pincode);
}
function setPasskey(address, passkey) {
if (!defaultAdapter)
return;
var key = parseInt(passkey, 10);
defaultAdapter.setPasskey(address, key);
}
// API
return {
update: updateDeviceList,
initWithAdapter: initial,
startDiscovery: startDiscovery,
onDeviceFound: onDeviceFound,
setConfirmation: setConfirmation,
setPinCode: setPinCode,
setPasskey: setPasskey,
onRequestPairing: onRequestPairing
};
})();
var lastMozSettingValue = false;
// enable Bluetooth if the related settings says so
// register an observer to monitor bluetooth.enabled changes
settings.addObserver('bluetooth.enabled', function(event) {
var enabled = event.settingValue;
if (lastMozSettingValue == enabled)
return;
lastMozSettingValue = enabled;
updateBluetoothState(enabled);
gDeviceList.update(enabled);
gMyDeviceInfo.update(enabled);
// clear defaultAdapter, we have to acquire it again when enabled.
if (!enabled)
defaultAdapter = null;
});
// startup, update status
var req = settings.createLock().get('bluetooth.enabled');
req.onsuccess = function bt_getSettingsSuccess() {
lastMozSettingValue = req.result['bluetooth.enabled'];
// if bluetooth is on when booting, the adapter probably is ready.
if (lastMozSettingValue)
initialDefaultAdapter();
updateBluetoothState(lastMozSettingValue);
gDeviceList.update(lastMozSettingValue);
gMyDeviceInfo.update(lastMozSettingValue);
};
bluetooth.onadapteradded = function bt_adapterAdded() {
initialDefaultAdapter();
};
});