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