Repository navigation
Expand file tree
/
Copy pathbluetooth.js
More file actions
949 lines (835 loc) · 30.1 KB
/
Copy pathbluetooth.js
File metadata and controls
949 lines (835 loc) · 30.1 KB
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
/* -*- 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() {
// Service ID for profiles
var Profiles = {
'HFP': 0x111E,
'A2DP': 0x110D
};
var _ = navigator.mozL10n.get;
var l10n = navigator.mozL10n;
var settings = Settings.mozSettings;
var bluetooth = getBluetooth();
var defaultAdapter = null;
var MAX_DEVICE_NAME_LENGTH = 20;
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. changeBluetooth() {
var req = settings.createLock().set({'bluetooth.enabled': this.checked});
this.disabled = true;
req. {
gBluetoothCheckBox.disabled = false;
};
};
function initialDefaultAdapter() {
if (!bluetooth.enabled)
return;
var req = bluetooth.getDefaultAdapter();
req. 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.>
// initial related components that need defaultAdapter.
gMyDeviceInfo.initWithAdapter();
gDeviceList.initWithAdapter();
};
req. 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. changeDiscoverable() {
setDiscoverable(this.checked);
};
renameButton. renameBtnClicked() {
if (myName === '') {
myName = visibleName.textContent = defaultAdapter.name;
}
var nameEntered = window.prompt(_('change-phone-name'), myName);
// If users click cancel button, we will get null here.
if (nameEntered === null) {
return;
}
nameEntered = nameEntered.replace(/^\s+|\s+$/g, '');
if (nameEntered.length > MAX_DEVICE_NAME_LENGTH) {
var wantToRetry = window.confirm(_('bluetooth-name-maxlength-alert',
{ length: MAX_DEVICE_NAME_LENGTH }));
if (wantToRetry) {
renameBtnClicked();
}
return;
}
if (nameEntered === myName || !bluetooth.enabled || !defaultAdapter) {
return;
}
if (nameEntered !== '') {
updateDeviceName(nameEntered);
}
else {
// 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. bt_getProductModel() {
var productModel = deviceInfo.result['deviceinfo.product_model'];
updateDeviceName(productModel);
};
}
};
function updateDeviceName(nameEntered) {
var req = defaultAdapter.setName(nameEntered);
req. 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. bt_getVisibleSuccess() {
var visible = req.result['bluetooth.visible'];
if (typeof visible === 'undefined') {
visible = true;
}
setDiscoverable(visible);
};
req. 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'),
confirmDlg: document.getElementById('unpair-device'),
confirmOpt: document.getElementById('confirm-option'),
showActions: function showActions() {
var self = this;
if (connectedAddress && this.device.address === connectedAddress) {
this.connectOpt.style.display = 'none';
this.disconnectOpt.style.display = 'block';
this.disconnectOpt. {
setDeviceDisconnect(self.device);
};
} else {
this.connectOpt.style.display = 'block';
this.disconnectOpt.style.display = 'none';
this.connectOpt. {
setDeviceConnect(self.device);
stopDiscovery();
};
}
this.unpairOpt. {
setDeviceUnpair(self.device);
};
this.menu. closeMenu() {
return self.close();
};
this.menu.hidden = false;
},
showConfirm: function showConfirm() {
var self = this;
this.confirmDlg. {
return self.close();
};
this.confirmOpt. {
setDeviceUnpair(self.device);
};
this.confirmDlg.hidden = false;
},
show: function showMenu(device) {
this.device = device;
// we only support audio-card device to connect atm
this[this.device.icon === 'audio-card' ?
'showActions' : 'showConfirm']();
},
close: function closeMenu() {
this.menu.hidden = true;
this.confirmDlg.hidden = true;
return false;
}
};
searchAgainBtn. 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');
if (device.name !== '') {
deviceName.textContent = device.name;
deviceName.dataset.l10nId = '';
} else {
l10n.localize(deviceName, 'unnamed-device');
}
var deviceDesc = document.createElement('small');
if (descL10nId) {
l10n.localize(deviceDesc, descL10nId);
} else {
deviceDesc.textContent = '';
deviceDesc.dataset.l10nId = '';
}
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('visibilitychange',
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('visibilitychange',
stopDiscoveryWhenLeaveApp);
}
}
// do default actions (start discover avaliable devices)
// when DefaultAdapter is ready.
function initial() {
// Bind message handler for incoming pairing requests
window.removeEventListener('bluetooth-pairing-request', onRequestPairing);
window.addEventListener('bluetooth-pairing-request', onRequestPairing);
navigator.mozSetMessageHandler('bluetooth-cancel',
function bt_gotCancelMessage(message) {
showDevicePaired(false, null);
}
);
defaultAdapter. bt_getPairedMessage(evt) {
dispatchEvent(new CustomEvent('bluetooth-pairedstatuschanged'));
showDevicePaired(evt.status, 'Authentication Failed');
};
defaultAdapter. bt_hfpStatusChanged(evt) {
showDeviceConnected(evt.address, evt.status, Profiles.HFP);
};
defaultAdapter.ona2dpstatuschanged = function bt_a2dpStatusChanged(evt) {
showDeviceConnected(evt.address, evt.status, Profiles.A2DP);
};
// Get paired device
getPairedDevice(function() {
for (var address in pairList.index) {
var deviceItem = pairList.index[address];
if (Object.keys(deviceItem.connectedProfiles).length > 0)
return;
}
// If there is no current connection and we have one device connected
// before, restore it.
restoreConnection();
});
startDiscovery();
}
function restoreConnection() {
// Reconnect the one kept in the async storage.
window.asyncStorage.getItem('device.connected', function(value) {
if (!value || !pairList.index[value])
return;
var device = pairList.index[value].device;
setDeviceConnect(device);
});
}
function getPairedDevice(callback) {
if (!bluetooth.enabled || !defaultAdapter)
return;
var req = defaultAdapter.getPairedDevices();
req. 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 aItem = newListItem(device, '');
aItem. {
optionMenu.show(device);
};
pairList.list.appendChild(aItem);
pairList.index[device.address] = {
device: device,
item: aItem,
connectedProfiles: {}
};
// 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');
l10n.localize(small, 'device-status-connecting');
setTimeout(function() {
setDeviceConnect(device);
}, 5000);
}
})(paired[i]);
}
// update the connection status
getConnectedDeviceItems(function(connectedDeviceItems) {
if (connectedDeviceItems.length > 0) {
connectedDeviceItems.forEach(function(item) {
var connectedDevice = item.device;
var connectedProfiles = item.connectedProfiles;
for (var profile in connectedProfiles) {
showDeviceConnected(connectedDevice.address, true, profile);
}
});
}
pairList.show(true);
// the callback function now is for restoring the connected device
// when the bluetooth is turned on.
if (callback)
callback();
});
};
}
// In the callback we returns an array of connected device items.
// Each device item contains "device" and "connectedProfiles".
function getConnectedDeviceItems(callback) {
if (!callback)
return;
if (!defaultAdapter) {
callback([]);
return;
}
var getConnectedDevicesByProfile = function(profileID, gcdCallback) {
if (!gcdCallback)
return;
var req = defaultAdapter.getConnectedDevices(profileID);
req. {
gcdCallback(req.result || []);
};
10BC8
req. {
gcdCallback(null);
};
};
var connectedDeviceItemsMap = {}; // hash by device address
var updateDeviceItemsMap = function(profileID, connectedDevices) {
if (!connectedDevices)
return;
connectedDevices.forEach(function(connectedDevice) {
var info = connectedDeviceItemsMap[connectedDevice.address];
if (info) {
info.connectedProfiles[profileID] = true;
} else {
info = {
'device': connectedDevice,
'connectedProfiles': {}
};
info.connectedProfiles[profileID] = true;
}
connectedDeviceItemsMap[connectedDevice.address] = info;
});
};
// XXX: we should have better ways of doing this.
getConnectedDevicesByProfile(Profiles.HFP, function(hfpResult) {
updateDeviceItemsMap(Profiles.HFP, hfpResult);
getConnectedDevicesByProfile(Profiles.A2DP, function(a2dpResult) {
updateDeviceItemsMap(Profiles.A2DP, a2dpResult);
var connectedDeviceItems = [];
for (var i in connectedDeviceItemsMap) {
var item = connectedDeviceItemsMap[i];
connectedDeviceItems.push(item);
}
callback(connectedDeviceItems);
});
});
}
// 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.item;
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. {
// block the pairing request if there is already one.
if (pairingAddress)
return;
var small = aItem.querySelector('small');
l10n.localize(small, 'device-status-pairing');
this.setAttribute('aria-disabled', true);
stopDiscovery();
var req = defaultAdapter.pair(device);
pairingMode = 'active';
pairingAddress = device.address;
req. bt_pairError(error) {
showDevicePaired(false, req.error.name);
};
};
openList.list.appendChild(aItem);
openList.index[device.address] = {
device: device,
item: aItem,
connectedProfiles: {}
};
}
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].device;
var item = openList.index[workingAddress].item;
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 item = openList.index[workingAddress].item;
var small = item.querySelector('small');
item.removeAttribute('aria-disabled');
l10n.localize(small, '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. bt_pairError() {
showDevicePaired(true, null);
};
}
function setDeviceDisconnect(device, callback) {
if (!bluetooth.enabled || !defaultAdapter ||
device.address !== connectedAddress) {
if (callback)
callback();
return;
}
var req = defaultAdapter.disconnect(device);
req. = function() {
if (callback)
callback();
};
}
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;
}
var doConnect = function() {
var connectSuccess = function bt_connectSuccess() {
if (connectingAddress) {
connectingAddress = null;
}
};
var connectError = function bt_connectError() {
// Connection state might be changed before DOM request response.
if (connectingAddress) {
// Clear the text of connecting status.
var small =
pairList.index[connectingAddress].item.querySelector('small');
small.textContent = '';
small.dataset.l10nId = '';
connectingAddress = null;
window.alert(_('error-connect-msg'));
}
};
var req = defaultAdapter.connect(device);
req. // At least one profile is connected.
req. // No available profiles are connected.
connectingAddress = device.address;
if (!pairList.index[connectingAddress]) {
return;
}
var small =
pairList.index[connectingAddress].item.querySelector('small');
l10n.localize(small, 'device-status-connecting');
};
// disconnect current connected device first
if (connectedAddress && pairList.index[connectedAddress]) {
setDeviceDisconnect(pairList.index[connectedAddress].device, doConnect);
} else {
doConnect();
}
}
function showDeviceConnected(deviceAddress, connected, profile) {
var deviceItem = pairList.index[deviceAddress];
if (!deviceItem)
return;
deviceItem.connectedProfiles[profile] = connected;
var existConnectedProfile = false;
if (connected) {
existConnectedProfile = true;
} else {
// Check if there are other connected profiles
for (var profile in deviceItem.connectedProfiles) {
existConnectedProfile = existConnectedProfile ||
deviceItem.connectedProfiles[profile];
}
}
if (existConnectedProfile) {
connectedAddress = deviceAddress;
// 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');
}
}
var l10nId = '';
var hfpConnected = deviceItem.connectedProfiles[Profiles.HFP];
var a2dpConnected = deviceItem.connectedProfiles[Profiles.A2DP];
if (hfpConnected && a2dpConnected) {
l10nId = 'device-status-connected-phone-media';
} else if (hfpConnected) {
l10nId = 'device-status-connected-phone';
} else if (a2dpConnected) {
l10nId = 'device-status-connected-media';
} else {
l10nId = null;
}
var small = pairList.index[deviceAddress].item.querySelector('small');
if (l10nId) {
l10n.localize(small, l10nId);
} else {
small.textContent = '';
small.dataset.l10nId = '';
}
}
function onRequestPairing(evt) {
var evt = evt.detail;
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. childWindowLoaded() {
childWindow.PairView.init(pairingMode, method, device, passkey);
};
};
var req = navigator.mozSettings.createLock().get('lockscreen.locked');
req. bt_onGetLocksuccess() {
if (!req.result['lockscreen.locked']) {
showPairView();
}
};
req. bt_onGetLockError() {
// fallback to default value 'unlocked'
showPairView();
};
}
function startDiscovery() {
if (!bluetooth.enabled || !defaultAdapter || discoverTimeout)
return;
var req = defaultAdapter.startDiscovery();
req. bt_discoveryStart() {
searchAgainBtn.disabled = true;
if (!discoverTimeout)
discoverTimeout = setTimeout(stopDiscovery, discoverTimeoutTime);
};
req. bt_discoveryFailed() {
searchingItem.hidden = true;
searchAgainBtn.disabled = false;
};
}
function stopDiscoveryWhenLeaveApp() {
//only stop discovery when Settings app is hidden
if (!document.hidden)
return;
stopDiscovery();
}
function stopDiscovery() {
if (!bluetooth.enabled || !defaultAdapter || !discoverTimeout)
return;
var req = defaultAdapter.stopDiscovery();
req. bt_discoveryStopped() {
searchAgainBtn.disabled = false;
searchingItem.hidden = true;
};
req. 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. 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'));
});
});