1 //! Anything related to the GATT API (IBluetoothGatt).
2 
3 use btif_macros::{btif_callback, btif_callbacks_dispatcher};
4 
5 use bt_topshim::btif::{
6     BluetoothInterface, BtStatus, BtTransport, DisplayAddress, DisplayUuid, RawAddress, Uuid,
7 };
8 use bt_topshim::profiles::gatt::{
9     AdvertisingStatus, AdvertisingTrackInfo, BtGattDbElement, BtGattNotifyParams, BtGattReadParams,
10     BtGattResponse, BtGattValue, Gatt, GattAdvCallbacksDispatcher,
11     GattAdvInbandCallbacksDispatcher, GattClientCallbacks, GattClientCallbacksDispatcher,
12     GattScannerCallbacks, GattScannerCallbacksDispatcher, GattScannerInbandCallbacks,
13     GattScannerInbandCallbacksDispatcher, GattServerCallbacks, GattServerCallbacksDispatcher,
14     GattStatus, LePhy, MsftAdvMonitor, MsftAdvMonitorAddress, MsftAdvMonitorPattern,
15 };
16 use bt_topshim::sysprop;
17 use bt_utils::adv_parser;
18 use bt_utils::array_utils;
19 
20 use crate::bluetooth::{Bluetooth, BluetoothDevice};
21 use crate::bluetooth_adv::{
22     AdvertiseData, AdvertiseManager, AdvertiserActions, AdvertisingSetParameters,
23     BtifGattAdvCallbacks, IAdvertisingSetCallback, PeriodicAdvertisingParameters,
24 };
25 use crate::callbacks::Callbacks;
26 use crate::{make_message_dispatcher, APIMessage, BluetoothAPI, Message, RPCProxy, SuspendMode};
27 use log::{debug, error, info, warn};
28 use num_derive::{FromPrimitive, ToPrimitive};
29 use num_traits::cast::{FromPrimitive, ToPrimitive};
30 use rand::rngs::SmallRng;
31 use rand::{RngCore, SeedableRng};
32 use std::collections::{HashMap, HashSet, VecDeque};
33 use std::convert::{TryFrom, TryInto};
34 use std::sync::{Arc, Mutex};
35 use tokio::sync::mpsc::Sender;
36 
37 struct Client {
38     id: Option<i32>,
39     cbid: u32,
40     uuid: Uuid,
41     is_congested: bool,
42 
43     // Queued on_characteristic_write callback.
44     congestion_queue: Vec<(RawAddress, GattStatus, i32)>,
45 }
46 
47 struct Connection {
48     conn_id: i32,
49     address: RawAddress,
50 
51     // Connections are made to either a client or server
52     client_id: i32,
53     server_id: i32,
54 }
55 
56 struct ContextMap {
57     // TODO(b/196635530): Consider using `multimap` for a more efficient implementation of get by
58     // multiple keys.
59     callbacks: Callbacks<dyn IBluetoothGattCallback + Send>,
60     clients: Vec<Client>,
61     connections: Vec<Connection>,
62 }
63 
64 type GattClientCallback = Box<dyn IBluetoothGattCallback + Send>;
65 
66 impl ContextMap {
new(tx: Sender<Message>) -> ContextMap67     fn new(tx: Sender<Message>) -> ContextMap {
68         ContextMap {
69             callbacks: Callbacks::new(tx, Message::GattClientCallbackDisconnected),
70             clients: vec![],
71             connections: vec![],
72         }
73     }
74 
get_by_uuid(&self, uuid: &Uuid) -> Option<&Client>75     fn get_by_uuid(&self, uuid: &Uuid) -> Option<&Client> {
76         self.clients.iter().find(|client| client.uuid == *uuid)
77     }
78 
get_by_client_id(&self, client_id: i32) -> Option<&Client>79     fn get_by_client_id(&self, client_id: i32) -> Option<&Client> {
80         self.clients.iter().find(|client| client.id.is_some() && client.id.unwrap() == client_id)
81     }
82 
get_by_client_id_mut(&mut self, client_id: i32) -> Option<&mut Client>83     fn get_by_client_id_mut(&mut self, client_id: i32) -> Option<&mut Client> {
84         self.clients
85             .iter_mut()
86             .find(|client| client.id.is_some() && client.id.unwrap() == client_id)
87     }
88 
get_by_callback_id(&self, callback_id: u32) -> Option<&Client>89     fn get_by_callback_id(&self, callback_id: u32) -> Option<&Client> {
90         self.clients.iter().find(|client| client.cbid == callback_id)
91     }
92 
get_address_by_conn_id(&self, conn_id: i32) -> Option<RawAddress>93     fn get_address_by_conn_id(&self, conn_id: i32) -> Option<RawAddress> {
94         self.connections.iter().find(|conn| conn.conn_id == conn_id).map(|conn| conn.address)
95     }
96 
get_client_by_conn_id(&self, conn_id: i32) -> Option<&Client>97     fn get_client_by_conn_id(&self, conn_id: i32) -> Option<&Client> {
98         match self.connections.iter().find(|conn| conn.conn_id == conn_id) {
99             None => None,
100             Some(conn) => self.get_by_client_id(conn.client_id),
101         }
102     }
103 
get_client_by_conn_id_mut(&mut self, conn_id: i32) -> Option<&mut Client>104     fn get_client_by_conn_id_mut(&mut self, conn_id: i32) -> Option<&mut Client> {
105         let client_id = match self.connections.iter().find(|conn| conn.conn_id == conn_id) {
106             None => return None,
107             Some(conn) => conn.client_id,
108         };
109 
110         self.get_by_client_id_mut(client_id)
111     }
112 
add(&mut self, uuid: &Uuid, callback: GattClientCallback)113     fn add(&mut self, uuid: &Uuid, callback: GattClientCallback) {
114         if self.get_by_uuid(uuid).is_some() {
115             return;
116         }
117 
118         let cbid = self.callbacks.add_callback(callback);
119 
120         self.clients.push(Client {
121             id: None,
122             cbid,
123             uuid: *uuid,
124             is_congested: false,
125             congestion_queue: vec![],
126         });
127     }
128 
remove(&mut self, id: i32)129     fn remove(&mut self, id: i32) {
130         // Remove any callbacks
131         if let Some(c) = self.get_by_client_id(id) {
132             let cbid = c.cbid;
133             self.remove_callback(cbid);
134         }
135 
136         self.clients.retain(|client| !(client.id.is_some() && client.id.unwrap() == id));
137     }
138 
remove_callback(&mut self, callback_id: u32)139     fn remove_callback(&mut self, callback_id: u32) {
140         self.callbacks.remove_callback(callback_id);
141     }
142 
set_client_id(&mut self, uuid: &Uuid, id: i32)143     fn set_client_id(&mut self, uuid: &Uuid, id: i32) {
144         if let Some(client) = self.clients.iter_mut().find(|client| client.uuid == *uuid) {
145             client.id = Some(id);
146         }
147     }
148 
add_connection(&mut self, client_id: i32, conn_id: i32, address: &RawAddress)149     fn add_connection(&mut self, client_id: i32, conn_id: i32, address: &RawAddress) {
150         if self.get_conn_id_from_address(client_id, address).is_some() {
151             return;
152         }
153 
154         self.connections.push(Connection { conn_id, address: *address, client_id, server_id: 0 });
155     }
156 
remove_connection(&mut self, _client_id: i32, conn_id: i32)157     fn remove_connection(&mut self, _client_id: i32, conn_id: i32) {
158         self.connections.retain(|conn| conn.conn_id != conn_id);
159     }
160 
get_conn_id_from_address(&self, client_id: i32, address: &RawAddress) -> Option<i32>161     fn get_conn_id_from_address(&self, client_id: i32, address: &RawAddress) -> Option<i32> {
162         self.connections
163             .iter()
164             .find(|conn| conn.client_id == client_id && conn.address == *address)
165             .map(|conn| conn.conn_id)
166     }
167 
get_client_ids_from_address(&self, address: &RawAddress) -> Vec<i32>168     fn get_client_ids_from_address(&self, address: &RawAddress) -> Vec<i32> {
169         self.connections
170             .iter()
171             .filter(|conn| conn.address == *address)
172             .map(|conn| conn.client_id)
173             .collect()
174     }
175 
get_connected_applications_from_address(&self, address: &RawAddress) -> Vec<Uuid>176     fn get_connected_applications_from_address(&self, address: &RawAddress) -> Vec<Uuid> {
177         self.get_client_ids_from_address(address)
178             .into_iter()
179             .filter_map(|id| self.get_by_client_id(id))
180             .map(|client| client.uuid)
181             .collect()
182     }
183 
get_callback_from_callback_id( &mut self, callback_id: u32, ) -> Option<&mut GattClientCallback>184     fn get_callback_from_callback_id(
185         &mut self,
186         callback_id: u32,
187     ) -> Option<&mut GattClientCallback> {
188         self.callbacks.get_by_id_mut(callback_id)
189     }
190 }
191 
192 struct Server {
193     id: Option<i32>,
194     cbid: u32,
195     uuid: Uuid,
196     services: Vec<BluetoothGattService>,
197     is_congested: bool,
198 
199     // Queued on_notification_sent callback.
200     congestion_queue: Vec<(RawAddress, GattStatus)>,
201 }
202 
203 struct Request {
204     id: i32,
205     handle: i32,
206 }
207 
208 struct ServerContextMap {
209     // TODO(b/196635530): Consider using `multimap` for a more efficient implementation of get by
210     // multiple keys.
211     callbacks: Callbacks<dyn IBluetoothGattServerCallback + Send>,
212     servers: Vec<Server>,
213     connections: Vec<Connection>,
214     requests: Vec<Request>,
215 }
216 
217 type GattServerCallback = Box<dyn IBluetoothGattServerCallback + Send>;
218 
219 impl ServerContextMap {
new(tx: Sender<Message>) -> ServerContextMap220     fn new(tx: Sender<Message>) -> ServerContextMap {
221         ServerContextMap {
222             callbacks: Callbacks::new(tx, Message::GattServerCallbackDisconnected),
223             servers: vec![],
224             connections: vec![],
225             requests: vec![],
226         }
227     }
228 
get_by_uuid(&self, uuid: &Uuid) -> Option<&Server>229     fn get_by_uuid(&self, uuid: &Uuid) -> Option<&Server> {
230         self.servers.iter().find(|server| server.uuid == *uuid)
231     }
232 
get_by_server_id(&self, server_id: i32) -> Option<&Server>233     fn get_by_server_id(&self, server_id: i32) -> Option<&Server> {
234         self.servers.iter().find(|server| server.id.map_or(false, |id| id == server_id))
235     }
236 
get_mut_by_server_id(&mut self, server_id: i32) -> Option<&mut Server>237     fn get_mut_by_server_id(&mut self, server_id: i32) -> Option<&mut Server> {
238         self.servers.iter_mut().find(|server| server.id.map_or(false, |id| id == server_id))
239     }
240 
get_by_callback_id(&self, callback_id: u32) -> Option<&Server>241     fn get_by_callback_id(&self, callback_id: u32) -> Option<&Server> {
242         self.servers.iter().find(|server| server.cbid == callback_id)
243     }
244 
get_by_conn_id(&self, conn_id: i32) -> Option<&Server>245     fn get_by_conn_id(&self, conn_id: i32) -> Option<&Server> {
246         self.connections
247             .iter()
248             .find(|conn| conn.conn_id == conn_id)
249             .and_then(|conn| self.get_by_server_id(conn.server_id))
250     }
251 
get_mut_by_conn_id(&mut self, conn_id: i32) -> Option<&mut Server>252     fn get_mut_by_conn_id(&mut self, conn_id: i32) -> Option<&mut Server> {
253         self.connections
254             .iter()
255             .find_map(|conn| (conn.conn_id == conn_id).then_some(conn.server_id))
256             .and_then(move |server_id| self.get_mut_by_server_id(server_id))
257     }
258 
add(&mut self, uuid: &Uuid, callback: GattServerCallback)259     fn add(&mut self, uuid: &Uuid, callback: GattServerCallback) {
260         if self.get_by_uuid(uuid).is_some() {
261             return;
262         }
263 
264         let cbid = self.callbacks.add_callback(callback);
265 
266         self.servers.push(Server {
267             id: None,
268             cbid,
269             uuid: *uuid,
270             services: vec![],
271             is_congested: false,
272             congestion_queue: vec![],
273         });
274     }
275 
remove(&mut self, id: i32)276     fn remove(&mut self, id: i32) {
277         // Remove any callbacks
278         if let Some(cbid) = self.get_by_server_id(id).map(|server| server.cbid) {
279             self.remove_callback(cbid);
280         }
281 
282         self.servers.retain(|server| !(server.id.is_some() && server.id.unwrap() == id));
283     }
284 
remove_callback(&mut self, callback_id: u32)285     fn remove_callback(&mut self, callback_id: u32) {
286         self.callbacks.remove_callback(callback_id);
287     }
288 
set_server_id(&mut self, uuid: &Uuid, id: i32)289     fn set_server_id(&mut self, uuid: &Uuid, id: i32) {
290         let server = self.servers.iter_mut().find(|server| server.uuid == *uuid);
291         if let Some(s) = server {
292             s.id = Some(id);
293         }
294     }
295 
get_callback_from_callback_id( &mut self, callback_id: u32, ) -> Option<&mut GattServerCallback>296     fn get_callback_from_callback_id(
297         &mut self,
298         callback_id: u32,
299     ) -> Option<&mut GattServerCallback> {
300         self.callbacks.get_by_id_mut(callback_id)
301     }
302 
add_connection(&mut self, server_id: i32, conn_id: i32, address: &RawAddress)303     fn add_connection(&mut self, server_id: i32, conn_id: i32, address: &RawAddress) {
304         if self.get_conn_id_from_address(server_id, address).is_some() {
305             return;
306         }
307 
308         self.connections.push(Connection { conn_id, address: *address, client_id: 0, server_id });
309     }
310 
remove_connection(&mut self, conn_id: i32)311     fn remove_connection(&mut self, conn_id: i32) {
312         self.connections.retain(|conn| conn.conn_id != conn_id);
313     }
314 
get_conn_id_from_address(&self, server_id: i32, address: &RawAddress) -> Option<i32>315     fn get_conn_id_from_address(&self, server_id: i32, address: &RawAddress) -> Option<i32> {
316         return self
317             .connections
318             .iter()
319             .find(|conn| conn.server_id == server_id && conn.address == *address)
320             .map(|conn| conn.conn_id);
321     }
322 
get_server_ids_from_address(&self, address: &RawAddress) -> Vec<i32>323     fn get_server_ids_from_address(&self, address: &RawAddress) -> Vec<i32> {
324         self.connections
325             .iter()
326             .filter(|conn| conn.address == *address)
327             .map(|conn| conn.server_id)
328             .collect()
329     }
330 
get_address_from_conn_id(&self, conn_id: i32) -> Option<RawAddress>331     fn get_address_from_conn_id(&self, conn_id: i32) -> Option<RawAddress> {
332         self.connections.iter().find_map(|conn| (conn.conn_id == conn_id).then_some(conn.address))
333     }
334 
add_service(&mut self, server_id: i32, service: BluetoothGattService)335     fn add_service(&mut self, server_id: i32, service: BluetoothGattService) {
336         if let Some(s) = self.get_mut_by_server_id(server_id) {
337             s.services.push(service)
338         }
339     }
340 
delete_service(&mut self, server_id: i32, handle: i32)341     fn delete_service(&mut self, server_id: i32, handle: i32) {
342         if let Some(s) = self.get_mut_by_server_id(server_id) {
343             s.services.retain(|service| service.instance_id != handle)
344         }
345     }
346 
add_request(&mut self, request_id: i32, handle: i32)347     fn add_request(&mut self, request_id: i32, handle: i32) {
348         self.requests.push(Request { id: request_id, handle });
349     }
350 
_delete_request(&mut self, request_id: i32)351     fn _delete_request(&mut self, request_id: i32) {
352         self.requests.retain(|request| request.id != request_id);
353     }
354 
get_request_handle_from_id(&self, request_id: i32) -> Option<i32>355     fn get_request_handle_from_id(&self, request_id: i32) -> Option<i32> {
356         self.requests
357             .iter()
358             .find_map(|request| (request.id == request_id).then_some(request.handle))
359     }
360 }
361 
362 /// Defines the GATT API.
363 // TODO(242083290): Split out interfaces.
364 pub trait IBluetoothGatt {
365     // Scanning
366 
367     /// Returns whether LE Scan can be performed by hardware offload defined by
368     /// [MSFT HCI Extension](https://learn.microsoft.com/en-us/windows-hardware/drivers/bluetooth/microsoft-defined-bluetooth-hci-commands-and-events).
is_msft_supported(&self) -> bool369     fn is_msft_supported(&self) -> bool;
370 
371     /// Registers an LE scanner callback.
372     ///
373     /// Returns the callback id.
register_scanner_callback(&mut self, callback: Box<dyn IScannerCallback + Send>) -> u32374     fn register_scanner_callback(&mut self, callback: Box<dyn IScannerCallback + Send>) -> u32;
375 
376     /// Unregisters an LE scanner callback identified by the given id.
unregister_scanner_callback(&mut self, callback_id: u32) -> bool377     fn unregister_scanner_callback(&mut self, callback_id: u32) -> bool;
378 
379     /// Registers LE scanner.
380     ///
381     /// `callback_id`: The callback to receive updates about the scanner state.
382     /// Returns the UUID of the registered scanner.
register_scanner(&mut self, callback_id: u32) -> Uuid383     fn register_scanner(&mut self, callback_id: u32) -> Uuid;
384 
385     /// Unregisters an LE scanner identified by the given scanner id.
unregister_scanner(&mut self, scanner_id: u8) -> bool386     fn unregister_scanner(&mut self, scanner_id: u8) -> bool;
387 
388     /// Activate scan of the given scanner id.
start_scan( &mut self, scanner_id: u8, settings: Option<ScanSettings>, filter: Option<ScanFilter>, ) -> BtStatus389     fn start_scan(
390         &mut self,
391         scanner_id: u8,
392         settings: Option<ScanSettings>,
393         filter: Option<ScanFilter>,
394     ) -> BtStatus;
395 
396     /// Deactivate scan of the given scanner id.
stop_scan(&mut self, scanner_id: u8) -> BtStatus397     fn stop_scan(&mut self, scanner_id: u8) -> BtStatus;
398 
399     /// Returns the current suspend mode.
get_scan_suspend_mode(&self) -> SuspendMode400     fn get_scan_suspend_mode(&self) -> SuspendMode;
401 
402     // Advertising
403 
404     /// Registers callback for BLE advertising.
register_advertiser_callback( &mut self, callback: Box<dyn IAdvertisingSetCallback + Send>, ) -> u32405     fn register_advertiser_callback(
406         &mut self,
407         callback: Box<dyn IAdvertisingSetCallback + Send>,
408     ) -> u32;
409 
410     /// Unregisters callback for BLE advertising.
unregister_advertiser_callback(&mut self, callback_id: u32) -> bool411     fn unregister_advertiser_callback(&mut self, callback_id: u32) -> bool;
412 
413     /// Creates a new BLE advertising set and start advertising.
414     ///
415     /// Returns the reg_id for the advertising set, which is used in the callback
416     /// `on_advertising_set_started` to identify the advertising set started.
417     ///
418     /// * `parameters` - Advertising set parameters.
419     /// * `advertise_data` - Advertisement data to be broadcasted.
420     /// * `scan_response` - Scan response.
421     /// * `periodic_parameters` - Periodic advertising parameters. If None, periodic advertising
422     ///     will not be started.
423     /// * `periodic_data` - Periodic advertising data.
424     /// * `duration` - Advertising duration, in 10 ms unit. Valid range is from 1 (10 ms) to
425     ///     65535 (655.35 sec). 0 means no advertising timeout.
426     /// * `max_ext_adv_events` - Maximum number of extended advertising events the controller
427     ///     shall attempt to send before terminating the extended advertising, even if the
428     ///     duration has not expired. Valid range is from 1 to 255. 0 means event count limitation.
429     /// * `callback_id` - Identifies callback registered in register_advertiser_callback.
start_advertising_set( &mut self, parameters: AdvertisingSetParameters, advertise_data: AdvertiseData, scan_response: Option<AdvertiseData>, periodic_parameters: Option<PeriodicAdvertisingParameters>, periodic_data: Option<AdvertiseData>, duration: i32, max_ext_adv_events: i32, callback_id: u32, ) -> i32430     fn start_advertising_set(
431         &mut self,
432         parameters: AdvertisingSetParameters,
433         advertise_data: AdvertiseData,
434         scan_response: Option<AdvertiseData>,
435         periodic_parameters: Option<PeriodicAdvertisingParameters>,
436         periodic_data: Option<AdvertiseData>,
437         duration: i32,
438         max_ext_adv_events: i32,
439         callback_id: u32,
440     ) -> i32;
441 
442     /// Disposes a BLE advertising set.
stop_advertising_set(&mut self, advertiser_id: i32)443     fn stop_advertising_set(&mut self, advertiser_id: i32);
444 
445     /// Queries address associated with the advertising set.
get_own_address(&mut self, advertiser_id: i32)446     fn get_own_address(&mut self, advertiser_id: i32);
447 
448     /// Enables or disables an advertising set.
enable_advertising_set( &mut self, advertiser_id: i32, enable: bool, duration: i32, max_ext_adv_events: i32, )449     fn enable_advertising_set(
450         &mut self,
451         advertiser_id: i32,
452         enable: bool,
453         duration: i32,
454         max_ext_adv_events: i32,
455     );
456 
457     /// Updates advertisement data of the advertising set.
set_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData)458     fn set_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData);
459 
460     /// Set the advertisement data of the advertising set.
set_raw_adv_data(&mut self, advertiser_id: i32, data: Vec<u8>)461     fn set_raw_adv_data(&mut self, advertiser_id: i32, data: Vec<u8>);
462 
463     /// Updates scan response of the advertising set.
set_scan_response_data(&mut self, advertiser_id: i32, data: AdvertiseData)464     fn set_scan_response_data(&mut self, advertiser_id: i32, data: AdvertiseData);
465 
466     /// Updates advertising parameters of the advertising set.
467     ///
468     /// It must be called when advertising is not active.
set_advertising_parameters( &mut self, advertiser_id: i32, parameters: AdvertisingSetParameters, )469     fn set_advertising_parameters(
470         &mut self,
471         advertiser_id: i32,
472         parameters: AdvertisingSetParameters,
473     );
474 
475     /// Updates periodic advertising parameters.
set_periodic_advertising_parameters( &mut self, advertiser_id: i32, parameters: PeriodicAdvertisingParameters, )476     fn set_periodic_advertising_parameters(
477         &mut self,
478         advertiser_id: i32,
479         parameters: PeriodicAdvertisingParameters,
480     );
481 
482     /// Updates periodic advertisement data.
483     ///
484     /// It must be called after `set_periodic_advertising_parameters`, or after
485     /// advertising was started with periodic advertising data set.
set_periodic_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData)486     fn set_periodic_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData);
487 
488     /// Enables or disables periodic advertising.
set_periodic_advertising_enable( &mut self, advertiser_id: i32, enable: bool, include_adi: bool, )489     fn set_periodic_advertising_enable(
490         &mut self,
491         advertiser_id: i32,
492         enable: bool,
493         include_adi: bool,
494     );
495 
496     // GATT Client
497 
498     /// Registers a GATT Client.
register_client( &mut self, app_uuid: String, callback: Box<dyn IBluetoothGattCallback + Send>, eatt_support: bool, )499     fn register_client(
500         &mut self,
501         app_uuid: String,
502         callback: Box<dyn IBluetoothGattCallback + Send>,
503         eatt_support: bool,
504     );
505 
506     /// Unregisters a GATT Client.
unregister_client(&mut self, client_id: i32)507     fn unregister_client(&mut self, client_id: i32);
508 
509     /// Initiates a GATT connection to a peer device.
client_connect( &self, client_id: i32, addr: RawAddress, is_direct: bool, transport: BtTransport, opportunistic: bool, phy: LePhy, )510     fn client_connect(
511         &self,
512         client_id: i32,
513         addr: RawAddress,
514         is_direct: bool,
515         transport: BtTransport,
516         opportunistic: bool,
517         phy: LePhy,
518     );
519 
520     /// Disconnects a GATT connection.
client_disconnect(&self, client_id: i32, addr: RawAddress)521     fn client_disconnect(&self, client_id: i32, addr: RawAddress);
522 
523     /// Clears the attribute cache of a device.
refresh_device(&self, client_id: i32, addr: RawAddress)524     fn refresh_device(&self, client_id: i32, addr: RawAddress);
525 
526     /// Enumerates all GATT services on a connected device.
discover_services(&self, client_id: i32, addr: RawAddress)527     fn discover_services(&self, client_id: i32, addr: RawAddress);
528 
529     /// Discovers all GATT services on a connected device. Only used by PTS.
btif_gattc_discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String)530     fn btif_gattc_discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String);
531 
532     /// Search a GATT service on a connected device based on a UUID.
discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String)533     fn discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String);
534 
535     /// Reads a characteristic on a remote device.
read_characteristic(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32)536     fn read_characteristic(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32);
537 
538     /// Reads a characteristic on a remote device.
read_using_characteristic_uuid( &self, client_id: i32, addr: RawAddress, uuid: String, start_handle: i32, end_handle: i32, auth_req: i32, )539     fn read_using_characteristic_uuid(
540         &self,
541         client_id: i32,
542         addr: RawAddress,
543         uuid: String,
544         start_handle: i32,
545         end_handle: i32,
546         auth_req: i32,
547     );
548 
549     /// Writes a remote characteristic.
write_characteristic( &mut self, client_id: i32, addr: RawAddress, handle: i32, write_type: GattWriteType, auth_req: i32, value: Vec<u8>, ) -> GattWriteRequestStatus550     fn write_characteristic(
551         &mut self,
552         client_id: i32,
553         addr: RawAddress,
554         handle: i32,
555         write_type: GattWriteType,
556         auth_req: i32,
557         value: Vec<u8>,
558     ) -> GattWriteRequestStatus;
559 
560     /// Reads the descriptor for a given characteristic.
read_descriptor(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32)561     fn read_descriptor(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32);
562 
563     /// Writes a remote descriptor for a given characteristic.
write_descriptor( &self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32, value: Vec<u8>, )564     fn write_descriptor(
565         &self,
566         client_id: i32,
567         addr: RawAddress,
568         handle: i32,
569         auth_req: i32,
570         value: Vec<u8>,
571     );
572 
573     /// Registers to receive notifications or indications for a given characteristic.
register_for_notification( &self, client_id: i32, addr: RawAddress, handle: i32, enable: bool, )574     fn register_for_notification(
575         &self,
576         client_id: i32,
577         addr: RawAddress,
578         handle: i32,
579         enable: bool,
580     );
581 
582     /// Begins reliable write.
begin_reliable_write(&mut self, client_id: i32, addr: RawAddress)583     fn begin_reliable_write(&mut self, client_id: i32, addr: RawAddress);
584 
585     /// Ends reliable write.
end_reliable_write(&mut self, client_id: i32, addr: RawAddress, execute: bool)586     fn end_reliable_write(&mut self, client_id: i32, addr: RawAddress, execute: bool);
587 
588     /// Requests RSSI for a given remote device.
read_remote_rssi(&self, client_id: i32, addr: RawAddress)589     fn read_remote_rssi(&self, client_id: i32, addr: RawAddress);
590 
591     /// Configures the MTU of a given connection.
configure_mtu(&self, client_id: i32, addr: RawAddress, mtu: i32)592     fn configure_mtu(&self, client_id: i32, addr: RawAddress, mtu: i32);
593 
594     /// Requests a connection parameter update.
595     /// This causes |on_connection_updated| to be called if there is already an existing
596     /// connection to |addr|; Otherwise the method won't generate any callbacks.
connection_parameter_update( &self, client_id: i32, addr: RawAddress, min_interval: i32, max_interval: i32, latency: i32, timeout: i32, min_ce_len: u16, max_ce_len: u16, )597     fn connection_parameter_update(
598         &self,
599         client_id: i32,
600         addr: RawAddress,
601         min_interval: i32,
602         max_interval: i32,
603         latency: i32,
604         timeout: i32,
605         min_ce_len: u16,
606         max_ce_len: u16,
607     );
608 
609     /// Sets preferred PHY.
client_set_preferred_phy( &self, client_id: i32, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, phy_options: i32, )610     fn client_set_preferred_phy(
611         &self,
612         client_id: i32,
613         addr: RawAddress,
614         tx_phy: LePhy,
615         rx_phy: LePhy,
616         phy_options: i32,
617     );
618 
619     /// Reads the PHY used by a peer.
client_read_phy(&mut self, client_id: i32, addr: RawAddress)620     fn client_read_phy(&mut self, client_id: i32, addr: RawAddress);
621 
622     // GATT Server
623 
624     /// Registers a GATT Server.
register_server( &mut self, app_uuid: String, callback: Box<dyn IBluetoothGattServerCallback + Send>, eatt_support: bool, )625     fn register_server(
626         &mut self,
627         app_uuid: String,
628         callback: Box<dyn IBluetoothGattServerCallback + Send>,
629         eatt_support: bool,
630     );
631 
632     /// Unregisters a GATT Server.
unregister_server(&mut self, server_id: i32)633     fn unregister_server(&mut self, server_id: i32);
634 
635     /// Initiates a GATT connection to the server.
server_connect( &self, server_id: i32, addr: RawAddress, is_direct: bool, transport: BtTransport, ) -> bool636     fn server_connect(
637         &self,
638         server_id: i32,
639         addr: RawAddress,
640         is_direct: bool,
641         transport: BtTransport,
642     ) -> bool;
643 
644     /// Disconnects the server GATT connection.
server_disconnect(&self, server_id: i32, addr: RawAddress) -> bool645     fn server_disconnect(&self, server_id: i32, addr: RawAddress) -> bool;
646 
647     /// Adds a service to the GATT server.
add_service(&self, server_id: i32, service: BluetoothGattService)648     fn add_service(&self, server_id: i32, service: BluetoothGattService);
649 
650     /// Removes a service from the GATT server.
remove_service(&self, server_id: i32, handle: i32)651     fn remove_service(&self, server_id: i32, handle: i32);
652 
653     /// Clears all services from the GATT server.
clear_services(&self, server_id: i32)654     fn clear_services(&self, server_id: i32);
655 
656     /// Sends a response to a read/write operation.
send_response( &self, server_id: i32, addr: RawAddress, request_id: i32, status: GattStatus, offset: i32, value: Vec<u8>, ) -> bool657     fn send_response(
658         &self,
659         server_id: i32,
660         addr: RawAddress,
661         request_id: i32,
662         status: GattStatus,
663         offset: i32,
664         value: Vec<u8>,
665     ) -> bool;
666 
667     /// Sends a notification to a remote device.
send_notification( &self, server_id: i32, addr: RawAddress, handle: i32, confirm: bool, value: Vec<u8>, ) -> bool668     fn send_notification(
669         &self,
670         server_id: i32,
671         addr: RawAddress,
672         handle: i32,
673         confirm: bool,
674         value: Vec<u8>,
675     ) -> bool;
676 
677     /// Sets preferred PHY.
server_set_preferred_phy( &self, server_id: i32, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, phy_options: i32, )678     fn server_set_preferred_phy(
679         &self,
680         server_id: i32,
681         addr: RawAddress,
682         tx_phy: LePhy,
683         rx_phy: LePhy,
684         phy_options: i32,
685     );
686 
687     /// Reads the PHY used by a peer.
server_read_phy(&self, server_id: i32, addr: RawAddress)688     fn server_read_phy(&self, server_id: i32, addr: RawAddress);
689 }
690 
691 #[derive(Debug, Default, Clone)]
692 /// Represents a GATT Descriptor.
693 pub struct BluetoothGattDescriptor {
694     pub uuid: Uuid,
695     pub instance_id: i32,
696     pub permissions: i32,
697 }
698 
699 impl BluetoothGattDescriptor {
new(uuid: Uuid, instance_id: i32, permissions: i32) -> BluetoothGattDescriptor700     pub fn new(uuid: Uuid, instance_id: i32, permissions: i32) -> BluetoothGattDescriptor {
701         BluetoothGattDescriptor { uuid, instance_id, permissions }
702     }
703 }
704 
705 #[derive(Debug, Default, Clone)]
706 /// Represents a GATT Characteristic.
707 pub struct BluetoothGattCharacteristic {
708     pub uuid: Uuid,
709     pub instance_id: i32,
710     pub properties: i32,
711     pub permissions: i32,
712     pub key_size: i32,
713     pub write_type: GattWriteType,
714     pub descriptors: Vec<BluetoothGattDescriptor>,
715 }
716 
717 impl BluetoothGattCharacteristic {
718     // Properties are u8 but i32 in these apis.
719     pub const PROPERTY_BROADCAST: i32 = 1 << 0;
720     pub const PROPERTY_READ: i32 = 1 << 1;
721     pub const PROPERTY_WRITE_NO_RESPONSE: i32 = 1 << 2;
722     pub const PROPERTY_WRITE: i32 = 1 << 3;
723     pub const PROPERTY_NOTIFY: i32 = 1 << 4;
724     pub const PROPERTY_INDICATE: i32 = 1 << 5;
725     pub const PROPERTY_SIGNED_WRITE: i32 = 1 << 6;
726     pub const PROPERTY_EXTENDED_PROPS: i32 = 1 << 7;
727 
728     // Permissions are u16 but i32 in these apis.
729     pub const PERMISSION_READ: i32 = 1 << 0;
730     pub const PERMISSION_READ_ENCRYPTED: i32 = 1 << 1;
731     pub const PERMISSION_READ_ENCRYPED_MITM: i32 = 1 << 2;
732     pub const PERMISSION_WRITE: i32 = 1 << 4;
733     pub const PERMISSION_WRITE_ENCRYPTED: i32 = 1 << 5;
734     pub const PERMISSION_WRITE_ENCRYPTED_MITM: i32 = 1 << 6;
735     pub const PERMISSION_WRITE_SIGNED: i32 = 1 << 7;
736     pub const PERMISSION_WRITE_SIGNED_MITM: i32 = 1 << 8;
737 
new( uuid: Uuid, instance_id: i32, properties: i32, permissions: i32, ) -> BluetoothGattCharacteristic738     pub fn new(
739         uuid: Uuid,
740         instance_id: i32,
741         properties: i32,
742         permissions: i32,
743     ) -> BluetoothGattCharacteristic {
744         BluetoothGattCharacteristic {
745             uuid,
746             instance_id,
747             properties,
748             permissions,
749             write_type: if properties & BluetoothGattCharacteristic::PROPERTY_WRITE_NO_RESPONSE != 0
750             {
751                 GattWriteType::WriteNoRsp
752             } else {
753                 GattWriteType::Write
754             },
755             key_size: 16,
756             descriptors: vec![],
757         }
758     }
759 }
760 
761 #[derive(Debug, Default, Clone)]
762 /// Represents a GATT Service.
763 pub struct BluetoothGattService {
764     pub uuid: Uuid,
765     pub instance_id: i32,
766     pub service_type: i32,
767     pub characteristics: Vec<BluetoothGattCharacteristic>,
768     pub included_services: Vec<BluetoothGattService>,
769 }
770 
771 impl BluetoothGattService {
new(uuid: Uuid, instance_id: i32, service_type: i32) -> BluetoothGattService772     pub fn new(uuid: Uuid, instance_id: i32, service_type: i32) -> BluetoothGattService {
773         BluetoothGattService {
774             uuid,
775             instance_id,
776             service_type,
777             characteristics: vec![],
778             included_services: vec![],
779         }
780     }
781 
from_db( elements: Vec<BtGattDbElement>, with_included_service: bool, ) -> Vec<BluetoothGattService>782     fn from_db(
783         elements: Vec<BtGattDbElement>,
784         with_included_service: bool,
785     ) -> Vec<BluetoothGattService> {
786         let mut db_out: Vec<BluetoothGattService> = vec![];
787 
788         for elem in elements {
789             match GattDbElementType::from_u32(elem.type_).unwrap() {
790                 GattDbElementType::PrimaryService | GattDbElementType::SecondaryService => {
791                     db_out.push(BluetoothGattService::new(
792                         elem.uuid,
793                         elem.attribute_handle as i32,
794                         elem.type_ as i32,
795                     ));
796                     // TODO(b/200065274): Mark restricted services.
797                 }
798 
799                 GattDbElementType::Characteristic => {
800                     match db_out.last_mut() {
801                         Some(s) => s.characteristics.push(BluetoothGattCharacteristic::new(
802                             elem.uuid,
803                             elem.attribute_handle as i32,
804                             elem.properties as i32,
805                             elem.permissions as i32,
806                         )),
807                         None => {
808                             // TODO(b/193685325): Log error.
809                         }
810                     }
811                     // TODO(b/200065274): Mark restricted characteristics.
812                 }
813 
814                 GattDbElementType::Descriptor => {
815                     match db_out.last_mut() {
816                         Some(s) => match s.characteristics.last_mut() {
817                             Some(c) => c.descriptors.push(BluetoothGattDescriptor::new(
818                                 elem.uuid,
819                                 elem.attribute_handle as i32,
820                                 elem.permissions as i32,
821                             )),
822                             None => {
823                                 // TODO(b/193685325): Log error.
824                             }
825                         },
826                         None => {
827                             // TODO(b/193685325): Log error.
828                         }
829                     }
830                     // TODO(b/200065274): Mark restricted descriptors.
831                 }
832 
833                 GattDbElementType::IncludedService => {
834                     if !with_included_service {
835                         continue;
836                     }
837                     match db_out.last_mut() {
838                         Some(s) => {
839                             s.included_services.push(BluetoothGattService::new(
840                                 elem.uuid,
841                                 elem.attribute_handle as i32,
842                                 elem.type_ as i32,
843                             ));
844                         }
845                         None => {
846                             // TODO(b/193685325): Log error.
847                         }
848                     }
849                 }
850             }
851         }
852 
853         db_out
854     }
855 
into_db( service: BluetoothGattService, services: &Vec<BluetoothGattService>, ) -> Vec<BtGattDbElement>856     fn into_db(
857         service: BluetoothGattService,
858         services: &Vec<BluetoothGattService>,
859     ) -> Vec<BtGattDbElement> {
860         let mut db_out: Vec<BtGattDbElement> = vec![];
861         db_out.push(BtGattDbElement {
862             id: service.instance_id as u16,
863             uuid: service.uuid,
864             type_: service.service_type as u32,
865             attribute_handle: service.instance_id as u16,
866             start_handle: service.instance_id as u16,
867             end_handle: 0,
868             properties: 0,
869             extended_properties: 0,
870             permissions: 0,
871         });
872 
873         for char in service.characteristics {
874             db_out.push(BtGattDbElement {
875                 id: char.instance_id as u16,
876                 uuid: char.uuid,
877                 type_: GattDbElementType::Characteristic as u32,
878                 attribute_handle: char.instance_id as u16,
879                 start_handle: 0,
880                 end_handle: 0,
881                 properties: char.properties as u8,
882                 extended_properties: 0,
883                 permissions: (((char.key_size - 7) << 12) + char.permissions) as u16,
884             });
885 
886             for desc in char.descriptors {
887                 db_out.push(BtGattDbElement {
888                     id: desc.instance_id as u16,
889                     uuid: desc.uuid,
890                     type_: GattDbElementType::Descriptor as u32,
891                     attribute_handle: desc.instance_id as u16,
892                     start_handle: 0,
893                     end_handle: 0,
894                     properties: 0,
895                     extended_properties: 0,
896                     permissions: (((char.key_size - 7) << 12) + desc.permissions) as u16,
897                 });
898             }
899         }
900 
901         for included_service in service.included_services {
902             if !services.iter().any(|s| {
903                 s.instance_id == included_service.instance_id && s.uuid == included_service.uuid
904             }) {
905                 log::error!(
906                     "Included service with uuid {} not found",
907                     DisplayUuid(&included_service.uuid)
908                 );
909                 continue;
910             }
911 
912             db_out.push(BtGattDbElement {
913                 id: included_service.instance_id as u16,
914                 uuid: included_service.uuid,
915                 type_: included_service.service_type as u32,
916                 attribute_handle: included_service.instance_id as u16,
917                 start_handle: 0,
918                 end_handle: 0,
919                 properties: 0,
920                 extended_properties: 0,
921                 permissions: 0,
922             });
923         }
924 
925         // Set end handle of primary/secondary attribute to last element's handle
926         if let Some(elem) = db_out.last() {
927             db_out[0].end_handle = elem.attribute_handle;
928         }
929 
930         db_out
931     }
932 }
933 
934 /// Callback for GATT Client API.
935 pub trait IBluetoothGattCallback: RPCProxy {
936     /// When the `register_client` request is done.
on_client_registered(&mut self, _status: GattStatus, _client_id: i32)937     fn on_client_registered(&mut self, _status: GattStatus, _client_id: i32);
938 
939     /// When there is a change in the state of a GATT client connection.
on_client_connection_state( &mut self, _status: GattStatus, _client_id: i32, _connected: bool, _addr: RawAddress, )940     fn on_client_connection_state(
941         &mut self,
942         _status: GattStatus,
943         _client_id: i32,
944         _connected: bool,
945         _addr: RawAddress,
946     );
947 
948     /// When there is a change of PHY.
on_phy_update( &mut self, _addr: RawAddress, _tx_phy: LePhy, _rx_phy: LePhy, _status: GattStatus, )949     fn on_phy_update(
950         &mut self,
951         _addr: RawAddress,
952         _tx_phy: LePhy,
953         _rx_phy: LePhy,
954         _status: GattStatus,
955     );
956 
957     /// The completion of IBluetoothGatt::read_phy.
on_phy_read( &mut self, _addr: RawAddress, _tx_phy: LePhy, _rx_phy: LePhy, _status: GattStatus, )958     fn on_phy_read(
959         &mut self,
960         _addr: RawAddress,
961         _tx_phy: LePhy,
962         _rx_phy: LePhy,
963         _status: GattStatus,
964     );
965 
966     /// When GATT db is available.
on_search_complete( &mut self, _addr: RawAddress, _services: Vec<BluetoothGattService>, _status: GattStatus, )967     fn on_search_complete(
968         &mut self,
969         _addr: RawAddress,
970         _services: Vec<BluetoothGattService>,
971         _status: GattStatus,
972     );
973 
974     /// The completion of IBluetoothGatt::read_characteristic.
on_characteristic_read( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, _value: Vec<u8>, )975     fn on_characteristic_read(
976         &mut self,
977         _addr: RawAddress,
978         _status: GattStatus,
979         _handle: i32,
980         _value: Vec<u8>,
981     );
982 
983     /// The completion of IBluetoothGatt::write_characteristic.
on_characteristic_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32)984     fn on_characteristic_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32);
985 
986     /// When a reliable write is completed.
on_execute_write(&mut self, _addr: RawAddress, _status: GattStatus)987     fn on_execute_write(&mut self, _addr: RawAddress, _status: GattStatus);
988 
989     /// The completion of IBluetoothGatt::read_descriptor.
on_descriptor_read( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, _value: Vec<u8>, )990     fn on_descriptor_read(
991         &mut self,
992         _addr: RawAddress,
993         _status: GattStatus,
994         _handle: i32,
995         _value: Vec<u8>,
996     );
997 
998     /// The completion of IBluetoothGatt::write_descriptor.
on_descriptor_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32)999     fn on_descriptor_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32);
1000 
1001     /// When notification or indication is received.
on_notify(&mut self, _addr: RawAddress, _handle: i32, _value: Vec<u8>)1002     fn on_notify(&mut self, _addr: RawAddress, _handle: i32, _value: Vec<u8>);
1003 
1004     /// The completion of IBluetoothGatt::read_remote_rssi.
on_read_remote_rssi(&mut self, _addr: RawAddress, _rssi: i32, _status: GattStatus)1005     fn on_read_remote_rssi(&mut self, _addr: RawAddress, _rssi: i32, _status: GattStatus);
1006 
1007     /// The completion of IBluetoothGatt::configure_mtu.
on_configure_mtu(&mut self, _addr: RawAddress, _mtu: i32, _status: GattStatus)1008     fn on_configure_mtu(&mut self, _addr: RawAddress, _mtu: i32, _status: GattStatus);
1009 
1010     /// When a connection parameter changes.
on_connection_updated( &mut self, _addr: RawAddress, _interval: i32, _latency: i32, _timeout: i32, _status: GattStatus, )1011     fn on_connection_updated(
1012         &mut self,
1013         _addr: RawAddress,
1014         _interval: i32,
1015         _latency: i32,
1016         _timeout: i32,
1017         _status: GattStatus,
1018     );
1019 
1020     /// When there is an addition, removal, or change of a GATT service.
on_service_changed(&mut self, _addr: RawAddress)1021     fn on_service_changed(&mut self, _addr: RawAddress);
1022 }
1023 
1024 /// Callback for GATT Server API.
1025 pub trait IBluetoothGattServerCallback: RPCProxy {
1026     /// When the `register_server` request is done.
on_server_registered(&mut self, _status: GattStatus, _server_id: i32)1027     fn on_server_registered(&mut self, _status: GattStatus, _server_id: i32);
1028 
1029     /// When there is a change in the state of a GATT server connection.
on_server_connection_state(&mut self, _server_id: i32, _connected: bool, _addr: RawAddress)1030     fn on_server_connection_state(&mut self, _server_id: i32, _connected: bool, _addr: RawAddress);
1031 
1032     /// When there is a service added to the GATT server.
on_service_added(&mut self, _status: GattStatus, _service: BluetoothGattService)1033     fn on_service_added(&mut self, _status: GattStatus, _service: BluetoothGattService);
1034 
1035     /// When a service has been removed from the GATT server.
on_service_removed(&mut self, status: GattStatus, handle: i32)1036     fn on_service_removed(&mut self, status: GattStatus, handle: i32);
1037 
1038     /// When a remote device has requested to read a characteristic.
on_characteristic_read_request( &mut self, _addr: RawAddress, _trans_id: i32, _offset: i32, _is_long: bool, _handle: i32, )1039     fn on_characteristic_read_request(
1040         &mut self,
1041         _addr: RawAddress,
1042         _trans_id: i32,
1043         _offset: i32,
1044         _is_long: bool,
1045         _handle: i32,
1046     );
1047 
1048     /// When a remote device has requested to read a descriptor.
on_descriptor_read_request( &mut self, _addr: RawAddress, _trans_id: i32, _offset: i32, _is_long: bool, _handle: i32, )1049     fn on_descriptor_read_request(
1050         &mut self,
1051         _addr: RawAddress,
1052         _trans_id: i32,
1053         _offset: i32,
1054         _is_long: bool,
1055         _handle: i32,
1056     );
1057 
1058     /// When a remote device has requested to write to a characteristic.
on_characteristic_write_request( &mut self, _addr: RawAddress, _trans_id: i32, _offset: i32, _len: i32, _is_prep: bool, _need_rsp: bool, _handle: i32, _value: Vec<u8>, )1059     fn on_characteristic_write_request(
1060         &mut self,
1061         _addr: RawAddress,
1062         _trans_id: i32,
1063         _offset: i32,
1064         _len: i32,
1065         _is_prep: bool,
1066         _need_rsp: bool,
1067         _handle: i32,
1068         _value: Vec<u8>,
1069     );
1070 
1071     /// When a remote device has requested to write to a descriptor.
on_descriptor_write_request( &mut self, _addr: RawAddress, _trans_id: i32, _offset: i32, _len: i32, _is_prep: bool, _need_rsp: bool, _handle: i32, _value: Vec<u8>, )1072     fn on_descriptor_write_request(
1073         &mut self,
1074         _addr: RawAddress,
1075         _trans_id: i32,
1076         _offset: i32,
1077         _len: i32,
1078         _is_prep: bool,
1079         _need_rsp: bool,
1080         _handle: i32,
1081         _value: Vec<u8>,
1082     );
1083 
1084     /// When a previously prepared write is to be executed.
on_execute_write(&mut self, _addr: RawAddress, _trans_id: i32, _exec_write: bool)1085     fn on_execute_write(&mut self, _addr: RawAddress, _trans_id: i32, _exec_write: bool);
1086 
1087     /// When a notification or indication has been sent to a remote device.
on_notification_sent(&mut self, _addr: RawAddress, _status: GattStatus)1088     fn on_notification_sent(&mut self, _addr: RawAddress, _status: GattStatus);
1089 
1090     /// When the MTU for a given connection changes
on_mtu_changed(&mut self, addr: RawAddress, mtu: i32)1091     fn on_mtu_changed(&mut self, addr: RawAddress, mtu: i32);
1092 
1093     /// When there is a change of PHY.
on_phy_update(&mut self, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, status: GattStatus)1094     fn on_phy_update(&mut self, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, status: GattStatus);
1095 
1096     /// The completion of IBluetoothGatt::server_read_phy.
on_phy_read(&mut self, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, status: GattStatus)1097     fn on_phy_read(&mut self, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, status: GattStatus);
1098 
1099     /// When the connection parameters for a given connection changes.
on_connection_updated( &mut self, addr: RawAddress, interval: i32, latency: i32, timeout: i32, status: GattStatus, )1100     fn on_connection_updated(
1101         &mut self,
1102         addr: RawAddress,
1103         interval: i32,
1104         latency: i32,
1105         timeout: i32,
1106         status: GattStatus,
1107     );
1108 
1109     /// When the subrate change event for a given connection is received.
on_subrate_change( &mut self, addr: RawAddress, subrate_factor: i32, latency: i32, cont_num: i32, timeout: i32, status: GattStatus, )1110     fn on_subrate_change(
1111         &mut self,
1112         addr: RawAddress,
1113         subrate_factor: i32,
1114         latency: i32,
1115         cont_num: i32,
1116         timeout: i32,
1117         status: GattStatus,
1118     );
1119 }
1120 
1121 /// Interface for scanner callbacks to clients, passed to
1122 /// `IBluetoothGatt::register_scanner_callback`.
1123 pub trait IScannerCallback: RPCProxy {
1124     /// When the `register_scanner` request is done.
on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus)1125     fn on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus);
1126 
1127     /// When an LE advertisement matching aggregate filters is detected. This callback is shared
1128     /// among all scanner callbacks and is triggered for *every* advertisement that the controller
1129     /// receives. For listening to the beginning and end of a specific scanner's advertisements
1130     /// detected while in RSSI range, use on_advertisement_found and on_advertisement_lost below.
on_scan_result(&mut self, scan_result: ScanResult)1131     fn on_scan_result(&mut self, scan_result: ScanResult);
1132 
1133     /// When an LE advertisement matching aggregate filters is found. The criteria of
1134     /// how a device is considered found is specified by ScanFilter.
on_advertisement_found(&mut self, scanner_id: u8, scan_result: ScanResult)1135     fn on_advertisement_found(&mut self, scanner_id: u8, scan_result: ScanResult);
1136 
1137     /// When an LE advertisement matching aggregate filters is no longer detected. The criteria of
1138     /// how a device is considered lost is specified by ScanFilter.
1139     // TODO(b/269343922): Rename this to on_advertisement_lost for symmetry with
1140     // on_advertisement_found.
on_advertisement_lost(&mut self, scanner_id: u8, scan_result: ScanResult)1141     fn on_advertisement_lost(&mut self, scanner_id: u8, scan_result: ScanResult);
1142 
1143     /// When LE Scan module changes suspend mode due to system suspend/resume.
on_suspend_mode_change(&mut self, suspend_mode: SuspendMode)1144     fn on_suspend_mode_change(&mut self, suspend_mode: SuspendMode);
1145 }
1146 
1147 #[derive(Debug, FromPrimitive, ToPrimitive)]
1148 #[repr(u8)]
1149 /// GATT write type.
1150 pub enum GattDbElementType {
1151     PrimaryService = 0,
1152     SecondaryService = 1,
1153     IncludedService = 2,
1154     Characteristic = 3,
1155     Descriptor = 4,
1156 }
1157 
1158 impl From<GattDbElementType> for i32 {
from(val: GattDbElementType) -> Self1159     fn from(val: GattDbElementType) -> Self {
1160         val.to_u8().unwrap_or(0).into()
1161     }
1162 }
1163 
1164 #[derive(Debug, Default, FromPrimitive, ToPrimitive, Copy, Clone)]
1165 #[repr(u8)]
1166 /// GATT write type.
1167 pub enum GattWriteType {
1168     Invalid = 0,
1169     WriteNoRsp = 1,
1170     #[default]
1171     Write = 2,
1172     WritePrepare = 3,
1173 }
1174 
1175 #[derive(Debug, Default, FromPrimitive, ToPrimitive, Clone, PartialEq)]
1176 #[repr(u32)]
1177 /// Scan type configuration.
1178 pub enum ScanType {
1179     #[default]
1180     Active = 0,
1181     Passive = 1,
1182 }
1183 
1184 /// Represents scanning configurations to be passed to `IBluetoothGatt::start_scan`.
1185 ///
1186 /// This configuration is general and supported on all Bluetooth hardware, irrelevant of the
1187 /// hardware filter offload (APCF or MSFT).
1188 #[derive(Debug, Clone)]
1189 pub struct ScanSettings {
1190     pub interval: i32,
1191     pub window: i32,
1192     pub scan_type: ScanType,
1193 }
1194 
1195 impl ScanSettings {
extract_scan_parameters(&self) -> Option<(u8, u16, u16)>1196     fn extract_scan_parameters(&self) -> Option<(u8, u16, u16)> {
1197         let scan_type = match self.scan_type {
1198             ScanType::Passive => 0x00,
1199             ScanType::Active => 0x01,
1200         };
1201         let interval = match u16::try_from(self.interval) {
1202             Ok(i) => i,
1203             Err(e) => {
1204                 println!("Invalid scan interval {}: {}", self.interval, e);
1205                 return None;
1206             }
1207         };
1208         let window = match u16::try_from(self.window) {
1209             Ok(w) => w,
1210             Err(e) => {
1211                 println!("Invalid scan window {}: {}", self.window, e);
1212                 return None;
1213             }
1214         };
1215         Some((scan_type, interval, window))
1216     }
1217 }
1218 
1219 /// Represents scan result
1220 #[derive(Debug)]
1221 pub struct ScanResult {
1222     pub name: String,
1223     pub address: RawAddress,
1224     pub addr_type: u8,
1225     pub event_type: u16,
1226     pub primary_phy: u8,
1227     pub secondary_phy: u8,
1228     pub advertising_sid: u8,
1229     pub tx_power: i8,
1230     pub rssi: i8,
1231     pub periodic_adv_int: u16,
1232     pub flags: u8,
1233     pub service_uuids: Vec<Uuid>,
1234     /// A map of 128-bit UUID and its corresponding service data.
1235     pub service_data: HashMap<String, Vec<u8>>,
1236     pub manufacturer_data: HashMap<u16, Vec<u8>>,
1237     pub adv_data: Vec<u8>,
1238 }
1239 
1240 #[derive(Debug, Clone)]
1241 pub struct ScanFilterPattern {
1242     /// Specifies the starting byte position of the pattern immediately following AD Type.
1243     pub start_position: u8,
1244 
1245     /// Advertising Data type (https://www.bluetooth.com/specifications/assigned-numbers/).
1246     pub ad_type: u8,
1247 
1248     /// The pattern to be matched for the specified AD Type within the advertisement packet from
1249     /// the specified starting byte.
1250     pub content: Vec<u8>,
1251 }
1252 
1253 #[derive(Debug, Clone)]
1254 pub struct ScanFilterAddress {
1255     pub addr_type: u8,
1256     pub bd_addr: RawAddress,
1257 }
1258 
1259 #[derive(Debug, Clone)]
1260 #[repr(u8)]
1261 pub enum ScanFilterConditionType {
1262     /// [MSFT HCI Extension](https://learn.microsoft.com/en-us/windows-hardware/drivers/bluetooth/microsoft-defined-bluetooth-hci-commands-and-events).
1263     MsftConditionTypeAll = 0x0,
1264     MsftConditionTypePatterns = 0x1,
1265     MsftConditionTypeUuid = 0x2,
1266     MsftConditionTypeIrkResolution = 0x3,
1267     MsftConditionTypeAddress = 0x4,
1268 }
1269 
1270 /// Represents the condition for matching advertisements.
1271 ///
1272 /// Only pattern-based matching is implemented.
1273 #[derive(Debug, Clone)]
1274 pub enum ScanFilterCondition {
1275     /// All advertisements are matched.
1276     All,
1277 
1278     /// Match by pattern anywhere in the advertisement data. Multiple patterns are "OR"-ed.
1279     Patterns(Vec<ScanFilterPattern>),
1280 
1281     /// Match by UUID (not implemented).
1282     Uuid,
1283 
1284     /// Match if the IRK resolves an advertisement (not implemented).
1285     Irk,
1286 
1287     /// Match by Bluetooth address (not implemented).
1288     BluetoothAddress(ScanFilterAddress),
1289 }
1290 
1291 /// Represents a scan filter to be passed to `IBluetoothGatt::start_scan`.
1292 ///
1293 /// This filter is intentionally modelled close to the MSFT hardware offload filter.
1294 /// Reference:
1295 /// https://learn.microsoft.com/en-us/windows-hardware/drivers/bluetooth/microsoft-defined-bluetooth-hci-commands-and-events
1296 #[derive(Debug, Clone)]
1297 pub struct ScanFilter {
1298     /// Advertisements with RSSI above or equal this value is considered "found".
1299     pub rssi_high_threshold: u8,
1300 
1301     /// Advertisements with RSSI below or equal this value (for a period of rssi_low_timeout) is
1302     /// considered "lost".
1303     pub rssi_low_threshold: u8,
1304 
1305     /// The time in seconds over which the RSSI value should be below rssi_low_threshold before
1306     /// being considered "lost".
1307     pub rssi_low_timeout: u8,
1308 
1309     /// The sampling interval in milliseconds.
1310     pub rssi_sampling_period: u8,
1311 
1312     /// The condition to match advertisements with.
1313     pub condition: ScanFilterCondition,
1314 }
1315 
1316 pub enum GattActions {
1317     /// Used when we need to invoke an update in this layer e.g. when there's no active connection,
1318     /// where LibBluetooth accepts the conn_parameter_update call but won't send out a callback.
1319     /// Params: client_id, address, interval, latency, timeout, status
1320     InvokeConnectionUpdated(i32, RawAddress, i32, i32, i32, GattStatus),
1321     /// This disconnects all server and client connections to the device.
1322     /// Params: remote_device
1323     Disconnect(BluetoothDevice),
1324 }
1325 
1326 enum MsftCommandQueue {
1327     Add(u8, ScanFilter), // (scanner_id, new_monitor)
1328     Remove(u8),          // (monitor_handle)
1329 }
1330 
1331 #[derive(Debug)]
1332 enum MsftCommandPending {
1333     NoPending,
1334     Aborted(u8, ScanFilter), // The pending command is an |Add| and it must be remove.
1335     Add(u8, ScanFilter),     // (scanner_id, new_monitor)
1336     Remove(u8),              // (monitor_handle)
1337     Enable(bool),            // (enabled)
1338 }
1339 
1340 #[derive(PartialEq)]
1341 enum ControllerScanType {
1342     NotScanning,
1343     ActiveScan,
1344     PassiveScan,
1345 }
1346 
1347 /// Implementation of the GATT API (IBluetoothGatt).
1348 pub struct BluetoothGatt {
1349     gatt: Arc<Mutex<Gatt>>,
1350     tx: Sender<Message>,
1351 
1352     context_map: ContextMap,
1353     server_context_map: ServerContextMap,
1354     reliable_queue: HashSet<RawAddress>,
1355     write_characteristic_permits: HashMap<RawAddress, Option<i32>>,
1356     scanner_callbacks: Callbacks<dyn IScannerCallback + Send>,
1357     scanners: HashMap<Uuid, ScannerInfo>,
1358 
1359     // Bookmarking the controller state could help avoid the redundant calls and error logs.
1360     controller_scan_type: ControllerScanType, // The controller LE scan type.
1361     msft_enabled: bool,                       // The controller MSFT state.
1362 
1363     // The MSFT commands that need to be dispatched by |msft_run_queue_and_update_scan|.
1364     // After the queue is emptied, |msft_run_queue_and_update_scan| would take care of the MSFT
1365     // enable state, standard LE scan enable state, and standard LE scan parameters.
1366     msft_command_queue: VecDeque<MsftCommandQueue>,
1367     // The MSFT command that LibBluetooth is currently processing.
1368     // This is only set by |msft_run_queue_and_update_scan| and reset by the MSFT callback handlers.
1369     msft_command_pending: MsftCommandPending,
1370 
1371     scan_suspend_mode: SuspendMode,
1372     adv_manager: AdvertiseManager,
1373 
1374     // Used for generating random UUIDs. SmallRng is chosen because it is fast, don't use this for
1375     // cryptography.
1376     small_rng: SmallRng,
1377 
1378     enabled: bool,
1379 }
1380 
1381 impl BluetoothGatt {
1382     /// Constructs a new IBluetoothGatt implementation.
new(intf: Arc<Mutex<BluetoothInterface>>, tx: Sender<Message>) -> BluetoothGatt1383     pub fn new(intf: Arc<Mutex<BluetoothInterface>>, tx: Sender<Message>) -> BluetoothGatt {
1384         BluetoothGatt {
1385             gatt: Arc::new(Mutex::new(Gatt::new(&intf.lock().unwrap()))),
1386             tx: tx.clone(),
1387             context_map: ContextMap::new(tx.clone()),
1388             server_context_map: ServerContextMap::new(tx.clone()),
1389             reliable_queue: HashSet::new(),
1390             write_characteristic_permits: HashMap::new(),
1391             scanner_callbacks: Callbacks::new(tx.clone(), Message::ScannerCallbackDisconnected),
1392             scanners: HashMap::new(),
1393             controller_scan_type: ControllerScanType::NotScanning,
1394             msft_enabled: false,
1395             msft_command_queue: VecDeque::new(),
1396             msft_command_pending: MsftCommandPending::NoPending,
1397             scan_suspend_mode: SuspendMode::Normal,
1398             small_rng: SmallRng::from_entropy(),
1399             adv_manager: AdvertiseManager::new(tx.clone()),
1400             enabled: false,
1401         }
1402     }
1403 
init_profiles(&mut self, api_tx: Sender<APIMessage>)1404     pub fn init_profiles(&mut self, api_tx: Sender<APIMessage>) {
1405         let gatt_client_callbacks_dispatcher = GattClientCallbacksDispatcher {
1406             dispatch: make_message_dispatcher(self.tx.clone(), Message::GattClient),
1407         };
1408         let gatt_server_callbacks_dispatcher = GattServerCallbacksDispatcher {
1409             dispatch: make_message_dispatcher(self.tx.clone(), Message::GattServer),
1410         };
1411         let gatt_scanner_callbacks_dispatcher = GattScannerCallbacksDispatcher {
1412             dispatch: make_message_dispatcher(self.tx.clone(), Message::LeScanner),
1413         };
1414         let gatt_scanner_inband_callbacks_dispatcher = GattScannerInbandCallbacksDispatcher {
1415             dispatch: make_message_dispatcher(self.tx.clone(), Message::LeScannerInband),
1416         };
1417         let gatt_adv_inband_callbacks_dispatcher = GattAdvInbandCallbacksDispatcher {
1418             dispatch: make_message_dispatcher(self.tx.clone(), Message::LeAdvInband),
1419         };
1420         let gatt_adv_callbacks_dispatcher = GattAdvCallbacksDispatcher {
1421             dispatch: make_message_dispatcher(self.tx.clone(), Message::LeAdv),
1422         };
1423 
1424         self.gatt.lock().unwrap().initialize(
1425             gatt_client_callbacks_dispatcher,
1426             gatt_server_callbacks_dispatcher,
1427             gatt_scanner_callbacks_dispatcher,
1428             gatt_scanner_inband_callbacks_dispatcher,
1429             gatt_adv_inband_callbacks_dispatcher,
1430             gatt_adv_callbacks_dispatcher,
1431         );
1432 
1433         tokio::spawn(async move {
1434             let _ = api_tx.send(APIMessage::IsReady(BluetoothAPI::Gatt)).await;
1435         });
1436     }
1437 
1438     /// Initializes the AdvertiseManager
1439     /// This needs to be called after Bluetooth is ready because we need to query LE features.
init_adv_manager(&mut self, adapter: Arc<Mutex<Box<Bluetooth>>>)1440     pub(crate) fn init_adv_manager(&mut self, adapter: Arc<Mutex<Box<Bluetooth>>>) {
1441         self.adv_manager.initialize(self.gatt.clone(), adapter);
1442     }
1443 
enable(&mut self, enabled: bool)1444     pub fn enable(&mut self, enabled: bool) {
1445         self.enabled = enabled;
1446     }
1447 
1448     /// Remove a scanner callback and unregisters all scanners associated with that callback.
remove_scanner_callback(&mut self, callback_id: u32) -> bool1449     pub fn remove_scanner_callback(&mut self, callback_id: u32) -> bool {
1450         let affected_scanner_ids: Vec<u8> = self
1451             .scanners
1452             .iter()
1453             .filter(|(_uuid, scanner)| scanner.callback_id == callback_id)
1454             .filter_map(|(_uuid, scanner)| scanner.scanner_id)
1455             .collect();
1456 
1457         // All scanners associated with the callback must be also unregistered.
1458         for scanner_id in affected_scanner_ids {
1459             self.unregister_scanner(scanner_id);
1460         }
1461 
1462         self.scanner_callbacks.remove_callback(callback_id)
1463     }
1464 
1465     /// Set the suspend mode.
set_scan_suspend_mode(&mut self, suspend_mode: SuspendMode)1466     pub fn set_scan_suspend_mode(&mut self, suspend_mode: SuspendMode) {
1467         if suspend_mode != self.scan_suspend_mode {
1468             self.scan_suspend_mode = suspend_mode.clone();
1469 
1470             // Notify current suspend mode to all active callbacks.
1471             self.scanner_callbacks.for_all_callbacks(|callback| {
1472                 callback.on_suspend_mode_change(suspend_mode.clone());
1473             });
1474         }
1475     }
1476 
1477     /// Enters suspend mode for LE Scan.
1478     ///
1479     /// This "pauses" all operations managed by this module to prepare for system suspend. A
1480     /// callback is triggered to let clients know that this module is in suspend mode and some
1481     /// subsequent API calls will be blocked in this mode.
scan_enter_suspend(&mut self) -> BtStatus1482     pub fn scan_enter_suspend(&mut self) -> BtStatus {
1483         if self.get_scan_suspend_mode() != SuspendMode::Normal {
1484             return BtStatus::Busy;
1485         }
1486         self.set_scan_suspend_mode(SuspendMode::Suspending);
1487 
1488         let scanners_to_suspend = self
1489             .scanners
1490             .iter()
1491             .filter_map(
1492                 |(_uuid, scanner)| if scanner.is_enabled { scanner.scanner_id } else { None },
1493             )
1494             .collect::<Vec<_>>();
1495         // Note: We can't simply disable the LE scanning. When a filter is offloaded
1496         // with the MSFT extension and it is monitoring a device, it sends a
1497         // `Monitor Device Event` to indicate that monitoring is stopped and this
1498         // can cause an early wake-up. Until we fix the disable + mask solution, we
1499         // must remove all monitors before suspend and re-monitor them on resume.
1500         for scanner_id in scanners_to_suspend {
1501             self.stop_scan(scanner_id);
1502             if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
1503                 scanner.is_suspended = true;
1504             }
1505         }
1506         self.set_scan_suspend_mode(SuspendMode::Suspended);
1507         BtStatus::Success
1508     }
1509 
1510     /// Exits suspend mode for LE Scan.
1511     ///
1512     /// To be called after system resume/wake up. This "unpauses" the operations that were "paused"
1513     /// due to suspend. A callback is triggered to let clients when this module has exited suspend
1514     /// mode.
scan_exit_suspend(&mut self) -> BtStatus1515     pub fn scan_exit_suspend(&mut self) -> BtStatus {
1516         if self.get_scan_suspend_mode() != SuspendMode::Suspended {
1517             return BtStatus::Busy;
1518         }
1519         self.set_scan_suspend_mode(SuspendMode::Resuming);
1520 
1521         let gatt = &mut self.gatt;
1522         self.scanners.retain(|_uuid, scanner| {
1523             if let (true, Some(scanner_id)) = (scanner.is_unregistered, scanner.scanner_id) {
1524                 gatt.lock().unwrap().scanner.unregister(scanner_id);
1525             }
1526             !scanner.is_unregistered
1527         });
1528 
1529         let scanners_to_resume = self
1530             .scanners
1531             .iter()
1532             .filter_map(
1533                 |(_uuid, scanner)| if scanner.is_suspended { scanner.scanner_id } else { None },
1534             )
1535             .collect::<Vec<_>>();
1536         for scanner_id in scanners_to_resume {
1537             let status = self.resume_scan(scanner_id);
1538             if status != BtStatus::Success {
1539                 error!("Failed to resume scanner {}, status={:?}", scanner_id, status);
1540             }
1541             if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
1542                 scanner.is_suspended = false;
1543             }
1544         }
1545 
1546         self.set_scan_suspend_mode(SuspendMode::Normal);
1547 
1548         BtStatus::Success
1549     }
1550 
find_scanner_by_id(&mut self, scanner_id: u8) -> Option<&mut ScannerInfo>1551     fn find_scanner_by_id(&mut self, scanner_id: u8) -> Option<&mut ScannerInfo> {
1552         self.scanners.values_mut().find(|scanner| scanner.scanner_id == Some(scanner_id))
1553     }
1554 
1555     /// Updates the scan state depending on the states of registered scanners:
1556     /// 1. Scan is started if there is at least 1 enabled scanner.
1557     /// 2. If there is an enabled ScanType::Active scanner, prefer its scan settings.
1558     ///    Otherwise, adopt the settings from any of the enabled scanners.
update_scan(&mut self, force_restart: bool)1559     fn update_scan(&mut self, force_restart: bool) {
1560         let mut new_controller_scan_type = ControllerScanType::NotScanning;
1561         let mut enabled_scanner_id = None;
1562         let mut enabled_scan_param = None;
1563         for scanner in self.scanners.values() {
1564             if !scanner.is_enabled {
1565                 continue;
1566             }
1567             new_controller_scan_type = ControllerScanType::PassiveScan;
1568             if let Some(ss) = &scanner.scan_settings {
1569                 enabled_scanner_id = scanner.scanner_id;
1570                 enabled_scan_param = ss.extract_scan_parameters();
1571                 if ss.scan_type == ScanType::Active {
1572                     new_controller_scan_type = ControllerScanType::ActiveScan;
1573                     break;
1574                 }
1575             }
1576         }
1577 
1578         if new_controller_scan_type == self.controller_scan_type && !force_restart {
1579             return;
1580         }
1581         // The scan type changed. We should either stop or restart.
1582 
1583         // First, stop if we are currently scanning.
1584         if self.controller_scan_type != ControllerScanType::NotScanning {
1585             self.gatt.lock().unwrap().scanner.stop_scan();
1586         }
1587 
1588         self.controller_scan_type = new_controller_scan_type;
1589         // If new state is not to scan, then we're done.
1590         if self.controller_scan_type == ControllerScanType::NotScanning {
1591             return;
1592         }
1593 
1594         // Update parameters and start scan.
1595         if let (Some(scanner_id), Some((scan_type, scan_interval, scan_window))) =
1596             (enabled_scanner_id, enabled_scan_param)
1597         {
1598             self.gatt.lock().unwrap().scanner.set_scan_parameters(
1599                 scanner_id,
1600                 scan_type,
1601                 scan_interval,
1602                 scan_window,
1603                 1,
1604             );
1605         } else {
1606             error!("Starting scan without settings");
1607         }
1608         self.gatt.lock().unwrap().scanner.start_scan();
1609     }
1610 
1611     /// Consumes the MSFT command queue and updates scan at the end.
1612     ///
1613     /// "Update scan" includes:
1614     /// 1. Configure the MSFT enable state
1615     /// 2. Configure the standard scan parameter and enable state
1616     ///    - Note that the scan filter policy is automatically selected by LibBluetooth based on the
1617     ///      MSFT enable state. In Rust layer we only need to restart scan. See:
1618     ///      system/main/shim/le_scanning_manager.cc BleScannerInterfaceImpl::OnMsftAdvMonitorEnable
msft_run_queue_and_update_scan(&mut self)1619     fn msft_run_queue_and_update_scan(&mut self) {
1620         match &self.msft_command_pending {
1621             &MsftCommandPending::NoPending => {}
1622             _ => {
1623                 // If there's already a pending command then just return and wait. After the pending
1624                 // command is done, the MSFT callbacks would reset |self.msft_command_pending| and
1625                 // call this.
1626                 return;
1627             }
1628         }
1629         match self.msft_command_queue.pop_front() {
1630             None => {
1631                 // The queue is emptied. Configure the MSFT enable and update scan.
1632                 let has_enabled_scanner = self.scanners.values().any(|s| s.is_enabled);
1633                 let has_enabled_unfiltered_scanner =
1634                     self.scanners.values().any(|s| s.is_enabled && s.filter.is_none());
1635                 let should_enable_msft = has_enabled_scanner && !has_enabled_unfiltered_scanner;
1636                 if should_enable_msft != self.msft_enabled {
1637                     self.gatt.lock().unwrap().scanner.msft_adv_monitor_enable(should_enable_msft);
1638                     self.msft_command_pending = MsftCommandPending::Enable(should_enable_msft);
1639                     // The standard scan will be force updated in MsftAdvMonitorEnableCallback.
1640                 } else {
1641                     self.update_scan(false); // No need to force restart as MSFT is unchanged.
1642                 }
1643             }
1644             Some(MsftCommandQueue::Add(scanner_id, monitor)) => {
1645                 self.gatt.lock().unwrap().scanner.msft_adv_monitor_add(&(&monitor).into());
1646                 self.msft_command_pending = MsftCommandPending::Add(scanner_id, monitor);
1647             }
1648             Some(MsftCommandQueue::Remove(monitor_handle)) => {
1649                 self.gatt.lock().unwrap().scanner.msft_adv_monitor_remove(monitor_handle);
1650                 self.msft_command_pending = MsftCommandPending::Remove(monitor_handle);
1651             }
1652         }
1653     }
1654 
msft_abort_add_commands_by_scanner_id(&mut self, scanner_id: u8)1655     fn msft_abort_add_commands_by_scanner_id(&mut self, scanner_id: u8) {
1656         // For the commands that have not yet dispatched to LibBluetooth, simply remove.
1657         self.msft_command_queue.retain(|cmd| {
1658             if let MsftCommandQueue::Add(id, _) = cmd {
1659                 if scanner_id == *id {
1660                     return false;
1661                 }
1662             }
1663             true
1664         });
1665         // If the pending command matches the target scanner ID, set Abort flag.
1666         if let MsftCommandPending::Add(id, monitor) = &self.msft_command_pending {
1667             if scanner_id == *id {
1668                 self.msft_command_pending = MsftCommandPending::Aborted(*id, monitor.clone());
1669             }
1670         }
1671     }
1672 
msft_drain_all_handles_by_scanner_id(&mut self, scanner_id: u8) -> Vec<u8>1673     fn msft_drain_all_handles_by_scanner_id(&mut self, scanner_id: u8) -> Vec<u8> {
1674         let mut handles: Vec<u8> = vec![];
1675         if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
1676             if let Some(handle) = scanner.monitor_handle.take() {
1677                 handles.push(handle);
1678             }
1679             for (_addr, handle) in scanner.addr_handle_map.drain() {
1680                 if let Some(h) = handle {
1681                     handles.push(h);
1682                 }
1683             }
1684         } else {
1685             warn!("msft_drain_all_handles_by_scanner_id: Scanner {} not found", scanner_id);
1686         }
1687         handles
1688     }
1689 
1690     /// The resume_scan method is used to resume scanning after system suspension.
1691     /// It assumes that scanner.filter has already had the filter data.
resume_scan(&mut self, scanner_id: u8) -> BtStatus1692     fn resume_scan(&mut self, scanner_id: u8) -> BtStatus {
1693         if !self.enabled {
1694             return BtStatus::UnexpectedState;
1695         }
1696 
1697         if self.get_scan_suspend_mode() != SuspendMode::Resuming {
1698             return BtStatus::Busy;
1699         }
1700 
1701         let filter = {
1702             if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
1703                 if scanner.is_suspended {
1704                     scanner.is_suspended = false;
1705                     scanner.is_enabled = true;
1706                     // When a scanner resumes from a suspended state, the
1707                     // scanner.filter has already had the filter data.
1708                     scanner.filter.clone()
1709                 } else {
1710                     warn!("This Scanner {} is supposed to resume from suspended state", scanner_id);
1711                     return BtStatus::UnexpectedState;
1712                 }
1713             } else {
1714                 warn!("Scanner {} not found", scanner_id);
1715                 return BtStatus::Fail;
1716             }
1717         };
1718 
1719         if self.is_msft_supported() {
1720             if let Some(filter) = filter {
1721                 self.msft_command_queue.push_back(MsftCommandQueue::Add(scanner_id, filter));
1722             }
1723             self.msft_run_queue_and_update_scan();
1724         } else {
1725             self.update_scan(false); // No need to force restart as MSFT is not supported.
1726         }
1727         BtStatus::Success
1728     }
1729 
on_address_monitor_added( &mut self, scanner_id: u8, monitor_handle: u8, scan_filter: &ScanFilter, )1730     fn on_address_monitor_added(
1731         &mut self,
1732         scanner_id: u8,
1733         monitor_handle: u8,
1734         scan_filter: &ScanFilter,
1735     ) {
1736         if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
1737             // After hci complete event is received, update the monitor_handle.
1738             // The address monitor handles are needed in stop_scan().
1739             let addr_info: MsftAdvMonitorAddress = (&scan_filter.condition).into();
1740 
1741             if let std::collections::hash_map::Entry::Occupied(mut e) =
1742                 scanner.addr_handle_map.entry(addr_info.bd_addr)
1743             {
1744                 e.insert(Some(monitor_handle));
1745                 debug!(
1746                     "Added adv addr monitor {} and updated bd_addr={} to addr filter map",
1747                     monitor_handle,
1748                     DisplayAddress(&addr_info.bd_addr)
1749                 );
1750                 return;
1751             } else {
1752                 error!(
1753                     "on_child_monitor_added: bd_addr {} has been removed, removing the addr monitor {}.",
1754                     DisplayAddress(&addr_info.bd_addr),
1755                     monitor_handle
1756                 );
1757             }
1758         } else {
1759             error!(
1760                 "on_child_monitor_added: scanner has been removed, removing the addr monitor {}",
1761                 monitor_handle
1762             );
1763         }
1764         self.msft_command_queue.push_back(MsftCommandQueue::Remove(monitor_handle));
1765     }
1766 
on_pattern_monitor_added(&mut self, scanner_id: u8, monitor_handle: u8)1767     fn on_pattern_monitor_added(&mut self, scanner_id: u8, monitor_handle: u8) {
1768         if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
1769             debug!("Added adv pattern monitor handle = {}", monitor_handle);
1770             scanner.monitor_handle = Some(monitor_handle);
1771         } else {
1772             error!(
1773                 "on_pattern_monitor_added: scanner has been removed, removing the addr monitor {}",
1774                 monitor_handle
1775             );
1776             self.msft_command_queue.push_back(MsftCommandQueue::Remove(monitor_handle));
1777         }
1778     }
1779 
1780     /// Remove an adv_manager callback and unregisters all advertising sets associated with that callback.
remove_adv_callback(&mut self, callback_id: u32) -> bool1781     pub fn remove_adv_callback(&mut self, callback_id: u32) -> bool {
1782         self.adv_manager.get_impl().unregister_callback(callback_id)
1783     }
1784 
remove_client_callback(&mut self, callback_id: u32)1785     pub fn remove_client_callback(&mut self, callback_id: u32) {
1786         // Unregister client if client id exists.
1787         if let Some(client) = self.context_map.get_by_callback_id(callback_id) {
1788             if let Some(id) = client.id {
1789                 self.unregister_client(id);
1790             }
1791         }
1792 
1793         // Always remove callback.
1794         self.context_map.remove_callback(callback_id);
1795     }
1796 
remove_server_callback(&mut self, callback_id: u32)1797     pub fn remove_server_callback(&mut self, callback_id: u32) {
1798         // Unregister server if server id exists.
1799         if let Some(server) = self.server_context_map.get_by_callback_id(callback_id) {
1800             if let Some(id) = server.id {
1801                 self.unregister_server(id);
1802             }
1803         }
1804 
1805         // Always remove callback.
1806         self.context_map.remove_callback(callback_id);
1807     }
1808 
1809     /// Enters suspend mode for LE advertising.
advertising_enter_suspend(&mut self)1810     pub fn advertising_enter_suspend(&mut self) {
1811         self.adv_manager.get_impl().enter_suspend()
1812     }
1813 
1814     /// Exits suspend mode for LE advertising.
advertising_exit_suspend(&mut self)1815     pub fn advertising_exit_suspend(&mut self) {
1816         self.adv_manager.get_impl().exit_suspend()
1817     }
1818 
1819     /// Start an active scan on given scanner id. This will look up and assign
1820     /// the correct ScanSettings for it as well.
start_active_scan(&mut self, scanner_id: u8) -> BtStatus1821     pub(crate) fn start_active_scan(&mut self, scanner_id: u8) -> BtStatus {
1822         let settings = ScanSettings {
1823             interval: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanInterval),
1824             window: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanWindow),
1825             scan_type: ScanType::Active,
1826         };
1827 
1828         self.start_scan(scanner_id, Some(settings), /*filter=*/ None)
1829     }
1830 
stop_active_scan(&mut self, scanner_id: u8) -> BtStatus1831     pub(crate) fn stop_active_scan(&mut self, scanner_id: u8) -> BtStatus {
1832         self.stop_scan(scanner_id)
1833     }
1834 
handle_action(&mut self, action: GattActions)1835     pub fn handle_action(&mut self, action: GattActions) {
1836         match action {
1837             GattActions::InvokeConnectionUpdated(
1838                 client_id,
1839                 addr,
1840                 interval,
1841                 latency,
1842                 timeout,
1843                 status,
1844             ) => {
1845                 if let Some(client) = self.context_map.get_by_client_id(client_id) {
1846                     if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
1847                         cb.on_connection_updated(addr, interval, latency, timeout, status);
1848                     }
1849                 }
1850             }
1851             GattActions::Disconnect(device) => {
1852                 for client_id in self.context_map.get_client_ids_from_address(&device.address) {
1853                     if let Some(conn_id) =
1854                         self.context_map.get_conn_id_from_address(client_id, &device.address)
1855                     {
1856                         self.gatt.lock().unwrap().client.disconnect(
1857                             client_id,
1858                             &device.address,
1859                             conn_id,
1860                         );
1861                     }
1862                 }
1863                 for server_id in
1864                     self.server_context_map.get_server_ids_from_address(&device.address)
1865                 {
1866                     if let Some(conn_id) =
1867                         self.server_context_map.get_conn_id_from_address(server_id, &device.address)
1868                     {
1869                         self.gatt.lock().unwrap().server.disconnect(
1870                             server_id,
1871                             &device.address,
1872                             conn_id,
1873                         );
1874                     }
1875                 }
1876             }
1877         }
1878     }
1879 
handle_adv_action(&mut self, action: AdvertiserActions)1880     pub fn handle_adv_action(&mut self, action: AdvertiserActions) {
1881         self.adv_manager.get_impl().handle_action(action);
1882     }
1883 
get_connected_applications(&self, device_address: &RawAddress) -> Vec<Uuid>1884     pub(crate) fn get_connected_applications(&self, device_address: &RawAddress) -> Vec<Uuid> {
1885         self.context_map.get_connected_applications_from_address(device_address)
1886     }
1887 }
1888 
1889 #[derive(Debug, FromPrimitive, ToPrimitive)]
1890 #[repr(u8)]
1891 /// Status of WriteCharacteristic methods.
1892 pub enum GattWriteRequestStatus {
1893     Success = 0,
1894     Fail = 1,
1895     Busy = 2,
1896 }
1897 
1898 // This structure keeps track of the lifecycle of a scanner.
1899 #[derive(Debug)]
1900 struct ScannerInfo {
1901     // The callback to which events about this scanner needs to be sent to.
1902     // Another purpose of keeping track of the callback id is that when a callback is disconnected
1903     // or unregistered we need to also unregister all scanners associated with that callback to
1904     // prevent dangling unowned scanners.
1905     callback_id: u32,
1906     // If the scanner is registered successfully, this contains the scanner id, otherwise None.
1907     scanner_id: Option<u8>,
1908     // If one of scanners is enabled, we scan.
1909     is_enabled: bool,
1910     // Scan filter.
1911     filter: Option<ScanFilter>,
1912     // Adv monitor handle, if exists.
1913     monitor_handle: Option<u8>,
1914     // If suspended then we need to resume it on exit_suspend.
1915     is_suspended: bool,
1916     /// Whether the unregistration of the scanner is held.
1917     /// This flag is set when a scanner is unregistered while we're not able to do it, such as:
1918     /// - The system is suspending / suspended
1919     ///
1920     /// The scanner would be unregistered after the system exits the suspended state.
1921     is_unregistered: bool,
1922     // The scan parameters to use
1923     scan_settings: Option<ScanSettings>,
1924     // Whether the MSFT extension monitor tracking by address filter quirk will be used.
1925     addr_tracking_quirk: bool,
1926     // Stores all the monitored handles for pattern and address.
1927     addr_handle_map: HashMap<RawAddress, Option<u8>>,
1928 }
1929 
1930 impl ScannerInfo {
new(callback_id: u32) -> Self1931     fn new(callback_id: u32) -> Self {
1932         Self {
1933             callback_id,
1934             scanner_id: None,
1935             is_enabled: false,
1936             filter: None,
1937             monitor_handle: None,
1938             is_suspended: false,
1939             is_unregistered: false,
1940             scan_settings: None,
1941             addr_tracking_quirk: sysprop::get_bool(sysprop::PropertyBool::LeAdvMonRtlQuirk),
1942             addr_handle_map: HashMap::new(),
1943         }
1944     }
1945 }
1946 
1947 impl From<&ScanFilterPattern> for MsftAdvMonitorPattern {
from(val: &ScanFilterPattern) -> Self1948     fn from(val: &ScanFilterPattern) -> Self {
1949         MsftAdvMonitorPattern {
1950             ad_type: val.ad_type,
1951             start_byte: val.start_position,
1952             pattern: val.content.clone(),
1953         }
1954     }
1955 }
1956 
1957 impl From<&ScanFilterCondition> for Vec<MsftAdvMonitorPattern> {
from(val: &ScanFilterCondition) -> Self1958     fn from(val: &ScanFilterCondition) -> Self {
1959         match val {
1960             ScanFilterCondition::Patterns(patterns) => {
1961                 patterns.iter().map(|pattern| pattern.into()).collect()
1962             }
1963             _ => vec![],
1964         }
1965     }
1966 }
1967 
1968 impl From<&ScanFilterAddress> for MsftAdvMonitorAddress {
from(val: &ScanFilterAddress) -> Self1969     fn from(val: &ScanFilterAddress) -> Self {
1970         MsftAdvMonitorAddress { addr_type: val.addr_type, bd_addr: val.bd_addr }
1971     }
1972 }
1973 
1974 impl From<&ScanFilterCondition> for MsftAdvMonitorAddress {
from(val: &ScanFilterCondition) -> Self1975     fn from(val: &ScanFilterCondition) -> Self {
1976         match &val {
1977             ScanFilterCondition::BluetoothAddress(addr_info) => addr_info.into(),
1978             _ => MsftAdvMonitorAddress { addr_type: 0, bd_addr: RawAddress::empty() },
1979         }
1980     }
1981 }
1982 
1983 impl From<&ScanFilter> for MsftAdvMonitor {
from(val: &ScanFilter) -> Self1984     fn from(val: &ScanFilter) -> Self {
1985         let scan_filter_condition_type = match val.condition {
1986             ScanFilterCondition::Patterns(_) => {
1987                 ScanFilterConditionType::MsftConditionTypePatterns as u8
1988             }
1989             ScanFilterCondition::BluetoothAddress(_) => {
1990                 ScanFilterConditionType::MsftConditionTypeAddress as u8
1991             }
1992             _ => ScanFilterConditionType::MsftConditionTypeAll as u8,
1993         };
1994         MsftAdvMonitor {
1995             rssi_high_threshold: val.rssi_high_threshold.try_into().unwrap(),
1996             rssi_low_threshold: val.rssi_low_threshold.try_into().unwrap(),
1997             rssi_low_timeout: val.rssi_low_timeout.try_into().unwrap(),
1998             rssi_sampling_period: val.rssi_sampling_period.try_into().unwrap(),
1999             condition_type: scan_filter_condition_type,
2000             patterns: (&val.condition).into(),
2001             addr_info: (&val.condition).into(),
2002         }
2003     }
2004 }
2005 
2006 impl IBluetoothGatt for BluetoothGatt {
is_msft_supported(&self) -> bool2007     fn is_msft_supported(&self) -> bool {
2008         self.gatt.lock().unwrap().scanner.is_msft_supported()
2009     }
2010 
register_scanner_callback(&mut self, callback: Box<dyn IScannerCallback + Send>) -> u322011     fn register_scanner_callback(&mut self, callback: Box<dyn IScannerCallback + Send>) -> u32 {
2012         self.scanner_callbacks.add_callback(callback)
2013     }
2014 
unregister_scanner_callback(&mut self, callback_id: u32) -> bool2015     fn unregister_scanner_callback(&mut self, callback_id: u32) -> bool {
2016         self.remove_scanner_callback(callback_id)
2017     }
2018 
register_scanner(&mut self, callback_id: u32) -> Uuid2019     fn register_scanner(&mut self, callback_id: u32) -> Uuid {
2020         if !self.enabled {
2021             return Uuid::empty();
2022         }
2023 
2024         let mut bytes: [u8; 16] = [0; 16];
2025         self.small_rng.fill_bytes(&mut bytes);
2026         let uuid = Uuid::from(bytes);
2027 
2028         self.scanners.insert(uuid, ScannerInfo::new(callback_id));
2029 
2030         // libbluetooth's register_scanner takes a UUID of the scanning application. This UUID does
2031         // not correspond to higher level concept of "application" so we use random UUID that
2032         // functions as a unique identifier of the scanner.
2033         self.gatt.lock().unwrap().scanner.register_scanner(uuid);
2034 
2035         uuid
2036     }
2037 
unregister_scanner(&mut self, scanner_id: u8) -> bool2038     fn unregister_scanner(&mut self, scanner_id: u8) -> bool {
2039         if self.get_scan_suspend_mode() != SuspendMode::Normal {
2040             if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
2041                 info!("Deferred scanner unregistration due to suspending");
2042                 scanner.is_unregistered = true;
2043                 return true;
2044             } else {
2045                 warn!("Scanner {} not found", scanner_id);
2046                 return false;
2047             }
2048         }
2049 
2050         self.gatt.lock().unwrap().scanner.unregister(scanner_id);
2051 
2052         // The unregistered scanner must also be stopped.
2053         self.stop_scan(scanner_id);
2054 
2055         self.scanners.retain(|_uuid, scanner| scanner.scanner_id != Some(scanner_id));
2056 
2057         true
2058     }
2059 
start_scan( &mut self, scanner_id: u8, settings: Option<ScanSettings>, filter: Option<ScanFilter>, ) -> BtStatus2060     fn start_scan(
2061         &mut self,
2062         scanner_id: u8,
2063         settings: Option<ScanSettings>,
2064         filter: Option<ScanFilter>,
2065     ) -> BtStatus {
2066         if !self.enabled {
2067             return BtStatus::UnexpectedState;
2068         }
2069 
2070         if self.get_scan_suspend_mode() != SuspendMode::Normal {
2071             return BtStatus::Busy;
2072         }
2073 
2074         // If the client is not specifying scan settings, the default one will be used.
2075         let settings = settings.unwrap_or_else(|| {
2076             // Offloaded filtering + Active scan doesn't work correctly on some QCA chips - It
2077             // behaves like "Filter policy: Accept all advertisement" and impacts the power
2078             // consumption. Thus, we by default select Passive scan if the quirk is on and the
2079             // filter is set.
2080             // OTOH the clients are still allowed to explicitly set the scan type Active, so in case
2081             // the scan response data is necessary this quirk will not cause any functionality
2082             // breakage.
2083             let scan_type =
2084                 if sysprop::get_bool(sysprop::PropertyBool::LeAdvMonQcaQuirk) && filter.is_some() {
2085                     ScanType::Passive
2086                 } else {
2087                     ScanType::default()
2088                 };
2089             ScanSettings {
2090                 interval: sysprop::get_i32(sysprop::PropertyI32::LeAdvMonScanInterval),
2091                 window: sysprop::get_i32(sysprop::PropertyI32::LeAdvMonScanWindow),
2092                 scan_type,
2093             }
2094         });
2095 
2096         // Multiplexing scanners happens at this layer. The implementations of start_scan
2097         // and stop_scan maintains the state of all registered scanners and based on the states
2098         // update the scanning and/or filter states of libbluetooth.
2099         if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
2100             scanner.is_enabled = true;
2101             scanner.filter = filter.clone();
2102             scanner.scan_settings = Some(settings);
2103         } else {
2104             warn!("start_scan: Scanner {} not found", scanner_id);
2105             return BtStatus::Fail;
2106         }
2107 
2108         if self.is_msft_supported() {
2109             // Remove all pending filters
2110             self.msft_abort_add_commands_by_scanner_id(scanner_id);
2111             // Remove all existing filters
2112             for handle in self.msft_drain_all_handles_by_scanner_id(scanner_id).into_iter() {
2113                 self.msft_command_queue.push_back(MsftCommandQueue::Remove(handle));
2114             }
2115             // Add the new filter
2116             if let Some(filter) = filter {
2117                 self.msft_command_queue.push_back(MsftCommandQueue::Add(scanner_id, filter));
2118             }
2119             self.msft_run_queue_and_update_scan();
2120         } else {
2121             self.update_scan(false); // No need to force restart as MSFT is not supported.
2122         }
2123         BtStatus::Success
2124     }
2125 
stop_scan(&mut self, scanner_id: u8) -> BtStatus2126     fn stop_scan(&mut self, scanner_id: u8) -> BtStatus {
2127         if !self.enabled {
2128             return BtStatus::UnexpectedState;
2129         }
2130 
2131         let scan_suspend_mode = self.get_scan_suspend_mode();
2132         if scan_suspend_mode != SuspendMode::Normal && scan_suspend_mode != SuspendMode::Suspending
2133         {
2134             return BtStatus::Busy;
2135         }
2136 
2137         if let Some(scanner) = self.find_scanner_by_id(scanner_id) {
2138             scanner.is_enabled = false;
2139         } else {
2140             warn!("stop_scan: Scanner {} not found", scanner_id);
2141             // Clients can assume success of the removal since the scanner does not exist.
2142             return BtStatus::Success;
2143         }
2144 
2145         if self.is_msft_supported() {
2146             // Remove all pending filters
2147             self.msft_abort_add_commands_by_scanner_id(scanner_id);
2148             // Remove all existing filters
2149             for handle in self.msft_drain_all_handles_by_scanner_id(scanner_id).into_iter() {
2150                 self.msft_command_queue.push_back(MsftCommandQueue::Remove(handle));
2151             }
2152             self.msft_run_queue_and_update_scan();
2153         } else {
2154             self.update_scan(false); // No need to force restart as MSFT is not supported.
2155         }
2156 
2157         BtStatus::Success
2158     }
2159 
get_scan_suspend_mode(&self) -> SuspendMode2160     fn get_scan_suspend_mode(&self) -> SuspendMode {
2161         self.scan_suspend_mode.clone()
2162     }
2163 
2164     // Advertising
2165 
register_advertiser_callback( &mut self, callback: Box<dyn IAdvertisingSetCallback + Send>, ) -> u322166     fn register_advertiser_callback(
2167         &mut self,
2168         callback: Box<dyn IAdvertisingSetCallback + Send>,
2169     ) -> u32 {
2170         self.adv_manager.get_impl().register_callback(callback)
2171     }
2172 
unregister_advertiser_callback(&mut self, callback_id: u32) -> bool2173     fn unregister_advertiser_callback(&mut self, callback_id: u32) -> bool {
2174         self.adv_manager.get_impl().unregister_callback(callback_id)
2175     }
2176 
start_advertising_set( &mut self, parameters: AdvertisingSetParameters, advertise_data: AdvertiseData, scan_response: Option<AdvertiseData>, periodic_parameters: Option<PeriodicAdvertisingParameters>, periodic_data: Option<AdvertiseData>, duration: i32, max_ext_adv_events: i32, callback_id: u32, ) -> i322177     fn start_advertising_set(
2178         &mut self,
2179         parameters: AdvertisingSetParameters,
2180         advertise_data: AdvertiseData,
2181         scan_response: Option<AdvertiseData>,
2182         periodic_parameters: Option<PeriodicAdvertisingParameters>,
2183         periodic_data: Option<AdvertiseData>,
2184         duration: i32,
2185         max_ext_adv_events: i32,
2186         callback_id: u32,
2187     ) -> i32 {
2188         self.adv_manager.get_impl().start_advertising_set(
2189             parameters,
2190             advertise_data,
2191             scan_response,
2192             periodic_parameters,
2193             periodic_data,
2194             duration,
2195             max_ext_adv_events,
2196             callback_id,
2197         )
2198     }
2199 
stop_advertising_set(&mut self, advertiser_id: i32)2200     fn stop_advertising_set(&mut self, advertiser_id: i32) {
2201         self.adv_manager.get_impl().stop_advertising_set(advertiser_id)
2202     }
2203 
get_own_address(&mut self, advertiser_id: i32)2204     fn get_own_address(&mut self, advertiser_id: i32) {
2205         self.adv_manager.get_impl().get_own_address(advertiser_id);
2206     }
2207 
enable_advertising_set( &mut self, advertiser_id: i32, enable: bool, duration: i32, max_ext_adv_events: i32, )2208     fn enable_advertising_set(
2209         &mut self,
2210         advertiser_id: i32,
2211         enable: bool,
2212         duration: i32,
2213         max_ext_adv_events: i32,
2214     ) {
2215         self.adv_manager.get_impl().enable_advertising_set(
2216             advertiser_id,
2217             enable,
2218             duration,
2219             max_ext_adv_events,
2220         );
2221     }
2222 
set_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData)2223     fn set_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData) {
2224         self.adv_manager.get_impl().set_advertising_data(advertiser_id, data);
2225     }
2226 
set_raw_adv_data(&mut self, advertiser_id: i32, data: Vec<u8>)2227     fn set_raw_adv_data(&mut self, advertiser_id: i32, data: Vec<u8>) {
2228         self.adv_manager.get_impl().set_raw_adv_data(advertiser_id, data);
2229     }
2230 
set_scan_response_data(&mut self, advertiser_id: i32, data: AdvertiseData)2231     fn set_scan_response_data(&mut self, advertiser_id: i32, data: AdvertiseData) {
2232         self.adv_manager.get_impl().set_scan_response_data(advertiser_id, data);
2233     }
2234 
set_advertising_parameters( &mut self, advertiser_id: i32, parameters: AdvertisingSetParameters, )2235     fn set_advertising_parameters(
2236         &mut self,
2237         advertiser_id: i32,
2238         parameters: AdvertisingSetParameters,
2239     ) {
2240         self.adv_manager.get_impl().set_advertising_parameters(advertiser_id, parameters);
2241     }
2242 
set_periodic_advertising_parameters( &mut self, advertiser_id: i32, parameters: PeriodicAdvertisingParameters, )2243     fn set_periodic_advertising_parameters(
2244         &mut self,
2245         advertiser_id: i32,
2246         parameters: PeriodicAdvertisingParameters,
2247     ) {
2248         self.adv_manager.get_impl().set_periodic_advertising_parameters(advertiser_id, parameters);
2249     }
2250 
set_periodic_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData)2251     fn set_periodic_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData) {
2252         self.adv_manager.get_impl().set_periodic_advertising_data(advertiser_id, data);
2253     }
2254 
set_periodic_advertising_enable( &mut self, advertiser_id: i32, enable: bool, include_adi: bool, )2255     fn set_periodic_advertising_enable(
2256         &mut self,
2257         advertiser_id: i32,
2258         enable: bool,
2259         include_adi: bool,
2260     ) {
2261         self.adv_manager.get_impl().set_periodic_advertising_enable(
2262             advertiser_id,
2263             enable,
2264             include_adi,
2265         );
2266     }
2267 
2268     // GATT Client
2269 
register_client( &mut self, app_uuid: String, callback: Box<dyn IBluetoothGattCallback + Send>, eatt_support: bool, )2270     fn register_client(
2271         &mut self,
2272         app_uuid: String,
2273         callback: Box<dyn IBluetoothGattCallback + Send>,
2274         eatt_support: bool,
2275     ) {
2276         let Some(uuid) = Uuid::from_string(app_uuid.clone()) else {
2277             warn!("register_client: Uuid is malformed: {}", app_uuid);
2278             return;
2279         };
2280         self.context_map.add(&uuid, callback);
2281         self.gatt.lock().unwrap().client.register_client(&uuid, eatt_support);
2282     }
2283 
unregister_client(&mut self, client_id: i32)2284     fn unregister_client(&mut self, client_id: i32) {
2285         self.context_map.remove(client_id);
2286         self.gatt.lock().unwrap().client.unregister_client(client_id);
2287     }
2288 
client_connect( &self, client_id: i32, addr: RawAddress, is_direct: bool, transport: BtTransport, opportunistic: bool, phy: LePhy, )2289     fn client_connect(
2290         &self,
2291         client_id: i32,
2292         addr: RawAddress,
2293         is_direct: bool,
2294         transport: BtTransport,
2295         opportunistic: bool,
2296         phy: LePhy,
2297     ) {
2298         self.gatt.lock().unwrap().client.connect(
2299             client_id,
2300             &addr,
2301             // Addr type is default PUBLIC.
2302             0,
2303             is_direct,
2304             transport.into(),
2305             opportunistic,
2306             phy.into(),
2307             0,
2308         );
2309     }
2310 
client_disconnect(&self, client_id: i32, addr: RawAddress)2311     fn client_disconnect(&self, client_id: i32, addr: RawAddress) {
2312         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2313             return;
2314         };
2315 
2316         self.gatt.lock().unwrap().client.disconnect(client_id, &addr, conn_id);
2317     }
2318 
refresh_device(&self, client_id: i32, addr: RawAddress)2319     fn refresh_device(&self, client_id: i32, addr: RawAddress) {
2320         self.gatt.lock().unwrap().client.refresh(client_id, &addr);
2321     }
2322 
discover_services(&self, client_id: i32, addr: RawAddress)2323     fn discover_services(&self, client_id: i32, addr: RawAddress) {
2324         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2325             return;
2326         };
2327 
2328         self.gatt.lock().unwrap().client.search_service(conn_id, None);
2329     }
2330 
discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String)2331     fn discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String) {
2332         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2333             return;
2334         };
2335 
2336         let uuid = Uuid::from_string(uuid);
2337         if uuid.is_none() {
2338             return;
2339         }
2340 
2341         self.gatt.lock().unwrap().client.search_service(conn_id, uuid);
2342     }
2343 
btif_gattc_discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String)2344     fn btif_gattc_discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String) {
2345         let conn_id = match self.context_map.get_conn_id_from_address(client_id, &addr) {
2346             None => return,
2347             Some(id) => id,
2348         };
2349         let Some(uuid) = Uuid::from_string(uuid) else { return };
2350 
2351         self.gatt.lock().unwrap().client.btif_gattc_discover_service_by_uuid(conn_id, &uuid);
2352     }
2353 
read_characteristic(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32)2354     fn read_characteristic(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32) {
2355         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2356             return;
2357         };
2358 
2359         // TODO(b/200065274): Perform check on restricted handles.
2360 
2361         self.gatt.lock().unwrap().client.read_characteristic(conn_id, handle as u16, auth_req);
2362     }
2363 
read_using_characteristic_uuid( &self, client_id: i32, addr: RawAddress, uuid: String, start_handle: i32, end_handle: i32, auth_req: i32, )2364     fn read_using_characteristic_uuid(
2365         &self,
2366         client_id: i32,
2367         addr: RawAddress,
2368         uuid: String,
2369         start_handle: i32,
2370         end_handle: i32,
2371         auth_req: i32,
2372     ) {
2373         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2374             return;
2375         };
2376         let Some(uuid) = Uuid::from_string(uuid) else { return };
2377 
2378         // TODO(b/200065274): Perform check on restricted handles.
2379 
2380         self.gatt.lock().unwrap().client.read_using_characteristic_uuid(
2381             conn_id,
2382             &uuid,
2383             start_handle as u16,
2384             end_handle as u16,
2385             auth_req,
2386         );
2387     }
2388 
write_characteristic( &mut self, client_id: i32, addr: RawAddress, handle: i32, mut write_type: GattWriteType, auth_req: i32, value: Vec<u8>, ) -> GattWriteRequestStatus2389     fn write_characteristic(
2390         &mut self,
2391         client_id: i32,
2392         addr: RawAddress,
2393         handle: i32,
2394         mut write_type: GattWriteType,
2395         auth_req: i32,
2396         value: Vec<u8>,
2397     ) -> GattWriteRequestStatus {
2398         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2399             return GattWriteRequestStatus::Fail;
2400         };
2401 
2402         if self.reliable_queue.contains(&addr) {
2403             write_type = GattWriteType::WritePrepare;
2404         }
2405 
2406         // TODO(b/200065274): Perform check on restricted handles.
2407 
2408         let permit = self.write_characteristic_permits.entry(addr).or_insert(None);
2409         if permit.is_none() {
2410             // Acquire the permit and pass it to BTIF.
2411             *permit = Some(conn_id);
2412             self.gatt.lock().unwrap().client.write_characteristic(
2413                 conn_id,
2414                 handle as u16,
2415                 write_type.to_i32().unwrap(),
2416                 auth_req,
2417                 &value,
2418             );
2419             GattWriteRequestStatus::Success
2420         } else {
2421             GattWriteRequestStatus::Busy
2422         }
2423     }
2424 
read_descriptor(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32)2425     fn read_descriptor(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32) {
2426         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2427             return;
2428         };
2429 
2430         // TODO(b/200065274): Perform check on restricted handles.
2431 
2432         self.gatt.lock().unwrap().client.read_descriptor(conn_id, handle as u16, auth_req);
2433     }
2434 
write_descriptor( &self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32, value: Vec<u8>, )2435     fn write_descriptor(
2436         &self,
2437         client_id: i32,
2438         addr: RawAddress,
2439         handle: i32,
2440         auth_req: i32,
2441         value: Vec<u8>,
2442     ) {
2443         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2444             return;
2445         };
2446 
2447         // TODO(b/200065274): Perform check on restricted handles.
2448 
2449         self.gatt.lock().unwrap().client.write_descriptor(conn_id, handle as u16, auth_req, &value);
2450     }
2451 
register_for_notification( &self, client_id: i32, addr: RawAddress, handle: i32, enable: bool, )2452     fn register_for_notification(
2453         &self,
2454         client_id: i32,
2455         addr: RawAddress,
2456         handle: i32,
2457         enable: bool,
2458     ) {
2459         let conn_id = self.context_map.get_conn_id_from_address(client_id, &addr);
2460         if conn_id.is_none() {
2461             return;
2462         }
2463 
2464         // TODO(b/200065274): Perform check on restricted handles.
2465 
2466         if enable {
2467             self.gatt.lock().unwrap().client.register_for_notification(
2468                 client_id,
2469                 &addr,
2470                 handle as u16,
2471             );
2472         } else {
2473             self.gatt.lock().unwrap().client.deregister_for_notification(
2474                 client_id,
2475                 &addr,
2476                 handle as u16,
2477             );
2478         }
2479     }
2480 
begin_reliable_write(&mut self, _client_id: i32, addr: RawAddress)2481     fn begin_reliable_write(&mut self, _client_id: i32, addr: RawAddress) {
2482         self.reliable_queue.insert(addr);
2483     }
2484 
end_reliable_write(&mut self, client_id: i32, addr: RawAddress, execute: bool)2485     fn end_reliable_write(&mut self, client_id: i32, addr: RawAddress, execute: bool) {
2486         self.reliable_queue.remove(&addr);
2487 
2488         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2489             return;
2490         };
2491 
2492         self.gatt.lock().unwrap().client.execute_write(conn_id, if execute { 1 } else { 0 });
2493     }
2494 
read_remote_rssi(&self, client_id: i32, addr: RawAddress)2495     fn read_remote_rssi(&self, client_id: i32, addr: RawAddress) {
2496         self.gatt.lock().unwrap().client.read_remote_rssi(client_id, &addr);
2497     }
2498 
configure_mtu(&self, client_id: i32, addr: RawAddress, mtu: i32)2499     fn configure_mtu(&self, client_id: i32, addr: RawAddress, mtu: i32) {
2500         let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else {
2501             return;
2502         };
2503 
2504         self.gatt.lock().unwrap().client.configure_mtu(conn_id, mtu);
2505     }
2506 
connection_parameter_update( &self, client_id: i32, addr: RawAddress, min_interval: i32, max_interval: i32, latency: i32, timeout: i32, min_ce_len: u16, max_ce_len: u16, )2507     fn connection_parameter_update(
2508         &self,
2509         client_id: i32,
2510         addr: RawAddress,
2511         min_interval: i32,
2512         max_interval: i32,
2513         latency: i32,
2514         timeout: i32,
2515         min_ce_len: u16,
2516         max_ce_len: u16,
2517     ) {
2518         self.gatt.lock().unwrap().client.conn_parameter_update(
2519             &addr,
2520             min_interval,
2521             max_interval,
2522             latency,
2523             timeout,
2524             min_ce_len,
2525             max_ce_len,
2526         );
2527         // If there's no connection for this client, LibBluetooth would not propagate a callback.
2528         // Thus make up a success callback here.
2529         if self.context_map.get_conn_id_from_address(client_id, &addr).is_none() {
2530             let tx = self.tx.clone();
2531             tokio::spawn(async move {
2532                 let _ = tx
2533                     .send(Message::GattActions(GattActions::InvokeConnectionUpdated(
2534                         client_id,
2535                         addr,
2536                         max_interval,
2537                         latency,
2538                         timeout,
2539                         GattStatus::Success,
2540                     )))
2541                     .await;
2542             });
2543         }
2544     }
2545 
client_set_preferred_phy( &self, client_id: i32, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, phy_options: i32, )2546     fn client_set_preferred_phy(
2547         &self,
2548         client_id: i32,
2549         addr: RawAddress,
2550         tx_phy: LePhy,
2551         rx_phy: LePhy,
2552         phy_options: i32,
2553     ) {
2554         let conn_id = self.context_map.get_conn_id_from_address(client_id, &addr);
2555         if conn_id.is_none() {
2556             return;
2557         }
2558 
2559         self.gatt.lock().unwrap().client.set_preferred_phy(
2560             &addr,
2561             tx_phy.to_u8().unwrap(),
2562             rx_phy.to_u8().unwrap(),
2563             phy_options as u16,
2564         );
2565     }
2566 
client_read_phy(&mut self, client_id: i32, addr: RawAddress)2567     fn client_read_phy(&mut self, client_id: i32, addr: RawAddress) {
2568         self.gatt.lock().unwrap().client.read_phy(client_id, &addr);
2569     }
2570 
2571     // GATT Server
2572 
register_server( &mut self, app_uuid: String, callback: Box<dyn IBluetoothGattServerCallback + Send>, eatt_support: bool, )2573     fn register_server(
2574         &mut self,
2575         app_uuid: String,
2576         callback: Box<dyn IBluetoothGattServerCallback + Send>,
2577         eatt_support: bool,
2578     ) {
2579         let Some(uuid) = Uuid::from_string(app_uuid.clone()) else {
2580             warn!("register_server: Uuid is malformed: {}", app_uuid);
2581             return;
2582         };
2583         self.server_context_map.add(&uuid, callback);
2584         self.gatt.lock().unwrap().server.register_server(&uuid, eatt_support);
2585     }
2586 
unregister_server(&mut self, server_id: i32)2587     fn unregister_server(&mut self, server_id: i32) {
2588         self.server_context_map.remove(server_id);
2589         self.gatt.lock().unwrap().server.unregister_server(server_id);
2590     }
2591 
server_connect( &self, server_id: i32, addr: RawAddress, is_direct: bool, transport: BtTransport, ) -> bool2592     fn server_connect(
2593         &self,
2594         server_id: i32,
2595         addr: RawAddress,
2596         is_direct: bool,
2597         transport: BtTransport,
2598     ) -> bool {
2599         self.gatt.lock().unwrap().server.connect(
2600             server_id,
2601             &addr,
2602             // Addr type is default PUBLIC.
2603             0,
2604             is_direct,
2605             transport.into(),
2606         );
2607 
2608         true
2609     }
2610 
server_disconnect(&self, server_id: i32, addr: RawAddress) -> bool2611     fn server_disconnect(&self, server_id: i32, addr: RawAddress) -> bool {
2612         let conn_id = match self.server_context_map.get_conn_id_from_address(server_id, &addr) {
2613             None => return false,
2614             Some(id) => id,
2615         };
2616 
2617         self.gatt.lock().unwrap().server.disconnect(server_id, &addr, conn_id);
2618 
2619         true
2620     }
2621 
add_service(&self, server_id: i32, service: BluetoothGattService)2622     fn add_service(&self, server_id: i32, service: BluetoothGattService) {
2623         if let Some(server) = self.server_context_map.get_by_server_id(server_id) {
2624             self.gatt
2625                 .lock()
2626                 .unwrap()
2627                 .server
2628                 .add_service(server_id, &BluetoothGattService::into_db(service, &server.services));
2629         } else {
2630             log::error!("Server id {} is not valid", server_id);
2631         }
2632     }
2633 
remove_service(&self, server_id: i32, handle: i32)2634     fn remove_service(&self, server_id: i32, handle: i32) {
2635         self.gatt.lock().unwrap().server.delete_service(server_id, handle);
2636     }
2637 
clear_services(&self, server_id: i32)2638     fn clear_services(&self, server_id: i32) {
2639         if let Some(s) = self.server_context_map.get_by_server_id(server_id) {
2640             for service in &s.services {
2641                 self.gatt.lock().unwrap().server.delete_service(server_id, service.instance_id);
2642             }
2643         }
2644     }
2645 
send_response( &self, server_id: i32, addr: RawAddress, request_id: i32, status: GattStatus, offset: i32, value: Vec<u8>, ) -> bool2646     fn send_response(
2647         &self,
2648         server_id: i32,
2649         addr: RawAddress,
2650         request_id: i32,
2651         status: GattStatus,
2652         offset: i32,
2653         value: Vec<u8>,
2654     ) -> bool {
2655         (|| {
2656             let conn_id = self.server_context_map.get_conn_id_from_address(server_id, &addr)?;
2657             let handle = self.server_context_map.get_request_handle_from_id(request_id)?;
2658             let len = value.len() as u16;
2659 
2660             let data: [u8; 512] = array_utils::to_sized_array(&value);
2661 
2662             self.gatt.lock().unwrap().server.send_response(
2663                 conn_id,
2664                 request_id,
2665                 status as i32,
2666                 &BtGattResponse {
2667                     attr_value: BtGattValue {
2668                         value: data,
2669                         handle: handle as u16,
2670                         offset: offset as u16,
2671                         len,
2672                         auth_req: 0_u8,
2673                     },
2674                 },
2675             );
2676 
2677             Some(())
2678         })()
2679         .is_some()
2680     }
2681 
send_notification( &self, server_id: i32, addr: RawAddress, handle: i32, confirm: bool, value: Vec<u8>, ) -> bool2682     fn send_notification(
2683         &self,
2684         server_id: i32,
2685         addr: RawAddress,
2686         handle: i32,
2687         confirm: bool,
2688         value: Vec<u8>,
2689     ) -> bool {
2690         let conn_id = match self.server_context_map.get_conn_id_from_address(server_id, &addr) {
2691             None => return false,
2692             Some(id) => id,
2693         };
2694 
2695         self.gatt.lock().unwrap().server.send_indication(
2696             server_id,
2697             handle,
2698             conn_id,
2699             confirm as i32,
2700             value.as_ref(),
2701         );
2702 
2703         true
2704     }
2705 
server_set_preferred_phy( &self, _server_id: i32, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, phy_options: i32, )2706     fn server_set_preferred_phy(
2707         &self,
2708         _server_id: i32,
2709         addr: RawAddress,
2710         tx_phy: LePhy,
2711         rx_phy: LePhy,
2712         phy_options: i32,
2713     ) {
2714         self.gatt.lock().unwrap().server.set_preferred_phy(
2715             &addr,
2716             tx_phy.to_u8().unwrap_or_default(),
2717             rx_phy.to_u8().unwrap_or_default(),
2718             phy_options as u16,
2719         );
2720     }
2721 
server_read_phy(&self, server_id: i32, addr: RawAddress)2722     fn server_read_phy(&self, server_id: i32, addr: RawAddress) {
2723         self.gatt.lock().unwrap().server.read_phy(server_id, &addr);
2724     }
2725 }
2726 
2727 #[btif_callbacks_dispatcher(dispatch_gatt_client_callbacks, GattClientCallbacks)]
2728 pub(crate) trait BtifGattClientCallbacks {
2729     #[btif_callback(RegisterClient)]
register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid)2730     fn register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid);
2731 
2732     #[btif_callback(Connect)]
connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress)2733     fn connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress);
2734 
2735     #[btif_callback(Disconnect)]
disconnect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress)2736     fn disconnect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress);
2737 
2738     #[btif_callback(SearchComplete)]
search_complete_cb(&mut self, conn_id: i32, status: GattStatus)2739     fn search_complete_cb(&mut self, conn_id: i32, status: GattStatus);
2740 
2741     #[btif_callback(RegisterForNotification)]
register_for_notification_cb( &mut self, conn_id: i32, registered: i32, status: GattStatus, handle: u16, )2742     fn register_for_notification_cb(
2743         &mut self,
2744         conn_id: i32,
2745         registered: i32,
2746         status: GattStatus,
2747         handle: u16,
2748     );
2749 
2750     #[btif_callback(Notify)]
notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams)2751     fn notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams);
2752 
2753     #[btif_callback(ReadCharacteristic)]
read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)2754     fn read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams);
2755 
2756     #[btif_callback(WriteCharacteristic)]
write_characteristic_cb( &mut self, conn_id: i32, status: GattStatus, handle: u16, len: u16, value: *const u8, )2757     fn write_characteristic_cb(
2758         &mut self,
2759         conn_id: i32,
2760         status: GattStatus,
2761         handle: u16,
2762         len: u16,
2763         value: *const u8,
2764     );
2765 
2766     #[btif_callback(ReadDescriptor)]
read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)2767     fn read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams);
2768 
2769     #[btif_callback(WriteDescriptor)]
write_descriptor_cb( &mut self, conn_id: i32, status: GattStatus, handle: u16, len: u16, value: *const u8, )2770     fn write_descriptor_cb(
2771         &mut self,
2772         conn_id: i32,
2773         status: GattStatus,
2774         handle: u16,
2775         len: u16,
2776         value: *const u8,
2777     );
2778 
2779     #[btif_callback(ExecuteWrite)]
execute_write_cb(&mut self, conn_id: i32, status: GattStatus)2780     fn execute_write_cb(&mut self, conn_id: i32, status: GattStatus);
2781 
2782     #[btif_callback(ReadRemoteRssi)]
read_remote_rssi_cb( &mut self, client_id: i32, addr: RawAddress, rssi: i32, status: GattStatus, )2783     fn read_remote_rssi_cb(
2784         &mut self,
2785         client_id: i32,
2786         addr: RawAddress,
2787         rssi: i32,
2788         status: GattStatus,
2789     );
2790 
2791     #[btif_callback(ConfigureMtu)]
configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32)2792     fn configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32);
2793 
2794     #[btif_callback(Congestion)]
congestion_cb(&mut self, conn_id: i32, congested: bool)2795     fn congestion_cb(&mut self, conn_id: i32, congested: bool);
2796 
2797     #[btif_callback(GetGattDb)]
get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, count: i32)2798     fn get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, count: i32);
2799 
2800     #[btif_callback(PhyUpdated)]
phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)2801     fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus);
2802 
2803     #[btif_callback(ConnUpdated)]
conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )2804     fn conn_updated_cb(
2805         &mut self,
2806         conn_id: i32,
2807         interval: u16,
2808         latency: u16,
2809         timeout: u16,
2810         status: GattStatus,
2811     );
2812 
2813     #[btif_callback(ServiceChanged)]
service_changed_cb(&mut self, conn_id: i32)2814     fn service_changed_cb(&mut self, conn_id: i32);
2815 
2816     #[btif_callback(ReadPhy)]
read_phy_cb( &mut self, client_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )2817     fn read_phy_cb(
2818         &mut self,
2819         client_id: i32,
2820         addr: RawAddress,
2821         tx_phy: u8,
2822         rx_phy: u8,
2823         status: GattStatus,
2824     );
2825 }
2826 
2827 impl BtifGattClientCallbacks for BluetoothGatt {
register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid)2828     fn register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid) {
2829         self.context_map.set_client_id(&app_uuid, client_id);
2830 
2831         let client = self.context_map.get_by_uuid(&app_uuid);
2832         match client {
2833             Some(c) => {
2834                 let cbid = c.cbid;
2835                 if let Some(cb) = self.context_map.get_callback_from_callback_id(cbid) {
2836                     cb.on_client_registered(status, client_id);
2837                 }
2838             }
2839             None => {
2840                 warn!("Warning: Client not registered for UUID {}", DisplayUuid(&app_uuid));
2841             }
2842         }
2843     }
2844 
connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress)2845     fn connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress) {
2846         if status == GattStatus::Success {
2847             self.context_map.add_connection(client_id, conn_id, &addr);
2848         }
2849 
2850         let Some(client) = self.context_map.get_by_client_id(client_id) else { return };
2851         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2852             cb.on_client_connection_state(status, client_id, status == GattStatus::Success, addr);
2853         }
2854     }
2855 
disconnect_cb( &mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress, )2856     fn disconnect_cb(
2857         &mut self,
2858         conn_id: i32,
2859         status: GattStatus,
2860         client_id: i32,
2861         addr: RawAddress,
2862     ) {
2863         let Some(client) = self.context_map.get_by_client_id(client_id) else { return };
2864         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2865             cb.on_client_connection_state(status, client_id, false, addr);
2866         }
2867         self.context_map.remove_connection(client_id, conn_id);
2868 
2869         if self.context_map.get_client_ids_from_address(&addr).is_empty() {
2870             // Cleaning up as no client connects to this address.
2871             self.write_characteristic_permits.remove(&addr);
2872         } else {
2873             // If the permit is held by this |conn_id|, reset it.
2874             if let Some(permit) = self.write_characteristic_permits.get_mut(&addr) {
2875                 if *permit == Some(conn_id) {
2876                     *permit = None;
2877                 }
2878             }
2879         }
2880 
2881         let tx = self.tx.clone();
2882         tokio::spawn(async move {
2883             let _ = tx.send(Message::ProfileDisconnected(addr)).await;
2884         });
2885     }
2886 
search_complete_cb(&mut self, conn_id: i32, _status: GattStatus)2887     fn search_complete_cb(&mut self, conn_id: i32, _status: GattStatus) {
2888         // Gatt DB is ready!
2889         self.gatt.lock().unwrap().client.get_gatt_db(conn_id);
2890     }
2891 
register_for_notification_cb( &mut self, _conn_id: i32, _registered: i32, _status: GattStatus, _handle: u16, )2892     fn register_for_notification_cb(
2893         &mut self,
2894         _conn_id: i32,
2895         _registered: i32,
2896         _status: GattStatus,
2897         _handle: u16,
2898     ) {
2899         // No-op.
2900     }
2901 
notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams)2902     fn notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams) {
2903         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
2904         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2905             cb.on_notify(data.bda, data.handle as i32, data.value[0..data.len as usize].to_vec());
2906         }
2907     }
2908 
read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)2909     fn read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams) {
2910         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
2911         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
2912         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2913             cb.on_characteristic_read(
2914                 addr,
2915                 status,
2916                 data.handle as i32,
2917                 data.value.value[0..data.value.len as usize].to_vec(),
2918             );
2919         }
2920     }
2921 
write_characteristic_cb( &mut self, conn_id: i32, mut status: GattStatus, handle: u16, _len: u16, _value: *const u8, )2922     fn write_characteristic_cb(
2923         &mut self,
2924         conn_id: i32,
2925         mut status: GattStatus,
2926         handle: u16,
2927         _len: u16,
2928         _value: *const u8,
2929     ) {
2930         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
2931         let Some(client) = self.context_map.get_client_by_conn_id_mut(conn_id) else { return };
2932 
2933         // Reset the permit.
2934         self.write_characteristic_permits.insert(addr, None);
2935 
2936         if client.is_congested {
2937             if status == GattStatus::Congested {
2938                 status = GattStatus::Success;
2939             }
2940             client.congestion_queue.push((addr, status, handle as i32));
2941             return;
2942         }
2943 
2944         let cbid = client.cbid;
2945         if let Some(cb) = self.context_map.get_callback_from_callback_id(cbid) {
2946             cb.on_characteristic_write(addr, status, handle as i32);
2947         }
2948     }
2949 
read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)2950     fn read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams) {
2951         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
2952         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
2953         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2954             cb.on_descriptor_read(
2955                 addr,
2956                 status,
2957                 data.handle as i32,
2958                 data.value.value[0..data.value.len as usize].to_vec(),
2959             );
2960         }
2961     }
2962 
write_descriptor_cb( &mut self, conn_id: i32, status: GattStatus, handle: u16, _len: u16, _value: *const u8, )2963     fn write_descriptor_cb(
2964         &mut self,
2965         conn_id: i32,
2966         status: GattStatus,
2967         handle: u16,
2968         _len: u16,
2969         _value: *const u8,
2970     ) {
2971         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
2972         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
2973         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2974             cb.on_descriptor_write(addr, status, handle as i32);
2975         }
2976     }
2977 
execute_write_cb(&mut self, conn_id: i32, status: GattStatus)2978     fn execute_write_cb(&mut self, conn_id: i32, status: GattStatus) {
2979         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
2980         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
2981         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2982             cb.on_execute_write(addr, status);
2983         }
2984     }
2985 
read_remote_rssi_cb( &mut self, client_id: i32, addr: RawAddress, rssi: i32, status: GattStatus, )2986     fn read_remote_rssi_cb(
2987         &mut self,
2988         client_id: i32,
2989         addr: RawAddress,
2990         rssi: i32,
2991         status: GattStatus,
2992     ) {
2993         let Some(client) = self.context_map.get_by_client_id(client_id) else { return };
2994         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
2995             cb.on_read_remote_rssi(addr, rssi, status);
2996         }
2997     }
2998 
configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32)2999     fn configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32) {
3000         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
3001         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
3002         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
3003             cb.on_configure_mtu(addr, mtu, status);
3004         }
3005     }
3006 
congestion_cb(&mut self, conn_id: i32, congested: bool)3007     fn congestion_cb(&mut self, conn_id: i32, congested: bool) {
3008         if let Some(client) = self.context_map.get_client_by_conn_id_mut(conn_id) {
3009             client.is_congested = congested;
3010             if !client.is_congested {
3011                 let cbid = client.cbid;
3012                 let mut congestion_queue: Vec<(RawAddress, GattStatus, i32)> = vec![];
3013                 client.congestion_queue.retain(|v| {
3014                     congestion_queue.push(*v);
3015                     false
3016                 });
3017 
3018                 self.context_map.get_callback_from_callback_id(cbid).map(
3019                     |cb: &mut GattClientCallback| {
3020                         for callback in congestion_queue.iter() {
3021                             cb.on_characteristic_write(callback.0, callback.1, callback.2);
3022                         }
3023                     },
3024                 );
3025             }
3026         }
3027     }
3028 
get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, _count: i32)3029     fn get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, _count: i32) {
3030         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
3031         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
3032         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
3033             cb.on_search_complete(
3034                 addr,
3035                 BluetoothGattService::from_db(elements, true),
3036                 GattStatus::Success,
3037             );
3038         }
3039     }
3040 
phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)3041     fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus) {
3042         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
3043         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
3044         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
3045             cb.on_phy_update(
3046                 addr,
3047                 LePhy::from_u8(tx_phy).unwrap(),
3048                 LePhy::from_u8(rx_phy).unwrap(),
3049                 status,
3050             );
3051         }
3052     }
3053 
read_phy_cb( &mut self, client_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )3054     fn read_phy_cb(
3055         &mut self,
3056         client_id: i32,
3057         addr: RawAddress,
3058         tx_phy: u8,
3059         rx_phy: u8,
3060         status: GattStatus,
3061     ) {
3062         let Some(client) = self.context_map.get_by_client_id(client_id) else { return };
3063         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
3064             cb.on_phy_read(
3065                 addr,
3066                 LePhy::from_u8(tx_phy).unwrap(),
3067                 LePhy::from_u8(rx_phy).unwrap(),
3068                 status,
3069             );
3070         }
3071     }
3072 
conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )3073     fn conn_updated_cb(
3074         &mut self,
3075         conn_id: i32,
3076         interval: u16,
3077         latency: u16,
3078         timeout: u16,
3079         status: GattStatus,
3080     ) {
3081         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
3082         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
3083         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
3084             cb.on_connection_updated(addr, interval as i32, latency as i32, timeout as i32, status);
3085         }
3086     }
3087 
service_changed_cb(&mut self, conn_id: i32)3088     fn service_changed_cb(&mut self, conn_id: i32) {
3089         let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return };
3090         let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return };
3091         if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) {
3092             cb.on_service_changed(addr);
3093         }
3094     }
3095 }
3096 
3097 #[btif_callbacks_dispatcher(dispatch_gatt_server_callbacks, GattServerCallbacks)]
3098 pub(crate) trait BtifGattServerCallbacks {
3099     #[btif_callback(RegisterServer)]
register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid)3100     fn register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid);
3101 
3102     #[btif_callback(Connection)]
connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress)3103     fn connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress);
3104 
3105     #[btif_callback(ServiceAdded)]
service_added_cb( &mut self, status: GattStatus, server_id: i32, elements: Vec<BtGattDbElement>, _count: usize, )3106     fn service_added_cb(
3107         &mut self,
3108         status: GattStatus,
3109         server_id: i32,
3110         elements: Vec<BtGattDbElement>,
3111         _count: usize,
3112     );
3113 
3114     #[btif_callback(ServiceDeleted)]
service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32)3115     fn service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32);
3116 
3117     #[btif_callback(RequestReadCharacteristic)]
request_read_characteristic_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3118     fn request_read_characteristic_cb(
3119         &mut self,
3120         conn_id: i32,
3121         trans_id: i32,
3122         addr: RawAddress,
3123         handle: i32,
3124         offset: i32,
3125         is_long: bool,
3126     );
3127 
3128     #[btif_callback(RequestReadDescriptor)]
request_read_descriptor_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3129     fn request_read_descriptor_cb(
3130         &mut self,
3131         conn_id: i32,
3132         trans_id: i32,
3133         addr: RawAddress,
3134         handle: i32,
3135         offset: i32,
3136         is_long: bool,
3137     );
3138 
3139     #[btif_callback(RequestWriteCharacteristic)]
request_write_characteristic_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, need_rsp: bool, is_prep: bool, data: Vec<u8>, len: usize, )3140     fn request_write_characteristic_cb(
3141         &mut self,
3142         conn_id: i32,
3143         trans_id: i32,
3144         addr: RawAddress,
3145         handle: i32,
3146         offset: i32,
3147         need_rsp: bool,
3148         is_prep: bool,
3149         data: Vec<u8>,
3150         len: usize,
3151     );
3152 
3153     #[btif_callback(RequestWriteDescriptor)]
request_write_descriptor_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, need_rsp: bool, is_prep: bool, data: Vec<u8>, len: usize, )3154     fn request_write_descriptor_cb(
3155         &mut self,
3156         conn_id: i32,
3157         trans_id: i32,
3158         addr: RawAddress,
3159         handle: i32,
3160         offset: i32,
3161         need_rsp: bool,
3162         is_prep: bool,
3163         data: Vec<u8>,
3164         len: usize,
3165     );
3166 
3167     #[btif_callback(RequestExecWrite)]
request_exec_write_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, exec_write: i32, )3168     fn request_exec_write_cb(
3169         &mut self,
3170         conn_id: i32,
3171         trans_id: i32,
3172         addr: RawAddress,
3173         exec_write: i32,
3174     );
3175 
3176     #[btif_callback(IndicationSent)]
indication_sent_cb(&mut self, conn_id: i32, status: GattStatus)3177     fn indication_sent_cb(&mut self, conn_id: i32, status: GattStatus);
3178 
3179     #[btif_callback(Congestion)]
congestion_cb(&mut self, conn_id: i32, congested: bool)3180     fn congestion_cb(&mut self, conn_id: i32, congested: bool);
3181 
3182     #[btif_callback(MtuChanged)]
mtu_changed_cb(&mut self, conn_id: i32, mtu: i32)3183     fn mtu_changed_cb(&mut self, conn_id: i32, mtu: i32);
3184 
3185     #[btif_callback(PhyUpdated)]
phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)3186     fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus);
3187 
3188     #[btif_callback(ReadPhy)]
read_phy_cb( &mut self, server_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )3189     fn read_phy_cb(
3190         &mut self,
3191         server_id: i32,
3192         addr: RawAddress,
3193         tx_phy: u8,
3194         rx_phy: u8,
3195         status: GattStatus,
3196     );
3197 
3198     #[btif_callback(ConnUpdated)]
conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )3199     fn conn_updated_cb(
3200         &mut self,
3201         conn_id: i32,
3202         interval: u16,
3203         latency: u16,
3204         timeout: u16,
3205         status: GattStatus,
3206     );
3207 
3208     #[btif_callback(SubrateChanged)]
subrate_chg_cb( &mut self, conn_id: i32, subrate_factor: u16, latency: u16, cont_num: u16, timeout: u16, status: GattStatus, )3209     fn subrate_chg_cb(
3210         &mut self,
3211         conn_id: i32,
3212         subrate_factor: u16,
3213         latency: u16,
3214         cont_num: u16,
3215         timeout: u16,
3216         status: GattStatus,
3217     );
3218 }
3219 
3220 impl BtifGattServerCallbacks for BluetoothGatt {
register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid)3221     fn register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid) {
3222         self.server_context_map.set_server_id(&app_uuid, server_id);
3223 
3224         let cbid = self.server_context_map.get_by_uuid(&app_uuid).map(|server| server.cbid);
3225         match cbid {
3226             Some(cbid) => {
3227                 if let Some(cb) =
3228                     self.server_context_map.get_callback_from_callback_id(cbid).as_mut()
3229                 {
3230                     cb.on_server_registered(status, server_id)
3231                 }
3232             }
3233             None => {
3234                 warn!("Warning: No callback found for UUID {}", DisplayUuid(&app_uuid));
3235             }
3236         }
3237     }
3238 
connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress)3239     fn connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress) {
3240         let is_connected = connected != 0;
3241         if is_connected {
3242             self.server_context_map.add_connection(server_id, conn_id, &addr);
3243         } else {
3244             self.server_context_map.remove_connection(conn_id);
3245         }
3246 
3247         let cbid = self.server_context_map.get_by_server_id(server_id).map(|server| server.cbid);
3248         match cbid {
3249             Some(cbid) => {
3250                 if let Some(cb) =
3251                     self.server_context_map.get_callback_from_callback_id(cbid).as_mut()
3252                 {
3253                     cb.on_server_connection_state(server_id, is_connected, addr);
3254                 }
3255             }
3256             None => {
3257                 warn!("Warning: No callback found for server ID {}", server_id);
3258             }
3259         }
3260     }
3261 
service_added_cb( &mut self, status: GattStatus, server_id: i32, elements: Vec<BtGattDbElement>, _count: usize, )3262     fn service_added_cb(
3263         &mut self,
3264         status: GattStatus,
3265         server_id: i32,
3266         elements: Vec<BtGattDbElement>,
3267         _count: usize,
3268     ) {
3269         for service in BluetoothGattService::from_db(elements, false) {
3270             if status == GattStatus::Success {
3271                 self.server_context_map.add_service(server_id, service.clone());
3272             }
3273 
3274             let cbid =
3275                 self.server_context_map.get_by_server_id(server_id).map(|server| server.cbid);
3276             match cbid {
3277                 Some(cbid) => {
3278                     if let Some(cb) =
3279                         self.server_context_map.get_callback_from_callback_id(cbid).as_mut()
3280                     {
3281                         cb.on_service_added(status, service);
3282                     }
3283                 }
3284                 None => {
3285                     warn!("Warning: No callback found for server ID {}", server_id);
3286                 }
3287             }
3288         }
3289     }
3290 
service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32)3291     fn service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32) {
3292         if status == GattStatus::Success {
3293             self.server_context_map.delete_service(server_id, handle);
3294         }
3295 
3296         let cbid = self.server_context_map.get_by_server_id(server_id).map(|server| server.cbid);
3297 
3298         if let Some(cbid) = cbid {
3299             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3300                 cb.on_service_removed(status, handle);
3301             }
3302         }
3303     }
3304 
request_read_characteristic_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3305     fn request_read_characteristic_cb(
3306         &mut self,
3307         conn_id: i32,
3308         trans_id: i32,
3309         addr: RawAddress,
3310         handle: i32,
3311         offset: i32,
3312         is_long: bool,
3313     ) {
3314         self.server_context_map.add_request(trans_id, handle);
3315 
3316         if let Some(cbid) =
3317             self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid)
3318         {
3319             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3320                 cb.on_characteristic_read_request(addr, trans_id, offset, is_long, handle);
3321             }
3322         }
3323     }
3324 
request_read_descriptor_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3325     fn request_read_descriptor_cb(
3326         &mut self,
3327         conn_id: i32,
3328         trans_id: i32,
3329         addr: RawAddress,
3330         handle: i32,
3331         offset: i32,
3332         is_long: bool,
3333     ) {
3334         self.server_context_map.add_request(trans_id, handle);
3335 
3336         if let Some(cbid) =
3337             self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid)
3338         {
3339             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3340                 cb.on_descriptor_read_request(addr, trans_id, offset, is_long, handle);
3341             }
3342         }
3343     }
3344 
request_write_characteristic_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, need_rsp: bool, is_prep: bool, data: Vec<u8>, len: usize, )3345     fn request_write_characteristic_cb(
3346         &mut self,
3347         conn_id: i32,
3348         trans_id: i32,
3349         addr: RawAddress,
3350         handle: i32,
3351         offset: i32,
3352         need_rsp: bool,
3353         is_prep: bool,
3354         data: Vec<u8>,
3355         len: usize,
3356     ) {
3357         self.server_context_map.add_request(trans_id, handle);
3358 
3359         if let Some(cbid) =
3360             self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid)
3361         {
3362             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3363                 cb.on_characteristic_write_request(
3364                     addr, trans_id, offset, len as i32, is_prep, need_rsp, handle, data,
3365                 );
3366             }
3367         }
3368     }
3369 
request_write_descriptor_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, need_rsp: bool, is_prep: bool, data: Vec<u8>, len: usize, )3370     fn request_write_descriptor_cb(
3371         &mut self,
3372         conn_id: i32,
3373         trans_id: i32,
3374         addr: RawAddress,
3375         handle: i32,
3376         offset: i32,
3377         need_rsp: bool,
3378         is_prep: bool,
3379         data: Vec<u8>,
3380         len: usize,
3381     ) {
3382         self.server_context_map.add_request(trans_id, handle);
3383 
3384         if let Some(cbid) =
3385             self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid)
3386         {
3387             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3388                 cb.on_descriptor_write_request(
3389                     addr, trans_id, offset, len as i32, is_prep, need_rsp, handle, data,
3390                 );
3391             }
3392         }
3393     }
3394 
request_exec_write_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, exec_write: i32, )3395     fn request_exec_write_cb(
3396         &mut self,
3397         conn_id: i32,
3398         trans_id: i32,
3399         addr: RawAddress,
3400         exec_write: i32,
3401     ) {
3402         self.server_context_map.add_request(trans_id, 0);
3403 
3404         if let Some(cbid) =
3405             self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid)
3406         {
3407             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3408                 cb.on_execute_write(addr, trans_id, exec_write != 0);
3409             }
3410         }
3411     }
3412 
indication_sent_cb(&mut self, conn_id: i32, mut status: GattStatus)3413     fn indication_sent_cb(&mut self, conn_id: i32, mut status: GattStatus) {
3414         (|| {
3415             let address = self.server_context_map.get_address_from_conn_id(conn_id)?;
3416             let server = self.server_context_map.get_mut_by_conn_id(conn_id)?;
3417 
3418             if server.is_congested {
3419                 if status == GattStatus::Congested {
3420                     status = GattStatus::Success;
3421                 }
3422 
3423                 server.congestion_queue.push((address, status));
3424                 return None;
3425             }
3426 
3427             let cbid = server.cbid;
3428             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3429                 cb.on_notification_sent(address, status);
3430             }
3431 
3432             Some(())
3433         })();
3434     }
3435 
congestion_cb(&mut self, conn_id: i32, congested: bool)3436     fn congestion_cb(&mut self, conn_id: i32, congested: bool) {
3437         if let Some(server) = self.server_context_map.get_mut_by_conn_id(conn_id) {
3438             server.is_congested = congested;
3439             if !server.is_congested {
3440                 let cbid = server.cbid;
3441                 let congestion_queue: Vec<_> = server.congestion_queue.drain(..).collect();
3442 
3443                 if let Some(cb) =
3444                     self.server_context_map.get_callback_from_callback_id(cbid).as_mut()
3445                 {
3446                     for callback in congestion_queue {
3447                         cb.on_notification_sent(callback.0, callback.1);
3448                     }
3449                 }
3450             }
3451         }
3452     }
3453 
mtu_changed_cb(&mut self, conn_id: i32, mtu: i32)3454     fn mtu_changed_cb(&mut self, conn_id: i32, mtu: i32) {
3455         (|| {
3456             let address = self.server_context_map.get_address_from_conn_id(conn_id)?;
3457             let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid;
3458 
3459             if let Some(cb) =
3460                 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut()
3461             {
3462                 cb.on_mtu_changed(address, mtu);
3463             }
3464 
3465             Some(())
3466         })();
3467     }
3468 
phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)3469     fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus) {
3470         (|| {
3471             let address = self.server_context_map.get_address_from_conn_id(conn_id)?;
3472             let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid;
3473 
3474             if let Some(cb) =
3475                 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut()
3476             {
3477                 cb.on_phy_update(
3478                     address,
3479                     LePhy::from_u8(tx_phy).unwrap_or_default(),
3480                     LePhy::from_u8(rx_phy).unwrap_or_default(),
3481                     status,
3482                 );
3483             }
3484 
3485             Some(())
3486         })();
3487     }
3488 
read_phy_cb( &mut self, server_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )3489     fn read_phy_cb(
3490         &mut self,
3491         server_id: i32,
3492         addr: RawAddress,
3493         tx_phy: u8,
3494         rx_phy: u8,
3495         status: GattStatus,
3496     ) {
3497         if let Some(cbid) =
3498             self.server_context_map.get_by_server_id(server_id).map(|server| server.cbid)
3499         {
3500             if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() {
3501                 cb.on_phy_read(
3502                     addr,
3503                     LePhy::from_u8(tx_phy).unwrap_or_default(),
3504                     LePhy::from_u8(rx_phy).unwrap_or_default(),
3505                     status,
3506                 );
3507             }
3508         }
3509     }
3510 
conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )3511     fn conn_updated_cb(
3512         &mut self,
3513         conn_id: i32,
3514         interval: u16,
3515         latency: u16,
3516         timeout: u16,
3517         status: GattStatus,
3518     ) {
3519         (|| {
3520             let address = self.server_context_map.get_address_from_conn_id(conn_id)?;
3521             let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid;
3522 
3523             if let Some(cb) =
3524                 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut()
3525             {
3526                 cb.on_connection_updated(
3527                     address,
3528                     interval as i32,
3529                     latency as i32,
3530                     timeout as i32,
3531                     status,
3532                 );
3533             }
3534 
3535             Some(())
3536         })();
3537     }
3538 
subrate_chg_cb( &mut self, conn_id: i32, subrate_factor: u16, latency: u16, cont_num: u16, timeout: u16, status: GattStatus, )3539     fn subrate_chg_cb(
3540         &mut self,
3541         conn_id: i32,
3542         subrate_factor: u16,
3543         latency: u16,
3544         cont_num: u16,
3545         timeout: u16,
3546         status: GattStatus,
3547     ) {
3548         (|| {
3549             let address = self.server_context_map.get_address_from_conn_id(conn_id)?;
3550             let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid;
3551 
3552             if let Some(cb) =
3553                 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut()
3554             {
3555                 cb.on_subrate_change(
3556                     address,
3557                     subrate_factor as i32,
3558                     latency as i32,
3559                     cont_num as i32,
3560                     timeout as i32,
3561                     status,
3562                 );
3563             }
3564 
3565             Some(())
3566         })();
3567     }
3568 }
3569 
3570 #[btif_callbacks_dispatcher(dispatch_le_scanner_callbacks, GattScannerCallbacks)]
3571 pub(crate) trait BtifGattScannerCallbacks {
3572     #[btif_callback(OnScannerRegistered)]
on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus)3573     fn on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus);
3574 
3575     #[btif_callback(OnScanResult)]
on_scan_result( &mut self, event_type: u16, addr_type: u8, bda: RawAddress, primary_phy: u8, secondary_phy: u8, advertising_sid: u8, tx_power: i8, rssi: i8, periodic_adv_int: u16, adv_data: Vec<u8>, )3576     fn on_scan_result(
3577         &mut self,
3578         event_type: u16,
3579         addr_type: u8,
3580         bda: RawAddress,
3581         primary_phy: u8,
3582         secondary_phy: u8,
3583         advertising_sid: u8,
3584         tx_power: i8,
3585         rssi: i8,
3586         periodic_adv_int: u16,
3587         adv_data: Vec<u8>,
3588     );
3589 
3590     #[btif_callback(OnTrackAdvFoundLost)]
on_track_adv_found_lost(&mut self, adv_track_info: AdvertisingTrackInfo)3591     fn on_track_adv_found_lost(&mut self, adv_track_info: AdvertisingTrackInfo);
3592 }
3593 
3594 #[btif_callbacks_dispatcher(dispatch_le_scanner_inband_callbacks, GattScannerInbandCallbacks)]
3595 pub(crate) trait BtifGattScannerInbandCallbacks {
3596     #[btif_callback(RegisterCallback)]
inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8)3597     fn inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8);
3598 
3599     #[btif_callback(StatusCallback)]
inband_status_callback(&mut self, scanner_id: u8, btm_status: u8)3600     fn inband_status_callback(&mut self, scanner_id: u8, btm_status: u8);
3601 
3602     #[btif_callback(EnableCallback)]
inband_enable_callback(&mut self, action: u8, btm_status: u8)3603     fn inband_enable_callback(&mut self, action: u8, btm_status: u8);
3604 
3605     #[btif_callback(FilterParamSetupCallback)]
inband_filter_param_setup_callback( &mut self, scanner_id: u8, available_space: u8, action_type: u8, btm_status: u8, )3606     fn inband_filter_param_setup_callback(
3607         &mut self,
3608         scanner_id: u8,
3609         available_space: u8,
3610         action_type: u8,
3611         btm_status: u8,
3612     );
3613 
3614     #[btif_callback(FilterConfigCallback)]
inband_filter_config_callback( &mut self, filter_index: u8, filter_type: u8, available_space: u8, action: u8, btm_status: u8, )3615     fn inband_filter_config_callback(
3616         &mut self,
3617         filter_index: u8,
3618         filter_type: u8,
3619         available_space: u8,
3620         action: u8,
3621         btm_status: u8,
3622     );
3623 
3624     #[btif_callback(MsftAdvMonitorAddCallback)]
inband_msft_adv_monitor_add_callback(&mut self, monitor_handle: u8, status: u8)3625     fn inband_msft_adv_monitor_add_callback(&mut self, monitor_handle: u8, status: u8);
3626 
3627     #[btif_callback(MsftAdvMonitorRemoveCallback)]
inband_msft_adv_monitor_remove_callback(&mut self, status: u8)3628     fn inband_msft_adv_monitor_remove_callback(&mut self, status: u8);
3629 
3630     #[btif_callback(MsftAdvMonitorEnableCallback)]
inband_msft_adv_monitor_enable_callback(&mut self, status: u8)3631     fn inband_msft_adv_monitor_enable_callback(&mut self, status: u8);
3632 
3633     #[btif_callback(StartSyncCallback)]
inband_start_sync_callback( &mut self, status: u8, sync_handle: u16, advertising_sid: u8, address_type: u8, address: RawAddress, phy: u8, interval: u16, )3634     fn inband_start_sync_callback(
3635         &mut self,
3636         status: u8,
3637         sync_handle: u16,
3638         advertising_sid: u8,
3639         address_type: u8,
3640         address: RawAddress,
3641         phy: u8,
3642         interval: u16,
3643     );
3644 
3645     #[btif_callback(SyncReportCallback)]
inband_sync_report_callback( &mut self, sync_handle: u16, tx_power: i8, rssi: i8, status: u8, data: Vec<u8>, )3646     fn inband_sync_report_callback(
3647         &mut self,
3648         sync_handle: u16,
3649         tx_power: i8,
3650         rssi: i8,
3651         status: u8,
3652         data: Vec<u8>,
3653     );
3654 
3655     #[btif_callback(SyncLostCallback)]
inband_sync_lost_callback(&mut self, sync_handle: u16)3656     fn inband_sync_lost_callback(&mut self, sync_handle: u16);
3657 
3658     #[btif_callback(SyncTransferCallback)]
inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress)3659     fn inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress);
3660 }
3661 
3662 impl BtifGattScannerInbandCallbacks for BluetoothGatt {
inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8)3663     fn inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8) {
3664         log::debug!(
3665             "Callback received: {:#?}",
3666             GattScannerInbandCallbacks::RegisterCallback(app_uuid, scanner_id, btm_status)
3667         );
3668     }
3669 
inband_status_callback(&mut self, scanner_id: u8, btm_status: u8)3670     fn inband_status_callback(&mut self, scanner_id: u8, btm_status: u8) {
3671         log::debug!(
3672             "Callback received: {:#?}",
3673             GattScannerInbandCallbacks::StatusCallback(scanner_id, btm_status)
3674         );
3675     }
3676 
inband_enable_callback(&mut self, action: u8, btm_status: u8)3677     fn inband_enable_callback(&mut self, action: u8, btm_status: u8) {
3678         log::debug!(
3679             "Callback received: {:#?}",
3680             GattScannerInbandCallbacks::EnableCallback(action, btm_status)
3681         );
3682     }
3683 
inband_filter_param_setup_callback( &mut self, scanner_id: u8, available_space: u8, action_type: u8, btm_status: u8, )3684     fn inband_filter_param_setup_callback(
3685         &mut self,
3686         scanner_id: u8,
3687         available_space: u8,
3688         action_type: u8,
3689         btm_status: u8,
3690     ) {
3691         log::debug!(
3692             "Callback received: {:#?}",
3693             GattScannerInbandCallbacks::FilterParamSetupCallback(
3694                 scanner_id,
3695                 available_space,
3696                 action_type,
3697                 btm_status
3698             )
3699         );
3700     }
3701 
inband_filter_config_callback( &mut self, filter_index: u8, filter_type: u8, available_space: u8, action: u8, btm_status: u8, )3702     fn inband_filter_config_callback(
3703         &mut self,
3704         filter_index: u8,
3705         filter_type: u8,
3706         available_space: u8,
3707         action: u8,
3708         btm_status: u8,
3709     ) {
3710         log::debug!(
3711             "Callback received: {:#?}",
3712             GattScannerInbandCallbacks::FilterConfigCallback(
3713                 filter_index,
3714                 filter_type,
3715                 available_space,
3716                 action,
3717                 btm_status,
3718             )
3719         );
3720     }
3721 
inband_msft_adv_monitor_add_callback(&mut self, monitor_handle: u8, status: u8)3722     fn inband_msft_adv_monitor_add_callback(&mut self, monitor_handle: u8, status: u8) {
3723         if !self.enabled {
3724             return;
3725         }
3726         let (should_abort, scanner_id, monitor) = match &self.msft_command_pending {
3727             MsftCommandPending::Aborted(scanner_id, monitor) => {
3728                 (true, *scanner_id, monitor.clone())
3729             }
3730             MsftCommandPending::Add(scanner_id, monitor) => (false, *scanner_id, monitor.clone()),
3731             _ => {
3732                 error!(
3733                     "Unexpected MsftAdvMonitorAddCallback monitor_handle={} status={}, pending={:?}",
3734                     monitor_handle, status, self.msft_command_pending
3735                 );
3736                 return;
3737             }
3738         };
3739         self.msft_command_pending = MsftCommandPending::NoPending;
3740 
3741         if status != 0 {
3742             error!(
3743                 "Error adding advertisement monitor {:?}, scanner_id={}, status={}",
3744                 monitor, scanner_id, status
3745             );
3746         } else if should_abort {
3747             debug!("Aborted MSFT monitor, removing");
3748             self.msft_command_queue.push_back(MsftCommandQueue::Remove(monitor_handle));
3749         } else {
3750             match monitor.condition {
3751                 ScanFilterCondition::Patterns(_) => {
3752                     self.on_pattern_monitor_added(scanner_id, monitor_handle);
3753                 }
3754                 ScanFilterCondition::BluetoothAddress(_) => {
3755                     self.on_address_monitor_added(scanner_id, monitor_handle, &monitor);
3756                 }
3757                 _ => error!("Unhandled MSFT monitor added {:?}", monitor),
3758             }
3759         }
3760         self.msft_run_queue_and_update_scan();
3761     }
3762 
inband_msft_adv_monitor_remove_callback(&mut self, status: u8)3763     fn inband_msft_adv_monitor_remove_callback(&mut self, status: u8) {
3764         if !self.enabled {
3765             return;
3766         }
3767         let MsftCommandPending::Remove(_monitor_handle) = self.msft_command_pending else {
3768             error!(
3769                 "Unexpected MsftAdvMonitorRemoveCallback status={}, pending={:?}",
3770                 status, self.msft_command_pending
3771             );
3772             return;
3773         };
3774         self.msft_command_pending = MsftCommandPending::NoPending;
3775 
3776         if status != 0 {
3777             error!("Error removing advertisement monitor, status={}", status);
3778         }
3779         self.msft_run_queue_and_update_scan();
3780     }
3781 
inband_msft_adv_monitor_enable_callback(&mut self, status: u8)3782     fn inband_msft_adv_monitor_enable_callback(&mut self, status: u8) {
3783         if !self.enabled {
3784             return;
3785         }
3786         let MsftCommandPending::Enable(enabled) = self.msft_command_pending else {
3787             error!(
3788                 "Unexpected MsftAdvMonitorEnableCallback status={}, pending={:?}",
3789                 status, self.msft_command_pending
3790             );
3791             return;
3792         };
3793         self.msft_command_pending = MsftCommandPending::NoPending;
3794 
3795         if status != 0 {
3796             error!("Error updating Advertisement Monitor enable, status={}", status);
3797         } else {
3798             self.msft_enabled = enabled;
3799         }
3800         self.update_scan(true); // Force restart the scan as the MSFT enable just changed.
3801         if !self.msft_command_queue.is_empty() {
3802             self.msft_run_queue_and_update_scan();
3803         }
3804     }
3805 
inband_start_sync_callback( &mut self, status: u8, sync_handle: u16, advertising_sid: u8, address_type: u8, address: RawAddress, phy: u8, interval: u16, )3806     fn inband_start_sync_callback(
3807         &mut self,
3808         status: u8,
3809         sync_handle: u16,
3810         advertising_sid: u8,
3811         address_type: u8,
3812         address: RawAddress,
3813         phy: u8,
3814         interval: u16,
3815     ) {
3816         log::debug!(
3817             "Callback received: StartSyncCallback({}, {}, {}, {}, {}, {}, {})",
3818             status,
3819             sync_handle,
3820             advertising_sid,
3821             address_type,
3822             DisplayAddress(&address),
3823             phy,
3824             interval
3825         );
3826     }
3827 
inband_sync_report_callback( &mut self, sync_handle: u16, tx_power: i8, rssi: i8, status: u8, data: Vec<u8>, )3828     fn inband_sync_report_callback(
3829         &mut self,
3830         sync_handle: u16,
3831         tx_power: i8,
3832         rssi: i8,
3833         status: u8,
3834         data: Vec<u8>,
3835     ) {
3836         log::debug!(
3837             "Callback received: {:#?}",
3838             GattScannerInbandCallbacks::SyncReportCallback(
3839                 sync_handle,
3840                 tx_power,
3841                 rssi,
3842                 status,
3843                 data
3844             )
3845         );
3846     }
3847 
inband_sync_lost_callback(&mut self, sync_handle: u16)3848     fn inband_sync_lost_callback(&mut self, sync_handle: u16) {
3849         log::debug!(
3850             "Callback received: {:#?}",
3851             GattScannerInbandCallbacks::SyncLostCallback(sync_handle,)
3852         );
3853     }
3854 
inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress)3855     fn inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress) {
3856         log::debug!(
3857             "Callback received: SyncTransferCallback({}, {})",
3858             status,
3859             DisplayAddress(&address)
3860         );
3861     }
3862 }
3863 
3864 impl BtifGattScannerCallbacks for BluetoothGatt {
on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus)3865     fn on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus) {
3866         debug!(
3867             "on_scanner_registered UUID = {}, scanner_id = {}, status = {}",
3868             DisplayUuid(&uuid),
3869             scanner_id,
3870             status
3871         );
3872 
3873         let scanner_info = self.scanners.get_mut(&uuid);
3874 
3875         if let Some(info) = scanner_info {
3876             info.scanner_id = Some(scanner_id);
3877             if let Some(cb) = self.scanner_callbacks.get_by_id_mut(info.callback_id) {
3878                 cb.on_scanner_registered(uuid, scanner_id, status);
3879             } else {
3880                 warn!("There is no callback for scanner UUID {}", DisplayUuid(&uuid));
3881             }
3882         } else {
3883             warn!(
3884                 "Scanner registered callback for non-existent scanner info, UUID = {}",
3885                 DisplayUuid(&uuid)
3886             );
3887         }
3888 
3889         if status != GattStatus::Success {
3890             error!("Error registering scanner UUID {}", DisplayUuid(&uuid));
3891             self.scanners.remove(&uuid);
3892         }
3893     }
3894 
on_scan_result( &mut self, event_type: u16, addr_type: u8, address: RawAddress, primary_phy: u8, secondary_phy: u8, advertising_sid: u8, tx_power: i8, rssi: i8, periodic_adv_int: u16, adv_data: Vec<u8>, )3895     fn on_scan_result(
3896         &mut self,
3897         event_type: u16,
3898         addr_type: u8,
3899         address: RawAddress,
3900         primary_phy: u8,
3901         secondary_phy: u8,
3902         advertising_sid: u8,
3903         tx_power: i8,
3904         rssi: i8,
3905         periodic_adv_int: u16,
3906         adv_data: Vec<u8>,
3907     ) {
3908         self.scanner_callbacks.for_all_callbacks(|callback| {
3909             callback.on_scan_result(ScanResult {
3910                 name: adv_parser::extract_name(adv_data.as_slice()),
3911                 address,
3912                 addr_type,
3913                 event_type,
3914                 primary_phy,
3915                 secondary_phy,
3916                 advertising_sid,
3917                 tx_power,
3918                 rssi,
3919                 periodic_adv_int,
3920                 flags: adv_parser::extract_flags(adv_data.as_slice()),
3921                 service_uuids: adv_parser::extract_service_uuids(adv_data.as_slice()),
3922                 service_data: adv_parser::extract_service_data(adv_data.as_slice()),
3923                 manufacturer_data: adv_parser::extract_manufacturer_data(adv_data.as_slice()),
3924                 adv_data: adv_data.clone(),
3925             });
3926         });
3927     }
3928 
on_track_adv_found_lost(&mut self, track_adv_info: AdvertisingTrackInfo)3929     fn on_track_adv_found_lost(&mut self, track_adv_info: AdvertisingTrackInfo) {
3930         let addr = track_adv_info.advertiser_address;
3931         let display_addr = DisplayAddress(&addr);
3932         let mut corresponding_scanner: Option<&mut ScannerInfo> =
3933             self.scanners.values_mut().find_map(|scanner| {
3934                 if scanner.monitor_handle == Some(track_adv_info.monitor_handle) {
3935                     Some(scanner)
3936                 } else {
3937                     None
3938                 }
3939             });
3940         if corresponding_scanner.is_none() {
3941             corresponding_scanner = self.scanners.values_mut().find_map(|scanner| {
3942                 if scanner.addr_handle_map.contains_key(&addr) {
3943                     Some(scanner)
3944                 } else {
3945                     None
3946                 }
3947             });
3948         }
3949 
3950         let Some(corresponding_scanner) = corresponding_scanner else {
3951             info!(
3952                 "No scanner having monitor handle {}, already removed?",
3953                 track_adv_info.monitor_handle
3954             );
3955             return;
3956         };
3957         let Some(scanner_id) = corresponding_scanner.scanner_id else {
3958             error!(
3959                 "Scanner having monitor handle {} is missing scanner id",
3960                 track_adv_info.monitor_handle
3961             );
3962             return;
3963         };
3964 
3965         let controller_need_separate_pattern_and_address =
3966             corresponding_scanner.addr_tracking_quirk;
3967 
3968         let mut address_monitor_succeed: bool = false;
3969         if controller_need_separate_pattern_and_address {
3970             if track_adv_info.advertiser_state == 0x01 {
3971                 if corresponding_scanner.addr_handle_map.contains_key(&addr) {
3972                     debug!(
3973                         "on_track_adv_found_lost: this addr {} is already handled, just return",
3974                         display_addr
3975                     );
3976                     return;
3977                 }
3978                 debug!(
3979                     "on_track_adv_found_lost: state == 0x01, adding addr {} to map",
3980                     display_addr
3981                 );
3982                 corresponding_scanner.addr_handle_map.insert(addr, None);
3983 
3984                 let scan_filter_addr = ScanFilterAddress {
3985                     addr_type: track_adv_info.advertiser_address_type,
3986                     bd_addr: addr,
3987                 };
3988 
3989                 if let Some(saved_filter) = corresponding_scanner.filter.clone() {
3990                     let scan_filter = ScanFilter {
3991                         rssi_high_threshold: saved_filter.rssi_high_threshold,
3992                         rssi_low_threshold: saved_filter.rssi_low_threshold,
3993                         rssi_low_timeout: saved_filter.rssi_low_timeout,
3994                         rssi_sampling_period: saved_filter.rssi_sampling_period,
3995                         condition: ScanFilterCondition::BluetoothAddress(scan_filter_addr),
3996                     };
3997                     self.msft_command_queue
3998                         .push_back(MsftCommandQueue::Add(scanner_id, scan_filter));
3999                     self.msft_run_queue_and_update_scan();
4000                     address_monitor_succeed = true;
4001                 }
4002             } else {
4003                 if let Some(handle) = corresponding_scanner.monitor_handle {
4004                     if handle == track_adv_info.monitor_handle {
4005                         debug!("pattern filter lost, addr={}", display_addr);
4006                         return;
4007                     }
4008                 }
4009 
4010                 if corresponding_scanner.addr_handle_map.remove(&addr).is_some() {
4011                     debug!("on_track_adv_found_lost: removing addr = {} from map", display_addr);
4012                     self.msft_command_queue
4013                         .push_back(MsftCommandQueue::Remove(track_adv_info.monitor_handle));
4014                     self.msft_run_queue_and_update_scan();
4015                 }
4016             }
4017         }
4018 
4019         self.scanner_callbacks.for_all_callbacks(|callback| {
4020             let adv_data =
4021                 [&track_adv_info.adv_packet[..], &track_adv_info.scan_response[..]].concat();
4022 
4023             let scan_result = ScanResult {
4024                 name: adv_parser::extract_name(adv_data.as_slice()),
4025                 address: addr,
4026                 addr_type: track_adv_info.advertiser_address_type,
4027                 event_type: 0, /* not used */
4028                 primary_phy: LePhy::Phy1m as u8,
4029                 secondary_phy: 0,      /* not used */
4030                 advertising_sid: 0xff, /* not present */
4031                 /* A bug in libbluetooth that uses u8 for TX power.
4032                  * TODO(b/261482382): Fix the data type in C++ layer to use i8 instead of u8. */
4033                 tx_power: track_adv_info.tx_power as i8,
4034                 rssi: track_adv_info.rssi,
4035                 periodic_adv_int: 0, /* not used */
4036                 flags: adv_parser::extract_flags(adv_data.as_slice()),
4037                 service_uuids: adv_parser::extract_service_uuids(adv_data.as_slice()),
4038                 service_data: adv_parser::extract_service_data(adv_data.as_slice()),
4039                 manufacturer_data: adv_parser::extract_manufacturer_data(adv_data.as_slice()),
4040                 adv_data,
4041             };
4042 
4043             if track_adv_info.advertiser_state == 0x01 {
4044                 if !controller_need_separate_pattern_and_address || address_monitor_succeed {
4045                     callback.on_advertisement_found(scanner_id, scan_result);
4046                 }
4047             } else {
4048                 callback.on_advertisement_lost(scanner_id, scan_result);
4049             }
4050         });
4051     }
4052 }
4053 
4054 impl BtifGattAdvCallbacks for BluetoothGatt {
on_advertising_set_started( &mut self, reg_id: i32, advertiser_id: u8, tx_power: i8, status: AdvertisingStatus, )4055     fn on_advertising_set_started(
4056         &mut self,
4057         reg_id: i32,
4058         advertiser_id: u8,
4059         tx_power: i8,
4060         status: AdvertisingStatus,
4061     ) {
4062         self.adv_manager.get_impl().on_advertising_set_started(
4063             reg_id,
4064             advertiser_id,
4065             tx_power,
4066             status,
4067         );
4068     }
4069 
on_advertising_enabled(&mut self, adv_id: u8, enabled: bool, status: AdvertisingStatus)4070     fn on_advertising_enabled(&mut self, adv_id: u8, enabled: bool, status: AdvertisingStatus) {
4071         self.adv_manager.get_impl().on_advertising_enabled(adv_id, enabled, status);
4072     }
4073 
on_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus)4074     fn on_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus) {
4075         self.adv_manager.get_impl().on_advertising_data_set(adv_id, status);
4076     }
4077 
on_scan_response_data_set(&mut self, adv_id: u8, status: AdvertisingStatus)4078     fn on_scan_response_data_set(&mut self, adv_id: u8, status: AdvertisingStatus) {
4079         self.adv_manager.get_impl().on_scan_response_data_set(adv_id, status);
4080     }
4081 
on_advertising_parameters_updated( &mut self, adv_id: u8, tx_power: i8, status: AdvertisingStatus, )4082     fn on_advertising_parameters_updated(
4083         &mut self,
4084         adv_id: u8,
4085         tx_power: i8,
4086         status: AdvertisingStatus,
4087     ) {
4088         self.adv_manager.get_impl().on_advertising_parameters_updated(adv_id, tx_power, status);
4089     }
4090 
on_periodic_advertising_parameters_updated( &mut self, adv_id: u8, status: AdvertisingStatus, )4091     fn on_periodic_advertising_parameters_updated(
4092         &mut self,
4093         adv_id: u8,
4094         status: AdvertisingStatus,
4095     ) {
4096         self.adv_manager.get_impl().on_periodic_advertising_parameters_updated(adv_id, status);
4097     }
4098 
on_periodic_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus)4099     fn on_periodic_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus) {
4100         self.adv_manager.get_impl().on_periodic_advertising_data_set(adv_id, status);
4101     }
4102 
on_periodic_advertising_enabled( &mut self, adv_id: u8, enabled: bool, status: AdvertisingStatus, )4103     fn on_periodic_advertising_enabled(
4104         &mut self,
4105         adv_id: u8,
4106         enabled: bool,
4107         status: AdvertisingStatus,
4108     ) {
4109         self.adv_manager.get_impl().on_periodic_advertising_enabled(adv_id, enabled, status);
4110     }
4111 
on_own_address_read(&mut self, adv_id: u8, addr_type: u8, address: RawAddress)4112     fn on_own_address_read(&mut self, adv_id: u8, addr_type: u8, address: RawAddress) {
4113         self.adv_manager.get_impl().on_own_address_read(adv_id, addr_type, address);
4114     }
4115 }
4116 
4117 #[cfg(test)]
4118 mod tests {
4119     struct TestBluetoothGattCallback {
4120         id: String,
4121     }
4122 
4123     impl TestBluetoothGattCallback {
new(id: String) -> TestBluetoothGattCallback4124         fn new(id: String) -> TestBluetoothGattCallback {
4125             TestBluetoothGattCallback { id }
4126         }
4127     }
4128 
4129     impl IBluetoothGattCallback for TestBluetoothGattCallback {
on_client_registered(&mut self, _status: GattStatus, _client_id: i32)4130         fn on_client_registered(&mut self, _status: GattStatus, _client_id: i32) {}
on_client_connection_state( &mut self, _status: GattStatus, _client_id: i32, _connected: bool, _addr: RawAddress, )4131         fn on_client_connection_state(
4132             &mut self,
4133             _status: GattStatus,
4134             _client_id: i32,
4135             _connected: bool,
4136             _addr: RawAddress,
4137         ) {
4138         }
4139 
on_phy_update( &mut self, _addr: RawAddress, _tx_phy: LePhy, _rx_phy: LePhy, _status: GattStatus, )4140         fn on_phy_update(
4141             &mut self,
4142             _addr: RawAddress,
4143             _tx_phy: LePhy,
4144             _rx_phy: LePhy,
4145             _status: GattStatus,
4146         ) {
4147         }
4148 
on_phy_read( &mut self, _addr: RawAddress, _tx_phy: LePhy, _rx_phy: LePhy, _status: GattStatus, )4149         fn on_phy_read(
4150             &mut self,
4151             _addr: RawAddress,
4152             _tx_phy: LePhy,
4153             _rx_phy: LePhy,
4154             _status: GattStatus,
4155         ) {
4156         }
4157 
on_search_complete( &mut self, _addr: RawAddress, _services: Vec<BluetoothGattService>, _status: GattStatus, )4158         fn on_search_complete(
4159             &mut self,
4160             _addr: RawAddress,
4161             _services: Vec<BluetoothGattService>,
4162             _status: GattStatus,
4163         ) {
4164         }
4165 
on_characteristic_read( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, _value: Vec<u8>, )4166         fn on_characteristic_read(
4167             &mut self,
4168             _addr: RawAddress,
4169             _status: GattStatus,
4170             _handle: i32,
4171             _value: Vec<u8>,
4172         ) {
4173         }
4174 
on_characteristic_write( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, )4175         fn on_characteristic_write(
4176             &mut self,
4177             _addr: RawAddress,
4178             _status: GattStatus,
4179             _handle: i32,
4180         ) {
4181         }
4182 
on_execute_write(&mut self, _addr: RawAddress, _status: GattStatus)4183         fn on_execute_write(&mut self, _addr: RawAddress, _status: GattStatus) {}
4184 
on_descriptor_read( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, _value: Vec<u8>, )4185         fn on_descriptor_read(
4186             &mut self,
4187             _addr: RawAddress,
4188             _status: GattStatus,
4189             _handle: i32,
4190             _value: Vec<u8>,
4191         ) {
4192         }
4193 
on_descriptor_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32)4194         fn on_descriptor_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32) {}
4195 
on_notify(&mut self, _addr: RawAddress, _handle: i32, _value: Vec<u8>)4196         fn on_notify(&mut self, _addr: RawAddress, _handle: i32, _value: Vec<u8>) {}
4197 
on_read_remote_rssi(&mut self, _addr: RawAddress, _rssi: i32, _status: GattStatus)4198         fn on_read_remote_rssi(&mut self, _addr: RawAddress, _rssi: i32, _status: GattStatus) {}
4199 
on_configure_mtu(&mut self, _addr: RawAddress, _mtu: i32, _status: GattStatus)4200         fn on_configure_mtu(&mut self, _addr: RawAddress, _mtu: i32, _status: GattStatus) {}
4201 
on_connection_updated( &mut self, _addr: RawAddress, _interval: i32, _latency: i32, _timeout: i32, _status: GattStatus, )4202         fn on_connection_updated(
4203             &mut self,
4204             _addr: RawAddress,
4205             _interval: i32,
4206             _latency: i32,
4207             _timeout: i32,
4208             _status: GattStatus,
4209         ) {
4210         }
4211 
on_service_changed(&mut self, _addr: RawAddress)4212         fn on_service_changed(&mut self, _addr: RawAddress) {}
4213     }
4214 
4215     impl RPCProxy for TestBluetoothGattCallback {
get_object_id(&self) -> String4216         fn get_object_id(&self) -> String {
4217             self.id.clone()
4218         }
4219     }
4220 
4221     use super::*;
4222 
4223     #[test]
test_uuid_from_string()4224     fn test_uuid_from_string() {
4225         let uuid = Uuid::from_string("abcdef");
4226         assert!(uuid.is_none());
4227 
4228         let uuid = Uuid::from_string("0123456789abcdef0123456789abcdef");
4229         assert!(uuid.is_some());
4230         let expected: [u8; 16] = [
4231             0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab,
4232             0xcd, 0xef,
4233         ];
4234         assert_eq!(Uuid::from(expected), uuid.unwrap());
4235     }
4236 
4237     #[test]
test_context_map_clients()4238     fn test_context_map_clients() {
4239         let (tx, _rx) = crate::Stack::create_channel();
4240         let mut map = ContextMap::new(tx.clone());
4241 
4242         // Add client 1.
4243         let callback1 = Box::new(TestBluetoothGattCallback::new(String::from("Callback 1")));
4244         let uuid1 = Uuid::from_string("00000000000000000000000000000001").unwrap();
4245         map.add(&uuid1, callback1);
4246         let found = map.get_by_uuid(&uuid1);
4247         assert!(found.is_some());
4248         assert_eq!(
4249             "Callback 1",
4250             match found {
4251                 Some(c) => {
4252                     let cbid = c.cbid;
4253                     map.callbacks.get_by_id(cbid).map(|cb| cb.get_object_id()).unwrap_or_default()
4254                 }
4255                 None => String::new(),
4256             }
4257         );
4258 
4259         // Add client 2.
4260         let callback2 = Box::new(TestBluetoothGattCallback::new(String::from("Callback 2")));
4261         let uuid2 = Uuid::from_string("00000000000000000000000000000002").unwrap();
4262         map.add(&uuid2, callback2);
4263         let found = map.get_by_uuid(&uuid2);
4264         assert!(found.is_some());
4265         assert_eq!(
4266             "Callback 2",
4267             match found {
4268                 Some(c) => {
4269                     let cbid = c.cbid;
4270                     map.callbacks.get_by_id(cbid).map(|cb| cb.get_object_id()).unwrap_or_default()
4271                 }
4272                 None => String::new(),
4273             }
4274         );
4275 
4276         // Set client ID and get by client ID.
4277         map.set_client_id(&uuid1, 3);
4278         let found = map.get_by_client_id(3);
4279         assert!(found.is_some());
4280 
4281         // Remove client 1.
4282         map.remove(3);
4283         let found = map.get_by_uuid(&uuid1);
4284         assert!(found.is_none());
4285     }
4286 
4287     #[test]
test_context_map_connections()4288     fn test_context_map_connections() {
4289         let (tx, _rx) = crate::Stack::create_channel();
4290         let mut map = ContextMap::new(tx.clone());
4291         let client_id = 1;
4292 
4293         map.add_connection(client_id, 3, &RawAddress::from_string("aa:bb:cc:dd:ee:ff").unwrap());
4294         map.add_connection(client_id, 4, &RawAddress::from_string("11:22:33:44:55:66").unwrap());
4295 
4296         let found = map.get_conn_id_from_address(
4297             client_id,
4298             &RawAddress::from_string("aa:bb:cc:dd:ee:ff").unwrap(),
4299         );
4300         assert!(found.is_some());
4301         assert_eq!(3, found.unwrap());
4302 
4303         let found = map.get_conn_id_from_address(
4304             client_id,
4305             &RawAddress::from_string("11:22:33:44:55:66").unwrap(),
4306         );
4307         assert!(found.is_some());
4308         assert_eq!(4, found.unwrap());
4309     }
4310 }
4311