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