1 /*
2  * Copyright (C) 2016 The Linux Foundation
3  * Copyright (C) 2012 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #ifndef ANDROID_INCLUDE_BLUETOOTH_H
19 #define ANDROID_INCLUDE_BLUETOOTH_H
20 
21 #include <stdbool.h>
22 #include <stdint.h>
23 #include <sys/cdefs.h>
24 #include <sys/types.h>
25 
26 #include <vector>
27 
28 #include "avrcp/avrcp.h"
29 #include "types/bluetooth/uuid.h"
30 #include "types/bt_transport.h"
31 #include "types/raw_address.h"
32 
33 /**
34  * The Bluetooth Hardware Module ID
35  */
36 
37 #define BT_HARDWARE_MODULE_ID "bluetooth"
38 #define BT_STACK_MODULE_ID "bluetooth"
39 
40 /** Bluetooth profile interface IDs */
41 #define BT_PROFILE_HANDSFREE_ID "handsfree"
42 #define BT_PROFILE_HANDSFREE_CLIENT_ID "handsfree_client"
43 #define BT_PROFILE_ADVANCED_AUDIO_ID "a2dp"
44 #define BT_PROFILE_ADVANCED_AUDIO_SINK_ID "a2dp_sink"
45 #define BT_PROFILE_SOCKETS_ID "socket"
46 #define BT_PROFILE_HIDHOST_ID "hidhost"
47 #define BT_PROFILE_HIDDEV_ID "hiddev"
48 #define BT_PROFILE_PAN_ID "pan"
49 #define BT_PROFILE_MAP_CLIENT_ID "map_client"
50 #define BT_PROFILE_SDP_CLIENT_ID "sdp"
51 #define BT_PROFILE_GATT_ID "gatt"
52 #define BT_PROFILE_AV_RC_ID "avrcp"
53 #define BT_PROFILE_AV_RC_CTRL_ID "avrcp_ctrl"
54 #define BT_PROFILE_HEARING_AID_ID "hearing_aid"
55 #define BT_PROFILE_HAP_CLIENT_ID "has_client"
56 #define BT_PROFILE_LE_AUDIO_ID "le_audio"
57 #define BT_KEYSTORE_ID "bluetooth_keystore"
58 #define BT_PROFILE_VC_ID "volume_control"
59 #define BT_PROFILE_CSIS_CLIENT_ID "csis_client"
60 #define BT_PROFILE_LE_AUDIO_ID "le_audio"
61 #define BT_PROFILE_LE_AUDIO_BROADCASTER_ID "le_audio_broadcaster"
62 #define BT_BQR_ID "bqr"
63 
64 /** Bluetooth Device Name */
65 typedef struct {
66   uint8_t name[249];
67 } __attribute__((packed)) bt_bdname_t;
68 
69 /** Bluetooth Adapter Visibility Modes*/
70 typedef enum {
71   BT_SCAN_MODE_NONE,
72   BT_SCAN_MODE_CONNECTABLE,
73   BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE,
74   BT_SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE
75 } bt_scan_mode_t;
76 
77 /** Bluetooth Adapter State */
78 typedef enum { BT_STATE_OFF, BT_STATE_ON } bt_state_t;
79 
80 /** Bluetooth Adapter Input Output Capabilities which determine Pairing/Security
81  */
82 typedef enum {
83   BT_IO_CAP_OUT,    /* DisplayOnly */
84   BT_IO_CAP_IO,     /* DisplayYesNo */
85   BT_IO_CAP_IN,     /* KeyboardOnly */
86   BT_IO_CAP_NONE,   /* NoInputNoOutput */
87   BT_IO_CAP_KBDISP, /* Keyboard display */
88   BT_IO_CAP_MAX,
89   BT_IO_CAP_UNKNOWN = 0xFF /* Unknown value */
90 } bt_io_cap_t;
91 
92 /** Bluetooth Error Status */
93 /** We need to build on this */
94 
95 typedef enum {
96   BT_STATUS_SUCCESS = 0,
97   BT_STATUS_FAIL,
98   BT_STATUS_NOT_READY,
99   BT_STATUS_NOMEM,
100   BT_STATUS_BUSY, /* retryable error */
101   BT_STATUS_DONE, /* request already completed */
102   BT_STATUS_UNSUPPORTED,
103   BT_STATUS_PARM_INVALID,
104   BT_STATUS_UNHANDLED,
105   BT_STATUS_AUTH_FAILURE,
106   BT_STATUS_RMT_DEV_DOWN,
107   BT_STATUS_AUTH_REJECTED,
108   BT_STATUS_JNI_ENVIRONMENT_ERROR,
109   BT_STATUS_JNI_THREAD_ATTACH_ERROR,
110   BT_STATUS_WAKELOCK_ERROR,
111   BT_STATUS_TIMEOUT,
112   BT_STATUS_DEVICE_NOT_FOUND,
113   BT_STATUS_UNEXPECTED_STATE,
114   BT_STATUS_SOCKET_ERROR
115 } bt_status_t;
116 
bt_status_text(const bt_status_t & status)117 inline std::string bt_status_text(const bt_status_t& status) {
118   switch (status) {
119     case BT_STATUS_SUCCESS:
120       return std::string("success");
121     case BT_STATUS_FAIL:
122       return std::string("fail");
123     case BT_STATUS_NOT_READY:
124       return std::string("not_ready");
125     case BT_STATUS_NOMEM:
126       return std::string("no_memory");
127     case BT_STATUS_BUSY:
128       return std::string("busy");
129     case BT_STATUS_DONE:
130       return std::string("already_done");
131     case BT_STATUS_UNSUPPORTED:
132       return std::string("unsupported");
133     case BT_STATUS_PARM_INVALID:
134       return std::string("parameter_invalid");
135     case BT_STATUS_UNHANDLED:
136       return std::string("unhandled");
137     case BT_STATUS_AUTH_FAILURE:
138       return std::string("auth_failure");
139     case BT_STATUS_RMT_DEV_DOWN:
140       return std::string("remote_device_down");
141     case BT_STATUS_AUTH_REJECTED:
142       return std::string("auth_rejected");
143     case BT_STATUS_JNI_ENVIRONMENT_ERROR:
144       return std::string("jni_env_error");
145     case BT_STATUS_JNI_THREAD_ATTACH_ERROR:
146       return std::string("jni_thread_error");
147     case BT_STATUS_WAKELOCK_ERROR:
148       return std::string("wakelock_error");
149     case BT_STATUS_TIMEOUT:
150       return std::string("timeout_error");
151     case BT_STATUS_DEVICE_NOT_FOUND:
152       return std::string("device_not_found");
153     case BT_STATUS_UNEXPECTED_STATE:
154       return std::string("unexpected_state");
155     case BT_STATUS_SOCKET_ERROR:
156       return std::string("socket_error");
157     default:
158       return std::string("UNKNOWN");
159   }
160 }
161 
162 /** Bluetooth HCI Error Codes */
163 /** Corresponding to [Vol 2] Part D, "Error Codes" of Core_v5.1 specs */
164 typedef uint8_t bt_hci_error_code_t;
165 
166 /** Bluetooth PinKey Code */
167 typedef struct {
168   uint8_t pin[16];
169 } __attribute__((packed)) bt_pin_code_t;
170 
171 typedef struct {
172   uint8_t status;
173   uint32_t ctrl_state;  /* stack reported state */
174   uint64_t tx_time;     /* in ms */
175   uint64_t rx_time;     /* in ms */
176   uint64_t idle_time;   /* in ms */
177   uint64_t energy_used; /* a product of mA, V and ms */
178 } __attribute__((packed)) bt_activity_energy_info;
179 
180 typedef struct {
181   int32_t app_uid;
182   uint64_t tx_bytes;
183   uint64_t rx_bytes;
184 } __attribute__((packed)) bt_uid_traffic_t;
185 
186 /** Bluetooth Adapter Discovery state */
187 typedef enum { BT_DISCOVERY_STOPPED, BT_DISCOVERY_STARTED } bt_discovery_state_t;
188 
189 /** Bluetooth ACL connection state */
190 typedef enum { BT_ACL_STATE_CONNECTED, BT_ACL_STATE_DISCONNECTED } bt_acl_state_t;
191 
192 /** Bluetooth ACL connection direction */
193 typedef enum {
194   BT_CONN_DIRECTION_UNKNOWN,
195   BT_CONN_DIRECTION_OUTGOING,
196   BT_CONN_DIRECTION_INCOMING
197 } bt_conn_direction_t;
198 
199 constexpr uint16_t INVALID_ACL_HANDLE = 0xFFFF;
200 
201 /** Bluetooth SDP service record */
202 typedef struct {
203   bluetooth::Uuid uuid;
204   uint16_t channel;
205   char name[256];  // what's the maximum length
206 } bt_service_record_t;
207 
208 /** Bluetooth Remote Version info */
209 typedef struct {
210   int version;
211   int sub_ver;
212   int manufacturer;
213 } bt_remote_version_t;
214 
215 typedef struct {
216   uint16_t version_supported;
217   uint8_t local_privacy_enabled;
218   uint8_t max_adv_instance;
219   uint8_t rpa_offload_supported;
220   uint8_t max_irk_list_size;
221   uint8_t max_adv_filter_supported;
222   uint8_t activity_energy_info_supported;
223   uint16_t scan_result_storage_size;
224   uint16_t total_trackable_advertisers;
225   bool extended_scan_support;
226   bool debug_logging_supported;
227   bool le_2m_phy_supported;
228   bool le_coded_phy_supported;
229   bool le_extended_advertising_supported;
230   bool le_periodic_advertising_supported;
231   uint16_t le_maximum_advertising_data_length;
232   uint32_t dynamic_audio_buffer_supported;
233   bool le_periodic_advertising_sync_transfer_sender_supported;
234   bool le_connected_isochronous_stream_central_supported;
235   bool le_isochronous_broadcast_supported;
236   bool le_periodic_advertising_sync_transfer_recipient_supported;
237   uint16_t adv_filter_extended_features_mask;
238   bool le_channel_sounding_supported;
239 } bt_local_le_features_t;
240 
241 typedef struct {
242   uint8_t number_of_supported_offloaded_le_coc_sockets;
243 } bt_lpp_offload_features_t;
244 
245 /** Bluetooth Vendor and Product ID info */
246 typedef struct {
247   uint8_t vendor_id_src;
248   uint16_t vendor_id;
249   uint16_t product_id;
250   uint16_t version;
251 } bt_vendor_product_info_t;
252 
253 /* Stored the default/maximum/minimum buffer time for dynamic audio buffer.
254  * For A2DP offload usage, the unit is millisecond.
255  * For A2DP legacy usage, the unit is buffer queue size*/
256 typedef struct {
257   uint16_t default_buffer_time;
258   uint16_t maximum_buffer_time;
259   uint16_t minimum_buffer_time;
260 } bt_dynamic_audio_buffer_type_t;
261 
262 typedef struct {
263   bt_dynamic_audio_buffer_type_t dab_item[32];
264 } bt_dynamic_audio_buffer_item_t;
265 
266 /* Bluetooth Adapter and Remote Device property types */
267 typedef enum {
268   /* Properties common to both adapter and remote device */
269   /**
270    * Description - Bluetooth Device Name
271    * Access mode - Adapter name can be GET/SET. Remote device can be GET
272    * Data type   - bt_bdname_t
273    */
274   BT_PROPERTY_BDNAME = 0x1,
275   /**
276    * Description - Bluetooth Device Address
277    * Access mode - Only GET.
278    * Data type   - RawAddress
279    */
280   BT_PROPERTY_BDADDR,
281   /**
282    * Description - Bluetooth Service 128-bit UUIDs
283    * Access mode - Only GET.
284    * Data type   - Array of bluetooth::Uuid (Array size inferred from property
285    *               length).
286    */
287   BT_PROPERTY_UUIDS,
288   /**
289    * Description - Bluetooth Class of Device as found in Assigned Numbers
290    * Access mode - Only GET.
291    * Data type   - uint32_t.
292    */
293   BT_PROPERTY_CLASS_OF_DEVICE,
294   /**
295    * Description - Device Type - BREDR, BLE or DUAL Mode
296    * Access mode - Only GET.
297    * Data type   - bt_device_type_t
298    */
299   BT_PROPERTY_TYPE_OF_DEVICE,
300   /**
301    * Description - Bluetooth Service Record
302    * Access mode - Only GET.
303    * Data type   - bt_service_record_t
304    */
305   BT_PROPERTY_SERVICE_RECORD,
306 
307   /* Properties unique to adapter */
308   BT_PROPERTY_RESERVED_07,
309   /**
310    * Description - List of bonded devices
311    * Access mode - Only GET.
312    * Data type   - Array of RawAddress of the bonded remote devices
313    *               (Array size inferred from property length).
314    */
315   BT_PROPERTY_ADAPTER_BONDED_DEVICES,
316   /**
317    * Description - Bluetooth Adapter Discoverable timeout (in seconds)
318    * Access mode - GET and SET
319    * Data type   - uint32_t
320    */
321   BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT,
322 
323   /* Properties unique to remote device */
324   /**
325    * Description - User defined friendly name of the remote device
326    * Access mode - GET and SET
327    * Data type   - bt_bdname_t.
328    */
329   BT_PROPERTY_REMOTE_FRIENDLY_NAME,
330   /**
331    * Description - RSSI value of the inquired remote device
332    * Access mode - Only GET.
333    * Data type   - int8_t.
334    */
335   BT_PROPERTY_REMOTE_RSSI,
336   /**
337    * Description - Remote version info
338    * Access mode - SET/GET.
339    * Data type   - bt_remote_version_t.
340    */
341 
342   BT_PROPERTY_REMOTE_VERSION_INFO,
343 
344   /**
345    * Description - Local LE features
346    * Access mode - GET.
347    * Data type   - bt_local_le_features_t.
348    */
349   BT_PROPERTY_LOCAL_LE_FEATURES,
350 
351   BT_PROPERTY_RESERVED_0E,
352 
353   BT_PROPERTY_RESERVED_0F,
354 
355   BT_PROPERTY_DYNAMIC_AUDIO_BUFFER,
356 
357   /**
358    * Description - True if Remote is a Member of a Coordinated Set.
359    * Access mode - GET.
360    * Data Type - bool.
361    */
362   BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER,
363 
364   /**
365    * Description - Appearance as specified in Assigned Numbers.
366    * Access mode - GET.
367    * Data Type - uint16_t.
368    */
369   BT_PROPERTY_APPEARANCE,
370 
371   /**
372    * Description - Peer devices' vendor and product ID.
373    * Access mode - GET.
374    * Data Type - bt_vendor_product_info_t.
375    */
376   BT_PROPERTY_VENDOR_PRODUCT_INFO,
377 
378   BT_PROPERTY_RESERVED_0x14,
379 
380   /**
381    * Description - ASHA capability.
382    * Access mode - GET.
383    * Data Type - int16_t.
384    */
385   BT_PROPERTY_REMOTE_ASHA_CAPABILITY,
386 
387   /**
388    * Description - ASHA truncated HiSyncID.
389    * Access mode - GET.
390    * Data Type - uint32_t.
391    */
392   BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID,
393 
394   /**
395    * Description - Model name read from Device Information Service(DIS).
396    * Access mode - GET and SET.
397    * Data Type - char array.
398    */
399   BT_PROPERTY_REMOTE_MODEL_NUM,
400 
401   /**
402    * Description - Address type of the remote device - PUBLIC or REMOTE
403    * Access mode - GET.
404    * Data Type - uint8_t.
405    */
406   BT_PROPERTY_REMOTE_ADDR_TYPE,
407 
408   /**
409    * Description - Whether remote device supports Secure Connections mode
410    * Access mode - GET and SET.
411    * Data Type - uint8_t.
412    */
413   BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED,
414 
415   /**
416    * Description - Maximum observed session key for remote device
417    * Access mode - GET and SET.
418    * Data Type - uint8_t.
419    */
420   BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE,
421 
422   /**
423    * Description - Low power processor offload features
424    * Access mode - GET.
425    * Data Type   - bt_lpp_offload_features_t.
426    */
427   BT_PROPERTY_LPP_OFFLOAD_FEATURES,
428 
429   BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP = 0xFF,
430 } bt_property_type_t;
431 
432 /** Bluetooth Adapter Property data structure */
433 typedef struct {
434   bt_property_type_t type;
435   int len;
436   void* val;
437 } bt_property_t;
438 
439 // OOB_ADDRESS_SIZE is 6 bytes address + 1 byte address type
440 #define OOB_ADDRESS_SIZE 7
441 #define OOB_C_SIZE 16
442 #define OOB_R_SIZE 16
443 #define OOB_NAME_MAX_SIZE 256
444 // Classic
445 #define OOB_DATA_LEN_SIZE 2
446 #define OOB_COD_SIZE 3
447 // LE
448 #define OOB_TK_SIZE 16
449 #define OOB_LE_FLAG_SIZE 1
450 #define OOB_LE_ROLE_SIZE 1
451 #define OOB_LE_APPEARANCE_SIZE 2
452 /** Represents the actual Out of Band data itself */
453 typedef struct bt_oob_data_s {
454   // Both
455   bool is_valid = false; /* Default to invalid data; force caller to verify */
456   uint8_t address[OOB_ADDRESS_SIZE];
457   uint8_t c[OOB_C_SIZE];                  /* Simple Pairing Hash C-192/256 (Classic or LE) */
458   uint8_t r[OOB_R_SIZE];                  /* Simple Pairing Randomizer R-192/256 (Classic or LE) */
459   uint8_t device_name[OOB_NAME_MAX_SIZE]; /* Name of the device */
460 
461   // Classic
462   uint8_t oob_data_length[OOB_DATA_LEN_SIZE]; /* Classic only data Length. Value includes this
463                                                  in length */
464   uint8_t class_of_device[OOB_COD_SIZE];      /* Class of Device (Classic or LE) */
465 
466   // LE
467   uint8_t le_device_role;                        /* Supported and preferred role of device */
468   uint8_t sm_tk[OOB_TK_SIZE];                    /* Security Manager TK Value (LE Only) */
469   uint8_t le_flags;                              /* LE Flags for discoverability and features */
470   uint8_t le_appearance[OOB_LE_APPEARANCE_SIZE]; /* For the appearance of the device */
471 } bt_oob_data_t;
472 
473 /** Bluetooth Device Type */
474 typedef enum {
475   BT_DEVICE_DEVTYPE_BREDR = 0x1,
476   BT_DEVICE_DEVTYPE_BLE,
477   BT_DEVICE_DEVTYPE_DUAL
478 } bt_device_type_t;
479 
480 /** Bluetooth Bond state */
481 typedef enum { BT_BOND_STATE_NONE, BT_BOND_STATE_BONDING, BT_BOND_STATE_BONDED } bt_bond_state_t;
482 
483 /** Bluetooth SSP Bonding Variant */
484 typedef enum {
485   BT_SSP_VARIANT_PASSKEY_CONFIRMATION,
486   BT_SSP_VARIANT_PASSKEY_ENTRY,
487   BT_SSP_VARIANT_CONSENT,
488   BT_SSP_VARIANT_PASSKEY_NOTIFICATION
489 } bt_ssp_variant_t;
490 
491 typedef struct {
492   RawAddress bd_addr;
493   uint8_t status; /* bt_hci_error_code_t */
494   bool encr_enable;
495   uint8_t key_size;
496   tBT_TRANSPORT transport;
497   bool secure_connections;
498 } bt_encryption_change_evt;
499 
500 #define BT_MAX_NUM_UUIDS 32
501 
502 /** Bluetooth Interface callbacks */
503 
504 /** Bluetooth Enable/Disable Callback. */
505 typedef void (*adapter_state_changed_callback)(bt_state_t state);
506 
507 /** GET/SET Adapter Properties callback */
508 /* TODO: For the GET/SET property APIs/callbacks, we may need a session
509  * identifier to associate the call with the callback. This would be needed
510  * whenever more than one simultaneous instance of the same adapter_type
511  * is get/set.
512  *
513  * If this is going to be handled in the Java framework, then we do not need
514  * to manage sessions here.
515  */
516 typedef void (*adapter_properties_callback)(bt_status_t status, int num_properties,
517                                             bt_property_t* properties);
518 
519 /** GET/SET Remote Device Properties callback */
520 /** TODO: For remote device properties, do not see a need to get/set
521  * multiple properties - num_properties shall be 1
522  */
523 typedef void (*remote_device_properties_callback)(bt_status_t status, RawAddress* bd_addr,
524                                                   int num_properties, bt_property_t* properties);
525 
526 /** New device discovered callback */
527 /** If EIR data is not present, then BD_NAME and RSSI shall be NULL and -1
528  * respectively */
529 typedef void (*device_found_callback)(int num_properties, bt_property_t* properties);
530 
531 /** Discovery state changed callback */
532 typedef void (*discovery_state_changed_callback)(bt_discovery_state_t state);
533 
534 /** Bluetooth Legacy PinKey Request callback */
535 typedef void (*pin_request_callback)(RawAddress* remote_bd_addr, bt_bdname_t* bd_name, uint32_t cod,
536                                      bool min_16_digit);
537 
538 /** Bluetooth SSP Request callback - Just Works & Numeric Comparison*/
539 /** pass_key - Shall be 0 for BT_SSP_PAIRING_VARIANT_CONSENT &
540  *  BT_SSP_PAIRING_PASSKEY_ENTRY */
541 /* TODO: Passkey request callback shall not be needed for devices with display
542  * capability. We still need support this in the stack for completeness */
543 typedef void (*ssp_request_callback)(RawAddress* remote_bd_addr, bt_ssp_variant_t pairing_variant,
544                                      uint32_t pass_key);
545 
546 /** Bluetooth Bond state changed callback */
547 /* Invoked in response to create_bond, cancel_bond or remove_bond */
548 typedef void (*bond_state_changed_callback)(bt_status_t status, RawAddress* remote_bd_addr,
549                                             bt_bond_state_t state, int fail_reason);
550 
551 /** Bluetooth Address consolidate callback */
552 /* Callback to inform upper layer that these two addresses come from same
553  * bluetooth device (DUAL mode) */
554 typedef void (*address_consolidate_callback)(RawAddress* main_bd_addr,
555                                              RawAddress* secondary_bd_addr);
556 
557 /** Bluetooth LE Address association callback */
558 /* Callback for the upper layer to associate the LE-only device's RPA to the
559  * identity address and identity address type */
560 typedef void (*le_address_associate_callback)(RawAddress* main_bd_addr,
561                                               RawAddress* secondary_bd_addr,
562                                               uint8_t identity_address_type);
563 
564 /** Bluetooth ACL connection state changed callback */
565 typedef void (*acl_state_changed_callback)(bt_status_t status, RawAddress* remote_bd_addr,
566                                            bt_acl_state_t state, int transport_link_type,
567                                            bt_hci_error_code_t hci_reason,
568                                            bt_conn_direction_t direction, uint16_t acl_handle);
569 
570 /** Bluetooth link quality report callback */
571 typedef void (*link_quality_report_callback)(uint64_t timestamp, int report_id, int rssi, int snr,
572                                              int retransmission_count,
573                                              int packets_not_receive_count,
574                                              int negative_acknowledgement_count);
575 
576 /** Switch the buffer size callback */
577 typedef void (*switch_buffer_size_callback)(bool is_low_latency_buffer_size);
578 
579 /** Switch the codec callback */
580 typedef void (*switch_codec_callback)(bool is_low_latency_buffer_size);
581 
582 typedef void (*le_rand_callback)(uint64_t random);
583 
584 typedef enum { ASSOCIATE_JVM, DISASSOCIATE_JVM } bt_cb_thread_evt;
585 
586 /** Thread Associate/Disassociate JVM Callback */
587 /* Callback that is invoked by the callback thread to allow upper layer to
588  * attach/detach to/from the JVM */
589 typedef void (*callback_thread_event)(bt_cb_thread_evt evt);
590 
591 /** Bluetooth Test Mode Callback */
592 /* Receive any HCI event from controller. Must be in DUT Mode for this callback
593  * to be received */
594 typedef void (*dut_mode_recv_callback)(uint16_t opcode, uint8_t* buf, uint8_t len);
595 
596 /* LE Test mode callbacks
597  * This callback shall be invoked whenever the le_tx_test, le_rx_test or
598  * le_test_end is invoked The num_packets is valid only for le_test_end command
599  */
600 typedef void (*le_test_mode_callback)(bt_status_t status, uint16_t num_packets);
601 
602 /** Callback invoked when energy details are obtained */
603 /* Ctrl_state-Current controller state-Active-1,scan-2,or idle-3 state as
604  * defined by HCI spec. If the ctrl_state value is 0, it means the API call
605  * failed Time values-In milliseconds as returned by the controller Energy
606  * used-Value as returned by the controller Status-Provides the status of the
607  * read_energy_info API call uid_data provides an array of bt_uid_traffic_t,
608  * where the array is terminated by an element with app_uid set to -1.
609  */
610 typedef void (*energy_info_callback)(bt_activity_energy_info* energy_info,
611                                      bt_uid_traffic_t* uid_data);
612 
613 /** Callback invoked when OOB data is returned from the controller */
614 typedef void (*generate_local_oob_data_callback)(tBT_TRANSPORT transport, bt_oob_data_t oob_data);
615 
616 typedef void (*key_missing_callback)(const RawAddress bd_addr);
617 
618 typedef void (*encryption_change_callback)(const bt_encryption_change_evt encryption_change);
619 
620 /** TODO: Add callbacks for Link Up/Down and other generic
621  *  notifications/callbacks */
622 
623 /** Bluetooth DM callback structure. */
624 typedef struct {
625   /** set to sizeof(bt_callbacks_t) */
626   size_t size;
627   adapter_state_changed_callback adapter_state_changed_cb;
628   adapter_properties_callback adapter_properties_cb;
629   remote_device_properties_callback remote_device_properties_cb;
630   device_found_callback device_found_cb;
631   discovery_state_changed_callback discovery_state_changed_cb;
632   pin_request_callback pin_request_cb;
633   ssp_request_callback ssp_request_cb;
634   bond_state_changed_callback bond_state_changed_cb;
635   address_consolidate_callback address_consolidate_cb;
636   le_address_associate_callback le_address_associate_cb;
637   acl_state_changed_callback acl_state_changed_cb;
638   callback_thread_event thread_evt_cb;
639   dut_mode_recv_callback dut_mode_recv_cb;
640   le_test_mode_callback le_test_mode_cb;
641   energy_info_callback energy_info_cb;
642   link_quality_report_callback link_quality_report_cb;
643   generate_local_oob_data_callback generate_local_oob_data_cb;
644   switch_buffer_size_callback switch_buffer_size_cb;
645   switch_codec_callback switch_codec_cb;
646   le_rand_callback le_rand_cb;
647   key_missing_callback key_missing_cb;
648   encryption_change_callback encryption_change_cb;
649 } bt_callbacks_t;
650 
651 typedef int (*acquire_wake_lock_callout)(const char* lock_name);
652 typedef int (*release_wake_lock_callout)(const char* lock_name);
653 
654 /** The set of functions required by bluedroid to set wake alarms and
655  * grab wake locks. This struct is passed into the stack through the
656  * |set_os_callouts| function on |bt_interface_t|.
657  */
658 typedef struct {
659   /* set to sizeof(bt_os_callouts_t) */
660   size_t size;
661 
662   acquire_wake_lock_callout acquire_wake_lock;
663   release_wake_lock_callout release_wake_lock;
664 } bt_os_callouts_t;
665 
666 /** NOTE: By default, no profiles are initialized at the time of init/enable.
667  *  Whenever the application invokes the 'init' API of a profile, then one of
668  *  the following shall occur:
669  *
670  *    1.) If Bluetooth is not enabled, then the Bluetooth core shall mark the
671  *        profile as enabled. Subsequently, when the application invokes the
672  *        Bluetooth 'enable', as part of the enable sequence the profile that
673  * were marked shall be enabled by calling appropriate stack APIs. The
674  *        'adapter_properties_cb' shall return the list of UUIDs of the
675  *        enabled profiles.
676  *
677  *    2.) If Bluetooth is enabled, then the Bluetooth core shall invoke the
678  * stack profile API to initialize the profile and trigger a
679  *        'adapter_properties_cb' with the current list of UUIDs including the
680  *        newly added profile's UUID.
681  *
682  *   The reverse shall occur whenever the profile 'cleanup' APIs are invoked
683  */
684 
685 /** Represents the standard Bluetooth DM interface. */
686 typedef struct {
687   /** set to sizeof(bt_interface_t) */
688   size_t size;
689 #ifdef TARGET_FLOSS
690   /** set index of the adapter to use */
691   void (*set_adapter_index)(int adapter_index);
692 #endif
693 
694   /**
695    * Opens the interface and provides the callback routines
696    * to the implementation of this interface.
697    * The |start_restricted| flag inits the adapter in restricted mode. In
698    * restricted mode, bonds that are created are marked as restricted in the
699    * config file. These devices are deleted upon leaving restricted mode.
700    * The |is_common_criteria_mode| flag inits the adapter in common criteria
701    * mode. The |config_compare_result| flag show the config checksum check
702    * result if is in common criteria mode. The |is_atv| flag indicates whether
703    * the local device is an Android TV
704    */
705   int (*init)(bt_callbacks_t* callbacks, bool guest_mode, bool is_common_criteria_mode,
706               int config_compare_result, bool is_atv);
707 
708   /** Enable Bluetooth. */
709   int (*enable)();
710 
711   /** Disable Bluetooth. */
712   int (*disable)(void);
713 
714   /** Closes the interface. */
715   void (*cleanup)(void);
716 
717   /** Start Rust Module */
718   void (*start_rust_module)(void);
719 
720   /** Stop Rust Module */
721   void (*stop_rust_module)(void);
722 
723   /** Get all Bluetooth Adapter properties at init */
724   int (*get_adapter_properties)(void);
725 
726   /** Get Bluetooth Adapter property of 'type' */
727   int (*get_adapter_property)(bt_property_type_t type);
728 
729   void (*set_scan_mode)(bt_scan_mode_t mode);
730 
731   /** Set Bluetooth Adapter property of 'type' */
732   /* Based on the type, val shall be one of
733    * RawAddress or bt_bdname_t etc
734    */
735   int (*set_adapter_property)(const bt_property_t* property);
736 
737   /** Get all Remote Device properties */
738   int (*get_remote_device_properties)(RawAddress* remote_addr);
739 
740   /** Get Remote Device property of 'type' */
741   int (*get_remote_device_property)(RawAddress* remote_addr, bt_property_type_t type);
742 
743   /** Set Remote Device property of 'type' */
744   int (*set_remote_device_property)(RawAddress* remote_addr, const bt_property_t* property);
745 
746   /** Get Remote Device's service record  for the given UUID */
747   int (*get_remote_service_record)(const RawAddress& remote_addr, const bluetooth::Uuid& uuid);
748 
749   /** Start service discovery with transport to get remote services */
750   int (*get_remote_services)(RawAddress* remote_addr, int transport);
751 
752   /** Start Discovery */
753   int (*start_discovery)(void);
754 
755   /** Cancel Discovery */
756   int (*cancel_discovery)(void);
757 
758   /** Create Bluetooth Bonding */
759   int (*create_bond)(const RawAddress* bd_addr, int transport);
760 
761   /** Create Bluetooth Bonding over le transport */
762   int (*create_bond_le)(const RawAddress* bd_addr, uint8_t addr_type);
763 
764   /** Create Bluetooth Bond using out of band data */
765   int (*create_bond_out_of_band)(const RawAddress* bd_addr, int transport,
766                                  const bt_oob_data_t* p192_data, const bt_oob_data_t* p256_data);
767 
768   /** Remove Bond */
769   int (*remove_bond)(const RawAddress* bd_addr);
770 
771   /** Cancel Bond */
772   int (*cancel_bond)(const RawAddress* bd_addr);
773 
774   bool (*pairing_is_busy)();
775 
776   /**
777    * Get the connection status for a given remote device.
778    * return value of 0 means the device is not connected,
779    * non-zero return status indicates an active connection.
780    */
781   int (*get_connection_state)(const RawAddress* bd_addr);
782 
783   /** BT Legacy PinKey Reply */
784   /** If accept==FALSE, then pin_len and pin_code shall be 0x0 */
785   int (*pin_reply)(const RawAddress* bd_addr, uint8_t accept, uint8_t pin_len,
786                    bt_pin_code_t* pin_code);
787 
788   /** BT SSP Reply - Just Works, Numeric Comparison and Passkey
789    * passkey shall be zero for BT_SSP_VARIANT_PASSKEY_COMPARISON &
790    * BT_SSP_VARIANT_CONSENT
791    * For BT_SSP_VARIANT_PASSKEY_ENTRY, if accept==FALSE, then passkey
792    * shall be zero */
793   int (*ssp_reply)(const RawAddress* bd_addr, bt_ssp_variant_t variant, uint8_t accept,
794                    uint32_t passkey);
795 
796   /** Get Bluetooth profile interface */
797   const void* (*get_profile_interface)(const char* profile_id);
798 
799   /** Bluetooth Test Mode APIs - Bluetooth must be enabled for these APIs */
800   /* Configure DUT Mode - Use this mode to enter/exit DUT mode */
801   int (*dut_mode_configure)(uint8_t enable);
802 
803   /* Send any test HCI (vendor-specific) command to the controller. Must be in
804    * DUT Mode */
805   int (*dut_mode_send)(uint16_t opcode, uint8_t* buf, uint8_t len);
806   /** BLE Test Mode APIs */
807   /* opcode MUST be one of: LE_Receiver_Test, LE_Transmitter_Test, LE_Test_End
808    */
809   int (*le_test_mode)(uint16_t opcode, uint8_t* buf, uint8_t len);
810 
811   /** Sets the OS call-out functions that bluedroid needs for alarms and wake
812    * locks. This should be called immediately after a successful |init|.
813    */
814   int (*set_os_callouts)(bt_os_callouts_t* callouts);
815 
816   /** Read Energy info details - return value indicates BT_STATUS_SUCCESS or
817    * BT_STATUS_NOT_READY Success indicates that the VSC command was sent to
818    * controller
819    */
820   int (*read_energy_info)();
821 
822   /**
823    * Native support for dumpsys function
824    * Function is synchronous and |fd| is owned by caller.
825    * |arguments| are arguments which may affect the output, encoded as
826    * UTF-8 strings.
827    */
828   void (*dump)(int fd, const char** arguments);
829 
830   /**
831    * Native support for metrics protobuf dumping. The dumping format will be
832    * raw byte array
833    *
834    * @param output an externally allocated string to dump serialized protobuf
835    */
836   void (*dumpMetrics)(std::string* output);
837 
838   /**
839    * Clear /data/misc/bt_config.conf and erase all stored connections
840    */
841   int (*config_clear)(void);
842 
843   /**
844    * Clear (reset) the dynamic portion of the device interoperability database.
845    */
846   void (*interop_database_clear)(void);
847 
848   /**
849    * Add a new device interoperability workaround for a remote device whose
850    * first |len| bytes of the its device address match |addr|.
851    * NOTE: |feature| has to match an item defined in interop_feature_t
852    * (interop.h).
853    */
854   void (*interop_database_add)(uint16_t feature, const RawAddress* addr, size_t len);
855 
856   /**
857    * Get the AvrcpTarget Service interface to interact with the Avrcp Service
858    */
859   bluetooth::avrcp::ServiceInterface* (*get_avrcp_service)(void);
860 
861   /**
862    * Obfuscate Bluetooth MAC address into a PII free ID string
863    *
864    * @param address Bluetooth MAC address to be obfuscated
865    * @return a string of uint8_t that is unique to this MAC address
866    */
867   std::string (*obfuscate_address)(const RawAddress& address);
868 
869   /**
870    * Get an incremental id for as primary key for Bluetooth metric and log
871    *
872    * @param address Bluetooth MAC address of Bluetooth device
873    * @return int incremental Bluetooth id
874    */
875   int (*get_metric_id)(const RawAddress& address);
876 
877   /**
878    * Set the dynamic audio buffer size to the Controller
879    */
880   int (*set_dynamic_audio_buffer_size)(int codec, int size);
881 
882   /**
883    * Fetches the local Out of Band data.
884    */
885   int (*generate_local_oob_data)(tBT_TRANSPORT transport);
886 
887   /**
888    * Allow or disallow audio low latency
889    *
890    * @param allowed true if allowing audio low latency
891    * @param address Bluetooth MAC address of Bluetooth device
892    * @return true if audio low latency is successfully allowed or disallowed
893    */
894   bool (*allow_low_latency_audio)(bool allowed, const RawAddress& address);
895 
896   /**
897    * Set the event filter for the controller
898    */
899   int (*clear_event_filter)();
900 
901   /**
902    * Call to clear event mask
903    */
904   int (*clear_event_mask)();
905 
906   /**
907    * Call to clear out the filter accept list
908    */
909   int (*clear_filter_accept_list)();
910 
911   /**
912    * Call to disconnect all ACL connections
913    */
914   int (*disconnect_all_acls)();
915 
916   /**
917    * Call to retrieve a generated random
918    */
919   int (*le_rand)();
920 
921   /**
922    *
923    * Floss: Set the event filter to inquiry result device all
924    *
925    */
926   int (*set_event_filter_inquiry_result_all_devices)();
927 
928   /**
929    *
930    * Floss: Set the default event mask for Classic and LE except the given
931    *        values (they will be disabled in the final set mask).
932    *
933    */
934   int (*set_default_event_mask_except)(uint64_t mask, uint64_t le_mask);
935 
936   /**
937    *
938    * Floss: Restore the state of the for the filter accept list
939    *
940    */
941   int (*restore_filter_accept_list)();
942 
943   /**
944    *
945    * Allow the device to be woken by HID devices
946    *
947    */
948   int (*allow_wake_by_hid)();
949 
950   /**
951    *
952    * Tell the controller to allow all devices
953    *
954    */
955   int (*set_event_filter_connection_setup_all_devices)();
956 
957   /**
958    *
959    * Is wbs supported by the controller
960    *
961    */
962   bool (*get_wbs_supported)();
963 
964   /**
965    *
966    * Is swb supported by the controller
967    *
968    */
969   bool (*get_swb_supported)();
970 
971   /**
972    *
973    * Is the specified coding format supported by the adapter
974    *
975    */
976   bool (*is_coding_format_supported)(uint8_t coding_format);
977 
978   /**
979    * Data passed from BluetoothDevice.metadata_changed
980    *
981    * @param remote_bd_addr remote address
982    * @param key Metadata key
983    * @param value Metadata value
984    */
985   void (*metadata_changed)(const RawAddress& remote_bd_addr, int key, std::vector<uint8_t> value);
986 
987   /** interop match address */
988   bool (*interop_match_addr)(const char* feature_name, const RawAddress* addr);
989 
990   /** interop match name */
991   bool (*interop_match_name)(const char* feature_name, const char* name);
992 
993   /** interop match address or name */
994   bool (*interop_match_addr_or_name)(const char* feature_name, const RawAddress* addr);
995 
996   /** add or remove address entry to interop database */
997   void (*interop_database_add_remove_addr)(bool do_add, const char* feature_name,
998                                            const RawAddress* addr, int length);
999 
1000   /** add or remove name entry to interop database */
1001   void (*interop_database_add_remove_name)(bool do_add, const char* feature_name, const char* name);
1002 
1003   /** get remote Pbap PCE  version*/
1004   int (*get_remote_pbap_pce_version)(const RawAddress* bd_addr);
1005 
1006   /** check if pbap pse dynamic version upgrade is enable */
1007   bool (*pbap_pse_dynamic_version_upgrade_is_enabled)();
1008 } bt_interface_t;
1009 
1010 #define BLUETOOTH_INTERFACE_STRING "bluetoothInterface"
1011 
1012 #if __has_include(<bluetooth/log.h>)
1013 #include <bluetooth/log.h>
1014 
1015 namespace std {
1016 template <>
1017 struct formatter<bt_status_t> : enum_formatter<bt_status_t> {};
1018 template <>
1019 struct formatter<bt_scan_mode_t> : enum_formatter<bt_scan_mode_t> {};
1020 template <>
1021 struct formatter<bt_bond_state_t> : enum_formatter<bt_bond_state_t> {};
1022 template <>
1023 struct formatter<bt_property_type_t> : enum_formatter<bt_property_type_t> {};
1024 }  // namespace std
1025 
1026 #endif  // __has_include(<bluetooth/log.h>)
1027 
1028 #endif /* ANDROID_INCLUDE_BLUETOOTH_H */
1029