OSDN Git Service

Merge "Additional headsets blacklisted for absolute volume" into mnc-dr1.5-dev
[android-x86/system-bt.git] / service / gatt_server_old.cpp
1 //
2 //  Copyright (C) 2015 Google, Inc.
3 //
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:
7 //
8 //  http://www.apache.org/licenses/LICENSE-2.0
9 //
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.
15 //
16
17 #define LOG_TAG "bt_gatts"
18
19 #include "gatt_server_old.h"
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24
25 #include <algorithm>
26 #include <array>
27 #include <condition_variable>
28 #include <map>
29 #include <memory>
30 #include <mutex>
31 #include <set>
32 #include <string>
33 #include <unordered_map>
34 #include <vector>
35
36 #include <hardware/bluetooth.h>
37 #include <hardware/bt_gatt.h>
38
39 #include "service/hal/bluetooth_interface.h"
40 #include "service/logging_helpers.h"
41
42 extern "C" {
43 #include "osi/include/log.h"
44 #include "osi/include/osi.h"
45 }  // extern "C"
46
47 namespace {
48
49 const size_t kMaxGattAttributeSize = 512;
50 // TODO(icoolidge): Difficult to generalize without knowing how many attributes.
51 const int kNumBlueDroidHandles = 60;
52
53 // TODO(icoolidge): Support multiple instances
54 // TODO(armansito): Remove this variable. No point of having this if
55 // each bluetooth::gatt::Server instance already keeps a pointer to the
56 // ServerInternals that is associated with it (which is much cleaner). It looks
57 // like this variable exists because the btif callbacks don't allow the
58 // upper-layer to pass user data to them. We could:
59 //
60 //    1. Fix the btif callbacks so that some sort of continuation can be
61 //    attached to a callback. This might be a long shot since the callback
62 //    interface doesn't allow more than one caller to register its own callbacks
63 //    (which might be what we want though, since this would make the API more
64 //    flexible).
65 //
66 //    2. Allow creation of Server objects using a factory method that returns
67 //    the result asynchronously in a base::Callback. The RegisterServerCallback
68 //    provides an |app_uuid|, which can be used to store callback structures in
69 //    a map and lazily instantiate the Server and invoke the correct callback.
70 //    This is a general pattern that we should use throughout the daemon, since
71 //    all operations can timeout or fail and this is best reported in an
72 //    asynchronous base::Callback.
73 //
74 static bluetooth::gatt::ServerInternals *g_internal = nullptr;
75
76 enum { kPipeReadEnd = 0, kPipeWriteEnd = 1, kPipeNumEnds = 2 };
77
78 }  // namespace
79
80 namespace bluetooth {
81 namespace gatt {
82
83 struct Characteristic {
84   UUID uuid;
85   int blob_section;
86   std::vector<uint8_t> blob;
87
88   // Support synchronized blob updates by latching under mutex.
89   std::vector<uint8_t> next_blob;
90   bool next_blob_pending;
91   bool notify;
92 };
93
94 struct ServerInternals {
95   ServerInternals();
96   ~ServerInternals();
97   int Initialize();
98   bt_status_t AddCharacteristic(
99       const UUID& uuid,
100       int properties,
101       int permissions);
102
103   // This maps API attribute UUIDs to BlueDroid handles.
104   std::map<UUID, int> uuid_to_attribute;
105
106   // The attribute cache, indexed by BlueDroid handles.
107   std::unordered_map<int, Characteristic> characteristics;
108
109   // Associate a control attribute with its value attribute.
110   std::unordered_map<int, int> controlled_blobs;
111
112   ScanResults scan_results;
113
114   UUID last_write;
115   const btgatt_interface_t *gatt;
116   int server_if;
117   int client_if;
118   int service_handle;
119   btgatt_srvc_id_t service_id;
120   std::set<int> connections;
121
122   std::mutex lock;
123   std::condition_variable api_synchronize;
124   int pipefd[kPipeNumEnds];
125 };
126
127 }  // namespace gatt
128 }  // namespace bluetooth
129
130 namespace {
131
132 /** Callback invoked in response to register_server */
133 void RegisterServerCallback(int status, int server_if, bt_uuid_t *app_uuid) {
134   LOG_INFO(LOG_TAG, "%s: status:%d server_if:%d app_uuid:%p", __func__, status,
135            server_if, app_uuid);
136
137   g_internal->server_if = server_if;
138
139   btgatt_srvc_id_t service_id;
140   service_id.id.uuid = *app_uuid;
141   service_id.id.inst_id = 0;
142   service_id.is_primary = true;
143
144   g_internal->gatt->server->add_service(
145       server_if, &service_id, kNumBlueDroidHandles);
146 }
147
148 void ServiceAddedCallback(int status, int server_if, btgatt_srvc_id_t *srvc_id,
149                           int srvc_handle) {
150   LOG_INFO(LOG_TAG, "%s: status:%d server_if:%d gatt_srvc_id:%u srvc_handle:%d",
151            __func__, status, server_if, srvc_id->id.inst_id, srvc_handle);
152
153   std::lock_guard<std::mutex> lock(g_internal->lock);
154   g_internal->server_if = server_if;
155   g_internal->service_handle = srvc_handle;
156   g_internal->service_id = *srvc_id;
157   // This finishes the Initialize call.
158   g_internal->api_synchronize.notify_one();
159 }
160
161 void RequestReadCallback(int conn_id, int trans_id, bt_bdaddr_t *bda,
162                          int attr_handle, int attribute_offset_octets,
163                          bool is_long) {
164   std::lock_guard<std::mutex> lock(g_internal->lock);
165
166   bluetooth::gatt::Characteristic &ch = g_internal->characteristics[attr_handle];
167
168   // Latch next_blob to blob on a 'fresh' read.
169   if (ch.next_blob_pending && attribute_offset_octets == 0 &&
170       ch.blob_section == 0) {
171     std::swap(ch.blob, ch.next_blob);
172     ch.next_blob_pending = false;
173   }
174
175   const size_t blob_offset_octets =
176       std::min(ch.blob.size(), ch.blob_section * kMaxGattAttributeSize);
177   const size_t blob_remaining = ch.blob.size() - blob_offset_octets;
178   const size_t attribute_size = std::min(kMaxGattAttributeSize, blob_remaining);
179
180   std::string addr(BtAddrString(bda));
181   LOG_INFO(LOG_TAG,
182       "%s: connection:%d (%s) reading attr:%d attribute_offset_octets:%d "
183       "blob_section:%u (is_long:%u)",
184       __func__, conn_id, addr.c_str(), attr_handle, attribute_offset_octets,
185       ch.blob_section, is_long);
186
187   btgatt_response_t response;
188   response.attr_value.len = 0;
189
190   if (attribute_offset_octets < static_cast<int>(attribute_size)) {
191     std::copy(ch.blob.begin() + blob_offset_octets + attribute_offset_octets,
192               ch.blob.begin() + blob_offset_octets + attribute_size,
193               response.attr_value.value);
194     response.attr_value.len = attribute_size - attribute_offset_octets;
195   }
196
197   response.attr_value.handle = attr_handle;
198   response.attr_value.offset = attribute_offset_octets;
199   response.attr_value.auth_req = 0;
200   g_internal->gatt->server->send_response(conn_id, trans_id, 0, &response);
201 }
202
203 void RequestWriteCallback(int conn_id, int trans_id, bt_bdaddr_t *bda,
204                           int attr_handle, int attribute_offset, int length,
205                           bool need_rsp, bool is_prep, uint8_t *value) {
206   std::string addr(BtAddrString(bda));
207   LOG_INFO(LOG_TAG,
208       "%s: connection:%d (%s:trans:%d) write attr:%d attribute_offset:%d "
209       "length:%d "
210       "need_resp:%u is_prep:%u",
211       __func__, conn_id, addr.c_str(), trans_id, attr_handle, attribute_offset,
212       length, need_rsp, is_prep);
213
214   std::lock_guard<std::mutex> lock(g_internal->lock);
215
216   bluetooth::gatt::Characteristic &ch =
217       g_internal->characteristics[attr_handle];
218
219   ch.blob.resize(attribute_offset + length);
220
221   std::copy(value, value + length, ch.blob.begin() + attribute_offset);
222
223   auto target_blob = g_internal->controlled_blobs.find(attr_handle);
224   // If this is a control attribute, adjust offset of the target blob.
225   if (target_blob != g_internal->controlled_blobs.end() &&
226       ch.blob.size() == 1u) {
227     g_internal->characteristics[target_blob->second].blob_section = ch.blob[0];
228     LOG_INFO(LOG_TAG, "%s: updating attribute %d blob_section to %u", __func__,
229         target_blob->second, ch.blob[0]);
230   } else if (!is_prep) {
231     // This is a single frame characteristic write.
232     // Notify upwards because we're done now.
233     const bluetooth::UUID::UUID128Bit &attr_uuid = ch.uuid.GetFullBigEndian();
234     int status = write(g_internal->pipefd[kPipeWriteEnd], attr_uuid.data(),
235                        attr_uuid.size());
236     if (-1 == status)
237       LOG_ERROR(LOG_TAG, "%s: write failed: %s", __func__, strerror(errno));
238   } else {
239     // This is a multi-frame characteristic write.
240     // Wait for an 'RequestExecWriteCallback' to notify completion.
241     g_internal->last_write = ch.uuid;
242   }
243
244   // Respond only if needed.
245   if (!need_rsp) return;
246
247   btgatt_response_t response;
248   response.attr_value.handle = attr_handle;
249   response.attr_value.offset = attribute_offset;
250   response.attr_value.len = length;
251   response.attr_value.auth_req = 0;
252   // Provide written data back to sender for the response.
253   // Remote stacks use this to validate the success of the write.
254   std::copy(value, value + length, response.attr_value.value);
255   g_internal->gatt->server->send_response(conn_id, trans_id, 0, &response);
256 }
257
258 void RequestExecWriteCallback(int conn_id, int trans_id, bt_bdaddr_t *bda,
259                               int exec_write) {
260   std::string addr(BtAddrString(bda));
261   LOG_INFO(LOG_TAG, "%s: connection:%d (%s:trans:%d) exec_write:%d", __func__,
262       conn_id, addr.c_str(), trans_id, exec_write);
263
264   // This 'response' data is unused for ExecWriteResponses.
265   // It is only used to pass BlueDroid argument validation.
266   btgatt_response_t response = {};
267   g_internal->gatt->server->send_response(conn_id, trans_id, 0, &response);
268
269   if (!exec_write)
270     return;
271
272   std::lock_guard<std::mutex> lock(g_internal->lock);
273   // Communicate the attribute UUID as notification of a write update.
274   const bluetooth::UUID::UUID128Bit uuid =
275       g_internal->last_write.GetFullBigEndian();
276   int status = write(g_internal->pipefd[kPipeWriteEnd],
277                      uuid.data(), uuid.size());
278   if (-1 == status)
279     LOG_ERROR(LOG_TAG, "%s: write failed: %s", __func__, strerror(errno));
280 }
281
282 void ConnectionCallback(int conn_id, int server_if, int connected,
283                         bt_bdaddr_t *bda) {
284   std::string addr(BtAddrString(bda));
285   LOG_INFO(LOG_TAG, "%s: connection:%d server_if:%d connected:%d addr:%s",
286       __func__, conn_id, server_if, connected, addr.c_str());
287   if (connected == 1) {
288     g_internal->connections.insert(conn_id);
289   } else if (connected == 0) {
290     g_internal->connections.erase(conn_id);
291   }
292 }
293
294 void CharacteristicAddedCallback(int status, int server_if, bt_uuid_t *uuid,
295                                  int srvc_handle, int char_handle) {
296   LOG_INFO(LOG_TAG,
297       "%s: status:%d server_if:%d service_handle:%d char_handle:%d", __func__,
298       status, server_if, srvc_handle, char_handle);
299
300   bluetooth::UUID id(*uuid);
301
302   std::lock_guard<std::mutex> lock(g_internal->lock);
303
304   g_internal->uuid_to_attribute[id] = char_handle;
305   g_internal->characteristics[char_handle].uuid = id;
306   g_internal->characteristics[char_handle].blob_section = 0;
307
308   // This terminates an AddCharacteristic.
309   g_internal->api_synchronize.notify_one();
310 }
311
312 void DescriptorAddedCallback(int status, int server_if, bt_uuid_t *uuid,
313                              int srvc_handle, int descr_handle) {
314   LOG_INFO(LOG_TAG,
315       "%s: status:%d server_if:%d service_handle:%d uuid[0]:%u "
316       "descr_handle:%d",
317       __func__, status, server_if, srvc_handle, uuid->uu[0], descr_handle);
318 }
319
320 void ServiceStartedCallback(int status, int server_if, int srvc_handle) {
321   LOG_INFO(LOG_TAG, "%s: status:%d server_if:%d srvc_handle:%d", __func__,
322       status, server_if, srvc_handle);
323
324   // The UUID provided here is unimportant, and is only used to satisfy
325   // BlueDroid.
326   // It must be different than any other registered UUID.
327   bt_uuid_t client_id = g_internal->service_id.id.uuid;
328   ++client_id.uu[15];
329
330   bt_status_t btstat = g_internal->gatt->client->register_client(&client_id);
331   if (btstat != BT_STATUS_SUCCESS) {
332     LOG_ERROR(LOG_TAG, "%s: Failed to register client", __func__);
333   }
334 }
335
336 void RegisterClientCallback(int status, int client_if, bt_uuid_t *app_uuid) {
337   LOG_INFO(LOG_TAG, "%s: status:%d client_if:%d uuid[0]:%u", __func__, status,
338       client_if, app_uuid->uu[0]);
339   g_internal->client_if = client_if;
340
341   // Setup our advertisement. This has no callback.
342   bt_status_t btstat = g_internal->gatt->client->set_adv_data(
343       client_if, false, /* beacon, not scan response */
344       false,            /* name */
345       false,            /* no txpower */
346       2, 2,             /* interval */
347       0,                /* appearance */
348       0, nullptr,       /* no mfg data */
349       0, nullptr,       /* no service data */
350       0, nullptr /* no service id yet */);
351   if (btstat != BT_STATUS_SUCCESS) {
352     LOG_ERROR(LOG_TAG, "Failed to set advertising data");
353     return;
354   }
355
356   // TODO(icoolidge): Deprecated, use multi-adv interface.
357   // This calls back to ListenCallback.
358   btstat = g_internal->gatt->client->listen(client_if, true);
359   if (btstat != BT_STATUS_SUCCESS) {
360     LOG_ERROR(LOG_TAG, "Failed to start listening");
361   }
362 }
363
364 void ListenCallback(int status, int client_if) {
365   LOG_INFO(LOG_TAG, "%s: status:%d client_if:%d", __func__, status, client_if);
366   // This terminates a Start call.
367   std::lock_guard<std::mutex> lock(g_internal->lock);
368   g_internal->api_synchronize.notify_one();
369 }
370
371 void ServiceStoppedCallback(int status, int server_if, int srvc_handle) {
372   LOG_INFO(LOG_TAG, "%s: status:%d server_if:%d srvc_handle:%d", __func__,
373       status, server_if, srvc_handle);
374   // This terminates a Stop call.
375   // TODO(icoolidge): make this symmetric with start
376   std::lock_guard<std::mutex> lock(g_internal->lock);
377   g_internal->api_synchronize.notify_one();
378 }
379
380 void ScanResultCallback(bt_bdaddr_t *bda, int rssi, uint8_t *adv_data) {
381   std::string addr(BtAddrString(bda));
382   (void)adv_data;
383   std::lock_guard<std::mutex> lock(g_internal->lock);
384   g_internal->scan_results[addr] = rssi;
385 }
386
387 void ClientConnectCallback(int conn_id, int status, int client_if,
388                            bt_bdaddr_t *bda) {
389   std::string addr(BtAddrString(bda));
390   LOG_INFO(LOG_TAG, "%s: conn_id:%d status:%d client_if:%d %s", __func__,
391       conn_id, status, client_if, addr.c_str());
392 }
393
394 void ClientDisconnectCallback(int conn_id, int status, int client_if,
395                               bt_bdaddr_t *bda) {
396   std::string addr(BtAddrString(bda));
397   LOG_INFO(LOG_TAG, "%s: conn_id:%d status:%d client_if:%d %s", __func__,
398       conn_id, status, client_if, addr.c_str());
399 }
400
401 void IndicationSentCallback(UNUSED_ATTR int conn_id,
402                             UNUSED_ATTR int status) {
403   // TODO(icoolidge): what to do
404 }
405
406 void ResponseConfirmationCallback(UNUSED_ATTR int status,
407                                   UNUSED_ATTR int handle) {
408   // TODO(icoolidge): what to do
409 }
410
411 const btgatt_server_callbacks_t gatt_server_callbacks = {
412     RegisterServerCallback,
413     ConnectionCallback,
414     ServiceAddedCallback,
415     nullptr, /* included_service_added_cb */
416     CharacteristicAddedCallback,
417     DescriptorAddedCallback,
418     ServiceStartedCallback,
419     ServiceStoppedCallback,
420     nullptr, /* service_deleted_cb */
421     RequestReadCallback,
422     RequestWriteCallback,
423     RequestExecWriteCallback,
424     ResponseConfirmationCallback,
425     IndicationSentCallback,
426     nullptr, /* congestion_cb*/
427     nullptr, /* mtu_changed_cb */
428 };
429
430 // TODO(eisenbach): Refactor GATT interface to not require servers
431 // to refer to the client interface.
432 const btgatt_client_callbacks_t gatt_client_callbacks = {
433     RegisterClientCallback,
434     ScanResultCallback,
435     ClientConnectCallback,
436     ClientDisconnectCallback,
437     nullptr, /* search_complete_cb; */
438     nullptr, /* register_for_notification_cb; */
439     nullptr, /* notify_cb; */
440     nullptr, /* read_characteristic_cb; */
441     nullptr, /* write_characteristic_cb; */
442     nullptr, /* read_descriptor_cb; */
443     nullptr, /* write_descriptor_cb; */
444     nullptr, /* execute_write_cb; */
445     nullptr, /* read_remote_rssi_cb; */
446     ListenCallback,
447     nullptr, /* configure_mtu_cb; */
448     nullptr, /* scan_filter_cfg_cb; */
449     nullptr, /* scan_filter_param_cb; */
450     nullptr, /* scan_filter_status_cb; */
451     nullptr, /* multi_adv_enable_cb */
452     nullptr, /* multi_adv_update_cb; */
453     nullptr, /* multi_adv_data_cb*/
454     nullptr, /* multi_adv_disable_cb; */
455     nullptr, /* congestion_cb; */
456     nullptr, /* batchscan_cfg_storage_cb; */
457     nullptr, /* batchscan_enb_disable_cb; */
458     nullptr, /* batchscan_reports_cb; */
459     nullptr, /* batchscan_threshold_cb; */
460     nullptr, /* track_adv_event_cb; */
461     nullptr, /* scan_parameter_setup_completed_cb; */
462     nullptr, /* get_gatt_db_cb; */
463     nullptr, /* services_removed_cb */
464     nullptr, /* services_added_cb */
465 };
466
467 const btgatt_callbacks_t gatt_callbacks = {
468     /** Set to sizeof(btgatt_callbacks_t) */
469     sizeof(btgatt_callbacks_t),
470
471     /** GATT Client callbacks */
472     &gatt_client_callbacks,
473
474     /** GATT Server callbacks */
475     &gatt_server_callbacks};
476
477 }  // namespace
478
479 namespace bluetooth {
480 namespace gatt {
481
482 int ServerInternals::Initialize() {
483   // Get the interface to the GATT profile.
484   const bt_interface_t* bt_iface =
485       hal::BluetoothInterface::Get()->GetHALInterface();
486   gatt = reinterpret_cast<const btgatt_interface_t *>(
487       bt_iface->get_profile_interface(BT_PROFILE_GATT_ID));
488   if (!gatt) {
489     LOG_ERROR(LOG_TAG, "Error getting GATT interface");
490     return -1;
491   }
492
493   bt_status_t btstat = gatt->init(&gatt_callbacks);
494   if (btstat != BT_STATUS_SUCCESS) {
495     LOG_ERROR(LOG_TAG, "Failed to initialize gatt interface");
496     return -1;
497   }
498
499   int status = pipe(pipefd);
500   if (status == -1) {
501     LOG_ERROR(LOG_TAG, "pipe creation failed: %s", strerror(errno));
502     return -1;
503   }
504
505   return 0;
506 }
507
508 bt_status_t ServerInternals::AddCharacteristic(
509     const UUID& uuid,
510     int properties,
511     int permissions) {
512   bt_uuid_t c_uuid = uuid.GetBlueDroid();
513   return gatt->server->add_characteristic(
514       server_if, service_handle, &c_uuid, properties, permissions);
515 }
516
517 ServerInternals::ServerInternals()
518     : gatt(nullptr),
519       server_if(0),
520       client_if(0),
521       service_handle(0),
522       pipefd{INVALID_FD, INVALID_FD} {}
523
524 ServerInternals::~ServerInternals() {
525   if (pipefd[0] != INVALID_FD)
526     close(pipefd[0]);
527   if (pipefd[1] != INVALID_FD)
528     close(pipefd[1]);
529
530   gatt->server->delete_service(server_if, service_handle);
531   gatt->server->unregister_server(server_if);
532   gatt->client->unregister_client(client_if);
533 }
534
535 Server::Server() : internal_(nullptr) {}
536
537 Server::~Server() {}
538
539 bool Server::Initialize(const UUID& service_id, int* gatt_pipe) {
540   internal_.reset(new ServerInternals);
541   if (!internal_) {
542     LOG_ERROR(LOG_TAG, "Error creating internals");
543     return false;
544   }
545   g_internal = internal_.get();
546
547   std::unique_lock<std::mutex> lock(internal_->lock);
548   int status = internal_->Initialize();
549   if (status) {
550     LOG_ERROR(LOG_TAG, "Error initializing internals");
551     return false;
552   }
553
554   bt_uuid_t uuid = service_id.GetBlueDroid();
555
556   bt_status_t btstat = internal_->gatt->server->register_server(&uuid);
557   if (btstat != BT_STATUS_SUCCESS) {
558     LOG_ERROR(LOG_TAG, "Failed to register server");
559     return false;
560   }
561
562   internal_->api_synchronize.wait(lock);
563   // TODO(icoolidge): Better error handling.
564   if (internal_->server_if == 0) {
565     LOG_ERROR(LOG_TAG, "Initialization of server failed");
566     return false;
567   }
568
569   *gatt_pipe = internal_->pipefd[kPipeReadEnd];
570   LOG_INFO(LOG_TAG, "Server Initialize succeeded");
571   return true;
572 }
573
574 bool Server::SetAdvertisement(const std::vector<UUID>& ids,
575                               const std::vector<uint8_t>& service_data,
576                               const std::vector<uint8_t>& manufacturer_data,
577                               bool transmit_name) {
578   std::vector<uint8_t> id_data;
579   auto mutable_manufacturer_data = manufacturer_data;
580   auto mutable_service_data = service_data;
581
582   for (const UUID &id : ids) {
583     const auto le_id = id.GetFullLittleEndian();
584     id_data.insert(id_data.end(), le_id.begin(), le_id.end());
585   }
586
587   std::lock_guard<std::mutex> lock(internal_->lock);
588
589   // Setup our advertisement. This has no callback.
590   bt_status_t btstat = internal_->gatt->client->set_adv_data(
591       internal_->client_if, false, /* beacon, not scan response */
592       transmit_name,               /* name */
593       false,                       /* no txpower */
594       2, 2,                        /* interval */
595       0,                           /* appearance */
596       mutable_manufacturer_data.size(),
597       reinterpret_cast<char *>(mutable_manufacturer_data.data()),
598       mutable_service_data.size(),
599       reinterpret_cast<char *>(mutable_service_data.data()), id_data.size(),
600       reinterpret_cast<char *>(id_data.data()));
601   if (btstat != BT_STATUS_SUCCESS) {
602     LOG_ERROR(LOG_TAG, "Failed to set advertising data");
603     return false;
604   }
605   return true;
606 }
607
608 bool Server::SetScanResponse(const std::vector<UUID>& ids,
609                              const std::vector<uint8_t>& service_data,
610                              const std::vector<uint8_t>& manufacturer_data,
611                              bool transmit_name) {
612   std::vector<uint8_t> id_data;
613   auto mutable_manufacturer_data = manufacturer_data;
614   auto mutable_service_data = service_data;
615
616   for (const UUID &id : ids) {
617     const auto le_id = id.GetFullLittleEndian();
618     id_data.insert(id_data.end(), le_id.begin(), le_id.end());
619   }
620
621   std::lock_guard<std::mutex> lock(internal_->lock);
622
623   // Setup our advertisement. This has no callback.
624   bt_status_t btstat = internal_->gatt->client->set_adv_data(
625       internal_->client_if, true, /* scan response */
626       transmit_name,              /* name */
627       false,                      /* no txpower */
628       2, 2,                       /* interval */
629       0,                          /* appearance */
630       mutable_manufacturer_data.size(),
631       reinterpret_cast<char *>(mutable_manufacturer_data.data()),
632       mutable_service_data.size(),
633       reinterpret_cast<char *>(mutable_service_data.data()), id_data.size(),
634       reinterpret_cast<char *>(id_data.data()));
635   if (btstat != BT_STATUS_SUCCESS) {
636     LOG_ERROR(LOG_TAG, "Failed to set scan response data");
637     return false;
638   }
639   return true;
640 }
641
642 bool Server::AddCharacteristic(
643     const UUID &id, int properties, int permissions) {
644   std::unique_lock<std::mutex> lock(internal_->lock);
645   bt_status_t btstat = internal_->AddCharacteristic(
646       id, properties, permissions);
647   if (btstat != BT_STATUS_SUCCESS) {
648     LOG_ERROR(LOG_TAG, "Failed to add characteristic to service: 0x%04x",
649               internal_->service_handle);
650     return false;
651   }
652   internal_->api_synchronize.wait(lock);
653   const int handle = internal_->uuid_to_attribute[id];
654   internal_->characteristics[handle].notify = properties & kPropertyNotify;
655   return true;
656 }
657
658 bool Server::AddBlob(const UUID &id, const UUID &control_id, int properties,
659                     int permissions) {
660   std::unique_lock<std::mutex> lock(internal_->lock);
661
662   // First, add the primary attribute (characteristic value)
663   bt_status_t btstat = internal_->AddCharacteristic(
664       id, properties, permissions);
665   if (btstat != BT_STATUS_SUCCESS) {
666     LOG_ERROR(LOG_TAG, "Failed to set scan response data");
667     return false;
668   }
669
670   internal_->api_synchronize.wait(lock);
671
672   // Next, add the secondary attribute (blob control).
673   // Control attributes have fixed permissions/properties.
674   btstat = internal_->AddCharacteristic(
675       control_id,
676       kPropertyRead | kPropertyWrite,
677       kPermissionRead | kPermissionWrite);
678   internal_->api_synchronize.wait(lock);
679
680   // Finally, associate the control attribute with the value attribute.
681   // Also, initialize the control attribute to a readable zero.
682   const int control_attribute = internal_->uuid_to_attribute[control_id];
683   const int blob_attribute = internal_->uuid_to_attribute[id];
684   internal_->controlled_blobs[control_attribute] = blob_attribute;
685   internal_->characteristics[blob_attribute].notify =
686       properties & kPropertyNotify;
687
688   Characteristic &ctrl = internal_->characteristics[control_attribute];
689   ctrl.next_blob.clear();
690   ctrl.next_blob.push_back(0);
691   ctrl.next_blob_pending = true;
692   ctrl.blob_section = 0;
693   ctrl.notify = false;
694   return true;
695 }
696
697 bool Server::Start() {
698   std::unique_lock<std::mutex> lock(internal_->lock);
699   bt_status_t btstat = internal_->gatt->server->start_service(
700       internal_->server_if, internal_->service_handle, GATT_TRANSPORT_LE);
701   if (btstat != BT_STATUS_SUCCESS) {
702     LOG_ERROR(LOG_TAG, "Failed to start service with handle: 0x%04x",
703               internal_->service_handle);
704     return false;
705   }
706   internal_->api_synchronize.wait(lock);
707   return true;
708 }
709
710 bool Server::Stop() {
711   std::unique_lock<std::mutex> lock(internal_->lock);
712   bt_status_t btstat = internal_->gatt->server->stop_service(
713       internal_->server_if, internal_->service_handle);
714   if (btstat != BT_STATUS_SUCCESS) {
715     LOG_ERROR(LOG_TAG, "Failed to stop service with handle: 0x%04x",
716               internal_->service_handle);
717     return false;
718   }
719   internal_->api_synchronize.wait(lock);
720   return true;
721 }
722
723 bool Server::ScanEnable() {
724   bt_status_t btstat = internal_->gatt->client->scan(true);
725   if (btstat) {
726     LOG_ERROR(LOG_TAG, "Enable scan failed: %d", btstat);
727     return false;
728   }
729   return true;
730 }
731
732 bool Server::ScanDisable() {
733   bt_status_t btstat = internal_->gatt->client->scan(false);
734   if (btstat) {
735     LOG_ERROR(LOG_TAG, "Disable scan failed: %d", btstat);
736     return false;
737   }
738   return true;
739 }
740
741 bool Server::GetScanResults(ScanResults *results) {
742   std::lock_guard<std::mutex> lock(internal_->lock);
743   *results = internal_->scan_results;
744   return true;
745 }
746
747 bool Server::SetCharacteristicValue(const UUID &id,
748                               const std::vector<uint8_t> &value) {
749   std::lock_guard<std::mutex> lock(internal_->lock);
750   const int attribute_id = internal_->uuid_to_attribute[id];
751   Characteristic &ch = internal_->characteristics[attribute_id];
752   ch.next_blob = value;
753   ch.next_blob_pending = true;
754
755   if (!ch.notify)
756     return true;
757
758   for (auto connection : internal_->connections) {
759     char dummy = 0;
760     internal_->gatt->server->send_indication(internal_->server_if,
761                                              attribute_id,
762                                              connection,
763                                              sizeof(dummy),
764                                              true,
765                                              &dummy);
766   }
767   return true;
768 }
769
770 bool Server::GetCharacteristicValue(const UUID &id, std::vector<uint8_t> *value) {
771   std::lock_guard<std::mutex> lock(internal_->lock);
772   const int attribute_id = internal_->uuid_to_attribute[id];
773   *value = internal_->characteristics[attribute_id].blob;
774   return true;
775 }
776
777 }  // namespace gatt
778 }  // namespace bluetooth