diff options
author | ortuno <ortuno@chromium.org> | 2015-09-04 21:44:42 -0700 |
---|---|---|
committer | Commit bot <commit-bot@chromium.org> | 2015-09-05 04:45:45 +0000 |
commit | 15102e2f6e8dd5af340f96bfe2043a5708b1de6b (patch) | |
tree | 1b685bc1f31c3421d6609c695c5065236f6b1929 /extensions | |
parent | 5e6ff6de73b07d289f236e5b2b4aa7b7e67bf2bb (diff) | |
download | chromium_src-15102e2f6e8dd5af340f96bfe2043a5708b1de6b.zip chromium_src-15102e2f6e8dd5af340f96bfe2043a5708b1de6b.tar.gz chromium_src-15102e2f6e8dd5af340f96bfe2043a5708b1de6b.tar.bz2 |
bluetooth-advertising: Move bluetooth low energy api to chrome/
'registerAdvertisment' which is part of bluetoothLowEnergy will now
only work on auto-launched apps in kiosk mode. Since implementing
that change adds a dependency on chromeos::KioskAppManager we move
the API to chrome/
BUG=528066
Review URL: https://codereview.chromium.org/1315193018
Cr-Commit-Position: refs/heads/master@{#347558}
Diffstat (limited to 'extensions')
18 files changed, 0 insertions, 5443 deletions
diff --git a/extensions/browser/api/bluetooth_low_energy/OWNERS b/extensions/browser/api/bluetooth_low_energy/OWNERS deleted file mode 100644 index 7bf8537..0000000 --- a/extensions/browser/api/bluetooth_low_energy/OWNERS +++ /dev/null @@ -1,2 +0,0 @@ -keybuk@chromium.org -armansito@chromium.org diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.cc b/extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.cc deleted file mode 100644 index c1a9248..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.cc +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2015 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. - -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.h" - -#include "base/lazy_instance.h" -#include "device/bluetooth/bluetooth_advertisement.h" -#include "net/base/io_buffer.h" - -namespace extensions { - -// static -static base::LazyInstance<BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothApiAdvertisement>>> g_server_factory = - LAZY_INSTANCE_INITIALIZER; - -// static -template <> -BrowserContextKeyedAPIFactory<ApiResourceManager<BluetoothApiAdvertisement>>* -ApiResourceManager<BluetoothApiAdvertisement>::GetFactoryInstance() { - return g_server_factory.Pointer(); -} - -BluetoothApiAdvertisement::BluetoothApiAdvertisement( - const std::string& owner_extension_id, - scoped_refptr<device::BluetoothAdvertisement> advertisement) - : ApiResource(owner_extension_id), advertisement_(advertisement) { - DCHECK(content::BrowserThread::CurrentlyOn(kThreadId)); -} - -BluetoothApiAdvertisement::~BluetoothApiAdvertisement() { -} - -} // namespace extensions diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.h b/extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.h deleted file mode 100644 index 9639b2b..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.h +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2015 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. - -#ifndef EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_API_ADVERTISEMENT_H_ -#define EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_API_ADVERTISEMENT_H_ - -#include <string> - -#include "device/bluetooth/bluetooth_advertisement.h" -#include "extensions/browser/api/api_resource.h" -#include "extensions/browser/api/api_resource_manager.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" - -namespace device { -class BluetoothAdvertisement; -} // namespace device - -namespace apibtle = extensions::api::bluetooth_low_energy; - -namespace extensions { - -// Representation of advertisement instances from the "bluetooth" namespace, -// abstracting the underlying BluetoothAdvertisementXxx class. All methods -// must be called on the |kThreadId| thread. -class BluetoothApiAdvertisement : public ApiResource { - public: - BluetoothApiAdvertisement(const std::string& owner_extension_id, - scoped_refptr<device::BluetoothAdvertisement>); - ~BluetoothApiAdvertisement() override; - - device::BluetoothAdvertisement* advertisement() { - return advertisement_.get(); - } - - // Implementations of |BluetoothAdvertisement| require being called on the - // UI thread. - static const content::BrowserThread::ID kThreadId = - content::BrowserThread::UI; - - private: - friend class ApiResourceManager<BluetoothApiAdvertisement>; - - static const char* service_name() { - return "BluetoothApiAdvertisementManager"; - } - - // The underlying advertisement instance. - scoped_refptr<device::BluetoothAdvertisement> advertisement_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothApiAdvertisement); -}; - -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_API_ADVERTISEMENT_H_ diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.cc b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.cc deleted file mode 100644 index 5efefe1..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.cc +++ /dev/null @@ -1,1015 +0,0 @@ -// Copyright 2014 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. - -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h" - -#include <algorithm> - -#include "base/bind.h" -#include "base/lazy_instance.h" -#include "base/strings/stringprintf.h" -#include "content/public/browser/browser_thread.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_api_advertisement.h" -#include "extensions/browser/api/bluetooth_low_energy/utils.h" -#include "extensions/browser/event_router.h" -#include "extensions/common/api/bluetooth/bluetooth_manifest_data.h" -#include "extensions/common/api/bluetooth_low_energy.h" -#include "extensions/common/permissions/permissions_data.h" - -using content::BrowserContext; -using content::BrowserThread; - -namespace apibtle = extensions::api::bluetooth_low_energy; - -namespace extensions { - -namespace { - -const char kErrorAdapterNotInitialized[] = - "Could not initialize Bluetooth adapter"; -const char kErrorAlreadyConnected[] = "Already connected"; -const char kErrorAlreadyNotifying[] = "Already notifying"; -const char kErrorAuthenticationFailed[] = "Authentication failed"; -const char kErrorCanceled[] = "Request canceled"; -const char kErrorGattNotSupported[] = "Operation not supported by this service"; -const char kErrorHigherSecurity[] = "Higher security needed"; -const char kErrorInProgress[] = "In progress"; -const char kErrorInsufficientAuthorization[] = "Insufficient authorization"; -const char kErrorInvalidLength[] = "Invalid attribute value length"; -const char kErrorNotConnected[] = "Not connected"; -const char kErrorNotFound[] = "Instance not found"; -const char kErrorNotNotifying[] = "Not notifying"; -const char kErrorOperationFailed[] = "Operation failed"; -const char kErrorPermissionDenied[] = "Permission denied"; -const char kErrorPlatformNotSupported[] = - "This operation is not supported on the current platform"; -const char kErrorTimeout[] = "Operation timed out"; -const char kErrorUnsupportedDevice[] = - "This device is not supported on the current platform"; -const char kErrorInvalidAdvertisementLength[] = "Invalid advertisement length"; -const char kStatusAdvertisementAlreadyExists[] = - "An advertisement is already advertising"; -const char kStatusAdvertisementDoesNotExist[] = - "This advertisement does not exist"; - -// Returns the correct error string based on error status |status|. This is used -// to set the value of |chrome.runtime.lastError.message| and should not be -// passed |BluetoothLowEnergyEventRouter::kStatusSuccess|. -std::string StatusToString(BluetoothLowEnergyEventRouter::Status status) { - switch (status) { - case BluetoothLowEnergyEventRouter::kStatusErrorPermissionDenied: - return kErrorPermissionDenied; - case BluetoothLowEnergyEventRouter::kStatusErrorNotFound: - return kErrorNotFound; - case BluetoothLowEnergyEventRouter::kStatusErrorAlreadyConnected: - return kErrorAlreadyConnected; - case BluetoothLowEnergyEventRouter::kStatusErrorAlreadyNotifying: - return kErrorAlreadyNotifying; - case BluetoothLowEnergyEventRouter::kStatusErrorNotConnected: - return kErrorNotConnected; - case BluetoothLowEnergyEventRouter::kStatusErrorInsufficientAuthorization: - return kErrorInsufficientAuthorization; - case BluetoothLowEnergyEventRouter::kStatusErrorNotNotifying: - return kErrorNotNotifying; - case BluetoothLowEnergyEventRouter::kStatusErrorInProgress: - return kErrorInProgress; - case BluetoothLowEnergyEventRouter::kStatusErrorAuthenticationFailed: - return kErrorAuthenticationFailed; - case BluetoothLowEnergyEventRouter::kStatusErrorHigherSecurity: - return kErrorHigherSecurity; - case BluetoothLowEnergyEventRouter::kStatusErrorCanceled: - return kErrorCanceled; - case BluetoothLowEnergyEventRouter::kStatusErrorTimeout: - return kErrorTimeout; - case BluetoothLowEnergyEventRouter::kStatusErrorUnsupportedDevice: - return kErrorUnsupportedDevice; - case BluetoothLowEnergyEventRouter::kStatusErrorInvalidLength: - return kErrorInvalidLength; - case BluetoothLowEnergyEventRouter::kStatusErrorGattNotSupported: - return kErrorGattNotSupported; - case BluetoothLowEnergyEventRouter::kStatusSuccess: - NOTREACHED(); - break; - default: - return kErrorOperationFailed; - } - return ""; -} - -extensions::BluetoothLowEnergyEventRouter* GetEventRouter( - BrowserContext* context) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - return extensions::BluetoothLowEnergyAPI::Get(context)->event_router(); -} - -void DoWorkCallback(const base::Callback<bool()>& callback) { - DCHECK(!callback.is_null()); - callback.Run(); -} - -scoped_ptr<device::BluetoothAdvertisement::ManufacturerData> -CreateManufacturerData( - std::vector<linked_ptr<apibtle::ManufacturerData>>* manufacturer_data) { - scoped_ptr<device::BluetoothAdvertisement::ManufacturerData> created_data( - new device::BluetoothAdvertisement::ManufacturerData()); - for (const auto& it : *manufacturer_data) { - std::vector<uint8_t> data(it->data.size()); - std::copy(it->data.begin(), it->data.end(), data.begin()); - (*created_data)[it->id] = data; - } - return created_data; -} - -scoped_ptr<device::BluetoothAdvertisement::ServiceData> CreateServiceData( - std::vector<linked_ptr<apibtle::ServiceData>>* service_data) { - scoped_ptr<device::BluetoothAdvertisement::ServiceData> created_data( - new device::BluetoothAdvertisement::ServiceData()); - for (const auto& it : *service_data) { - std::vector<uint8_t> data(it->data.size()); - std::copy(it->data.begin(), it->data.end(), data.begin()); - (*created_data)[it->uuid] = data; - } - return created_data; -} - -} // namespace - - -static base::LazyInstance<BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI> > - g_factory = LAZY_INSTANCE_INITIALIZER; - -// static -BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI>* -BluetoothLowEnergyAPI::GetFactoryInstance() { - return g_factory.Pointer(); -} - -// static -BluetoothLowEnergyAPI* BluetoothLowEnergyAPI::Get(BrowserContext* context) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - return GetFactoryInstance()->Get(context); -} - -BluetoothLowEnergyAPI::BluetoothLowEnergyAPI(BrowserContext* context) - : event_router_(new BluetoothLowEnergyEventRouter(context)) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); -} - -BluetoothLowEnergyAPI::~BluetoothLowEnergyAPI() { -} - -void BluetoothLowEnergyAPI::Shutdown() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); -} - -namespace api { - -BluetoothLowEnergyExtensionFunction::BluetoothLowEnergyExtensionFunction() { -} - -BluetoothLowEnergyExtensionFunction::~BluetoothLowEnergyExtensionFunction() { -} - -bool BluetoothLowEnergyExtensionFunction::RunAsync() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (!BluetoothManifestData::CheckLowEnergyPermitted(extension())) { - error_ = kErrorPermissionDenied; - return false; - } - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - if (!event_router->IsBluetoothSupported()) { - SetError(kErrorPlatformNotSupported); - return false; - } - - // It is safe to pass |this| here as ExtensionFunction is refcounted. - if (!event_router->InitializeAdapterAndInvokeCallback(base::Bind( - &DoWorkCallback, - base::Bind(&BluetoothLowEnergyExtensionFunction::DoWork, this)))) { - SetError(kErrorAdapterNotInitialized); - return false; - } - - return true; -} - -bool BluetoothLowEnergyConnectFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::Connect::Params> params( - apibtle::Connect::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - bool persistent = false; // Not persistent by default. - apibtle::ConnectProperties* properties = params.get()->properties.get(); - if (properties) - persistent = properties->persistent; - - event_router->Connect( - persistent, - extension(), - params->device_address, - base::Bind(&BluetoothLowEnergyConnectFunction::SuccessCallback, this), - base::Bind(&BluetoothLowEnergyConnectFunction::ErrorCallback, this)); - - return true; -} - -void BluetoothLowEnergyConnectFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyConnectFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyDisconnectFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::Disconnect::Params> params( - apibtle::Disconnect::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - event_router->Disconnect( - extension(), - params->device_address, - base::Bind(&BluetoothLowEnergyDisconnectFunction::SuccessCallback, this), - base::Bind(&BluetoothLowEnergyDisconnectFunction::ErrorCallback, this)); - - return true; -} - -void BluetoothLowEnergyDisconnectFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyDisconnectFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyGetServiceFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::GetService::Params> params( - apibtle::GetService::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - apibtle::Service service; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetService(params->service_id, &service); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - results_ = apibtle::GetService::Results::Create(service); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetServicesFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::GetServices::Params> params( - apibtle::GetServices::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::ServiceList service_list; - if (!event_router->GetServices(params->device_address, &service_list)) { - SetError(kErrorNotFound); - SendResponse(false); - return false; - } - - results_ = apibtle::GetServices::Results::Create(service_list); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetCharacteristicFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::GetCharacteristic::Params> params( - apibtle::GetCharacteristic::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - apibtle::Characteristic characteristic; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetCharacteristic( - extension(), params->characteristic_id, &characteristic); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetCharacteristic::Result::Create as it doesn't convert lists of - // enums correctly. - SetResult(apibtle::CharacteristicToValue(&characteristic).release()); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetCharacteristicsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::GetCharacteristics::Params> params( - apibtle::GetCharacteristics::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::CharacteristicList characteristic_list; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetCharacteristics( - extension(), params->service_id, &characteristic_list); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetCharacteristics::Result::Create as it doesn't convert lists of - // enums correctly. - scoped_ptr<base::ListValue> result(new base::ListValue()); - for (BluetoothLowEnergyEventRouter::CharacteristicList::iterator iter = - characteristic_list.begin(); - iter != characteristic_list.end(); - ++iter) - result->Append(apibtle::CharacteristicToValue(iter->get()).release()); - - SetResult(result.release()); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetIncludedServicesFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::GetIncludedServices::Params> params( - apibtle::GetIncludedServices::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::ServiceList service_list; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetIncludedServices(params->service_id, &service_list); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - results_ = apibtle::GetIncludedServices::Results::Create(service_list); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetDescriptorFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::GetDescriptor::Params> params( - apibtle::GetDescriptor::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - apibtle::Descriptor descriptor; - BluetoothLowEnergyEventRouter::Status status = event_router->GetDescriptor( - extension(), params->descriptor_id, &descriptor); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetDescriptor::Result::Create as it doesn't convert lists of enums - // correctly. - SetResult(apibtle::DescriptorToValue(&descriptor).release()); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetDescriptorsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::GetDescriptors::Params> params( - apibtle::GetDescriptors::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::DescriptorList descriptor_list; - BluetoothLowEnergyEventRouter::Status status = event_router->GetDescriptors( - extension(), params->characteristic_id, &descriptor_list); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetDescriptors::Result::Create as it doesn't convert lists of - // enums correctly. - scoped_ptr<base::ListValue> result(new base::ListValue()); - for (BluetoothLowEnergyEventRouter::DescriptorList::iterator iter = - descriptor_list.begin(); - iter != descriptor_list.end(); - ++iter) - result->Append(apibtle::DescriptorToValue(iter->get()).release()); - - SetResult(result.release()); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyReadCharacteristicValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::ReadCharacteristicValue::Params> params( - apibtle::ReadCharacteristicValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - instance_id_ = params->characteristic_id; - event_router->ReadCharacteristicValue( - extension(), - instance_id_, - base::Bind( - &BluetoothLowEnergyReadCharacteristicValueFunction::SuccessCallback, - this), - base::Bind( - &BluetoothLowEnergyReadCharacteristicValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyReadCharacteristicValueFunction::SuccessCallback() { - // Obtain info on the characteristic and see whether or not the characteristic - // is still around. - apibtle::Characteristic characteristic; - BluetoothLowEnergyEventRouter::Status status = - GetEventRouter(browser_context()) - ->GetCharacteristic(extension(), instance_id_, &characteristic); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return; - } - - // Manually construct the result instead of using - // apibtle::GetCharacteristic::Result::Create as it doesn't convert lists of - // enums correctly. - SetResult(apibtle::CharacteristicToValue(&characteristic).release()); - SendResponse(true); -} - -void BluetoothLowEnergyReadCharacteristicValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyWriteCharacteristicValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::WriteCharacteristicValue::Params> params( - apibtle::WriteCharacteristicValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - std::vector<uint8> value(params->value.begin(), params->value.end()); - event_router->WriteCharacteristicValue( - extension(), - params->characteristic_id, - value, - base::Bind( - &BluetoothLowEnergyWriteCharacteristicValueFunction::SuccessCallback, - this), - base::Bind( - &BluetoothLowEnergyWriteCharacteristicValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyWriteCharacteristicValueFunction::SuccessCallback() { - results_ = apibtle::WriteCharacteristicValue::Results::Create(); - SendResponse(true); -} - -void BluetoothLowEnergyWriteCharacteristicValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyStartCharacteristicNotificationsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::StartCharacteristicNotifications::Params> params( - apibtle::StartCharacteristicNotifications::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - bool persistent = false; // Not persistent by default. - apibtle::NotificationProperties* properties = params.get()->properties.get(); - if (properties) - persistent = properties->persistent; - - event_router->StartCharacteristicNotifications( - persistent, - extension(), - params->characteristic_id, - base::Bind(&BluetoothLowEnergyStartCharacteristicNotificationsFunction:: - SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyStartCharacteristicNotificationsFunction:: - ErrorCallback, - this)); - - return true; -} - -void -BluetoothLowEnergyStartCharacteristicNotificationsFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyStartCharacteristicNotificationsFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyStopCharacteristicNotificationsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::StopCharacteristicNotifications::Params> params( - apibtle::StopCharacteristicNotifications::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - event_router->StopCharacteristicNotifications( - extension(), - params->characteristic_id, - base::Bind(&BluetoothLowEnergyStopCharacteristicNotificationsFunction:: - SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyStopCharacteristicNotificationsFunction:: - ErrorCallback, - this)); - - return true; -} - -void -BluetoothLowEnergyStopCharacteristicNotificationsFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyStopCharacteristicNotificationsFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyReadDescriptorValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::ReadDescriptorValue::Params> params( - apibtle::ReadDescriptorValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - instance_id_ = params->descriptor_id; - event_router->ReadDescriptorValue( - extension(), - instance_id_, - base::Bind( - &BluetoothLowEnergyReadDescriptorValueFunction::SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyReadDescriptorValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyReadDescriptorValueFunction::SuccessCallback() { - // Obtain info on the descriptor and see whether or not the descriptor is - // still around. - apibtle::Descriptor descriptor; - BluetoothLowEnergyEventRouter::Status status = - GetEventRouter(browser_context()) - ->GetDescriptor(extension(), instance_id_, &descriptor); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return; - } - - // Manually construct the result instead of using - // apibtle::GetDescriptor::Results::Create as it doesn't convert lists of - // enums correctly. - SetResult(apibtle::DescriptorToValue(&descriptor).release()); - SendResponse(true); -} - -void BluetoothLowEnergyReadDescriptorValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyWriteDescriptorValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::WriteDescriptorValue::Params> params( - apibtle::WriteDescriptorValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - std::vector<uint8> value(params->value.begin(), params->value.end()); - event_router->WriteDescriptorValue( - extension(), - params->descriptor_id, - value, - base::Bind( - &BluetoothLowEnergyWriteDescriptorValueFunction::SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyWriteDescriptorValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyWriteDescriptorValueFunction::SuccessCallback() { - results_ = apibtle::WriteDescriptorValue::Results::Create(); - SendResponse(true); -} - -void BluetoothLowEnergyWriteDescriptorValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -BluetoothLowEnergyAdvertisementFunction:: - BluetoothLowEnergyAdvertisementFunction() - : advertisements_manager_(nullptr) { -} - -BluetoothLowEnergyAdvertisementFunction:: - ~BluetoothLowEnergyAdvertisementFunction() { -} - -int BluetoothLowEnergyAdvertisementFunction::AddAdvertisement( - BluetoothApiAdvertisement* advertisement) { - DCHECK(advertisements_manager_); - return advertisements_manager_->Add(advertisement); -} - -BluetoothApiAdvertisement* -BluetoothLowEnergyAdvertisementFunction::GetAdvertisement( - int advertisement_id) { - DCHECK(advertisements_manager_); - return advertisements_manager_->Get(extension_id(), advertisement_id); -} - -void BluetoothLowEnergyAdvertisementFunction::RemoveAdvertisement( - int advertisement_id) { - DCHECK(advertisements_manager_); - advertisements_manager_->Remove(extension_id(), advertisement_id); -} - -bool BluetoothLowEnergyAdvertisementFunction::RunAsync() { - Initialize(); - return BluetoothLowEnergyExtensionFunction::RunAsync(); -} - -void BluetoothLowEnergyAdvertisementFunction::Initialize() { - advertisements_manager_ = - ApiResourceManager<BluetoothApiAdvertisement>::Get(browser_context()); -} - -// RegisterAdvertisement: - -bool BluetoothLowEnergyRegisterAdvertisementFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (!BluetoothManifestData::CheckPeripheralPermitted(extension())) { - error_ = kErrorPermissionDenied; - SendResponse(false); - return false; - } - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - scoped_ptr<apibtle::RegisterAdvertisement::Params> params( - apibtle::RegisterAdvertisement::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - scoped_ptr<device::BluetoothAdvertisement::Data> advertisement_data( - new device::BluetoothAdvertisement::Data( - params->advertisement.type == - apibtle::AdvertisementType::ADVERTISEMENT_TYPE_BROADCAST - ? device::BluetoothAdvertisement::AdvertisementType:: - ADVERTISEMENT_TYPE_BROADCAST - : device::BluetoothAdvertisement::AdvertisementType:: - ADVERTISEMENT_TYPE_PERIPHERAL)); - - advertisement_data->set_service_uuids( - params->advertisement.service_uuids.Pass()); - advertisement_data->set_solicit_uuids( - params->advertisement.solicit_uuids.Pass()); - if (params->advertisement.manufacturer_data) { - advertisement_data->set_manufacturer_data( - CreateManufacturerData(params->advertisement.manufacturer_data.get()) - .Pass()); - } - if (params->advertisement.service_data) { - advertisement_data->set_service_data( - CreateServiceData(params->advertisement.service_data.get()).Pass()); - } - - event_router->adapter()->RegisterAdvertisement( - advertisement_data.Pass(), - base::Bind( - &BluetoothLowEnergyRegisterAdvertisementFunction::SuccessCallback, - this), - base::Bind( - &BluetoothLowEnergyRegisterAdvertisementFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyRegisterAdvertisementFunction::SuccessCallback( - scoped_refptr<device::BluetoothAdvertisement> advertisement) { - results_ = apibtle::RegisterAdvertisement::Results::Create(AddAdvertisement( - new BluetoothApiAdvertisement(extension_id(), advertisement))); - SendResponse(true); -} - -void BluetoothLowEnergyRegisterAdvertisementFunction::ErrorCallback( - device::BluetoothAdvertisement::ErrorCode status) { - switch (status) { - case device::BluetoothAdvertisement::ErrorCode:: - ERROR_ADVERTISEMENT_ALREADY_EXISTS: - SetError(kStatusAdvertisementAlreadyExists); - break; - case device::BluetoothAdvertisement::ErrorCode:: - ERROR_ADVERTISEMENT_INVALID_LENGTH: - SetError(kErrorInvalidAdvertisementLength); - break; - default: - SetError(kErrorOperationFailed); - } - SendResponse(false); -} - -// UnregisterAdvertisement: - -bool BluetoothLowEnergyUnregisterAdvertisementFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (!BluetoothManifestData::CheckPeripheralPermitted(extension())) { - error_ = kErrorPermissionDenied; - SendResponse(false); - return false; - } - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // If we don't have an initialized adapter, unregistering is a no-op. - if (!event_router->HasAdapter()) - return true; - - scoped_ptr<apibtle::UnregisterAdvertisement::Params> params( - apibtle::UnregisterAdvertisement::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothApiAdvertisement* advertisement = - GetAdvertisement(params->advertisement_id); - if (!advertisement) { - error_ = kStatusAdvertisementDoesNotExist; - SendResponse(false); - return false; - } - - advertisement->advertisement()->Unregister( - base::Bind( - &BluetoothLowEnergyUnregisterAdvertisementFunction::SuccessCallback, - this, params->advertisement_id), - base::Bind( - &BluetoothLowEnergyUnregisterAdvertisementFunction::ErrorCallback, - this, params->advertisement_id)); - - return true; -} - -void BluetoothLowEnergyUnregisterAdvertisementFunction::SuccessCallback( - int advertisement_id) { - RemoveAdvertisement(advertisement_id); - SendResponse(true); -} - -void BluetoothLowEnergyUnregisterAdvertisementFunction::ErrorCallback( - int advertisement_id, - device::BluetoothAdvertisement::ErrorCode status) { - RemoveAdvertisement(advertisement_id); - switch (status) { - case device::BluetoothAdvertisement::ErrorCode:: - ERROR_ADVERTISEMENT_DOES_NOT_EXIST: - SetError(kStatusAdvertisementDoesNotExist); - break; - default: - SetError(kErrorOperationFailed); - } - SendResponse(false); -} - -} // namespace api -} // namespace extensions diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h deleted file mode 100644 index d161728..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h +++ /dev/null @@ -1,403 +0,0 @@ -// Copyright 2014 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. - -#ifndef EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_API_H_ -#define EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_API_H_ - -#include "base/memory/scoped_ptr.h" -#include "device/bluetooth/bluetooth_advertisement.h" -#include "extensions/browser/api/api_resource_manager.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_function.h" -#include "extensions/browser/extension_function_histogram_value.h" - -namespace extensions { - -class BluetoothApiAdvertisement; -class BluetoothLowEnergyEventRouter; - -// The profile-keyed service that manages the bluetoothLowEnergy extension API. -class BluetoothLowEnergyAPI : public BrowserContextKeyedAPI { - public: - static BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI>* - GetFactoryInstance(); - - // Convenience method to get the BluetoothLowEnergy API for a browser context. - static BluetoothLowEnergyAPI* Get(content::BrowserContext* context); - - explicit BluetoothLowEnergyAPI(content::BrowserContext* context); - ~BluetoothLowEnergyAPI() override; - - // KeyedService implementation.. - void Shutdown() override; - - BluetoothLowEnergyEventRouter* event_router() const { - return event_router_.get(); - } - - // BrowserContextKeyedAPI implementation. - static const char* service_name() { return "BluetoothLowEnergyAPI"; } - static const bool kServiceRedirectedInIncognito = true; - static const bool kServiceIsNULLWhileTesting = true; - - private: - friend class BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI>; - - scoped_ptr<BluetoothLowEnergyEventRouter> event_router_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyAPI); -}; - -namespace api { - -// Base class for bluetoothLowEnergy API functions. This class handles some of -// the common logic involved in all API functions, such as checking for -// platform support and returning the correct error. -class BluetoothLowEnergyExtensionFunction : public AsyncExtensionFunction { - public: - BluetoothLowEnergyExtensionFunction(); - - protected: - ~BluetoothLowEnergyExtensionFunction() override; - - // ExtensionFunction override. - bool RunAsync() override; - - // Implemented by individual bluetoothLowEnergy extension functions to perform - // the body of the function. This invoked asynchonously after RunAsync after - // the BluetoothLowEnergyEventRouter has obtained a handle on the - // BluetoothAdapter. - virtual bool DoWork() = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyExtensionFunction); -}; - -class BluetoothLowEnergyConnectFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.connect", - BLUETOOTHLOWENERGY_CONNECT); - - protected: - ~BluetoothLowEnergyConnectFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::Connect. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyDisconnectFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.disconnect", - BLUETOOTHLOWENERGY_DISCONNECT); - - protected: - ~BluetoothLowEnergyDisconnectFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::Disconnect. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyGetServiceFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getService", - BLUETOOTHLOWENERGY_GETSERVICE); - - protected: - ~BluetoothLowEnergyGetServiceFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetServicesFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getServices", - BLUETOOTHLOWENERGY_GETSERVICES); - - protected: - ~BluetoothLowEnergyGetServicesFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetCharacteristicFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getCharacteristic", - BLUETOOTHLOWENERGY_GETCHARACTERISTIC); - - protected: - ~BluetoothLowEnergyGetCharacteristicFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetCharacteristicsFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getCharacteristics", - BLUETOOTHLOWENERGY_GETCHARACTERISTICS); - - protected: - ~BluetoothLowEnergyGetCharacteristicsFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetIncludedServicesFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getIncludedServices", - BLUETOOTHLOWENERGY_GETINCLUDEDSERVICES); - - protected: - ~BluetoothLowEnergyGetIncludedServicesFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetDescriptorFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getDescriptor", - BLUETOOTHLOWENERGY_GETDESCRIPTOR); - - protected: - ~BluetoothLowEnergyGetDescriptorFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetDescriptorsFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getDescriptors", - BLUETOOTHLOWENERGY_GETDESCRIPTORS); - - protected: - ~BluetoothLowEnergyGetDescriptorsFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; -}; - -class BluetoothLowEnergyReadCharacteristicValueFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.readCharacteristicValue", - BLUETOOTHLOWENERGY_READCHARACTERISTICVALUE); - - protected: - ~BluetoothLowEnergyReadCharacteristicValueFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::ReadCharacteristicValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested characteristic. - std::string instance_id_; -}; - -class BluetoothLowEnergyWriteCharacteristicValueFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.writeCharacteristicValue", - BLUETOOTHLOWENERGY_WRITECHARACTERISTICVALUE); - - protected: - ~BluetoothLowEnergyWriteCharacteristicValueFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::WriteCharacteristicValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested characteristic. - std::string instance_id_; -}; - -class BluetoothLowEnergyStartCharacteristicNotificationsFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION( - "bluetoothLowEnergy.startCharacteristicNotifications", - BLUETOOTHLOWENERGY_STARTCHARACTERISTICNOTIFICATIONS); - - protected: - ~BluetoothLowEnergyStartCharacteristicNotificationsFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::StartCharacteristicNotifications. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyStopCharacteristicNotificationsFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION( - "bluetoothLowEnergy.stopCharacteristicNotifications", - BLUETOOTHLOWENERGY_STOPCHARACTERISTICNOTIFICATIONS); - - protected: - ~BluetoothLowEnergyStopCharacteristicNotificationsFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::StopCharacteristicNotifications. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyReadDescriptorValueFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.readDescriptorValue", - BLUETOOTHLOWENERGY_READDESCRIPTORVALUE); - - protected: - ~BluetoothLowEnergyReadDescriptorValueFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::ReadDescriptorValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -class BluetoothLowEnergyWriteDescriptorValueFunction - : public BluetoothLowEnergyExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.writeDescriptorValue", - BLUETOOTHLOWENERGY_WRITEDESCRIPTORVALUE); - - protected: - ~BluetoothLowEnergyWriteDescriptorValueFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::WriteDescriptorValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -class BluetoothLowEnergyAdvertisementFunction - : public BluetoothLowEnergyExtensionFunction { - public: - BluetoothLowEnergyAdvertisementFunction(); - - protected: - ~BluetoothLowEnergyAdvertisementFunction() override; - - // Takes ownership. - int AddAdvertisement(BluetoothApiAdvertisement* advertisement); - BluetoothApiAdvertisement* GetAdvertisement(int advertisement_id); - void RemoveAdvertisement(int advertisement_id); - - // ExtensionFunction override. - bool RunAsync() override; - - private: - void Initialize(); - - ApiResourceManager<BluetoothApiAdvertisement>* advertisements_manager_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyAdvertisementFunction); -}; - -class BluetoothLowEnergyRegisterAdvertisementFunction - : public BluetoothLowEnergyAdvertisementFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.registerAdvertisement", - BLUETOOTHLOWENERGY_REGISTERADVERTISEMENT); - - protected: - ~BluetoothLowEnergyRegisterAdvertisementFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - void SuccessCallback(scoped_refptr<device::BluetoothAdvertisement>); - void ErrorCallback(device::BluetoothAdvertisement::ErrorCode status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -class BluetoothLowEnergyUnregisterAdvertisementFunction - : public BluetoothLowEnergyAdvertisementFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.unregisterAdvertisement", - BLUETOOTHLOWENERGY_UNREGISTERADVERTISEMENT); - - protected: - ~BluetoothLowEnergyUnregisterAdvertisementFunction() override {} - - // BluetoothLowEnergyExtensionFunction override. - bool DoWork() override; - - private: - void SuccessCallback(int advertisement_id); - void ErrorCallback(int advertisement_id, - device::BluetoothAdvertisement::ErrorCode status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -} // namespace api -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_API_H_ diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc deleted file mode 100644 index 398cca8..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc +++ /dev/null @@ -1,1340 +0,0 @@ -// Copyright 2014 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. - -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/extensions/extension_apitest.h" -#include "device/bluetooth/test/mock_bluetooth_adapter.h" -#include "device/bluetooth/test/mock_bluetooth_device.h" -#include "device/bluetooth/test/mock_bluetooth_gatt_characteristic.h" -#include "device/bluetooth/test/mock_bluetooth_gatt_connection.h" -#include "device/bluetooth/test/mock_bluetooth_gatt_descriptor.h" -#include "device/bluetooth/test/mock_bluetooth_gatt_notify_session.h" -#include "device/bluetooth/test/mock_bluetooth_gatt_service.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" -#include "extensions/common/test_util.h" -#include "extensions/test/extension_test_message_listener.h" -#include "extensions/test/result_catcher.h" -#include "testing/gmock/include/gmock/gmock.h" - -using device::BluetoothUUID; -using device::BluetoothAdapter; -using device::BluetoothDevice; -using device::BluetoothGattCharacteristic; -using device::BluetoothGattConnection; -using device::BluetoothGattDescriptor; -using device::BluetoothGattService; -using device::BluetoothGattNotifySession; -using device::MockBluetoothAdapter; -using device::MockBluetoothDevice; -using device::MockBluetoothGattCharacteristic; -using device::MockBluetoothGattConnection; -using device::MockBluetoothGattDescriptor; -using device::MockBluetoothGattService; -using device::MockBluetoothGattNotifySession; -using extensions::BluetoothLowEnergyEventRouter; -using extensions::ResultCatcher; -using testing::Invoke; -using testing::Return; -using testing::ReturnRef; -using testing::ReturnRefOfCopy; -using testing::SaveArg; -using testing::_; - -namespace { - -// Test service constants. -const char kTestLeDeviceAddress0[] = "11:22:33:44:55:66"; -const char kTestLeDeviceName0[] = "Test LE Device 0"; - -const char kTestLeDeviceAddress1[] = "77:88:99:AA:BB:CC"; -const char kTestLeDeviceName1[] = "Test LE Device 1"; - -const char kTestServiceId0[] = "service_id0"; -const char kTestServiceUuid0[] = "1234"; - -const char kTestServiceId1[] = "service_id1"; -const char kTestServiceUuid1[] = "5678"; - -// Test characteristic constants. -const char kTestCharacteristicId0[] = "char_id0"; -const char kTestCharacteristicUuid0[] = "1211"; -const BluetoothGattCharacteristic::Properties kTestCharacteristicProperties0 = - BluetoothGattCharacteristic::PROPERTY_BROADCAST | - BluetoothGattCharacteristic::PROPERTY_READ | - BluetoothGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE | - BluetoothGattCharacteristic::PROPERTY_INDICATE; -const uint8 kTestCharacteristicDefaultValue0[] = {0x01, 0x02, 0x03, 0x04, 0x05}; - -const char kTestCharacteristicId1[] = "char_id1"; -const char kTestCharacteristicUuid1[] = "1212"; -const BluetoothGattCharacteristic::Properties kTestCharacteristicProperties1 = - BluetoothGattCharacteristic::PROPERTY_READ | - BluetoothGattCharacteristic::PROPERTY_WRITE | - BluetoothGattCharacteristic::PROPERTY_NOTIFY; -const uint8 kTestCharacteristicDefaultValue1[] = {0x06, 0x07, 0x08}; - -const char kTestCharacteristicId2[] = "char_id2"; -const char kTestCharacteristicUuid2[] = "1213"; -const BluetoothGattCharacteristic::Properties kTestCharacteristicProperties2 = - BluetoothGattCharacteristic::PROPERTY_NONE; - -// Test descriptor constants. -const char kTestDescriptorId0[] = "desc_id0"; -const char kTestDescriptorUuid0[] = "1221"; -const uint8 kTestDescriptorDefaultValue0[] = {0x01, 0x02, 0x03}; - -const char kTestDescriptorId1[] = "desc_id1"; -const char kTestDescriptorUuid1[] = "1222"; -const uint8 kTestDescriptorDefaultValue1[] = {0x04, 0x05}; - -class BluetoothLowEnergyApiTest : public ExtensionApiTest { - public: - BluetoothLowEnergyApiTest() {} - - ~BluetoothLowEnergyApiTest() override {} - - void SetUpOnMainThread() override { - ExtensionApiTest::SetUpOnMainThread(); - empty_extension_ = extensions::test_util::CreateEmptyExtension(); - SetUpMocks(); - } - - void TearDownOnMainThread() override { - EXPECT_CALL(*mock_adapter_, RemoveObserver(_)); - } - - void SetUpMocks() { - mock_adapter_ = new testing::StrictMock<MockBluetoothAdapter>(); - EXPECT_CALL(*mock_adapter_, GetDevices()) - .WillOnce(Return(BluetoothAdapter::ConstDeviceList())); - - event_router()->SetAdapterForTesting(mock_adapter_); - - device0_.reset( - new testing::NiceMock<MockBluetoothDevice>(mock_adapter_, - 0, - kTestLeDeviceName0, - kTestLeDeviceAddress0, - false /* paired */, - true /* connected */)); - - device1_.reset( - new testing::NiceMock<MockBluetoothDevice>(mock_adapter_, - 0, - kTestLeDeviceName1, - kTestLeDeviceAddress1, - false /* paired */, - false /* connected */)); - - service0_.reset(new testing::NiceMock<MockBluetoothGattService>( - device0_.get(), - kTestServiceId0, - BluetoothUUID(kTestServiceUuid0), - true /* is_primary */, - false /* is_local */)); - - service1_.reset(new testing::NiceMock<MockBluetoothGattService>( - device0_.get(), - kTestServiceId1, - BluetoothUUID(kTestServiceUuid1), - false /* is_primary */, - false /* is_local */)); - - // Assign characteristics some random properties and permissions. They don't - // need to reflect what the characteristic is actually capable of, since - // the JS API just passes values through from - // device::BluetoothGattCharacteristic. - std::vector<uint8> default_value; - chrc0_.reset(new testing::NiceMock<MockBluetoothGattCharacteristic>( - service0_.get(), - kTestCharacteristicId0, - BluetoothUUID(kTestCharacteristicUuid0), - false /* is_local */, - kTestCharacteristicProperties0, - BluetoothGattCharacteristic::PERMISSION_NONE)); - default_value.assign(kTestCharacteristicDefaultValue0, - (kTestCharacteristicDefaultValue0 + - sizeof(kTestCharacteristicDefaultValue0))); - ON_CALL(*chrc0_, GetValue()).WillByDefault(ReturnRefOfCopy(default_value)); - - chrc1_.reset(new testing::NiceMock<MockBluetoothGattCharacteristic>( - service0_.get(), - kTestCharacteristicId1, - BluetoothUUID(kTestCharacteristicUuid1), - false /* is_local */, - kTestCharacteristicProperties1, - BluetoothGattCharacteristic::PERMISSION_NONE)); - default_value.assign(kTestCharacteristicDefaultValue1, - (kTestCharacteristicDefaultValue1 + - sizeof(kTestCharacteristicDefaultValue1))); - ON_CALL(*chrc1_, GetValue()).WillByDefault(ReturnRefOfCopy(default_value)); - - chrc2_.reset(new testing::NiceMock<MockBluetoothGattCharacteristic>( - service1_.get(), - kTestCharacteristicId2, - BluetoothUUID(kTestCharacteristicUuid2), - false /* is_local */, - kTestCharacteristicProperties2, - BluetoothGattCharacteristic::PERMISSION_NONE)); - - desc0_.reset(new testing::NiceMock<MockBluetoothGattDescriptor>( - chrc0_.get(), - kTestDescriptorId0, - BluetoothUUID(kTestDescriptorUuid0), - false /* is_local */, - BluetoothGattCharacteristic::PERMISSION_NONE)); - default_value.assign( - kTestDescriptorDefaultValue0, - (kTestDescriptorDefaultValue0 + sizeof(kTestDescriptorDefaultValue0))); - ON_CALL(*desc0_, GetValue()).WillByDefault(ReturnRefOfCopy(default_value)); - - desc1_.reset(new testing::NiceMock<MockBluetoothGattDescriptor>( - chrc0_.get(), - kTestDescriptorId1, - BluetoothUUID(kTestDescriptorUuid1), - false /* is_local */, - BluetoothGattCharacteristic::PERMISSION_NONE)); - default_value.assign( - kTestDescriptorDefaultValue1, - (kTestDescriptorDefaultValue1 + sizeof(kTestDescriptorDefaultValue1))); - ON_CALL(*desc1_, GetValue()).WillByDefault(ReturnRefOfCopy(default_value)); - } - - protected: - BluetoothLowEnergyEventRouter* event_router() { - return extensions::BluetoothLowEnergyAPI::Get(browser()->profile()) - ->event_router(); - } - - testing::StrictMock<MockBluetoothAdapter>* mock_adapter_; - scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device0_; - scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device1_; - scoped_ptr<testing::NiceMock<MockBluetoothGattService> > service0_; - scoped_ptr<testing::NiceMock<MockBluetoothGattService> > service1_; - scoped_ptr<testing::NiceMock<MockBluetoothGattCharacteristic> > chrc0_; - scoped_ptr<testing::NiceMock<MockBluetoothGattCharacteristic> > chrc1_; - scoped_ptr<testing::NiceMock<MockBluetoothGattCharacteristic> > chrc2_; - scoped_ptr<testing::NiceMock<MockBluetoothGattDescriptor> > desc0_; - scoped_ptr<testing::NiceMock<MockBluetoothGattDescriptor> > desc1_; - - private: - scoped_refptr<extensions::Extension> empty_extension_; -}; - -ACTION_TEMPLATE(InvokeCallbackArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { - ::std::tr1::get<k>(args).Run(); -} - -ACTION_TEMPLATE(InvokeCallbackArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(p0)) { - ::std::tr1::get<k>(args).Run(p0); -} - -ACTION_TEMPLATE(InvokeCallbackWithScopedPtrArg, - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(p0)) { - ::std::tr1::get<k>(args).Run(scoped_ptr<T>(p0)); -} - -BluetoothGattConnection* CreateGattConnection( - const std::string& device_address, - bool expect_disconnect) { - testing::NiceMock<MockBluetoothGattConnection>* conn = - new testing::NiceMock<MockBluetoothGattConnection>(device_address); - - if (expect_disconnect) { - EXPECT_CALL(*conn, Disconnect(_)) - .Times(1) - .WillOnce(InvokeCallbackArgument<0>()); - } else { - EXPECT_CALL(*conn, Disconnect(_)).Times(0); - } - - return conn; -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetServices) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - std::vector<BluetoothGattService*> services; - services.push_back(service0_.get()); - services.push_back(service1_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(3) - .WillOnce(Return(static_cast<BluetoothDevice*>(NULL))) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattServices()) - .Times(2) - .WillOnce(Return(std::vector<BluetoothGattService*>())) - .WillOnce(Return(services)); - - // Load and wait for setup. - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/get_services"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetService) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(3) - .WillOnce(Return(static_cast<BluetoothDevice*>(NULL))) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(2) - .WillOnce(Return(static_cast<BluetoothGattService*>(NULL))) - .WillOnce(Return(service0_.get())); - - // Load and wait for setup. - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/get_service"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ServiceEvents) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - // Load the extension and let it set up. - ExtensionTestMessageListener listener(true); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/service_events"))); - - // These will create the identifier mappings. - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service1_.get()); - - // These will send the onServiceAdded event to apps. - event_router()->GattDiscoveryCompleteForService(mock_adapter_, - service0_.get()); - event_router()->GattDiscoveryCompleteForService(mock_adapter_, - service1_.get()); - - // This will send the onServiceChanged event to apps. - event_router()->GattServiceChanged(mock_adapter_, service1_.get()); - - // This will send the onServiceRemoved event to apps. - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - ASSERT_EQ("ready", listener.message()) << listener.message(); - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service1_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetRemovedService) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - // Load the extension and let it set up. - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/get_removed_service"))); - - // 1. getService success. - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(1) - .WillOnce(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(1) - .WillOnce(Return(service0_.get())); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattDiscoveryCompleteForService(mock_adapter_, - service0_.get()); - - ExtensionTestMessageListener get_service_success_listener(true); - EXPECT_TRUE(get_service_success_listener.WaitUntilSatisfied()); - ASSERT_EQ("getServiceSuccess", get_service_success_listener.message()) - << get_service_success_listener.message(); - testing::Mock::VerifyAndClearExpectations(mock_adapter_); - testing::Mock::VerifyAndClearExpectations(device0_.get()); - - // 2. getService fail. - EXPECT_CALL(*mock_adapter_, GetDevice(_)).Times(0); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)).Times(0); - - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); - - ExtensionTestMessageListener get_service_fail_listener(true); - EXPECT_TRUE(get_service_fail_listener.WaitUntilSatisfied()); - ASSERT_EQ("getServiceFail", get_service_fail_listener.message()) - << get_service_fail_listener.message(); - testing::Mock::VerifyAndClearExpectations(mock_adapter_); - testing::Mock::VerifyAndClearExpectations(device0_.get()); - - get_service_fail_listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetIncludedServices) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/get_included_services"))); - - // Wait for initial call to end with failure as there is no mapping. - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - // Set up for the rest of the calls before replying. Included services can be - // returned even if there is no instance ID mapping for them yet, so no need - // to call GattServiceAdded for |service1_| here. - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - - std::vector<BluetoothGattService*> includes; - includes.push_back(service1_.get()); - EXPECT_CALL(*mock_adapter_, GetDevice(kTestLeDeviceAddress0)) - .Times(2) - .WillRepeatedly(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(2) - .WillRepeatedly(Return(service0_.get())); - EXPECT_CALL(*service0_, GetIncludedServices()) - .Times(2) - .WillOnce(Return(std::vector<BluetoothGattService*>())) - .WillOnce(Return(includes)); - - listener.Reply("go"); - listener.Reset(); - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetCharacteristics) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - std::vector<BluetoothGattCharacteristic*> characteristics; - characteristics.push_back(chrc0_.get()); - characteristics.push_back(chrc1_.get()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)).Times(3).WillRepeatedly( - Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(3) - .WillOnce(Return(static_cast<BluetoothGattService*>(NULL))) - .WillRepeatedly(Return(service0_.get())); - EXPECT_CALL(*service0_, GetCharacteristics()) - .Times(2) - .WillOnce(Return(std::vector<BluetoothGattCharacteristic*>())) - .WillOnce(Return(characteristics)); - - ExtensionTestMessageListener listener("ready", true); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/get_characteristics"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetCharacteristic) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(4) - .WillOnce(Return(static_cast<BluetoothDevice*>(NULL))) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(3) - .WillOnce(Return(static_cast<BluetoothGattService*>(NULL))) - .WillRepeatedly(Return(service0_.get())); - - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(2) - .WillOnce(Return(static_cast<BluetoothGattCharacteristic*>(NULL))) - .WillOnce(Return(chrc0_.get())); - - // Load the extension and wait for first test. - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/get_characteristic"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, CharacteristicProperties) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(12) - .WillRepeatedly(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(12) - .WillRepeatedly(Return(service0_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(12) - .WillRepeatedly(Return(chrc0_.get())); - EXPECT_CALL(*chrc0_, GetProperties()) - .Times(12) - .WillOnce(Return(BluetoothGattCharacteristic::PROPERTY_NONE)) - .WillOnce(Return(BluetoothGattCharacteristic::PROPERTY_BROADCAST)) - .WillOnce(Return(BluetoothGattCharacteristic::PROPERTY_READ)) - .WillOnce( - Return(BluetoothGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE)) - .WillOnce(Return(BluetoothGattCharacteristic::PROPERTY_WRITE)) - .WillOnce(Return(BluetoothGattCharacteristic::PROPERTY_NOTIFY)) - .WillOnce(Return(BluetoothGattCharacteristic::PROPERTY_INDICATE)) - .WillOnce(Return( - BluetoothGattCharacteristic::PROPERTY_AUTHENTICATED_SIGNED_WRITES)) - .WillOnce( - Return(BluetoothGattCharacteristic::PROPERTY_EXTENDED_PROPERTIES)) - .WillOnce(Return(BluetoothGattCharacteristic::PROPERTY_RELIABLE_WRITE)) - .WillOnce( - Return(BluetoothGattCharacteristic::PROPERTY_WRITABLE_AUXILIARIES)) - .WillOnce(Return( - BluetoothGattCharacteristic::PROPERTY_BROADCAST | - BluetoothGattCharacteristic::PROPERTY_READ | - BluetoothGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE | - BluetoothGattCharacteristic::PROPERTY_WRITE | - BluetoothGattCharacteristic::PROPERTY_NOTIFY | - BluetoothGattCharacteristic::PROPERTY_INDICATE | - BluetoothGattCharacteristic::PROPERTY_AUTHENTICATED_SIGNED_WRITES | - BluetoothGattCharacteristic::PROPERTY_EXTENDED_PROPERTIES | - BluetoothGattCharacteristic::PROPERTY_RELIABLE_WRITE | - BluetoothGattCharacteristic::PROPERTY_WRITABLE_AUXILIARIES)); - - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/characteristic_properties"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetRemovedCharacteristic) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(1) - .WillOnce(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(1) - .WillOnce(Return(service0_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(1) - .WillOnce(Return(chrc0_.get())); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/get_removed_characteristic"))); - - ExtensionTestMessageListener listener(true); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - ASSERT_EQ("ready", listener.message()) << listener.message(); - testing::Mock::VerifyAndClearExpectations(mock_adapter_); - testing::Mock::VerifyAndClearExpectations(device0_.get()); - testing::Mock::VerifyAndClearExpectations(service0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)).Times(0); - EXPECT_CALL(*device0_, GetGattService(_)).Times(0); - EXPECT_CALL(*service0_, GetCharacteristic(_)).Times(0); - - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - - listener.Reply("go"); - listener.Reset(); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - ASSERT_EQ("ready", listener.message()) << listener.message(); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, CharacteristicValueChanged) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - // Cause events to be sent to the extension. - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service1_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc2_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(2) - .WillRepeatedly(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(1) - .WillOnce(Return(service0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId1)) - .Times(1) - .WillOnce(Return(service1_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(1) - .WillOnce(Return(chrc0_.get())); - EXPECT_CALL(*service1_, GetCharacteristic(kTestCharacteristicId2)) - .Times(1) - .WillOnce(Return(chrc2_.get())); - - BluetoothGattNotifySession* session0 = - new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId0); - BluetoothGattNotifySession* session1 = - new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId2); - - EXPECT_CALL(*chrc0_, StartNotifySession(_, _)) - .Times(1) - .WillOnce( - InvokeCallbackWithScopedPtrArg<0, BluetoothGattNotifySession>( - session0)); - EXPECT_CALL(*chrc2_, StartNotifySession(_, _)) - .Times(1) - .WillOnce( - InvokeCallbackWithScopedPtrArg<0, BluetoothGattNotifySession>( - session1)); - - ExtensionTestMessageListener listener("ready", true); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/characteristic_value_changed"))); - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - std::vector<uint8> value; - event_router()->GattCharacteristicValueChanged( - mock_adapter_, chrc0_.get(), value); - event_router()->GattCharacteristicValueChanged( - mock_adapter_, chrc2_.get(), value); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc2_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service1_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ReadCharacteristicValue) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(3) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(3) - .WillRepeatedly(Return(service0_.get())); - - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(3) - .WillRepeatedly(Return(chrc0_.get())); - - std::vector<uint8> value; - EXPECT_CALL(*chrc0_, ReadRemoteCharacteristic(_, _)) - .Times(2) - .WillOnce( - InvokeCallbackArgument<1>(BluetoothGattService::GATT_ERROR_FAILED)) - .WillOnce(InvokeCallbackArgument<0>(value)); - - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/read_characteristic_value"))); - listener.WaitUntilSatisfied(); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, WriteCharacteristicValue) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(3) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(3) - .WillRepeatedly(Return(service0_.get())); - - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(3) - .WillRepeatedly(Return(chrc0_.get())); - - std::vector<uint8> write_value; - EXPECT_CALL(*chrc0_, WriteRemoteCharacteristic(_, _, _)) - .Times(2) - .WillOnce( - InvokeCallbackArgument<2>(BluetoothGattService::GATT_ERROR_FAILED)) - .WillOnce(DoAll(SaveArg<0>(&write_value), InvokeCallbackArgument<1>())); - - EXPECT_CALL(*chrc0_, GetValue()).Times(1).WillOnce(ReturnRef(write_value)); - - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/write_characteristic_value"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetDescriptors) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - std::vector<BluetoothGattDescriptor*> descriptors; - descriptors.push_back(desc0_.get()); - descriptors.push_back(desc1_.get()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(3) - .WillRepeatedly(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(3) - .WillRepeatedly(Return(service0_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(3) - .WillOnce(Return(static_cast<BluetoothGattCharacteristic*>(NULL))) - .WillRepeatedly(Return(chrc0_.get())); - EXPECT_CALL(*chrc0_, GetDescriptors()) - .Times(2) - .WillOnce(Return(std::vector<BluetoothGattDescriptor*>())) - .WillOnce(Return(descriptors)); - - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/get_descriptors"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetDescriptor) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(5) - .WillOnce(Return(static_cast<BluetoothDevice*>(NULL))) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(4) - .WillOnce(Return(static_cast<BluetoothGattService*>(NULL))) - .WillRepeatedly(Return(service0_.get())); - - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(3) - .WillOnce(Return(static_cast<BluetoothGattCharacteristic*>(NULL))) - .WillRepeatedly(Return(chrc0_.get())); - - EXPECT_CALL(*chrc0_, GetDescriptor(kTestDescriptorId0)) - .Times(2) - .WillOnce(Return(static_cast<BluetoothGattDescriptor*>(NULL))) - .WillOnce(Return(desc0_.get())); - - // Load the extension and wait for first test. - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/get_descriptor"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattDescriptorRemoved(mock_adapter_, desc0_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetRemovedDescriptor) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(1) - .WillOnce(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(1) - .WillOnce(Return(service0_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(1) - .WillOnce(Return(chrc0_.get())); - EXPECT_CALL(*chrc0_, GetDescriptor(kTestDescriptorId0)) - .Times(1) - .WillOnce(Return(desc0_.get())); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc0_.get()); - - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/get_removed_descriptor"))); - - ExtensionTestMessageListener listener(true); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - ASSERT_EQ("ready", listener.message()) << listener.message(); - testing::Mock::VerifyAndClearExpectations(mock_adapter_); - testing::Mock::VerifyAndClearExpectations(device0_.get()); - testing::Mock::VerifyAndClearExpectations(service0_.get()); - testing::Mock::VerifyAndClearExpectations(chrc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)).Times(0); - EXPECT_CALL(*device0_, GetGattService(_)).Times(0); - EXPECT_CALL(*service0_, GetCharacteristic(_)).Times(0); - EXPECT_CALL(*chrc0_, GetDescriptor(_)).Times(0); - - event_router()->GattDescriptorRemoved(mock_adapter_, desc0_.get()); - - listener.Reply("go"); - listener.Reset(); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - ASSERT_EQ("ready", listener.message()) << listener.message(); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, DescriptorValueChanged) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc1_.get()); - - // Load the extension and let it set up. - ExtensionTestMessageListener listener("ready", true); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/descriptor_value_changed"))); - - // Cause events to be sent to the extension. - std::vector<uint8> value; - event_router()->GattDescriptorValueChanged( - mock_adapter_, desc0_.get(), value); - event_router()->GattDescriptorValueChanged( - mock_adapter_, desc1_.get(), value); - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattDescriptorRemoved(mock_adapter_, desc1_.get()); - event_router()->GattDescriptorRemoved(mock_adapter_, desc0_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ReadDescriptorValue) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(9) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(9) - .WillRepeatedly(Return(service0_.get())); - - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(9) - .WillRepeatedly(Return(chrc0_.get())); - - EXPECT_CALL(*chrc0_, GetDescriptor(kTestDescriptorId0)) - .Times(9) - .WillRepeatedly(Return(desc0_.get())); - - std::vector<uint8> value; - EXPECT_CALL(*desc0_, ReadRemoteDescriptor(_, _)) - .Times(8) - .WillOnce( - InvokeCallbackArgument<1>(BluetoothGattService::GATT_ERROR_FAILED)) - .WillOnce(InvokeCallbackArgument<1>( - BluetoothGattService::GATT_ERROR_INVALID_LENGTH)) - .WillOnce(InvokeCallbackArgument<1>( - BluetoothGattService::GATT_ERROR_NOT_PERMITTED)) - .WillOnce(InvokeCallbackArgument<1>( - BluetoothGattService::GATT_ERROR_NOT_AUTHORIZED)) - .WillOnce(InvokeCallbackArgument<1>( - BluetoothGattService::GATT_ERROR_NOT_PAIRED)) - .WillOnce(InvokeCallbackArgument<1>( - BluetoothGattService::GATT_ERROR_NOT_SUPPORTED)) - .WillOnce(InvokeCallbackArgument<1>( - BluetoothGattService::GATT_ERROR_IN_PROGRESS)) - .WillOnce(InvokeCallbackArgument<0>(value)); - - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/read_descriptor_value"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattDescriptorRemoved(mock_adapter_, desc0_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, WriteDescriptorValue) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .Times(3) - .WillRepeatedly(Return(device0_.get())); - - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .Times(3) - .WillRepeatedly(Return(service0_.get())); - - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(3) - .WillRepeatedly(Return(chrc0_.get())); - - EXPECT_CALL(*chrc0_, GetDescriptor(kTestDescriptorId0)) - .Times(3) - .WillRepeatedly(Return(desc0_.get())); - - std::vector<uint8> write_value; - EXPECT_CALL(*desc0_, WriteRemoteDescriptor(_, _, _)) - .Times(2) - .WillOnce( - InvokeCallbackArgument<2>(BluetoothGattService::GATT_ERROR_FAILED)) - .WillOnce(DoAll(SaveArg<0>(&write_value), InvokeCallbackArgument<1>())); - - EXPECT_CALL(*desc0_, GetValue()).Times(1).WillOnce(ReturnRef(write_value)); - - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/write_descriptor_value"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattDescriptorRemoved(mock_adapter_, desc0_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, PermissionDenied) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/permission_denied"))); - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, UuidPermissionMethods) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc0_.get()); - - std::vector<BluetoothGattService*> services; - services.push_back(service0_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .WillRepeatedly(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattServices()).WillOnce(Return(services)); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .WillRepeatedly(Return(service0_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .WillRepeatedly(Return(chrc0_.get())); - EXPECT_CALL(*chrc0_, GetDescriptor(kTestDescriptorId0)) - .WillRepeatedly(Return(desc0_.get())); - - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/uuid_permission_methods"))); - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - - event_router()->GattDescriptorRemoved(mock_adapter_, desc0_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, UuidPermissionEvents) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - ExtensionTestMessageListener listener(true); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/uuid_permission_events"))); - - // Cause events to be sent to the extension. - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattDescriptorAdded(mock_adapter_, desc0_.get()); - - std::vector<uint8> value; - event_router()->GattCharacteristicValueChanged( - mock_adapter_, chrc0_.get(), value); - event_router()->GattDescriptorValueChanged( - mock_adapter_, desc0_.get(), value); - event_router()->GattServiceChanged(mock_adapter_, service0_.get()); - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - listener.Reply("go"); - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - ASSERT_EQ("ready", listener.message()) << listener.message(); - - event_router()->GattDescriptorRemoved(mock_adapter_, desc0_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GattConnection) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .WillRepeatedly(Return(static_cast<BluetoothDevice*>(NULL))); - EXPECT_CALL(*mock_adapter_, GetDevice(kTestLeDeviceAddress0)) - .WillRepeatedly(Return(device0_.get())); - EXPECT_CALL(*mock_adapter_, GetDevice(kTestLeDeviceAddress1)) - .WillRepeatedly(Return(device1_.get())); - EXPECT_CALL(*device0_, CreateGattConnection(_, _)) - .Times(9) - .WillOnce(InvokeCallbackArgument<1>(BluetoothDevice::ERROR_FAILED)) - .WillOnce(InvokeCallbackArgument<1>(BluetoothDevice::ERROR_INPROGRESS)) - .WillOnce(InvokeCallbackArgument<1>(BluetoothDevice::ERROR_AUTH_FAILED)) - .WillOnce(InvokeCallbackArgument<1>(BluetoothDevice::ERROR_AUTH_REJECTED)) - .WillOnce(InvokeCallbackArgument<1>(BluetoothDevice::ERROR_AUTH_CANCELED)) - .WillOnce(InvokeCallbackArgument<1>(BluetoothDevice::ERROR_AUTH_TIMEOUT)) - .WillOnce( - InvokeCallbackArgument<1>(BluetoothDevice::ERROR_UNSUPPORTED_DEVICE)) - .WillOnce(InvokeCallbackWithScopedPtrArg<0, BluetoothGattConnection>( - CreateGattConnection(kTestLeDeviceAddress0, - true /* expect_disconnect */))) - .WillOnce(InvokeCallbackWithScopedPtrArg<0, BluetoothGattConnection>( - CreateGattConnection(kTestLeDeviceAddress0, - false /* expect_disconnect */))); - EXPECT_CALL(*device1_, CreateGattConnection(_, _)) - .Times(1) - .WillOnce(InvokeCallbackWithScopedPtrArg<0, BluetoothGattConnection>( - CreateGattConnection(kTestLeDeviceAddress1, - true /* expect_disconnect */))); - - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("bluetooth_low_energy/gatt_connection"))); - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ReconnectAfterDisconnected) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - EXPECT_CALL(*mock_adapter_, GetDevice(kTestLeDeviceAddress0)) - .WillRepeatedly(Return(device0_.get())); - - MockBluetoothGattConnection* first_conn = - static_cast<MockBluetoothGattConnection*>(CreateGattConnection( - kTestLeDeviceAddress0, false /* expect_disconnect */)); - EXPECT_CALL(*first_conn, IsConnected()) - .Times(2) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_CALL(*device0_, CreateGattConnection(_, _)) - .Times(2) - .WillOnce(InvokeCallbackWithScopedPtrArg<0, BluetoothGattConnection>( - first_conn)) - .WillOnce(InvokeCallbackWithScopedPtrArg<0, BluetoothGattConnection>( - CreateGattConnection(kTestLeDeviceAddress0, - false /* expect_disconnect */))); - - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/reconnect_after_disconnected"))); - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ConnectInProgress) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - EXPECT_CALL(*mock_adapter_, GetDevice(kTestLeDeviceAddress0)) - .WillRepeatedly(Return(device0_.get())); - - BluetoothDevice::GattConnectionCallback connect_callback; - base::Closure disconnect_callback; - - testing::NiceMock<MockBluetoothGattConnection>* conn = - new testing::NiceMock<MockBluetoothGattConnection>( - kTestLeDeviceAddress0); - scoped_ptr<BluetoothGattConnection> conn_ptr(conn); - EXPECT_CALL(*conn, Disconnect(_)) - .Times(1) - .WillOnce(SaveArg<0>(&disconnect_callback)); - - EXPECT_CALL(*device0_, CreateGattConnection(_, _)) - .Times(1) - .WillOnce(SaveArg<0>(&connect_callback)); - - ExtensionTestMessageListener listener(true); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/connect_in_progress"))); - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - ASSERT_EQ("ready", listener.message()) << listener.message(); - connect_callback.Run(conn_ptr.Pass()); - - listener.Reset(); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - ASSERT_EQ("ready", listener.message()) << listener.message(); - disconnect_callback.Run(); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, StartStopNotifications) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service0_.get()); - event_router()->GattServiceAdded( - mock_adapter_, device0_.get(), service1_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc0_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc1_.get()); - event_router()->GattCharacteristicAdded(mock_adapter_, chrc2_.get()); - - EXPECT_CALL(*mock_adapter_, GetDevice(_)) - .WillRepeatedly(Return(device0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)) - .WillRepeatedly(Return(service0_.get())); - EXPECT_CALL(*device0_, GetGattService(kTestServiceId1)) - .WillRepeatedly(Return(service1_.get())); - EXPECT_CALL(*service1_, GetCharacteristic(kTestCharacteristicId2)) - .Times(1) - .WillOnce(Return(chrc2_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId0)) - .Times(2) - .WillRepeatedly(Return(chrc0_.get())); - EXPECT_CALL(*service0_, GetCharacteristic(kTestCharacteristicId1)) - .Times(1) - .WillOnce(Return(chrc1_.get())); - - BluetoothGattNotifySession* session0 = - new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId0); - MockBluetoothGattNotifySession* session1 = - new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId1); - - EXPECT_CALL(*session1, Stop(_)) - .Times(1) - .WillOnce(InvokeCallbackArgument<0>()); - - EXPECT_CALL(*chrc0_, StartNotifySession(_, _)) - .Times(2) - .WillOnce( - InvokeCallbackArgument<1>(BluetoothGattService::GATT_ERROR_FAILED)) - .WillOnce(InvokeCallbackWithScopedPtrArg<0, BluetoothGattNotifySession>( - session0)); - EXPECT_CALL(*chrc1_, StartNotifySession(_, _)) - .Times(1) - .WillOnce( - InvokeCallbackWithScopedPtrArg<0, BluetoothGattNotifySession>( - session1)); - - ExtensionTestMessageListener listener("ready", true); - listener.set_failure_message("fail"); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/start_stop_notifications"))); - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - std::vector<uint8> value; - event_router()->GattCharacteristicValueChanged( - mock_adapter_, chrc0_.get(), value); - event_router()->GattCharacteristicValueChanged( - mock_adapter_, chrc1_.get(), value); - event_router()->GattCharacteristicValueChanged( - mock_adapter_, chrc2_.get(), value); - - listener.Reply("go"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc2_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc1_.get()); - event_router()->GattCharacteristicRemoved(mock_adapter_, chrc0_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service1_.get()); - event_router()->GattServiceRemoved( - mock_adapter_, device0_.get(), service0_.get()); -} - -#if defined(OS_CHROMEOS) -#define MAYBE_RegisterAdvertisement RegisterAdvertisement -#else -#define MAYBE_RegisterAdvertisement DISABLED_RegisterAdvertisement -#endif - -IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, MAYBE_RegisterAdvertisement) { - ResultCatcher catcher; - catcher.RestrictToBrowserContext(browser()->profile()); - - // Run the test. - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "bluetooth_low_energy/register_advertisement"))); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -} // namespace diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.cc b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.cc deleted file mode 100644 index c975a82..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.cc +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 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. - -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.h" - -#include "base/lazy_instance.h" - -namespace extensions { - -static base::LazyInstance<BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyConnection> > > g_factory = - LAZY_INSTANCE_INITIALIZER; - -template <> -BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyConnection> >* -ApiResourceManager<BluetoothLowEnergyConnection>::GetFactoryInstance() { - return g_factory.Pointer(); -} - -BluetoothLowEnergyConnection::BluetoothLowEnergyConnection( - bool persistent, - const std::string& owner_extension_id, - scoped_ptr<device::BluetoothGattConnection> connection) - : ApiResource(owner_extension_id), - persistent_(persistent), - connection_(connection.release()) { -} - -BluetoothLowEnergyConnection::~BluetoothLowEnergyConnection() { -} - -device::BluetoothGattConnection* -BluetoothLowEnergyConnection::GetConnection() const { - return connection_.get(); -} - -bool BluetoothLowEnergyConnection::IsPersistent() const { - return persistent_; -} - -} // namespace extensions diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.h b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.h deleted file mode 100644 index ec82d82..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.h +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2014 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. - -#ifndef EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_CONNECTION_H_ -#define EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_CONNECTION_H_ - -#include "base/memory/scoped_ptr.h" -#include "device/bluetooth/bluetooth_gatt_connection.h" -#include "extensions/browser/api/api_resource.h" -#include "extensions/browser/api/api_resource_manager.h" - -namespace extensions { - -// An ApiResource wrapper for a device::BluetoothGattConnection. -class BluetoothLowEnergyConnection : public ApiResource { - public: - explicit BluetoothLowEnergyConnection( - bool persistent, - const std::string& owner_extension_id, - scoped_ptr<device::BluetoothGattConnection> connection); - ~BluetoothLowEnergyConnection() override; - - // Returns a pointer to the underlying connection object. - device::BluetoothGattConnection* GetConnection() const; - - // ApiResource override. - bool IsPersistent() const override; - - // This resource should be managed on the UI thread. - static const content::BrowserThread::ID kThreadId = - content::BrowserThread::UI; - - private: - friend class ApiResourceManager<BluetoothLowEnergyConnection>; - static const char* service_name() { - return "BluetoothLowEnergyConnectionManager"; - } - - // True, if this resource should be persistent. - bool persistent_; - - // The connection is owned by this instance and will automatically disconnect - // when deleted. - scoped_ptr<device::BluetoothGattConnection> connection_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyConnection); -}; - -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_CONNECTION_H_ diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc deleted file mode 100644 index 51f8143..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc +++ /dev/null @@ -1,1500 +0,0 @@ -// Copyright 2014 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. - -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" - -#include "base/bind.h" -#include "base/logging.h" -#include "base/values.h" -#include "content/public/browser/browser_thread.h" -#include "device/bluetooth/bluetooth_adapter_factory.h" -#include "device/bluetooth/bluetooth_gatt_characteristic.h" -#include "device/bluetooth/bluetooth_gatt_connection.h" -#include "device/bluetooth/bluetooth_gatt_descriptor.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h" -#include "extensions/browser/api/bluetooth_low_energy/utils.h" -#include "extensions/browser/event_router.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/common/api/bluetooth/bluetooth_manifest_data.h" - -using content::BrowserThread; - -using device::BluetoothAdapter; -using device::BluetoothAdapterFactory; -using device::BluetoothDevice; -using device::BluetoothGattCharacteristic; -using device::BluetoothGattConnection; -using device::BluetoothGattDescriptor; -using device::BluetoothGattService; - -namespace apibtle = extensions::api::bluetooth_low_energy; - -namespace { - -void PopulateService(const BluetoothGattService* service, - apibtle::Service* out) { - DCHECK(out); - - out->uuid = service->GetUUID().canonical_value(); - out->is_primary = service->IsPrimary(); - out->is_local = service->IsLocal(); - out->instance_id.reset(new std::string(service->GetIdentifier())); - - if (!service->GetDevice()) - return; - - out->device_address.reset( - new std::string(service->GetDevice()->GetAddress())); -} - -void PopulateCharacteristicProperties( - BluetoothGattCharacteristic::Properties properties, - std::vector<apibtle::CharacteristicProperty>* api_properties) { - DCHECK(api_properties && api_properties->empty()); - - if (properties == BluetoothGattCharacteristic::PROPERTY_NONE) - return; - - if (properties & BluetoothGattCharacteristic::PROPERTY_BROADCAST) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_BROADCAST); - if (properties & BluetoothGattCharacteristic::PROPERTY_READ) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_READ); - if (properties & - BluetoothGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_WRITEWITHOUTRESPONSE); - } - if (properties & BluetoothGattCharacteristic::PROPERTY_WRITE) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_WRITE); - if (properties & BluetoothGattCharacteristic::PROPERTY_NOTIFY) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_NOTIFY); - if (properties & BluetoothGattCharacteristic::PROPERTY_INDICATE) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_INDICATE); - if (properties & - BluetoothGattCharacteristic::PROPERTY_AUTHENTICATED_SIGNED_WRITES) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_AUTHENTICATEDSIGNEDWRITES); - } - if (properties & BluetoothGattCharacteristic::PROPERTY_EXTENDED_PROPERTIES) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_EXTENDEDPROPERTIES); - } - if (properties & BluetoothGattCharacteristic::PROPERTY_RELIABLE_WRITE) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_RELIABLEWRITE); - if (properties & BluetoothGattCharacteristic::PROPERTY_WRITABLE_AUXILIARIES) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_WRITABLEAUXILIARIES); - } -} - -void PopulateCharacteristic(const BluetoothGattCharacteristic* characteristic, - apibtle::Characteristic* out) { - DCHECK(out); - - out->uuid = characteristic->GetUUID().canonical_value(); - out->is_local = characteristic->IsLocal(); - out->instance_id.reset(new std::string(characteristic->GetIdentifier())); - - PopulateService(characteristic->GetService(), &out->service); - PopulateCharacteristicProperties(characteristic->GetProperties(), - &out->properties); - - const std::vector<uint8>& value = characteristic->GetValue(); - if (value.empty()) - return; - - out->value.reset(new std::vector<char>(value.begin(), value.end())); -} - -void PopulateDescriptor(const BluetoothGattDescriptor* descriptor, - apibtle::Descriptor* out) { - DCHECK(out); - - out->uuid = descriptor->GetUUID().canonical_value(); - out->is_local = descriptor->IsLocal(); - out->instance_id.reset(new std::string(descriptor->GetIdentifier())); - - PopulateCharacteristic(descriptor->GetCharacteristic(), &out->characteristic); - - const std::vector<uint8>& value = descriptor->GetValue(); - if (value.empty()) - return; - - out->value.reset(new std::vector<char>(value.begin(), value.end())); -} - -typedef extensions::ApiResourceManager<extensions::BluetoothLowEnergyConnection> - ConnectionResourceManager; -ConnectionResourceManager* GetConnectionResourceManager( - content::BrowserContext* context) { - ConnectionResourceManager* manager = ConnectionResourceManager::Get(context); - DCHECK(manager) - << "There is no Bluetooth low energy connection manager. " - "If this assertion is failing during a test, then it is likely that " - "TestExtensionSystem is failing to provide an instance of " - "ApiResourceManager<BluetoothLowEnergyConnection>."; - return manager; -} - -typedef extensions::ApiResourceManager< - extensions::BluetoothLowEnergyNotifySession> NotifySessionResourceManager; -NotifySessionResourceManager* GetNotifySessionResourceManager( - content::BrowserContext* context) { - NotifySessionResourceManager* manager = - NotifySessionResourceManager::Get(context); - DCHECK(manager) - << "There is no Bluetooth low energy value update session manager." - "If this assertion is failing during a test, then it is likely that " - "TestExtensionSystem is failing to provide an instance of " - "ApiResourceManager<BluetoothLowEnergyNotifySession>."; - return manager; -} - -// Translates GattErrorCodes to RouterError Codes -extensions::BluetoothLowEnergyEventRouter::Status GattErrorToRouterError( - BluetoothGattService::GattErrorCode error_code) { - extensions::BluetoothLowEnergyEventRouter::Status error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorFailed; - if (error_code == BluetoothGattService::GATT_ERROR_IN_PROGRESS) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorInProgress; - } else if (error_code == BluetoothGattService::GATT_ERROR_INVALID_LENGTH) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorInvalidLength; - } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_PERMITTED) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorPermissionDenied; - } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_AUTHORIZED) { - error_status = extensions::BluetoothLowEnergyEventRouter:: - kStatusErrorInsufficientAuthorization; - } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_PAIRED) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorHigherSecurity; - } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_SUPPORTED) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorGattNotSupported; - } - - return error_status; -} - -} // namespace - -namespace extensions { - -BluetoothLowEnergyEventRouter::BluetoothLowEnergyEventRouter( - content::BrowserContext* context) - : adapter_(NULL), browser_context_(context), weak_ptr_factory_(this) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(browser_context_); - VLOG(1) << "Initializing BluetoothLowEnergyEventRouter."; - - if (!IsBluetoothSupported()) { - VLOG(1) << "Bluetooth not supported on the current platform."; - return; - } -} - -BluetoothLowEnergyEventRouter::~BluetoothLowEnergyEventRouter() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) - return; - - adapter_->RemoveObserver(this); - adapter_ = NULL; -} - -bool BluetoothLowEnergyEventRouter::IsBluetoothSupported() const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - return adapter_.get() || - BluetoothAdapterFactory::IsBluetoothAdapterAvailable(); -} - -bool BluetoothLowEnergyEventRouter::InitializeAdapterAndInvokeCallback( - const base::Closure& callback) { - if (!IsBluetoothSupported()) - return false; - - if (adapter_.get()) { - callback.Run(); - return true; - } - - BluetoothAdapterFactory::GetAdapter( - base::Bind(&BluetoothLowEnergyEventRouter::OnGetAdapter, - weak_ptr_factory_.GetWeakPtr(), - callback)); - return true; -} - -bool BluetoothLowEnergyEventRouter::HasAdapter() const { - return (adapter_.get() != NULL); -} - -void BluetoothLowEnergyEventRouter::Connect( - bool persistent, - const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - const std::string connect_id = extension_id + device_address; - - if (connecting_devices_.count(connect_id) != 0) { - error_callback.Run(kStatusErrorInProgress); - return; - } - - BluetoothLowEnergyConnection* conn = - FindConnection(extension_id, device_address); - if (conn) { - if (conn->GetConnection()->IsConnected()) { - VLOG(1) << "Application already connected to device: " << device_address; - error_callback.Run(kStatusErrorAlreadyConnected); - return; - } - - // There is a connection object but it's no longer active. Simply remove it. - RemoveConnection(extension_id, device_address); - } - - BluetoothDevice* device = adapter_->GetDevice(device_address); - if (!device) { - VLOG(1) << "Bluetooth device not found: " << device_address; - error_callback.Run(kStatusErrorNotFound); - return; - } - - connecting_devices_.insert(connect_id); - device->CreateGattConnection( - base::Bind(&BluetoothLowEnergyEventRouter::OnCreateGattConnection, - weak_ptr_factory_.GetWeakPtr(), - persistent, - extension_id, - device_address, - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnConnectError, - weak_ptr_factory_.GetWeakPtr(), - extension_id, - device_address, - error_callback)); -} - -void BluetoothLowEnergyEventRouter::Disconnect( - const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - const std::string disconnect_id = extension_id + device_address; - - if (disconnecting_devices_.count(disconnect_id) != 0) { - error_callback.Run(kStatusErrorInProgress); - return; - } - - BluetoothLowEnergyConnection* conn = - FindConnection(extension_id, device_address); - if (!conn || !conn->GetConnection()->IsConnected()) { - VLOG(1) << "Application not connected to device: " << device_address; - error_callback.Run(kStatusErrorNotConnected); - return; - } - - disconnecting_devices_.insert(disconnect_id); - conn->GetConnection()->Disconnect( - base::Bind(&BluetoothLowEnergyEventRouter::OnDisconnect, - weak_ptr_factory_.GetWeakPtr(), - extension_id, - device_address, - callback)); -} - -bool BluetoothLowEnergyEventRouter::GetServices( - const std::string& device_address, - ServiceList* out_services) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(out_services); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return false; - } - - BluetoothDevice* device = adapter_->GetDevice(device_address); - if (!device) { - VLOG(1) << "Bluetooth device not found: " << device_address; - return false; - } - - out_services->clear(); - - const std::vector<BluetoothGattService*>& services = - device->GetGattServices(); - for (std::vector<BluetoothGattService*>::const_iterator iter = - services.begin(); - iter != services.end(); - ++iter) { - // Populate an API service and add it to the return value. - const BluetoothGattService* service = *iter; - linked_ptr<apibtle::Service> api_service(new apibtle::Service()); - PopulateService(service, api_service.get()); - - out_services->push_back(api_service); - } - - return true; -} - -BluetoothLowEnergyEventRouter::Status BluetoothLowEnergyEventRouter::GetService( - const std::string& instance_id, - apibtle::Service* out_service) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(out_service); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothGattService* gatt_service = FindServiceById(instance_id); - if (!gatt_service) { - VLOG(1) << "Service not found: " << instance_id; - return kStatusErrorNotFound; - } - - PopulateService(gatt_service, out_service); - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetIncludedServices( - const std::string& instance_id, - ServiceList* out_services) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(out_services); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothGattService* service = FindServiceById(instance_id); - if (!service) { - VLOG(1) << "Service not found: " << instance_id; - return kStatusErrorNotFound; - } - - out_services->clear(); - - const std::vector<BluetoothGattService*>& includes = - service->GetIncludedServices(); - for (std::vector<BluetoothGattService*>::const_iterator iter = - includes.begin(); - iter != includes.end(); - ++iter) { - // Populate an API service and add it to the return value. - const BluetoothGattService* included = *iter; - linked_ptr<apibtle::Service> api_service(new apibtle::Service()); - PopulateService(included, api_service.get()); - - out_services->push_back(api_service); - } - - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetCharacteristics( - const Extension* extension, - const std::string& instance_id, - CharacteristicList* out_characteristics) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_characteristics); - if (!adapter_.get()) { - VLOG(1) << "BlutoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothGattService* service = FindServiceById(instance_id); - if (!service) { - VLOG(1) << "Service not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request(service->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access the characteristics of this " - << "service: " << instance_id; - return kStatusErrorPermissionDenied; - } - - out_characteristics->clear(); - - const std::vector<BluetoothGattCharacteristic*>& characteristics = - service->GetCharacteristics(); - for (std::vector<BluetoothGattCharacteristic*>::const_iterator iter = - characteristics.begin(); - iter != characteristics.end(); - ++iter) { - // Populate an API characteristic and add it to the return value. - const BluetoothGattCharacteristic* characteristic = *iter; - linked_ptr<apibtle::Characteristic> api_characteristic( - new apibtle::Characteristic()); - PopulateCharacteristic(characteristic, api_characteristic.get()); - - out_characteristics->push_back(api_characteristic); - } - - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetCharacteristic( - const Extension* extension, - const std::string& instance_id, - apibtle::Characteristic* out_characteristic) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_characteristic); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - return kStatusErrorPermissionDenied; - } - - PopulateCharacteristic(characteristic, out_characteristic); - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetDescriptors( - const Extension* extension, - const std::string& instance_id, - DescriptorList* out_descriptors) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_descriptors); - if (!adapter_.get()) { - VLOG(1) << "BlutoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access the descriptors of this " - << "characteristic: " << instance_id; - return kStatusErrorPermissionDenied; - } - - out_descriptors->clear(); - - const std::vector<BluetoothGattDescriptor*>& descriptors = - characteristic->GetDescriptors(); - for (std::vector<BluetoothGattDescriptor*>::const_iterator iter = - descriptors.begin(); - iter != descriptors.end(); - ++iter) { - // Populate an API descriptor and add it to the return value. - const BluetoothGattDescriptor* descriptor = *iter; - linked_ptr<apibtle::Descriptor> api_descriptor(new apibtle::Descriptor()); - PopulateDescriptor(descriptor, api_descriptor.get()); - - out_descriptors->push_back(api_descriptor); - } - - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetDescriptor( - const Extension* extension, - const std::string& instance_id, - api::bluetooth_low_energy::Descriptor* out_descriptor) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_descriptor); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothGattDescriptor* descriptor = FindDescriptorById(instance_id); - if (!descriptor) { - VLOG(1) << "Descriptor not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request( - descriptor->GetCharacteristic()->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this descriptor: " - << instance_id; - return kStatusErrorPermissionDenied; - } - - PopulateDescriptor(descriptor, out_descriptor); - return kStatusSuccess; -} - -void BluetoothLowEnergyEventRouter::ReadCharacteristicValue( - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - characteristic->ReadRemoteCharacteristic( - base::Bind(&BluetoothLowEnergyEventRouter::OnValueSuccess, - weak_ptr_factory_.GetWeakPtr(), - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::WriteCharacteristicValue( - const Extension* extension, - const std::string& instance_id, - const std::vector<uint8>& value, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - characteristic->WriteRemoteCharacteristic( - value, - callback, - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::StartCharacteristicNotifications( - bool persistent, - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - const std::string session_id = extension_id + instance_id; - - if (pending_session_calls_.count(session_id) != 0) { - error_callback.Run(kStatusErrorInProgress); - return; - } - - BluetoothLowEnergyNotifySession* session = - FindNotifySession(extension_id, instance_id); - if (session) { - if (session->GetSession()->IsActive()) { - VLOG(1) << "Application has already enabled notifications from " - << "characteristic: " << instance_id; - error_callback.Run(kStatusErrorAlreadyNotifying); - return; - } - - RemoveNotifySession(extension_id, instance_id); - } - - BluetoothGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - pending_session_calls_.insert(session_id); - characteristic->StartNotifySession( - base::Bind(&BluetoothLowEnergyEventRouter::OnStartNotifySession, - weak_ptr_factory_.GetWeakPtr(), - persistent, - extension_id, - instance_id, - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnStartNotifySessionError, - weak_ptr_factory_.GetWeakPtr(), - extension_id, - instance_id, - error_callback)); -} - -void BluetoothLowEnergyEventRouter::StopCharacteristicNotifications( - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - - BluetoothLowEnergyNotifySession* session = - FindNotifySession(extension_id, instance_id); - if (!session || !session->GetSession()->IsActive()) { - VLOG(1) << "Application has not enabled notifications from " - << "characteristic: " << instance_id; - error_callback.Run(kStatusErrorNotNotifying); - return; - } - - session->GetSession()->Stop( - base::Bind(&BluetoothLowEnergyEventRouter::OnStopNotifySession, - weak_ptr_factory_.GetWeakPtr(), - extension_id, - instance_id, - callback)); -} - -void BluetoothLowEnergyEventRouter::ReadDescriptorValue( - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothGattDescriptor* descriptor = FindDescriptorById(instance_id); - if (!descriptor) { - VLOG(1) << "Descriptor not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - descriptor->GetCharacteristic()->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this descriptor: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - descriptor->ReadRemoteDescriptor( - base::Bind(&BluetoothLowEnergyEventRouter::OnValueSuccess, - weak_ptr_factory_.GetWeakPtr(), - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::WriteDescriptorValue( - const Extension* extension, - const std::string& instance_id, - const std::vector<uint8>& value, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothGattDescriptor* descriptor = FindDescriptorById(instance_id); - if (!descriptor) { - VLOG(1) << "Descriptor not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - descriptor->GetCharacteristic()->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this descriptor: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - descriptor->WriteRemoteDescriptor( - value, - callback, - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::SetAdapterForTesting( - device::BluetoothAdapter* adapter) { - adapter_ = adapter; - InitializeIdentifierMappings(); -} - -void BluetoothLowEnergyEventRouter::GattServiceAdded( - BluetoothAdapter* adapter, - BluetoothDevice* device, - BluetoothGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service added: " << service->GetIdentifier(); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) == - service_id_to_device_address_.end()); - - service_id_to_device_address_[service->GetIdentifier()] = - device->GetAddress(); -} - -void BluetoothLowEnergyEventRouter::GattServiceRemoved( - BluetoothAdapter* adapter, - BluetoothDevice* device, - BluetoothGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service removed: " << service->GetIdentifier(); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - DCHECK(device->GetAddress() == - service_id_to_device_address_[service->GetIdentifier()]); - service_id_to_device_address_.erase(service->GetIdentifier()); - - // Signal API event. - apibtle::Service api_service; - PopulateService(service, &api_service); - - scoped_ptr<base::ListValue> args = - apibtle::OnServiceRemoved::Create(api_service); - scoped_ptr<Event> event( - new Event(events::BLUETOOTH_LOW_ENERGY_ON_SERVICE_REMOVED, - apibtle::OnServiceRemoved::kEventName, args.Pass())); - EventRouter::Get(browser_context_)->BroadcastEvent(event.Pass()); -} - -void BluetoothLowEnergyEventRouter::GattDiscoveryCompleteForService( - BluetoothAdapter* adapter, - BluetoothGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service discovery complete: " << service->GetIdentifier(); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - // Signal the service added event here. - apibtle::Service api_service; - PopulateService(service, &api_service); - - scoped_ptr<base::ListValue> args = - apibtle::OnServiceAdded::Create(api_service); - scoped_ptr<Event> event( - new Event(events::BLUETOOTH_LOW_ENERGY_ON_SERVICE_ADDED, - apibtle::OnServiceAdded::kEventName, args.Pass())); - EventRouter::Get(browser_context_)->BroadcastEvent(event.Pass()); -} - -void BluetoothLowEnergyEventRouter::GattServiceChanged( - BluetoothAdapter* adapter, - BluetoothGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service changed: " << service->GetIdentifier(); - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - // Signal API event. - apibtle::Service api_service; - PopulateService(service, &api_service); - - DispatchEventToExtensionsWithPermission( - events::BLUETOOTH_LOW_ENERGY_ON_SERVICE_CHANGED, - apibtle::OnServiceChanged::kEventName, service->GetUUID(), - "" /* characteristic_id */, - apibtle::OnServiceChanged::Create(api_service)); -} - -void BluetoothLowEnergyEventRouter::GattCharacteristicAdded( - BluetoothAdapter* adapter, - BluetoothGattCharacteristic* characteristic) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT characteristic added: " << characteristic->GetIdentifier(); - - BluetoothGattService* service = characteristic->GetService(); - DCHECK(service); - - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) == - chrc_id_to_service_id_.end()); - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - chrc_id_to_service_id_[characteristic->GetIdentifier()] = - service->GetIdentifier(); -} - -void BluetoothLowEnergyEventRouter::GattCharacteristicRemoved( - BluetoothAdapter* adapter, - BluetoothGattCharacteristic* characteristic) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT characteristic removed: " << characteristic->GetIdentifier(); - - BluetoothGattService* service = characteristic->GetService(); - DCHECK(service); - - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) != - chrc_id_to_service_id_.end()); - DCHECK(service->GetIdentifier() == - chrc_id_to_service_id_[characteristic->GetIdentifier()]); - - chrc_id_to_service_id_.erase(characteristic->GetIdentifier()); -} - -void BluetoothLowEnergyEventRouter::GattDescriptorAdded( - BluetoothAdapter* adapter, - BluetoothGattDescriptor* descriptor) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT descriptor added: " << descriptor->GetIdentifier(); - - BluetoothGattCharacteristic* characteristic = descriptor->GetCharacteristic(); - DCHECK(characteristic); - - DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) == - desc_id_to_chrc_id_.end()); - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) != - chrc_id_to_service_id_.end()); - - desc_id_to_chrc_id_[descriptor->GetIdentifier()] = - characteristic->GetIdentifier(); -} - -void BluetoothLowEnergyEventRouter::GattDescriptorRemoved( - BluetoothAdapter* adapter, - BluetoothGattDescriptor* descriptor) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT descriptor removed: " << descriptor->GetIdentifier(); - - BluetoothGattCharacteristic* characteristic = descriptor->GetCharacteristic(); - DCHECK(characteristic); - - DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) != - desc_id_to_chrc_id_.end()); - DCHECK(characteristic->GetIdentifier() == - desc_id_to_chrc_id_[descriptor->GetIdentifier()]); - - desc_id_to_chrc_id_.erase(descriptor->GetIdentifier()); -} - -void BluetoothLowEnergyEventRouter::GattCharacteristicValueChanged( - BluetoothAdapter* adapter, - BluetoothGattCharacteristic* characteristic, - const std::vector<uint8>& value) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT characteristic value changed: " - << characteristic->GetIdentifier(); - - BluetoothGattService* service = characteristic->GetService(); - DCHECK(service); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) != - chrc_id_to_service_id_.end()); - DCHECK(chrc_id_to_service_id_[characteristic->GetIdentifier()] == - service->GetIdentifier()); - - // Send the event; manually construct the arguments, instead of using - // apibtle::OnCharacteristicValueChanged::Create, as it doesn't convert - // lists of enums correctly. - apibtle::Characteristic api_characteristic; - PopulateCharacteristic(characteristic, &api_characteristic); - scoped_ptr<base::ListValue> args(new base::ListValue()); - args->Append(apibtle::CharacteristicToValue(&api_characteristic).release()); - - DispatchEventToExtensionsWithPermission( - events::BLUETOOTH_LOW_ENERGY_ON_CHARACTERISTIC_VALUE_CHANGED, - apibtle::OnCharacteristicValueChanged::kEventName, service->GetUUID(), - characteristic->GetIdentifier(), args.Pass()); -} - -void BluetoothLowEnergyEventRouter::GattDescriptorValueChanged( - BluetoothAdapter* adapter, - BluetoothGattDescriptor* descriptor, - const std::vector<uint8>& value) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT descriptor value changed: " << descriptor->GetIdentifier(); - - BluetoothGattCharacteristic* characteristic = descriptor->GetCharacteristic(); - DCHECK(characteristic); - - DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) != - desc_id_to_chrc_id_.end()); - DCHECK(characteristic->GetIdentifier() == - desc_id_to_chrc_id_[descriptor->GetIdentifier()]); - - // Send the event; manually construct the arguments, instead of using - // apibtle::OnDescriptorValueChanged::Create, as it doesn't convert - // lists of enums correctly. - apibtle::Descriptor api_descriptor; - PopulateDescriptor(descriptor, &api_descriptor); - scoped_ptr<base::ListValue> args(new base::ListValue()); - args->Append(apibtle::DescriptorToValue(&api_descriptor).release()); - - DispatchEventToExtensionsWithPermission( - events::BLUETOOTH_LOW_ENERGY_ON_DESCRIPTOR_VALUE_CHANGED, - apibtle::OnDescriptorValueChanged::kEventName, - characteristic->GetService()->GetUUID(), "" /* characteristic_id */, - args.Pass()); -} - -void BluetoothLowEnergyEventRouter::OnGetAdapter( - const base::Closure& callback, - scoped_refptr<device::BluetoothAdapter> adapter) { - adapter_ = adapter; - - // Initialize instance ID mappings for all discovered GATT objects and add - // observers. - InitializeIdentifierMappings(); - adapter_->AddObserver(this); - - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::InitializeIdentifierMappings() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(service_id_to_device_address_.empty()); - DCHECK(chrc_id_to_service_id_.empty()); - - // Devices - BluetoothAdapter::DeviceList devices = adapter_->GetDevices(); - for (BluetoothAdapter::DeviceList::iterator iter = devices.begin(); - iter != devices.end(); - ++iter) { - BluetoothDevice* device = *iter; - - // Services - std::vector<BluetoothGattService*> services = device->GetGattServices(); - for (std::vector<BluetoothGattService*>::iterator siter = services.begin(); - siter != services.end(); - ++siter) { - BluetoothGattService* service = *siter; - - const std::string& service_id = service->GetIdentifier(); - service_id_to_device_address_[service_id] = device->GetAddress(); - - // Characteristics - const std::vector<BluetoothGattCharacteristic*>& characteristics = - service->GetCharacteristics(); - for (std::vector<BluetoothGattCharacteristic*>::const_iterator citer = - characteristics.begin(); - citer != characteristics.end(); - ++citer) { - BluetoothGattCharacteristic* characteristic = *citer; - - const std::string& chrc_id = characteristic->GetIdentifier(); - chrc_id_to_service_id_[chrc_id] = service_id; - - // Descriptors - const std::vector<BluetoothGattDescriptor*>& descriptors = - characteristic->GetDescriptors(); - for (std::vector<BluetoothGattDescriptor*>::const_iterator diter = - descriptors.begin(); - diter != descriptors.end(); - ++diter) { - BluetoothGattDescriptor* descriptor = *diter; - - const std::string& desc_id = descriptor->GetIdentifier(); - desc_id_to_chrc_id_[desc_id] = chrc_id; - } - } - } - } -} - -void BluetoothLowEnergyEventRouter::DispatchEventToExtensionsWithPermission( - events::HistogramValue histogram_value, - const std::string& event_name, - const device::BluetoothUUID& uuid, - const std::string& characteristic_id, - scoped_ptr<base::ListValue> args) { - // Obtain the listeners of |event_name|. The list can contain multiple - // entries for the same extension, so we keep track of the extensions that we - // already sent the event to, since we want the send an event to an extension - // only once. - BluetoothPermissionRequest request(uuid.value()); - std::set<std::string> handled_extensions; - const EventListenerMap::ListenerList listeners = - EventRouter::Get(browser_context_)->listeners().GetEventListenersByName( - event_name); - - for (EventListenerMap::ListenerList::const_iterator iter = listeners.begin(); - iter != listeners.end(); - ++iter) { - const std::string extension_id = (*iter)->extension_id(); - if (handled_extensions.find(extension_id) != handled_extensions.end()) - continue; - - handled_extensions.insert(extension_id); - - const Extension* extension = - ExtensionRegistry::Get(browser_context_) - ->GetExtensionById(extension_id, ExtensionRegistry::EVERYTHING); - - // For all API methods, the "low_energy" permission check is handled by - // BluetoothLowEnergyExtensionFunction but for events we have to do the - // check here. - if (!BluetoothManifestData::CheckRequest(extension, request) || - !BluetoothManifestData::CheckLowEnergyPermitted(extension)) - continue; - - // If |event_name| is "onCharacteristicValueChanged", then send the - // event only if the extension has requested notifications from the - // related characteristic. - if (event_name == apibtle::OnCharacteristicValueChanged::kEventName && - !characteristic_id.empty() && - !FindNotifySession(extension_id, characteristic_id)) - continue; - - // Send the event. - scoped_ptr<base::ListValue> args_copy(args->DeepCopy()); - scoped_ptr<Event> event( - new Event(histogram_value, event_name, args_copy.Pass())); - EventRouter::Get(browser_context_)->DispatchEventToExtension( - extension_id, event.Pass()); - } -} - -BluetoothGattService* BluetoothLowEnergyEventRouter::FindServiceById( - const std::string& instance_id) const { - InstanceIdMap::const_iterator iter = - service_id_to_device_address_.find(instance_id); - if (iter == service_id_to_device_address_.end()) { - VLOG(1) << "GATT service identifier unknown: " << instance_id; - return NULL; - } - - const std::string& address = iter->second; - - BluetoothDevice* device = adapter_->GetDevice(address); - if (!device) { - VLOG(1) << "Bluetooth device not found: " << address; - return NULL; - } - - BluetoothGattService* service = device->GetGattService(instance_id); - if (!service) { - VLOG(1) << "GATT service with ID \"" << instance_id - << "\" not found on device \"" << address << "\""; - return NULL; - } - - return service; -} - -BluetoothGattCharacteristic* -BluetoothLowEnergyEventRouter::FindCharacteristicById( - const std::string& instance_id) const { - InstanceIdMap::const_iterator iter = chrc_id_to_service_id_.find(instance_id); - if (iter == chrc_id_to_service_id_.end()) { - VLOG(1) << "GATT characteristic identifier unknown: " << instance_id; - return NULL; - } - - const std::string& service_id = iter->second; - - BluetoothGattService* service = FindServiceById(service_id); - if (!service) { - VLOG(1) << "Failed to obtain service for characteristic: " << instance_id; - return NULL; - } - - BluetoothGattCharacteristic* characteristic = - service->GetCharacteristic(instance_id); - if (!characteristic) { - VLOG(1) << "GATT characteristic with ID \"" << instance_id - << "\" not found on service \"" << service_id << "\""; - return NULL; - } - - return characteristic; -} - -BluetoothGattDescriptor* BluetoothLowEnergyEventRouter::FindDescriptorById( - const std::string& instance_id) const { - InstanceIdMap::const_iterator iter = desc_id_to_chrc_id_.find(instance_id); - if (iter == desc_id_to_chrc_id_.end()) { - VLOG(1) << "GATT descriptor identifier unknown: " << instance_id; - return NULL; - } - - const std::string& chrc_id = iter->second; - BluetoothGattCharacteristic* chrc = FindCharacteristicById(chrc_id); - if (!chrc) { - VLOG(1) << "Failed to obtain characteristic for descriptor: " - << instance_id; - return NULL; - } - - BluetoothGattDescriptor* descriptor = chrc->GetDescriptor(instance_id); - if (!descriptor) { - VLOG(1) << "GATT descriptor with ID \"" << instance_id - << "\" not found on characteristic \"" << chrc_id << "\""; - return NULL; - } - - return descriptor; -} - -void BluetoothLowEnergyEventRouter::OnValueSuccess( - const base::Closure& callback, - const std::vector<uint8>& value) { - VLOG(2) << "Remote characteristic/descriptor value read successful."; - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnCreateGattConnection( - bool persistent, - const std::string& extension_id, - const std::string& device_address, - const base::Closure& callback, - scoped_ptr<BluetoothGattConnection> connection) { - VLOG(2) << "GATT connection created."; - DCHECK(connection.get()); - DCHECK(!FindConnection(extension_id, device_address)); - DCHECK_EQ(device_address, connection->GetDeviceAddress()); - - const std::string connect_id = extension_id + device_address; - DCHECK_NE(0U, connecting_devices_.count(connect_id)); - - BluetoothLowEnergyConnection* conn = new BluetoothLowEnergyConnection( - persistent, extension_id, connection.Pass()); - ConnectionResourceManager* manager = - GetConnectionResourceManager(browser_context_); - manager->Add(conn); - - connecting_devices_.erase(connect_id); - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnDisconnect( - const std::string& extension_id, - const std::string& device_address, - const base::Closure& callback) { - VLOG(2) << "GATT connection terminated."; - - const std::string disconnect_id = extension_id + device_address; - DCHECK_NE(0U, disconnecting_devices_.count(disconnect_id)); - - if (!RemoveConnection(extension_id, device_address)) { - VLOG(1) << "The connection was removed before disconnect completed, id: " - << extension_id << ", device: " << device_address; - } - - disconnecting_devices_.erase(disconnect_id); - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnError( - const ErrorCallback& error_callback, - BluetoothGattService::GattErrorCode error_code) { - VLOG(2) << "Remote characteristic/descriptor value read/write failed."; - - error_callback.Run(GattErrorToRouterError(error_code)); -} - -void BluetoothLowEnergyEventRouter::OnConnectError( - const std::string& extension_id, - const std::string& device_address, - const ErrorCallback& error_callback, - BluetoothDevice::ConnectErrorCode error_code) { - VLOG(2) << "Failed to create GATT connection: " << error_code; - - const std::string connect_id = extension_id + device_address; - DCHECK_NE(0U, connecting_devices_.count(connect_id)); - - connecting_devices_.erase(connect_id); - Status error_status = kStatusErrorFailed; - if (error_code == BluetoothDevice::ERROR_INPROGRESS) { - error_status = kStatusErrorInProgress; - } else if (error_code == BluetoothDevice::ERROR_AUTH_FAILED || - error_code == BluetoothDevice::ERROR_AUTH_REJECTED) { - error_status = kStatusErrorAuthenticationFailed; - } else if (error_code == BluetoothDevice::ERROR_AUTH_CANCELED) { - error_status = kStatusErrorCanceled; - } else if (error_code == BluetoothDevice::ERROR_AUTH_TIMEOUT) { - error_status = kStatusErrorTimeout; - } else if (error_code == BluetoothDevice::ERROR_UNSUPPORTED_DEVICE) { - error_status = kStatusErrorUnsupportedDevice; - } - // ERROR_UNKNOWN and ERROR_FAILED defaulted to kStatusErrorFailed - - error_callback.Run(error_status); -} - -void BluetoothLowEnergyEventRouter::OnStartNotifySession( - bool persistent, - const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback, - scoped_ptr<device::BluetoothGattNotifySession> session) { - VLOG(2) << "Value update session created for characteristic: " - << characteristic_id; - DCHECK(session.get()); - DCHECK(!FindNotifySession(extension_id, characteristic_id)); - DCHECK_EQ(characteristic_id, session->GetCharacteristicIdentifier()); - - const std::string session_id = extension_id + characteristic_id; - DCHECK_NE(0U, pending_session_calls_.count(session_id)); - - BluetoothLowEnergyNotifySession* resource = - new BluetoothLowEnergyNotifySession( - persistent, extension_id, session.Pass()); - - NotifySessionResourceManager* manager = - GetNotifySessionResourceManager(browser_context_); - manager->Add(resource); - - pending_session_calls_.erase(session_id); - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnStartNotifySessionError( - const std::string& extension_id, - const std::string& characteristic_id, - const ErrorCallback& error_callback, - device::BluetoothGattService::GattErrorCode error_code) { - VLOG(2) << "Failed to create value update session for characteristic: " - << characteristic_id; - - const std::string session_id = extension_id + characteristic_id; - DCHECK_NE(0U, pending_session_calls_.count(session_id)); - - pending_session_calls_.erase(session_id); - error_callback.Run(GattErrorToRouterError(error_code)); -} - -void BluetoothLowEnergyEventRouter::OnStopNotifySession( - const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback) { - VLOG(2) << "Value update session terminated."; - - if (!RemoveNotifySession(extension_id, characteristic_id)) { - VLOG(1) << "The value update session was removed before Stop completed, " - << "id: " << extension_id - << ", characteristic: " << characteristic_id; - } - - callback.Run(); -} - -BluetoothLowEnergyConnection* BluetoothLowEnergyEventRouter::FindConnection( - const std::string& extension_id, - const std::string& device_address) { - ConnectionResourceManager* manager = - GetConnectionResourceManager(browser_context_); - - base::hash_set<int>* connection_ids = manager->GetResourceIds(extension_id); - if (!connection_ids) - return NULL; - - for (base::hash_set<int>::const_iterator iter = connection_ids->begin(); - iter != connection_ids->end(); - ++iter) { - extensions::BluetoothLowEnergyConnection* conn = - manager->Get(extension_id, *iter); - if (!conn) - continue; - - if (conn->GetConnection()->GetDeviceAddress() == device_address) - return conn; - } - - return NULL; -} - -bool BluetoothLowEnergyEventRouter::RemoveConnection( - const std::string& extension_id, - const std::string& device_address) { - ConnectionResourceManager* manager = - GetConnectionResourceManager(browser_context_); - - base::hash_set<int>* connection_ids = manager->GetResourceIds(extension_id); - if (!connection_ids) - return false; - - for (base::hash_set<int>::const_iterator iter = connection_ids->begin(); - iter != connection_ids->end(); - ++iter) { - extensions::BluetoothLowEnergyConnection* conn = - manager->Get(extension_id, *iter); - if (!conn || conn->GetConnection()->GetDeviceAddress() != device_address) - continue; - - manager->Remove(extension_id, *iter); - return true; - } - - return false; -} - -BluetoothLowEnergyNotifySession* -BluetoothLowEnergyEventRouter::FindNotifySession( - const std::string& extension_id, - const std::string& characteristic_id) { - NotifySessionResourceManager* manager = - GetNotifySessionResourceManager(browser_context_); - - base::hash_set<int>* ids = manager->GetResourceIds(extension_id); - if (!ids) - return NULL; - - for (base::hash_set<int>::const_iterator iter = ids->begin(); - iter != ids->end(); - ++iter) { - BluetoothLowEnergyNotifySession* session = - manager->Get(extension_id, *iter); - if (!session) - continue; - - if (session->GetSession()->GetCharacteristicIdentifier() == - characteristic_id) - return session; - } - - return NULL; -} - -bool BluetoothLowEnergyEventRouter::RemoveNotifySession( - const std::string& extension_id, - const std::string& characteristic_id) { - NotifySessionResourceManager* manager = - GetNotifySessionResourceManager(browser_context_); - - base::hash_set<int>* ids = manager->GetResourceIds(extension_id); - if (!ids) - return false; - - for (base::hash_set<int>::const_iterator iter = ids->begin(); - iter != ids->end(); - ++iter) { - BluetoothLowEnergyNotifySession* session = - manager->Get(extension_id, *iter); - if (!session || - session->GetSession()->GetCharacteristicIdentifier() != - characteristic_id) - continue; - - manager->Remove(extension_id, *iter); - return true; - } - - return false; -} - -} // namespace extensions diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h deleted file mode 100644 index a420918..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright 2014 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. - -#ifndef EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_EVENT_ROUTER_H_ -#define EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_EVENT_ROUTER_H_ - -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/weak_ptr.h" -#include "content/public/browser/notification_observer.h" -#include "device/bluetooth/bluetooth_adapter.h" -#include "device/bluetooth/bluetooth_device.h" -#include "device/bluetooth/bluetooth_gatt_service.h" -#include "extensions/browser/extension_event_histogram_value.h" -#include "extensions/common/api/bluetooth_low_energy.h" - -namespace base { - -class ListValue; - -} // namespace base - -namespace content { - -class BrowserContext; - -} // namespace content - -namespace device { - -class BluetoothGattNotifySession; - -} // namespace device - -namespace extensions { - -class BluetoothLowEnergyConnection; -class BluetoothLowEnergyNotifySession; -class Extension; - -// The BluetoothLowEnergyEventRouter is used by the bluetoothLowEnergy API to -// interface with the internal Bluetooth API in device/bluetooth. -class BluetoothLowEnergyEventRouter - : public device::BluetoothAdapter::Observer { - public: - explicit BluetoothLowEnergyEventRouter(content::BrowserContext* context); - ~BluetoothLowEnergyEventRouter() override; - - // Possible ways that an API method can fail or succeed. - enum Status { - kStatusSuccess = 0, - kStatusErrorAlreadyConnected, - kStatusErrorAlreadyNotifying, - kStatusErrorAuthenticationFailed, - kStatusErrorCanceled, - kStatusErrorFailed, - kStatusErrorGattNotSupported, - kStatusErrorHigherSecurity, - kStatusErrorInProgress, - kStatusErrorInsufficientAuthorization, - kStatusErrorInvalidLength, - kStatusErrorNotConnected, - kStatusErrorNotFound, - kStatusErrorNotNotifying, - kStatusErrorPermissionDenied, - kStatusErrorTimeout, - kStatusErrorUnsupportedDevice, - kStatusErrorInvalidArguments, - }; - - // Error callback is used by asynchronous methods to report failures. - typedef base::Callback<void(Status)> ErrorCallback; - - // Returns true if Bluetooth is supported on the current platform or if the - // internal |adapter_| instance has been initialized for testing. - bool IsBluetoothSupported() const; - - // Obtains a handle on the BluetoothAdapter and invokes |callback|. Returns - // false, if Bluetooth is not supported. Otherwise, asynchronously initializes - // it and invokes |callback|. Until the first successful call to this method, - // none of the methods in this class will succeed and no device::Bluetooth* - // API events will be observed. - bool InitializeAdapterAndInvokeCallback(const base::Closure& callback); - - // Returns true, if the BluetoothAdapter was initialized. - bool HasAdapter() const; - - // Creates a GATT connection to the device with address |device_address| for - // extension |extension|. The connection is kept alive until the extension is - // unloaded, the device is removed, or is disconnect by the host subsystem. - // |error_callback| is called with an error status in case of failure. If - // |persistent| is true, then the allocated connection resource is persistent - // across unloads. - void Connect(bool persistent, - const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Disconnects the currently open GATT connection of extension |extension| to - // device with address |device_address|. |error_callback| is called with an - // error status in case of failure, e.g. if the device is not found or the - // given - // extension does not have an open connection to the device. - void Disconnect(const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Returns the list of api::bluetooth_low_energy::Service objects - // associated with the Bluetooth device with address |device_address| in - // |out_services|. - // Returns false, if no device with the given address is known. If the device - // is found but it has no GATT services, then returns true and leaves - // |out_services| empty. Returns true, on success. |out_services| must not - // be NULL. If it is non-empty, then its contents will be cleared. - typedef std::vector<linked_ptr<api::bluetooth_low_energy::Service>> - ServiceList; - bool GetServices(const std::string& device_address, - ServiceList* out_services) const; - - // Populates |out_service| based on GATT service with instance ID - // |instance_id|. |out_service| must not be NULL. - Status GetService(const std::string& instance_id, - api::bluetooth_low_energy::Service* out_service) const; - - // Populates |out_services| with the list of GATT services that are included - // by the GATT service with instance ID |instance_id|. Returns false, if not - // GATT service with the given ID is known. If the given service has no - // included services, then |out_service| will be empty. |out_service| must not - // be NULL. If it is non-empty, then its contents will be cleared. - Status GetIncludedServices(const std::string& instance_id, - ServiceList* out_services) const; - - // Returns the list of api::bluetooth_low_energy::Characteristic objects - // associated with the GATT service with instance ID |instance_id| in - // |out_characteristics|. Returns false, if no service with the given instance - // ID is known. If the service is found but it has no characteristics, then - // returns true and leaves |out_characteristics| empty. - // |out_characteristics| must not be NULL and if it is non-empty, - // then its contents will be cleared. |extension| is the extension that made - // the call. - typedef std::vector<linked_ptr<api::bluetooth_low_energy::Characteristic>> - CharacteristicList; - Status GetCharacteristics(const Extension* extension, - const std::string& instance_id, - CharacteristicList* out_characteristics) const; - - // Populates |out_characteristic| based on GATT characteristic with instance - // ID |instance_id|. |out_characteristic| must not be NULL. |extension| is the - // extension that made the call. - Status GetCharacteristic( - const Extension* extension, - const std::string& instance_id, - api::bluetooth_low_energy::Characteristic* out_characteristic) const; - - // Returns the list of api::bluetooth_low_energy::Descriptor objects - // associated with the GATT characteristic with instance ID |instance_id| in - // |out_descriptors|. If the characteristic is found but it has no - // descriptors, then returns true and leaves |out_descriptors| empty. - // |out_descriptors| must not be NULL and if it is non-empty, - // then its contents will be cleared. |extension| is the extension that made - // the call. - typedef std::vector<linked_ptr<api::bluetooth_low_energy::Descriptor>> - DescriptorList; - Status GetDescriptors(const Extension* extension, - const std::string& instance_id, - DescriptorList* out_descriptors) const; - - // Populates |out_descriptor| based on GATT characteristic descriptor with - // instance ID |instance_id|. |out_descriptor| must not be NULL. - // |extension| is the extension that made the call. - Status GetDescriptor( - const Extension* extension, - const std::string& instance_id, - api::bluetooth_low_energy::Descriptor* out_descriptor) const; - - // Sends a request to read the value of the characteristic with intance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void ReadCharacteristicValue(const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to write the value of the characteristic with instance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void WriteCharacteristicValue(const Extension* extension, - const std::string& instance_id, - const std::vector<uint8>& value, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to start characteristic notifications from characteristic - // with instance ID |instance_id|, for extension |extension|. Invokes - // |callback| on success and |error_callback| on failure. If |persistent| is - // true, then the allocated connection resource is persistent across unloads. - void StartCharacteristicNotifications(bool persistent, - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to stop characteristic notifications from characteristic - // with instance ID |instance_id|, for extension |extension|. Invokes - // |callback| on success and |error_callback| on failure. - void StopCharacteristicNotifications(const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to read the value of the descriptor with instance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void ReadDescriptorValue(const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to write the value of the descriptor with instance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void WriteDescriptorValue(const Extension* extension, - const std::string& instance_id, - const std::vector<uint8>& value, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Initializes the adapter for testing. Used by unit tests only. - void SetAdapterForTesting(device::BluetoothAdapter* adapter); - - // device::BluetoothAdapter::Observer overrides. - void GattServiceAdded(device::BluetoothAdapter* adapter, - device::BluetoothDevice* device, - device::BluetoothGattService* service) override; - void GattServiceRemoved(device::BluetoothAdapter* adapter, - device::BluetoothDevice* device, - device::BluetoothGattService* service) override; - void GattDiscoveryCompleteForService( - device::BluetoothAdapter* adapter, - device::BluetoothGattService* service) override; - void GattServiceChanged(device::BluetoothAdapter* adapter, - device::BluetoothGattService* service) override; - void GattCharacteristicAdded( - device::BluetoothAdapter* adapter, - device::BluetoothGattCharacteristic* characteristic) override; - void GattCharacteristicRemoved( - device::BluetoothAdapter* adapter, - device::BluetoothGattCharacteristic* characteristic) override; - void GattDescriptorAdded( - device::BluetoothAdapter* adapter, - device::BluetoothGattDescriptor* descriptor) override; - void GattDescriptorRemoved( - device::BluetoothAdapter* adapter, - device::BluetoothGattDescriptor* descriptor) override; - void GattCharacteristicValueChanged( - device::BluetoothAdapter* adapter, - device::BluetoothGattCharacteristic* characteristic, - const std::vector<uint8>& value) override; - void GattDescriptorValueChanged(device::BluetoothAdapter* adapter, - device::BluetoothGattDescriptor* descriptor, - const std::vector<uint8>& value) override; - - device::BluetoothAdapter* adapter() { return adapter_.get(); } - - private: - // Called by BluetoothAdapterFactory. - void OnGetAdapter(const base::Closure& callback, - scoped_refptr<device::BluetoothAdapter> adapter); - - // Initializes the identifier for all existing GATT objects and devices. - // Called by OnGetAdapter and SetAdapterForTesting. - void InitializeIdentifierMappings(); - - // Sends the event named |event_name| to all listeners of that event that - // have the Bluetooth UUID manifest permission for UUID |uuid| and the - // "low_energy" manifest permission, with |args| as the argument to that - // event. If the event involves a characteristic, then |characteristic_id| - // should be the instance ID of the involved characteristic. Otherwise, an - // empty string should be passed. - void DispatchEventToExtensionsWithPermission( - events::HistogramValue histogram_value, - const std::string& event_name, - const device::BluetoothUUID& uuid, - const std::string& characteristic_id, - scoped_ptr<base::ListValue> args); - - // Returns a BluetoothGattService by its instance ID |instance_id|. Returns - // NULL, if the service cannot be found. - device::BluetoothGattService* FindServiceById( - const std::string& instance_id) const; - - // Returns a BluetoothGattCharacteristic by its instance ID |instance_id|. - // Returns NULL, if the characteristic cannot be found. - device::BluetoothGattCharacteristic* FindCharacteristicById( - const std::string& instance_id) const; - - // Returns a BluetoothGattDescriptor by its instance ID |instance_id|. - // Returns NULL, if the descriptor cannot be found. - device::BluetoothGattDescriptor* FindDescriptorById( - const std::string& instance_id) const; - - // Called by BluetoothGattCharacteristic and BluetoothGattDescriptor in - // response to ReadRemoteCharacteristic and ReadRemoteDescriptor. - void OnValueSuccess(const base::Closure& callback, - const std::vector<uint8>& value); - - // Called by BluetoothDevice in response to a call to CreateGattConnection. - void OnCreateGattConnection( - bool persistent, - const std::string& extension_id, - const std::string& device_address, - const base::Closure& callback, - scoped_ptr<device::BluetoothGattConnection> connection); - - // Called by BluetoothGattConnection in response to a call to Disconnect. - void OnDisconnect(const std::string& extension_id, - const std::string& device_address, - const base::Closure& callback); - - // Called by BluetoothGattCharacteristic and BluetoothGattDescriptor in - // case of an error during the read/write operations. - void OnError(const ErrorCallback& error_callback, - device::BluetoothGattService::GattErrorCode error_code); - - // Called by BluetoothDevice in response to a call to CreateGattConnection. - void OnConnectError(const std::string& extension_id, - const std::string& device_address, - const ErrorCallback& error_callback, - device::BluetoothDevice::ConnectErrorCode error_code); - - // Called by BluetoothGattCharacteristic in response to a call to - // StartNotifySession. - void OnStartNotifySession( - bool persistent, - const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback, - scoped_ptr<device::BluetoothGattNotifySession> session); - - // Called by BluetoothGattCharacteristic in response to a call to - // StartNotifySession. - void OnStartNotifySessionError( - const std::string& extension_id, - const std::string& characteristic_id, - const ErrorCallback& error_callback, - device::BluetoothGattService::GattErrorCode error_code); - - // Called by BluetoothGattNotifySession in response to a call to Stop. - void OnStopNotifySession(const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback); - - // Finds and returns a BluetoothLowEnergyConnection to device with address - // |device_address| from the managed API resources for extension with ID - // |extension_id|. - BluetoothLowEnergyConnection* FindConnection( - const std::string& extension_id, - const std::string& device_address); - - // Removes the connection to device with address |device_address| from the - // managed API resources for extension with ID |extension_id|. Returns false, - // if the connection could not be found. - bool RemoveConnection(const std::string& extension_id, - const std::string& device_address); - - // Finds and returns a BluetoothLowEnergyNotifySession associated with - // characteristic with instance ID |characteristic_id| from the managed API - // API resources for extension with ID |extension_id|. - BluetoothLowEnergyNotifySession* FindNotifySession( - const std::string& extension_id, - const std::string& characteristic_id); - - // Removes the notify session associated with characteristic with - // instance ID |characteristic_id| from the managed API resources for - // extension with ID |extension_id|. Returns false, if the session could - // not be found. - bool RemoveNotifySession(const std::string& extension_id, - const std::string& characteristic_id); - - // Mapping from instance ids to identifiers of owning instances. The keys are - // used to identify individual instances of GATT objects and are used by - // bluetoothLowEnergy API functions to obtain the correct GATT object to - // operate on. Instance IDs are string identifiers that are returned by the - // device/bluetooth API, by calling GetIdentifier() on the corresponding - // device::BluetoothGatt* instance. - // - // This mapping is necessary, as GATT object instances can only be obtained - // from the object that owns it, where raw pointers should not be cached. E.g. - // to obtain a device::BluetoothGattCharacteristic, it is necessary to obtain - // a pointer to the associated device::BluetoothDevice, and then to the - // device::BluetoothGattService that owns the characteristic. - typedef std::map<std::string, std::string> InstanceIdMap; - InstanceIdMap service_id_to_device_address_; - InstanceIdMap chrc_id_to_service_id_; - InstanceIdMap desc_id_to_chrc_id_; - - // Pointer to the current BluetoothAdapter instance. This represents a local - // Bluetooth adapter of the system. - scoped_refptr<device::BluetoothAdapter> adapter_; - - // Set of extension ID + device addresses to which a connect/disconnect is - // currently pending. - std::set<std::string> connecting_devices_; - std::set<std::string> disconnecting_devices_; - - // Set of extension ID + characteristic ID to which a request to start a - // notify session is currently pending. - std::set<std::string> pending_session_calls_; - - // BrowserContext passed during initialization. - content::BrowserContext* browser_context_; - - // Note: This should remain the last member so it'll be destroyed and - // invalidate its weak pointers before any other members are destroyed. - base::WeakPtrFactory<BluetoothLowEnergyEventRouter> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyEventRouter); -}; - -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_EVENT_ROUTER_H_ diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.cc b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.cc deleted file mode 100644 index be99781..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.cc +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 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. - -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h" - -#include "base/lazy_instance.h" - -namespace extensions { - -static base::LazyInstance<BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyNotifySession> > > g_factory = - LAZY_INSTANCE_INITIALIZER; - -template <> -BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyNotifySession> >* -ApiResourceManager<BluetoothLowEnergyNotifySession>::GetFactoryInstance() { - return g_factory.Pointer(); -} - -BluetoothLowEnergyNotifySession::BluetoothLowEnergyNotifySession( - bool persistent, - const std::string& owner_extension_id, - scoped_ptr<device::BluetoothGattNotifySession> session) - : ApiResource(owner_extension_id), - persistent_(persistent), - session_(session.release()) { -} - -BluetoothLowEnergyNotifySession::~BluetoothLowEnergyNotifySession() { -} - -device::BluetoothGattNotifySession* -BluetoothLowEnergyNotifySession::GetSession() const { - return session_.get(); -} - -bool BluetoothLowEnergyNotifySession::IsPersistent() const { - return persistent_; -} - -} // namespace extensions diff --git a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h b/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h deleted file mode 100644 index 1337438..0000000 --- a/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 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. - -#ifndef EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_NOTIFY_SESSION_H_ -#define EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_NOTIFY_SESSION_H_ - -#include <string> - -#include "base/memory/scoped_ptr.h" -#include "device/bluetooth/bluetooth_gatt_notify_session.h" -#include "extensions/browser/api/api_resource.h" -#include "extensions/browser/api/api_resource_manager.h" - -namespace extensions { - -// An ApiResource wrapper for a device::BluetoothGattNotifySession -class BluetoothLowEnergyNotifySession : public ApiResource { - public: - explicit BluetoothLowEnergyNotifySession( - bool persistent, - const std::string& owner_extension_id, - scoped_ptr<device::BluetoothGattNotifySession> session); - ~BluetoothLowEnergyNotifySession() override; - - // Returns a pointer to the underlying session object. - device::BluetoothGattNotifySession* GetSession() const; - - // ApiResource override. - bool IsPersistent() const override; - - // This resource should be managed on the UI thread. - static const content::BrowserThread::ID kThreadId = - content::BrowserThread::UI; - - private: - friend class ApiResourceManager<BluetoothLowEnergyNotifySession>; - static const char* service_name() { - return "BluetoothLowEnergyNotifySessionManager"; - } - - // True, if this resource should be persistent across suspends. - bool persistent_; - - // The session is owned by this instance and will automatically stop when - // deleted. - scoped_ptr<device::BluetoothGattNotifySession> session_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyNotifySession); -}; - -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_NOTIFY_SESSION_H_ diff --git a/extensions/browser/api/bluetooth_low_energy/utils.cc b/extensions/browser/api/bluetooth_low_energy/utils.cc deleted file mode 100644 index 87c3486..0000000 --- a/extensions/browser/api/bluetooth_low_energy/utils.cc +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 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. - -#include "extensions/browser/api/bluetooth_low_energy/utils.h" - -namespace extensions { -namespace api { -namespace bluetooth_low_energy { - -namespace { - -// Converts a list of CharacteristicProperty to a base::ListValue of strings. -scoped_ptr<base::ListValue> CharacteristicPropertiesToValue( - const std::vector<CharacteristicProperty> properties) { - scoped_ptr<base::ListValue> property_list(new base::ListValue()); - for (std::vector<CharacteristicProperty>::const_iterator iter = - properties.begin(); - iter != properties.end(); - ++iter) - property_list->Append(new base::StringValue(ToString(*iter))); - return property_list.Pass(); -} - -} // namespace - -scoped_ptr<base::DictionaryValue> CharacteristicToValue(Characteristic* from) { - // Copy the properties. Use Characteristic::ToValue to generate the result - // dictionary without the properties, to prevent json_schema_compiler from - // failing. - std::vector<CharacteristicProperty> properties = from->properties; - from->properties.clear(); - scoped_ptr<base::DictionaryValue> to = from->ToValue(); - to->SetWithoutPathExpansion( - "properties", CharacteristicPropertiesToValue(properties).release()); - return to.Pass(); -} - -scoped_ptr<base::DictionaryValue> DescriptorToValue(Descriptor* from) { - // Copy the characteristic properties and set them later manually. - std::vector<CharacteristicProperty> properties = - from->characteristic.properties; - from->characteristic.properties.clear(); - scoped_ptr<base::DictionaryValue> to = from->ToValue(); - - base::DictionaryValue* chrc_value = NULL; - to->GetDictionaryWithoutPathExpansion("characteristic", &chrc_value); - DCHECK(chrc_value); - chrc_value->SetWithoutPathExpansion( - "properties", CharacteristicPropertiesToValue(properties).release()); - return to.Pass(); -} - -} // namespace bluetooth_low_energy -} // namespace api -} // namespace extensions diff --git a/extensions/browser/api/bluetooth_low_energy/utils.h b/extensions/browser/api/bluetooth_low_energy/utils.h deleted file mode 100644 index 1fae831..0000000 --- a/extensions/browser/api/bluetooth_low_energy/utils.h +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2014 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. - -#ifndef EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_UTILS_H_ -#define EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_UTILS_H_ - -#include "base/memory/scoped_ptr.h" -#include "base/values.h" -#include "extensions/common/api/bluetooth_low_energy.h" - -namespace extensions { -namespace api { -namespace bluetooth_low_energy { - -// TODO(armansito): Remove these functions once the described bug is fixed. -// (See crbug.com/368368) - -// Converts a Characteristic to a base::Value. This function is necessary as -// json_schema_compiler::util::AddItemToList has no template specialization for -// user defined enums, which get treated as integers. This is because -// Characteristic contains a list of enum CharacteristicProperty. -scoped_ptr<base::DictionaryValue> CharacteristicToValue(Characteristic* from); - -// Converts a Descriptor to a base::Value. This function is necessary as a -// Descriptor embeds a Characteristic and that needs special handling as -// described above. -scoped_ptr<base::DictionaryValue> DescriptorToValue(Descriptor* from); - -} // namespace bluetooth_low_energy -} // namespace api -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_API_BLUETOOTH_LOW_ENERGY_UTILS_H_ diff --git a/extensions/browser/browser_context_keyed_service_factories.cc b/extensions/browser/browser_context_keyed_service_factories.cc index 215cf4e..8d1061f 100644 --- a/extensions/browser/browser_context_keyed_service_factories.cc +++ b/extensions/browser/browser_context_keyed_service_factories.cc @@ -9,7 +9,6 @@ #include "extensions/browser/api/audio/audio_api.h" #include "extensions/browser/api/bluetooth/bluetooth_api.h" #include "extensions/browser/api/bluetooth/bluetooth_private_api.h" -#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h" #include "extensions/browser/api/bluetooth_socket/bluetooth_socket_event_dispatcher.h" #include "extensions/browser/api/hid/hid_device_manager.h" #include "extensions/browser/api/idle/idle_manager_factory.h" @@ -53,7 +52,6 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { ApiResourceManager<UsbDeviceResource>::GetFactoryInstance(); AudioAPI::GetFactoryInstance(); BluetoothAPI::GetFactoryInstance(); - BluetoothLowEnergyAPI::GetFactoryInstance(); BluetoothPrivateAPI::GetFactoryInstance(); #if defined(OS_CHROMEOS) chromeos::VpnServiceFactory::GetInstance(); diff --git a/extensions/common/api/bluetooth_low_energy.idl b/extensions/common/api/bluetooth_low_energy.idl deleted file mode 100644 index 63c45ed..0000000 --- a/extensions/common/api/bluetooth_low_energy.idl +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2014 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. - -// The <code>chrome.bluetoothLowEnergy</code> API is used to communicate with -// Bluetooth Smart (Low Energy) devices using the -// <a href="https://developer.bluetooth.org/TechnologyOverview/Pages/GATT.aspx"> -// Generic Attribute Profile (GATT)</a>. -namespace bluetoothLowEnergy { - // Values representing the possible properties of a characteristic. - enum CharacteristicProperty {broadcast, read, writeWithoutResponse, write, - notify, indicate, authenticatedSignedWrites, - extendedProperties, reliableWrite, - writableAuxiliaries}; - - // Type of advertisement. If 'broadcast' is chosen, the sent advertisement - // type will be ADV_NONCONN_IND. If set to 'peripheral', the advertisement - // type will be ADV_IND or ADV_SCAN_IND. - [nodoc] enum AdvertisementType {broadcast, peripheral}; - - // Represents a peripheral's Bluetooth GATT Service, a collection of - // characteristics and relationships to other services that encapsulate - // the behavior of part of a device. - dictionary Service { - // The UUID of the service, e.g. 0000180d-0000-1000-8000-00805f9b34fb. - DOMString uuid; - - // Indicates whether the type of this service is primary or secondary. - boolean isPrimary; - - // Indicates whether this service represents a local service hosted by the - // application and available to other peripherals, or a remote service - // hosted and received from a remote peripheral. - [nodoc] boolean isLocal; - - // Returns the identifier assigned to this service. Use the instance ID to - // distinguish between services from a peripheral with the same UUID and - // to make function calls that take in a service identifier. Present, if - // this instance represents a remote service. - DOMString? instanceId; - - // The device address of the remote peripheral that the GATT service belongs - // to. Present, if this instance represents a remote service. - DOMString? deviceAddress; - }; - - // Represents a GATT characteristic, which is a basic data element that - // provides further information about a peripheral's service. - dictionary Characteristic { - // The UUID of the characteristic, e.g. - // 00002a37-0000-1000-8000-00805f9b34fb. - DOMString uuid; - - // Indicates whether this characteristic represents a local characteristic - // hosted by the application and available to other peripherals, or a remote - // characteristic hosted and received from a remote peripheral. - [nodoc] boolean isLocal; - - // The GATT service this characteristic belongs to. - Service service; - - // The properties of this characteristic. - CharacteristicProperty[] properties; - - // Returns the identifier assigned to this characteristic. Use the instance - // ID to distinguish between characteristics from a peripheral with the same - // UUID and to make function calls that take in a characteristic identifier. - // Present, if this instance represents a remote characteristic. - DOMString? instanceId; - - // The currently cached characteristic value. This value gets updated when - // the value of the characteristic is read or updated via a notification - // or indication. - ArrayBuffer? value; - }; - - // Represents a GATT characteristic descriptor, which provides further - // information about a characteristic's value. - dictionary Descriptor { - // The UUID of the characteristic descriptor, e.g. - // 00002902-0000-1000-8000-00805f9b34fb. - DOMString uuid; - - // Indicates whether this descriptor represents a local descriptor - // hosted by the application and available to other peripherals, or a remote - // descriptor hosted and received from a remote peripheral. - [nodoc] boolean isLocal; - - // The GATT characteristic this descriptor belongs to. - Characteristic characteristic; - - // Returns the identifier assigned to this descriptor. Use the instance ID - // to distinguish between descriptors from a peripheral with the same UUID - // and to make function calls that take in a descriptor identifier. Present, - // if this instance represents a remote characteristic. - DOMString? instanceId; - - // The currently cached descriptor value. This value gets updated when - // the value of the descriptor is read. - ArrayBuffer? value; - }; - - // The connection properties specified during a call to $(ref:connect). - dictionary ConnectProperties { - // Flag indicating whether a connection to the device is left open when the - // event page of the application is unloaded (see <a - // href="http://developer.chrome.com/apps/app_lifecycle.html">Manage App - // Lifecycle</a>). The default value is <code>false.</code> - boolean persistent; - }; - - // Optional characteristic notification session properties specified during a - // call to $(ref:startCharacteristicNotifications). - dictionary NotificationProperties { - // Flag indicating whether the app should receive notifications when the - // event page of the application is unloaded (see <a - // href="http://developer.chrome.com/apps/app_lifecycle.html">Manage App - // Lifecycle</a>). The default value is <code>false</code>. - boolean persistent; - }; - - // Represents an entry of the "Manufacturer Specific Data" field of Bluetooth - // LE advertisement data. - [nodoc] dictionary ManufacturerData { - long id; - long[] data; - }; - - // Represents an entry of the "Service Data" field of Bluetooth LE advertisement - // data. - [nodoc] dictionary ServiceData { - DOMString uuid; - long[] data; - }; - - // Represents a Bluetooth LE advertisement instance. - [nodoc] dictionary Advertisement { - // Type of advertisement. - AdvertisementType type; - - // List of UUIDs to include in the "Service UUIDs" field of the Advertising - // Data. These UUIDs can be of the 16bit, 32bit or 128 formats. - DOMString[]? serviceUuids; - - // List of manufacturer specific data to be included in "Manufacturer Specific - // Data" fields of the advertising data. - ManufacturerData[]? manufacturerData; - - // List of UUIDs to include in the "Solicit UUIDs" field of the Advertising - // Data. These UUIDs can be of the 16bit, 32bit or 128 formats. - DOMString[]? solicitUuids; - - // List of service data to be included in "Service Data" fields of the advertising - // data. - ServiceData[]? serviceData; - }; - - callback CharacteristicCallback = void(Characteristic result); - callback CharacteristicsCallback = void(Characteristic[] result); - callback DescriptorCallback = void(Descriptor result); - callback DescriptorsCallback = void(Descriptor[] result); - callback ResultCallback = void(); - callback ServiceCallback = void(Service result); - callback ServicesCallback = void(Service[] result); - callback RegisterAdvertisementCallback = void (long advertisementId); - - // These functions all report failures via chrome.runtime.lastError. - interface Functions { - // Establishes a connection between the application and the device with the - // given address. A device may be already connected and its GATT services - // available without calling <code>connect</code>, however, an app that - // wants to access GATT services of a device should call this function to - // make sure that a connection to the device is maintained. If the device - // is not connected, all GATT services of the device will be discovered - // after a successful call to <code>connect</code>. - // |deviceAddress| : The Bluetooth address of the remote device to which a - // GATT connection should be opened. - // |properties| : Connection properties (optional). - // |callback| : Called when the connect request has completed. - static void connect(DOMString deviceAddress, - optional ConnectProperties properties, - ResultCallback callback); - - // Closes the app's connection to the device with the given address. Note - // that this will not always destroy the physical link itself, since there - // may be other apps with open connections. - // |deviceAddress| : The Bluetooth address of the remote device. - // |callback| : Called when the disconnect request has completed. - static void disconnect(DOMString deviceAddress, - optional ResultCallback callback); - - // Get the GATT service with the given instance ID. - // |serviceId| : The instance ID of the requested GATT service. - // |callback| : Called with the requested Service object. - static void getService(DOMString serviceId, ServiceCallback callback); - - // Get all the GATT services that were discovered on the remote device with - // the given device address. - // |deviceAddress| : The Bluetooth address of the remote device whose GATT - // services should be returned. - // |callback| : Called with the list of requested Service objects. - static void getServices(DOMString deviceAddress, ServicesCallback callback); - - // Get the GATT characteristic with the given instance ID that belongs to - // the given GATT service, if the characteristic exists. - // |characteristicId| : The instance ID of the requested GATT - // characteristic. - // |callback| : Called with the requested Characteristic object. - static void getCharacteristic(DOMString characteristicId, - CharacteristicCallback callback); - - // Get a list of all discovered GATT characteristics that belong to the - // given service. - // |serviceId| : The instance ID of the GATT service whose characteristics - // should be returned. - // |callback| : Called with the list of characteristics that belong to the - // given service. - static void getCharacteristics(DOMString serviceId, - CharacteristicsCallback callback); - - // Get a list of GATT services that are included by the given service. - // |serviceId| : The instance ID of the GATT service whose included - // services should be returned. - // |callback| : Called with the list of GATT services included from the - // given service. - static void getIncludedServices(DOMString serviceId, - ServicesCallback callback); - - // Get the GATT characteristic descriptor with the given instance ID. - // |descriptorId| : The instance ID of the requested GATT characteristic - // descriptor. - // |callback| : Called with the requested Descriptor object. - static void getDescriptor(DOMString descriptorId, - DescriptorCallback callback); - - // Get a list of GATT characteristic descriptors that belong to the given - // characteristic. - // |characteristicId| : The instance ID of the GATT characteristic whose - // descriptors should be returned. - // |callback| : Called with the list of descriptors that belong to the given - // characteristic. - static void getDescriptors(DOMString characteristicId, - DescriptorsCallback callback); - - // Retrieve the value of a specified characteristic from a remote - // peripheral. - // |characteristicId| : The instance ID of the GATT characteristic whose - // value should be read from the remote device. - // |callback| : Called with the Characteristic object whose value was - // requested. The <code>value</code> field of the returned Characteristic - // object contains the result of the read request. - static void readCharacteristicValue(DOMString characteristicId, - CharacteristicCallback callback); - - // Write the value of a specified characteristic from a remote peripheral. - // |characteristicId| : The instance ID of the GATT characteristic whose - // value should be written to. - // |value| : The value that should be sent to the remote characteristic as - // part of the write request. - // |callback| : Called when the write request has completed. - static void writeCharacteristicValue(DOMString characteristicId, - ArrayBuffer value, - ResultCallback callback); - - // Enable value notifications/indications from the specified characteristic. - // Once enabled, an application can listen to notifications using the - // $(ref:onCharacteristicValueChanged) event. - // |characteristicId| : The instance ID of the GATT characteristic that - // notifications should be enabled on. - // |properties| : Notification session properties (optional). - // |callback| : Called when the request has completed. - static void startCharacteristicNotifications( - DOMString characteristicId, - optional NotificationProperties properties, - ResultCallback callback); - - // Disable value notifications/indications from the specified - // characteristic. After a successful call, the application will stop - // receiving notifications/indications from this characteristic. - // |characteristicId| : The instance ID of the GATT characteristic on which - // this app's notification session should be stopped. - // |callback| : Called when the request has completed (optional). - static void stopCharacteristicNotifications( - DOMString characteristicId, - optional ResultCallback callback); - - // Retrieve the value of a specified characteristic descriptor from a remote - // peripheral. - // |descriptorId| : The instance ID of the GATT characteristic descriptor - // whose value should be read from the remote device. - // |callback| : Called with the Descriptor object whose value was requested. - // The <code>value</code> field of the returned Descriptor object contains - // the result of the read request. - static void readDescriptorValue(DOMString descriptorId, - DescriptorCallback callback); - - // Write the value of a specified characteristic descriptor from a remote - // peripheral. - // |descriptorId| : The instance ID of the GATT characteristic descriptor - // whose value should be written to. - // |value| : The value that should be sent to the remote descriptor as part - // of the write request. - // |callback| : Called when the write request has completed. - static void writeDescriptorValue(DOMString descriptorId, - ArrayBuffer value, - ResultCallback callback); - - // Create an advertisement and register it for advertising. To call this - // function, the app must have the bluetooth:low_energy and - // bluetooth:peripheral permissions set to true. - // See https://developer.chrome.com/apps/manifest/bluetooth - // Note: On some hardware central and peripheral modes at the same time is - // supported but on hardware that doesn't support this, making this call - // will switch the device to peripheral mode. In the case of hardware which - // does not support both central and peripheral mode, attempting to use the - // device in both modes will lead to undefined behavior or prevent other - // central-role applications from behaving correctly (including the - // discovery of Bluetooth Low Energy devices). - // |advertisement| : The advertisement to advertise. - // |callback| : Called once the registeration is done and we've started - // advertising. Returns the id of the created advertisement. - [nodoc] static void registerAdvertisement( - Advertisement advertisement, RegisterAdvertisementCallback callback); - - // Unregisters an advertisement and stops its advertising. - // |advertisementId| : Id of the advertisement to unregister. - // |callback| : Called once the advertisement is unregistered and is no - // longer being advertised. - [nodoc] static void unregisterAdvertisement(long advertisementId, - ResultCallback callback); - }; - - interface Events { - // Fired whan a new GATT service has been discovered on a remote device. - // |service| : The GATT service that was added. - static void onServiceAdded(Service service); - - // Fired when the state of a remote GATT service changes. This involves any - // characteristics and/or descriptors that get added or removed from the - // service, as well as "ServiceChanged" notifications from the remote - // device. - // |service| : The GATT service whose state has changed. - static void onServiceChanged(Service service); - - // Fired when a GATT service that was previously discovered on a remote - // device has been removed. - // |service| : The GATT service that was removed. - static void onServiceRemoved(Service service); - - // Fired when the value of a remote GATT characteristic changes, either as - // a result of a read request, or a value change notification/indication - // This event will only be sent if the app has enabled notifications by - // calling $(ref:startCharacteristicNotifications). - // |characteristic| : The GATT characteristic whose value has changed. - static void onCharacteristicValueChanged(Characteristic characteristic); - - // Fired when the value of a remote GATT characteristic descriptor changes, - // usually as a result of a read request. This event exists - // mostly for convenience and will always be sent after a successful - // call to $(ref:readDescriptorValue). - // |descriptor| : The GATT characteristic descriptor whose value has - // changed. - static void onDescriptorValueChanged(Descriptor descriptor); - }; -}; diff --git a/extensions/common/api/schemas.gypi b/extensions/common/api/schemas.gypi index 3b23b2f..0361233 100644 --- a/extensions/common/api/schemas.gypi +++ b/extensions/common/api/schemas.gypi @@ -16,7 +16,6 @@ 'app_window.idl', 'audio.idl', 'bluetooth.idl', - 'bluetooth_low_energy.idl', 'bluetooth_private.json', 'bluetooth_socket.idl', 'cast_channel.idl', diff --git a/extensions/extensions.gypi b/extensions/extensions.gypi index e1d14f3d..ed1a722 100644 --- a/extensions/extensions.gypi +++ b/extensions/extensions.gypi @@ -269,18 +269,6 @@ 'browser/api/bluetooth/bluetooth_extension_function.h', 'browser/api/bluetooth/bluetooth_private_api.cc', 'browser/api/bluetooth/bluetooth_private_api.h', - 'browser/api/bluetooth_low_energy/bluetooth_api_advertisement.cc', - 'browser/api/bluetooth_low_energy/bluetooth_api_advertisement.h', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_api.cc', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.cc', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.h', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.cc', - 'browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h', - 'browser/api/bluetooth_low_energy/utils.cc', - 'browser/api/bluetooth_low_energy/utils.h', 'browser/api/bluetooth_socket/bluetooth_api_socket.cc', 'browser/api/bluetooth_socket/bluetooth_api_socket.h', 'browser/api/bluetooth_socket/bluetooth_socket_api.cc', |