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