gatt_server.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. #pragma once
  17. #include <deque>
  18. #include <functional>
  19. #include <mutex>
  20. #include <string>
  21. #include <unordered_map>
  22. #include <unordered_set>
  23. #include <vector>
  24. #include <base/macros.h>
  25. #include <bluetooth/uuid.h>
  26. #include "service/bluetooth_instance.h"
  27. #include "service/common/bluetooth/service.h"
  28. #include "service/hal/bluetooth_gatt_interface.h"
  29. namespace bluetooth {
  30. // A GattServer instance represents an application's handle to perform GATT
  31. // server-role operations. Instances cannot be created directly and should be
  32. // obtained through the factory.
  33. class GattServer : public BluetoothInstance,
  34. private hal::BluetoothGattInterface::ServerObserver {
  35. public:
  36. // Delegate interface is used to handle incoming requests and confirmations
  37. // for a GATT service.
  38. class Delegate {
  39. public:
  40. Delegate() = default;
  41. virtual ~Delegate() = default;
  42. // Called when there is an incoming read request for the characteristic with
  43. // ID |characteristic_id| from a remote device with address
  44. // |device_address|. |request_id| can be used to respond to this request by
  45. // calling SendResponse below.
  46. virtual void OnCharacteristicReadRequest(GattServer* gatt_server,
  47. const std::string& device_address,
  48. int request_id, int offset,
  49. bool is_long, uint16_t handle) = 0;
  50. // Called when there is an incoming read request for the descriptor with
  51. // ID |descriptor_id| from a remote device with address |device_address|.
  52. // |request_id| can be used to respond to this request by
  53. // calling SendResponse below.
  54. virtual void OnDescriptorReadRequest(GattServer* gatt_server,
  55. const std::string& device_address,
  56. int request_id, int offset,
  57. bool is_long, uint16_t handle) = 0;
  58. // Called when there is an incoming write request for the characteristic
  59. // with ID |characteristic_id| from a remote device with address
  60. // |device_address|. |request_id| can be used to respond to this request by
  61. // calling SendResponse, if the |need_response| parameter is true. Otherwise
  62. // this is a "Write Without Reponse" procedure and SendResponse will fail.
  63. // If |is_prepare_write| is true, then the write should not be committed
  64. // immediately as this is a "Prepared Write Request". Instead, the Delegate
  65. // should hold on to the value and either discard it or complete the write
  66. // when it receives the OnExecuteWriteRequest event.
  67. virtual void OnCharacteristicWriteRequest(
  68. GattServer* gatt_server, const std::string& device_address,
  69. int request_id, int offset, bool is_prepare_write, bool need_response,
  70. const std::vector<uint8_t>& value, uint16_t handle) = 0;
  71. // Called when there is an incoming write request for the descriptor
  72. // with ID |descriptor_id| from a remote device with address
  73. // |device_address|. |request_id| can be used to respond to this request by
  74. // calling SendResponse, if the |need_response| parameter is true. Otherwise
  75. // this is a "Write Without Response" procedure and SendResponse will fail.
  76. // If |is_prepare_write| is true, then the write should not be committed
  77. // immediately as this is a "Prepared Write Request". Instead, the Delegate
  78. // should hold on to the value and either discard it or complete the write
  79. // when it receives the OnExecuteWriteRequest event.
  80. virtual void OnDescriptorWriteRequest(
  81. GattServer* gatt_server, const std::string& device_address,
  82. int request_id, int offset, bool is_prepare_write, bool need_response,
  83. const std::vector<uint8_t>& value, uint16_t handle) = 0;
  84. // Called when there is an incoming "Execute Write Request". If |is_execute|
  85. // is true, then the Delegate should commit all previously prepared writes.
  86. // Otherwise, all prepared writes should be aborted. The Delegate should
  87. // call "SendResponse" to complete the procedure.
  88. virtual void OnExecuteWriteRequest(GattServer* gatt_server,
  89. const std::string& device_address,
  90. int request_id, bool is_execute) = 0;
  91. virtual void OnConnectionStateChanged(GattServer* gatt_server,
  92. const std::string& device_addres,
  93. bool connected) = 0;
  94. private:
  95. DISALLOW_COPY_AND_ASSIGN(Delegate);
  96. };
  97. // The desctructor automatically unregisters this instance from the stack.
  98. ~GattServer() override;
  99. // Assigns a delegate to this instance. |delegate| must out-live this
  100. // GattServer instance.
  101. void SetDelegate(Delegate* delegate);
  102. // BluetoothClientInstace overrides:
  103. const Uuid& GetAppIdentifier() const override;
  104. int GetInstanceId() const override;
  105. // Callback type used to report the status of an asynchronous GATT server
  106. // operation.
  107. using ResultCallback =
  108. std::function<void(BLEStatus status, const Service& id)>;
  109. using GattCallback = std::function<void(GATTError error)>;
  110. // Add service declaration. This method immediately
  111. // returns false if a service hasn't been started. Otherwise, |callback| will
  112. // be called asynchronously with the result of the operation.
  113. //
  114. // TODO(armansito): It is unclear to me what it means for this function to
  115. // fail. What is the state that we're in? Is the service declaration over so
  116. // we can add other services to this server instance? Do we need to clean up
  117. // all the entries or does the upper-layer need to remove the service? Or are
  118. // we in a stuck-state where the service declaration hasn't ended?
  119. bool AddService(const Service&, const ResultCallback& callback);
  120. // Sends a response for a pending notification. |request_id| and
  121. // |device_address| should match those that were received through one of the
  122. // Delegate callbacks. |value| and |offset| are used for read requests and
  123. // prepare write requests and should match the value of the attribute. Returns
  124. // false if the pending request could not be resolved using the given
  125. // parameters or if the call to the underlying stack fails.
  126. bool SendResponse(const std::string& device_address, int request_id,
  127. GATTError error, int offset,
  128. const std::vector<uint8_t>& value);
  129. // Sends an ATT Handle-Value Notification to the device with BD_ADDR
  130. // |device_address| for the characteristic with handle |handle| and
  131. // value |value|. If |confirm| is true, then an ATT Handle-Value Indication
  132. // will be sent instead, which requires the remote to confirm receipt. Returns
  133. // false if there was an immediate error in initiating the notification
  134. // procedure. Otherwise, returns true and reports the asynchronous result of
  135. // the operation in |callback|.
  136. //
  137. // If |confirm| is true, then |callback| will be run when the remote device
  138. // sends a ATT Handle-Value Confirmation packet. Otherwise, it will be run as
  139. // soon as the notification has been sent out.
  140. bool SendNotification(const std::string& device_address,
  141. const uint16_t handle, bool confirm,
  142. const std::vector<uint8_t>& value,
  143. const GattCallback& callback);
  144. private:
  145. friend class GattServerFactory;
  146. // Used for the internal remote connection tracking. Keeps track of the
  147. // request ID and the device address for the connection. If |request_id| is -1
  148. // then no ATT read/write request is currently pending.
  149. struct Connection {
  150. Connection(int conn_id, const RawAddress& bdaddr)
  151. : conn_id(conn_id), bdaddr(bdaddr) {}
  152. Connection() : conn_id(-1) { memset(&bdaddr, 0, sizeof(bdaddr)); }
  153. int conn_id;
  154. std::unordered_map<int, int> request_id_to_handle;
  155. RawAddress bdaddr;
  156. };
  157. // Used to keep track of a pending Handle-Value indication.
  158. struct PendingIndication {
  159. explicit PendingIndication(const GattCallback& callback)
  160. : has_success(false), callback(callback) {}
  161. bool has_success;
  162. GattCallback callback;
  163. };
  164. // Constructor shouldn't be called directly as instances are meant to be
  165. // obtained from the factory.
  166. GattServer(const Uuid& uuid, int server_id);
  167. // hal::BluetoothGattInterface::ServerObserver overrides:
  168. void ConnectionCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id,
  169. int server_id, int connected,
  170. const RawAddress& bda) override;
  171. void ServiceAddedCallback(hal::BluetoothGattInterface* gatt_iface, int status,
  172. int server_if,
  173. std::vector<btgatt_db_element_t>) override;
  174. void ServiceStoppedCallback(hal::BluetoothGattInterface* gatt_iface,
  175. int status, int server_id,
  176. int service_handle) override;
  177. void RequestReadCharacteristicCallback(
  178. hal::BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
  179. const RawAddress& bda, int attribute_handle, int offset,
  180. bool is_long) override;
  181. void RequestReadDescriptorCallback(hal::BluetoothGattInterface* gatt_iface,
  182. int conn_id, int trans_id,
  183. const RawAddress& bda,
  184. int attribute_handle, int offset,
  185. bool is_long) override;
  186. void RequestWriteCharacteristicCallback(
  187. hal::BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
  188. const RawAddress& bda, int attr_handle, int offset, bool need_rsp,
  189. bool is_prep, std::vector<uint8_t> value) override;
  190. void RequestWriteDescriptorCallback(hal::BluetoothGattInterface* gatt_iface,
  191. int conn_id, int trans_id,
  192. const RawAddress& bda, int attr_handle,
  193. int offset, bool need_rsp, bool is_prep,
  194. std::vector<uint8_t> value) override;
  195. void RequestExecWriteCallback(hal::BluetoothGattInterface* gatt_iface,
  196. int conn_id, int trans_id,
  197. const RawAddress& bda, int exec_write) override;
  198. void IndicationSentCallback(hal::BluetoothGattInterface* gatt_iface,
  199. int conn_id, int status) override;
  200. // Helper function that notifies and clears the pending callback.
  201. void CleanUpPendingData();
  202. // Handles the next attribute entry in the pending service declaration.
  203. void HandleNextEntry(hal::BluetoothGattInterface* gatt_iface);
  204. // Helper method that returns a pointer to an internal Connection instance
  205. // that matches the given parameters.
  206. std::shared_ptr<Connection> GetConnection(int conn_id, const RawAddress& bda,
  207. int request_id);
  208. // See getters for documentation.
  209. Uuid app_identifier_;
  210. int server_id_;
  211. // Mutex that synchronizes access to the entries below.
  212. std::mutex mutex_;
  213. ResultCallback pending_end_decl_cb_;
  214. // GATT connection mappings from stack-provided "conn_id" IDs and remote
  215. // device addresses to Connection structures. The conn_id map is one-to-one
  216. // while the conn_addr map is one to many, as a remote device may support
  217. // multiple transports (BR/EDR & LE) and use the same device address for both.
  218. std::unordered_map<int, std::shared_ptr<Connection>> conn_id_map_;
  219. std::unordered_map<std::string, std::vector<std::shared_ptr<Connection>>>
  220. conn_addr_map_;
  221. // Connections for which a Handle-Value indication is pending. Since there can
  222. // be multiple indications to the same device (in the case of a dual-mode
  223. // device with simulatenous BR/EDR & LE GATT connections), we also keep track
  224. // of whether there has been at least one successful confirmation.
  225. std::unordered_map<int, std::shared_ptr<PendingIndication>>
  226. pending_indications_;
  227. // Raw handle to the Delegate, which must outlive this GattServer instance.
  228. Delegate* delegate_;
  229. DISALLOW_COPY_AND_ASSIGN(GattServer);
  230. };
  231. // GattServerFactory is used to register and obtain a per-application GattServer
  232. // instance. Users should call RegisterClient to obtain their own unique
  233. // GattServer instance that has been registered with the Bluetooth stack.
  234. class GattServerFactory : public BluetoothInstanceFactory,
  235. private hal::BluetoothGattInterface::ServerObserver {
  236. public:
  237. // Don't construct/destruct directly except in tests. Instead, obtain a handle
  238. // from an Adapter instance.
  239. GattServerFactory();
  240. ~GattServerFactory() override;
  241. // BluetoothInstanceFactory override:
  242. bool RegisterInstance(const Uuid& uuid,
  243. const RegisterCallback& callback) override;
  244. private:
  245. // hal::BluetoothGattInterface::ServerObserver override:
  246. void RegisterServerCallback(hal::BluetoothGattInterface* gatt_iface,
  247. int status, int server_id,
  248. const Uuid& app_uuid) override;
  249. // Map of pending calls to register.
  250. std::mutex pending_calls_lock_;
  251. std::unordered_map<Uuid, RegisterCallback> pending_calls_;
  252. DISALLOW_COPY_AND_ASSIGN(GattServerFactory);
  253. };
  254. } // namespace bluetooth