OLD | NEW |
(Empty) | |
| 1 // Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 /** |
| 6 * Javascript for device_broker, served from chrome://bluetooth-internals/. |
| 7 * Provides a single source to access DevicePtrs. DevicePtrs are cached for |
| 8 * for repeated use. Multiple connection requests will result in the same |
| 9 * DevicePtr being shared among all requesters. |
| 10 */ |
| 11 |
| 12 // Expose for testing. |
| 13 /** @type {!Map<string, !interfaces.BluetoothDevice.DevicePtr|!Promise} */ |
| 14 var connectedDevices = null; |
| 15 |
| 16 cr.define('device_broker', function() { |
| 17 connectedDevices = new Map(); |
| 18 |
| 19 /** |
| 20 * Creates a GATT connection to the device with |address|. If a connection to |
| 21 * the device already exists, the promise is resolved with the existing |
| 22 * DevicePtr. If a connection is in progress, the promise resolves when |
| 23 * the existing connection request promise is fulfilled. |
| 24 * @param {string} address |
| 25 * @return {!Promise<!interfaces.BluetoothDevice.DevicePtr>} |
| 26 */ |
| 27 function connectToDevice(address) { |
| 28 var deviceOrPromise = connectedDevices.get(address) || null; |
| 29 if (deviceOrPromise !== null) |
| 30 return Promise.resolve(deviceOrPromise); |
| 31 |
| 32 var promise = adapter_broker.getAdapterBroker().then( |
| 33 function(adapterBroker) { |
| 34 return adapterBroker.connectToDevice(address); |
| 35 }).then(function(device) { |
| 36 connectedDevices.set(address, device); |
| 37 |
| 38 device.ptr.setConnectionErrorHandler(function() { |
| 39 connectedDevices.delete(address); |
| 40 }); |
| 41 |
| 42 return device; |
| 43 }).catch(function(error) { |
| 44 connectedDevices.delete(address); |
| 45 throw error; |
| 46 }); |
| 47 |
| 48 connectedDevices.set(address, promise); |
| 49 return promise; |
| 50 } |
| 51 |
| 52 return { |
| 53 connectToDevice: connectToDevice |
| 54 }; |
| 55 }); |
OLD | NEW |