Chromium Code Reviews| Index: chrome/browser/resources/bluetooth_internals/device_broker.js |
| diff --git a/chrome/browser/resources/bluetooth_internals/device_broker.js b/chrome/browser/resources/bluetooth_internals/device_broker.js |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..4be40d5ecacf901cd57364bb80471813fdfe5092 |
| --- /dev/null |
| +++ b/chrome/browser/resources/bluetooth_internals/device_broker.js |
| @@ -0,0 +1,54 @@ |
| +// Copyright 2017 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +/** |
| + * Javascript for device_broker, served from chrome://bluetooth-internals/. |
| + * Provides a single source to access DevicePtrs. DevicePtrs are cached for |
| + * for repeated use. Multiple connection requests will result in the same |
| + * DevicePtr being shared among all requesters. |
| + */ |
| + |
| +// Expose for testing. |
| +/** @type {!Map<string, !interfaces.BluetoothDevice.DevicePtr|!Promise} */ |
| +var connectedDevices = null; |
| + |
| +cr.define('device_broker', function() { |
| + connectedDevices = new Map(); |
| + |
| + /** |
| + * Creates a GATT connection to the device with |address|. If a connection to |
| + * the device already exists, the promise is resolved with the existing |
| + * DevicePtr. If a connection is in progress, the promise resolves when |
| + * the existing connection request promise is fulfilled. |
| + * @param {string} address |
| + * @return {!Promise<!interfaces.BluetoothDevice.DevicePtr>} |
| + */ |
| + function connectToDevice(address) { |
|
dpapad
2017/01/19 17:41:45
Nit (optional): You can avoid querying the map twi
mbrunson
2017/01/19 23:34:10
Done.
|
| + if (connectedDevices.has(address)) |
| + return Promise.resolve(connectedDevices.get(address)); |
| + |
| + var promise = adapter_broker.getAdapterBroker().then( |
| + function(adapterBroker) { |
| + return adapterBroker.connectToDevice(address); |
| + }).then(function(device) { |
| + connectedDevices.set(address, device); |
| + |
| + device.ptr.setConnectionErrorHandler(function() { |
| + connectedDevices.delete(address); |
| + }); |
| + |
| + return device; |
| + }).catch(function(error) { |
| + connectedDevices.delete(address); |
| + throw error; |
| + }); |
| + |
| + connectedDevices.set(address, promise); |
| + return promise; |
| + } |
| + |
| + return { |
| + connectToDevice: connectToDevice |
| + }; |
| +}); |