forked from mozilla-b2g/gaia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.js
836 lines (744 loc) · 27.3 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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
/* -*- 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
navigator.mozL10n.ready(function bluetoothSettings() {
var _ = navigator.mozL10n.get;
var settings = Settings.mozSettings;
var bluetooth = getBluetooth();
var defaultAdapter = null;
if (!settings || !bluetooth) {
return;
}
var gBluetoothCheckBox = document.querySelector('#bluetooth-status input');
// display Bluetooth power state
function updateBluetoothState(value) {
gBluetoothCheckBox.checked = value;
}
// activate main button
gBluetoothCheckBox.onchange = function changeBluetooth() {
var req = settings.createLock().set({'bluetooth.enabled': this.checked});
this.disabled = true;
req.onerror = function() {
gBluetoothCheckBox.disabled = false;
};
};
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 bluetoothRename = document.getElementById('bluetooth-rename');
var renameButton = document.getElementById('rename-device');
var visibleTimeout = null;
var visibleTimeoutTime = 120000; // visibility will timeout after 2 minutes
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);
// Bug 847459: Default name of the bluetooth device is set by bluetoothd
// to the value of the Android ro.product.model property upon first
// start. In case the user gives an empty bluetooth device name, we want
// to revert to the original ro.product.model. Gecko exposes it under
// the deviceinfo.product_model setting.
var deviceInfo = settings.createLock().get('deviceinfo.product_model');
deviceInfo.onsuccess = function bt_getProductModel() {
var productModel = deviceInfo.result['deviceinfo.product_model'];
nameEntered = nameEntered.replace(/^\s+|\s+$/g, '');
if (nameEntered === myName || !bluetooth.enabled || !defaultAdapter) {
return;
}
var req = defaultAdapter.setName(nameEntered || productModel);
req.onsuccess = function bt_renameSuccess() {
myName = visibleName.textContent = defaultAdapter.name;
};
};
};
// immediatly UI update, DOM element manipulation.
function updateDeviceInfo(show) {
bluetoothRename.hidden = !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() {
visibleCheckBox.checked = defaultAdapter.discoverable;
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) {
if (!bluetooth.enabled || !defaultAdapter)
return;
settings.createLock().set({'bluetooth.visible': visible});
defaultAdapter.setDiscoverable(visible);
// Visibility will time out after 2 mins.
if (visible) {
if (!visibleTimeout) {
visibleTimeout = setTimeout(function() {
setDiscoverable(false);
}, visibleTimeoutTime);
}
} else {
if (visibleTimeout) {
clearTimeout(visibleTimeout);
visibleTimeout = null;
}
}
visibleCheckBox.checked = visible;
}
// API
return {
update: updateDeviceInfo,
initWithAdapter: initial
};
})();
// device list
gDeviceList = (function deviceList() {
var bluetoothSearch = document.getElementById('bluetooth-search');
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 userCanceledPairing = false;
var pairingAddress = null;
var connectingAddress = null;
var connectedAddress = null;
// stop discover other device after 60 seconds
var discoverTimeoutTime = 60000;
var discoverTimeout = null;
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() {
stopDiscovery();
setDeviceConnect(device);
};
}
} 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;
}
};
searchAgainBtn.onclick = function searchAgainClicked() {
updateDeviceList(true); // reset network list
openList.clear();
startDiscovery();
};
// private DOM helper: create a device list item
function newListItem(device, descL10nId) {
var deviceName = document.createElement('a');
var aName = (device.name === '') ? _('unnamed-device') : device.name;
var aL10nId = (device.name === '') ? 'unnamed-device' : '';
deviceName.textContent = aName;
deviceName.dataset.l10nId = aL10nId;
var deviceDesc = document.createElement('small');
deviceDesc.textContent = (descL10nId === '') ? '' : _(descL10nId);
deviceDesc.dataset.l10nId = descL10nId;
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) {
bluetoothSearch.hidden = !show;
if (show) {
enableMsg.hidden = true;
openList.show(true);
searchingItem.hidden = false;
document.addEventListener('mozvisibilitychange',
stopDiscoveryWhenLeaveApp);
} else {
openList.show(false);
pairList.show(false);
enableMsg.hidden = false;
searchingItem.hidden = true;
optionMenu.close();
pairingAddress = null;
connectingAddress = null;
connectedAddress = null;
// clear discoverTimeout
clearTimeout(discoverTimeout);
discoverTimeout = null;
document.removeEventListener('mozvisibilitychange',
stopDiscoveryWhenLeaveApp);
}
}
// 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);
}
);
navigator.mozSetMessageHandler('bluetooth-cancel',
function bt_gotCancelMessage(message) {
showDevicePaired(false, null);
}
);
navigator.mozSetMessageHandler('bluetooth-pairedstatuschanged',
function bt_getPairedMessage(message) {
dispatchEvent(new CustomEvent('bluetooth-pairedstatuschanged'));
showDevicePaired(message.paired, 'Authentication Failed');
}
);
navigator.mozSetMessageHandler('bluetooth-hfp-status-changed',
function bt_getConnectedMessage(message) {
showDeviceConnected(message.address, message.connected);
}
);
// get paired device and restore connection
// if we have one device connected before.
getPairedDevice(restoreConnection);
startDiscovery();
}
function restoreConnection() {
window.asyncStorage.getItem('device.connected', function(value) {
if (!value || !pairList.index[value])
return;
var device = pairList.index[value][0];
isDeviceConnected(device, function(connected) {
if (connected) {
showDeviceConnected(device.address, true);
} else {
setDeviceConnect(device);
}
});
});
}
function getPairedDevice(callback) {
if (!bluetooth.enabled || !defaultAdapter)
return;
var req = defaultAdapter.getPairedDevices();
req.onsuccess = function bt_getPairedSuccess() {
// copy for sorting
var paired = req.result.slice();
var length = paired.length;
if (length == 0) {
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 stateL10nId = (device.address === connectedAddress) ?
'device-status-connected' : '';
var aItem = newListItem(device, stateL10nId);
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') {
var small = aItem.querySelector('small');
small.textContent = _('device-status-connecting');
small.dataset.l10nId = 'device-status-connecting';
setTimeout(function() {
setDeviceConnect(device);
}, 5000);
}
})(paired[i]);
}
pairList.show(true);
// the callback function now is for restoring the connected device
// when the bluetooth is turned on.
if (callback)
callback();
};
}
function isDeviceConnected(device, callback) {
if (!callback)
return;
if (defaultAdapter && device) {
var getConnectedDevices = function(profileID, gcdCallback) {
var req = defaultAdapter.getConnectedDevices(profileID);
req.onsuccess = function() {
if (gcdCallback) {
gcdCallback(req.result || []);
}
};
req.onerror = function() {
if (gcdCallback) {
gcdCallback(null);
}
};
};
var findDeviceByAddress = function(address, connectedDevices) {
if (!connectedDevices)
return false;
var found = false;
for (var i in connectedDevices) {
var connectedDevice = connectedDevices[i];
if (connectedDevice.address === address) {
found = true;
break;
}
}
return found;
};
// '0x111E' is a service id of HFP.
// '0x1108' is a service id of HSP.
getConnectedDevices(0x111E, function(hfpResult) {
if (findDeviceByAddress(device.address, hfpResult)) {
callback(true);
} else {
getConnectedDevices(0x1108, function(hspResult) {
if (findDeviceByAddress(device.address, hspResult)) {
callback(true);
} else {
callback(false);
}
});
}
});
} else {
callback(false);
}
}
// callback function when an avaliable device found
function onDeviceFound(evt) {
var device = evt.device;
// Ignore duplicate and paired device. Update the name if needed.
var existingDevice = openList.index[device.address] ||
pairList.index[device.address];
if (existingDevice) {
var existingItem = existingDevice[1];
if (device.name && existingItem) {
var deviceName = existingItem.querySelector('a');
if (deviceName) {
deviceName.dataset.l10nId = '';
deviceName.textContent = device.name;
}
}
return;
}
var aItem = newListItem(device, 'device-status-tap-connect');
// bind paired callback
aItem.onclick = function() {
var small = aItem.querySelector('small');
small.textContent = _('device-status-pairing');
small.dataset.l10nId = 'device-status-pairing';
stopDiscovery();
var req = defaultAdapter.pair(device);
pairingMode = 'active';
pairingAddress = device.address;
req.onerror = function bt_pairError(error) {
showDevicePaired(false, req.error.name);
};
};
openList.list.appendChild(aItem);
openList.index[device.address] = [device, aItem];
}
function showDevicePaired(paired, errorMessage) {
// If we don't know the pairing device address,
// it means the pair request is handled by interface level.
// So we just need to update paired list.
if (!pairingAddress) {
getPairedDevice();
return;
}
// clear pairingAddress first to prevent execute
// the same status update twice.
var workingAddress = pairingAddress;
pairingAddress = null;
if (paired) {
// if the device is on the list, remove it.
// it will show on paired list later.
if (openList.index[workingAddress]) {
var device = openList.index[workingAddress][0];
var item = openList.index[workingAddress][1];
openList.list.removeChild(item);
delete openList.index[workingAddress];
connectingAddress = workingAddress;
}
} else {
// if the attention screen still open, close it
if (childWindow) {
childWindow.PairView.closeInput();
childWindow.close();
}
// display failure only when active request
if (pairingMode === 'active' && !userCanceledPairing) {
// show pair process fail.
var msg = _('error-pair-title');
if (errorMessage === 'Repeated Attempts') {
msg = msg + '\n' + _('error-pair-toofast');
} else if (errorMessage === 'Authentication Failed') {
msg = msg + '\n' + _('error-pair-pincode');
}
window.alert(msg);
}
userCanceledPairing = false;
// rollback device status
if (openList.index[workingAddress]) {
var small = openList.index[workingAddress][1].querySelector('small');
small.textContent = _('device-status-tap-connect');
small.dataset.l10nId = 'device-status-tap-connect';
}
}
// 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, null);
};
}
function setDeviceDisconnect(device) {
if (!bluetooth.enabled || !defaultAdapter ||
device.address !== connectedAddress)
return;
// '0x111E' is a service id of HFP.
// https://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
// XXX: Bug 870689. The device maybe connected using HFP or HSP. Always
// pass 0x111E here until gecko separates these two profiles.
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 (!bluetooth.enabled || !defaultAdapter ||
device.icon !== 'audio-card' ||
device.address === connectedAddress) {
connectingAddress = null;
return;
}
// disconnect current connected device first
if (connectedAddress && pairList.index[connectedAddress]) {
setDeviceDisconnect(pairList.index[connectedAddress][0]);
}
var connectToDevice =
function bt_connectToDevice(address, serviceID, onsuccess, onerror) {
var req = defaultAdapter.connect(address, serviceID);
req.onerror = onerror;
req.onsuccess = onsuccess;
return req;
};
var connectError = function bt_connectError() {
// Connection state might be changed before DOM request response.
if (connectingAddress) {
showDeviceConnected(connectingAddress, false);
connectingAddress = null;
window.alert(_('error-connect-msg'));
}
};
// '0x111E' is a service id of HFP.
// '0x1108' is a service id of HSP.
// https://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
var req = connectToDevice(device.address, 0x111E, null, function() {
if (req.error.name === 'DeviceChannelRetrievalError') {
// Try to connect using HSP again.
connectToDevice(device.address, 0x1108, null, function() {
connectError();
});
} else {
connectError();
}
});
connectingAddress = device.address;
if (!pairList.index[connectingAddress]) {
return;
}
var small = pairList.index[connectingAddress][1].querySelector('small');
small.textContent = _('device-status-connecting');
small.dataset.l10nId = 'device-status-connecting';
}
function showDeviceConnected(deviceAddress, connected) {
if (connected) {
connectedAddress = deviceAddress;
// clear it because we are not in a connecting status now.
connectingAddress = null;
// record connected device so if Bluetooth is turned off and then on
// we can restore the connection
window.asyncStorage.setItem('device.connected', connectedAddress);
} else {
if (connectedAddress === deviceAddress) {
connectedAddress = null;
window.asyncStorage.removeItem('device.connected');
}
}
if (!pairList.index[deviceAddress]) {
return;
}
var small = pairList.index[deviceAddress][1].querySelector('small');
small.textContent = (connected) ? _('device-status-connected') : '';
small.dataset.l10nId = (connected) ? 'device-status-connected' : '';
}
function onRequestPairing(evt) {
var showPairView = function bt_showPairView() {
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 method = evt.method;
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);
};
};
var req = navigator.mozSettings.createLock().get('lockscreen.locked');
req.onsuccess = function bt_onGetLocksuccess() {
if (!req.result['lockscreen.locked']) {
showPairView();
}
};
req.onerror = function bt_onGetLockError() {
// fallback to default value 'unlocked'
showPairView();
};
}
function startDiscovery() {
if (!bluetooth.enabled || !defaultAdapter || discoverTimeout)
return;
var req = defaultAdapter.startDiscovery();
req.onsuccess = function bt_discoveryStart() {
searchAgainBtn.disabled = true;
if (!discoverTimeout)
discoverTimeout = setTimeout(stopDiscovery, discoverTimeoutTime);
};
req.onerror = function bt_discoveryFailed() {
searchingItem.hidden = true;
searchAgainBtn.disabled = false;
};
}
function stopDiscoveryWhenLeaveApp() {
//only stop discovery when Settings app is hidden
if (!document.mozHidden)
return;
stopDiscovery();
}
function stopDiscovery() {
if (!bluetooth.enabled || !defaultAdapter || !discoverTimeout)
return;
var req = defaultAdapter.stopDiscovery();
req.onsuccess = function bt_discoveryStopped() {
searchAgainBtn.disabled = false;
searchingItem.hidden = true;
};
req.onerror = function bt_discoveryStopFailed() {
console.error('Can not stop discover nearby device');
searchAgainBtn.disabled = true;
searchingItem.hidden = false;
};
clearTimeout(discoverTimeout);
discoverTimeout = null;
}
function setConfirmation(address, confirmed) {
if (!bluetooth.enabled || !defaultAdapter)
return;
userCanceledPairing = !confirmed;
var req = defaultAdapter.setPairingConfirmation(address, confirmed);
}
function setPinCode(address, pincode) {
if (!bluetooth.enabled || !defaultAdapter)
return;
defaultAdapter.setPinCode(address, pincode);
}
function setPasskey(address, passkey) {
if (!bluetooth.enabled || !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;
// lock UI toggle
gBluetoothCheckBox.disabled = true;
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.addEventListener('adapteradded', function() {
// enable UI toggle
gBluetoothCheckBox.disabled = false;
initialDefaultAdapter();
dispatchEvent(new CustomEvent('bluetooth-adapter-added'));
});
bluetooth.addEventListener('disabled', function() {
gBluetoothCheckBox.disabled = false; // enable UI toggle
defaultAdapter = null; // clear defaultAdapter
dispatchEvent(new CustomEvent('bluetooth-disabled'));
});
});