2 // Copyright (C) 2015 Google, Inc.
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at:
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
17 #include "service/gatt_client.h"
19 #include <base/logging.h>
21 using std::lock_guard;
26 // GattClient implementation
27 // ========================================================
29 GattClient::GattClient(const UUID& uuid, int client_id)
30 : app_identifier_(uuid),
31 client_id_(client_id) {
34 GattClient::~GattClient() {
35 // Automatically unregister the client.
36 VLOG(1) << "GattClient unregistering client: " << client_id_;
38 hal::BluetoothGattInterface::Get()->GetClientHALInterface()->
39 unregister_client(client_id_);
42 const UUID& GattClient::GetAppIdentifier() const {
43 return app_identifier_;
46 int GattClient::GetInstanceId() const {
50 // GattClientFactory implementation
51 // ========================================================
53 GattClientFactory::GattClientFactory() {
54 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
57 GattClientFactory::~GattClientFactory() {
58 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
61 bool GattClientFactory::RegisterInstance(
63 const RegisterCallback& callback) {
64 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
65 lock_guard<mutex> lock(pending_calls_lock_);
67 if (pending_calls_.find(uuid) != pending_calls_.end()) {
68 LOG(ERROR) << "GATT client with given UUID already registered - "
69 << "UUID: " << uuid.ToString();
73 const btgatt_client_interface_t* hal_iface =
74 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
75 bt_uuid_t app_uuid = uuid.GetBlueDroid();
77 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
80 pending_calls_[uuid] = callback;
85 void GattClientFactory::RegisterClientCallback(
86 hal::BluetoothGattInterface* /* gatt_iface */,
87 int status, int client_id,
88 const bt_uuid_t& app_uuid) {
91 auto iter = pending_calls_.find(uuid);
92 if (iter == pending_calls_.end()) {
93 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
97 bool success = (status == BT_STATUS_SUCCESS);
98 BLEStatus result = success ? BLE_STATUS_SUCCESS : BLE_STATUS_FAILURE;
100 // No need to construct a client if the call wasn't successful.
101 std::unique_ptr<GattClient> client;
103 client.reset(new GattClient(uuid, client_id));
105 // Notify the result via the result callback.
106 iter->second(result, uuid, std::move(client));
108 pending_calls_.erase(iter);
111 } // namespace bluetooth