1 //! Anything related to the GATT API (IBluetoothGatt). 2 3 use btif_macros::{btif_callback, btif_callbacks_dispatcher}; 4 5 use bt_topshim::btif::{ 6 BluetoothInterface, BtStatus, BtTransport, DisplayAddress, DisplayUuid, RawAddress, Uuid, 7 }; 8 use bt_topshim::profiles::gatt::{ 9 AdvertisingStatus, AdvertisingTrackInfo, BtGattDbElement, BtGattNotifyParams, BtGattReadParams, 10 BtGattResponse, BtGattValue, Gatt, GattAdvCallbacksDispatcher, 11 GattAdvInbandCallbacksDispatcher, GattClientCallbacks, GattClientCallbacksDispatcher, 12 GattScannerCallbacks, GattScannerCallbacksDispatcher, GattScannerInbandCallbacks, 13 GattScannerInbandCallbacksDispatcher, GattServerCallbacks, GattServerCallbacksDispatcher, 14 GattStatus, LePhy, MsftAdvMonitor, MsftAdvMonitorAddress, MsftAdvMonitorPattern, 15 }; 16 use bt_topshim::sysprop; 17 use bt_topshim::topstack; 18 use bt_utils::adv_parser; 19 use bt_utils::array_utils; 20 21 use crate::async_helper::{AsyncHelper, CallbackSender}; 22 use crate::bluetooth::{Bluetooth, BluetoothDevice}; 23 use crate::bluetooth_adv::{ 24 AdvertiseData, AdvertiseManager, AdvertiserActions, AdvertisingSetParameters, 25 BtifGattAdvCallbacks, IAdvertisingSetCallback, PeriodicAdvertisingParameters, 26 }; 27 use crate::callbacks::Callbacks; 28 use crate::{APIMessage, BluetoothAPI, Message, RPCProxy, SuspendMode}; 29 use log::{info, warn}; 30 use num_derive::{FromPrimitive, ToPrimitive}; 31 use num_traits::cast::{FromPrimitive, ToPrimitive}; 32 use rand::rngs::SmallRng; 33 use rand::{RngCore, SeedableRng}; 34 use std::collections::{HashMap, HashSet}; 35 use std::convert::{TryFrom, TryInto}; 36 use std::sync::{Arc, Mutex, MutexGuard}; 37 use tokio::sync::mpsc::Sender; 38 use tokio::time; 39 40 struct Client { 41 id: Option<i32>, 42 cbid: u32, 43 uuid: Uuid, 44 is_congested: bool, 45 46 // Queued on_characteristic_write callback. 47 congestion_queue: Vec<(RawAddress, GattStatus, i32)>, 48 } 49 50 struct Connection { 51 conn_id: i32, 52 address: RawAddress, 53 54 // Connections are made to either a client or server 55 client_id: i32, 56 server_id: i32, 57 } 58 59 struct ContextMap { 60 // TODO(b/196635530): Consider using `multimap` for a more efficient implementation of get by 61 // multiple keys. 62 callbacks: Callbacks<dyn IBluetoothGattCallback + Send>, 63 clients: Vec<Client>, 64 connections: Vec<Connection>, 65 } 66 67 type GattClientCallback = Box<dyn IBluetoothGattCallback + Send>; 68 69 impl ContextMap { new(tx: Sender<Message>) -> ContextMap70 fn new(tx: Sender<Message>) -> ContextMap { 71 ContextMap { 72 callbacks: Callbacks::new(tx, Message::GattClientCallbackDisconnected), 73 clients: vec![], 74 connections: vec![], 75 } 76 } 77 get_by_uuid(&self, uuid: &Uuid) -> Option<&Client>78 fn get_by_uuid(&self, uuid: &Uuid) -> Option<&Client> { 79 self.clients.iter().find(|client| client.uuid == *uuid) 80 } 81 get_by_client_id(&self, client_id: i32) -> Option<&Client>82 fn get_by_client_id(&self, client_id: i32) -> Option<&Client> { 83 self.clients.iter().find(|client| client.id.is_some() && client.id.unwrap() == client_id) 84 } 85 get_by_client_id_mut(&mut self, client_id: i32) -> Option<&mut Client>86 fn get_by_client_id_mut(&mut self, client_id: i32) -> Option<&mut Client> { 87 self.clients 88 .iter_mut() 89 .find(|client| client.id.is_some() && client.id.unwrap() == client_id) 90 } 91 get_by_callback_id(&self, callback_id: u32) -> Option<&Client>92 fn get_by_callback_id(&self, callback_id: u32) -> Option<&Client> { 93 self.clients.iter().find(|client| client.cbid == callback_id) 94 } 95 get_address_by_conn_id(&self, conn_id: i32) -> Option<RawAddress>96 fn get_address_by_conn_id(&self, conn_id: i32) -> Option<RawAddress> { 97 match self.connections.iter().find(|conn| conn.conn_id == conn_id) { 98 None => None, 99 Some(conn) => Some(conn.address), 100 } 101 } 102 get_client_by_conn_id(&self, conn_id: i32) -> Option<&Client>103 fn get_client_by_conn_id(&self, conn_id: i32) -> Option<&Client> { 104 match self.connections.iter().find(|conn| conn.conn_id == conn_id) { 105 None => None, 106 Some(conn) => self.get_by_client_id(conn.client_id), 107 } 108 } 109 get_client_by_conn_id_mut(&mut self, conn_id: i32) -> Option<&mut Client>110 fn get_client_by_conn_id_mut(&mut self, conn_id: i32) -> Option<&mut Client> { 111 let client_id = match self.connections.iter().find(|conn| conn.conn_id == conn_id) { 112 None => return None, 113 Some(conn) => conn.client_id, 114 }; 115 116 self.get_by_client_id_mut(client_id) 117 } 118 add(&mut self, uuid: &Uuid, callback: GattClientCallback)119 fn add(&mut self, uuid: &Uuid, callback: GattClientCallback) { 120 if self.get_by_uuid(uuid).is_some() { 121 return; 122 } 123 124 let cbid = self.callbacks.add_callback(callback); 125 126 self.clients.push(Client { 127 id: None, 128 cbid, 129 uuid: uuid.clone(), 130 is_congested: false, 131 congestion_queue: vec![], 132 }); 133 } 134 remove(&mut self, id: i32)135 fn remove(&mut self, id: i32) { 136 // Remove any callbacks 137 if let Some(c) = self.get_by_client_id(id) { 138 let cbid = c.cbid; 139 self.remove_callback(cbid); 140 } 141 142 self.clients.retain(|client| !(client.id.is_some() && client.id.unwrap() == id)); 143 } 144 remove_callback(&mut self, callback_id: u32)145 fn remove_callback(&mut self, callback_id: u32) { 146 self.callbacks.remove_callback(callback_id); 147 } 148 set_client_id(&mut self, uuid: &Uuid, id: i32)149 fn set_client_id(&mut self, uuid: &Uuid, id: i32) { 150 if let Some(client) = self.clients.iter_mut().find(|client| client.uuid == *uuid) { 151 client.id = Some(id); 152 } 153 } 154 add_connection(&mut self, client_id: i32, conn_id: i32, address: &RawAddress)155 fn add_connection(&mut self, client_id: i32, conn_id: i32, address: &RawAddress) { 156 if self.get_conn_id_from_address(client_id, address).is_some() { 157 return; 158 } 159 160 self.connections.push(Connection { conn_id, address: *address, client_id, server_id: 0 }); 161 } 162 remove_connection(&mut self, _client_id: i32, conn_id: i32)163 fn remove_connection(&mut self, _client_id: i32, conn_id: i32) { 164 self.connections.retain(|conn| conn.conn_id != conn_id); 165 } 166 get_conn_id_from_address(&self, client_id: i32, address: &RawAddress) -> Option<i32>167 fn get_conn_id_from_address(&self, client_id: i32, address: &RawAddress) -> Option<i32> { 168 match self 169 .connections 170 .iter() 171 .find(|conn| conn.client_id == client_id && conn.address == *address) 172 { 173 None => None, 174 Some(conn) => Some(conn.conn_id), 175 } 176 } 177 get_client_ids_from_address(&self, address: &RawAddress) -> Vec<i32>178 fn get_client_ids_from_address(&self, address: &RawAddress) -> Vec<i32> { 179 self.connections 180 .iter() 181 .filter(|conn| conn.address == *address) 182 .map(|conn| conn.client_id) 183 .collect() 184 } 185 get_callback_from_callback_id( &mut self, callback_id: u32, ) -> Option<&mut GattClientCallback>186 fn get_callback_from_callback_id( 187 &mut self, 188 callback_id: u32, 189 ) -> Option<&mut GattClientCallback> { 190 self.callbacks.get_by_id_mut(callback_id) 191 } 192 } 193 194 struct Server { 195 id: Option<i32>, 196 cbid: u32, 197 uuid: Uuid, 198 services: Vec<BluetoothGattService>, 199 is_congested: bool, 200 201 // Queued on_notification_sent callback. 202 congestion_queue: Vec<(RawAddress, GattStatus)>, 203 } 204 205 struct Request { 206 id: i32, 207 handle: i32, 208 } 209 210 struct ServerContextMap { 211 // TODO(b/196635530): Consider using `multimap` for a more efficient implementation of get by 212 // multiple keys. 213 callbacks: Callbacks<dyn IBluetoothGattServerCallback + Send>, 214 servers: Vec<Server>, 215 connections: Vec<Connection>, 216 requests: Vec<Request>, 217 } 218 219 type GattServerCallback = Box<dyn IBluetoothGattServerCallback + Send>; 220 221 impl ServerContextMap { new(tx: Sender<Message>) -> ServerContextMap222 fn new(tx: Sender<Message>) -> ServerContextMap { 223 ServerContextMap { 224 callbacks: Callbacks::new(tx, Message::GattServerCallbackDisconnected), 225 servers: vec![], 226 connections: vec![], 227 requests: vec![], 228 } 229 } 230 get_by_uuid(&self, uuid: &Uuid) -> Option<&Server>231 fn get_by_uuid(&self, uuid: &Uuid) -> Option<&Server> { 232 self.servers.iter().find(|server| server.uuid == *uuid) 233 } 234 get_by_server_id(&self, server_id: i32) -> Option<&Server>235 fn get_by_server_id(&self, server_id: i32) -> Option<&Server> { 236 self.servers.iter().find(|server| server.id.map_or(false, |id| id == server_id)) 237 } 238 get_mut_by_server_id(&mut self, server_id: i32) -> Option<&mut Server>239 fn get_mut_by_server_id(&mut self, server_id: i32) -> Option<&mut Server> { 240 self.servers.iter_mut().find(|server| server.id.map_or(false, |id| id == server_id)) 241 } 242 get_by_callback_id(&self, callback_id: u32) -> Option<&Server>243 fn get_by_callback_id(&self, callback_id: u32) -> Option<&Server> { 244 self.servers.iter().find(|server| server.cbid == callback_id) 245 } 246 get_by_conn_id(&self, conn_id: i32) -> Option<&Server>247 fn get_by_conn_id(&self, conn_id: i32) -> Option<&Server> { 248 self.connections 249 .iter() 250 .find(|conn| conn.conn_id == conn_id) 251 .and_then(|conn| self.get_by_server_id(conn.server_id)) 252 } 253 get_mut_by_conn_id(&mut self, conn_id: i32) -> Option<&mut Server>254 fn get_mut_by_conn_id(&mut self, conn_id: i32) -> Option<&mut Server> { 255 self.connections 256 .iter() 257 .find_map(|conn| (conn.conn_id == conn_id).then(|| conn.server_id.clone())) 258 .and_then(move |server_id| self.get_mut_by_server_id(server_id)) 259 } 260 add(&mut self, uuid: &Uuid, callback: GattServerCallback)261 fn add(&mut self, uuid: &Uuid, callback: GattServerCallback) { 262 if self.get_by_uuid(uuid).is_some() { 263 return; 264 } 265 266 let cbid = self.callbacks.add_callback(callback); 267 268 self.servers.push(Server { 269 id: None, 270 cbid, 271 uuid: uuid.clone(), 272 services: vec![], 273 is_congested: false, 274 congestion_queue: vec![], 275 }); 276 } 277 remove(&mut self, id: i32)278 fn remove(&mut self, id: i32) { 279 // Remove any callbacks 280 if let Some(cbid) = self.get_by_server_id(id).map(|server| server.cbid) { 281 self.remove_callback(cbid); 282 } 283 284 self.servers.retain(|server| !(server.id.is_some() && server.id.unwrap() == id)); 285 } 286 remove_callback(&mut self, callback_id: u32)287 fn remove_callback(&mut self, callback_id: u32) { 288 self.callbacks.remove_callback(callback_id); 289 } 290 set_server_id(&mut self, uuid: &Uuid, id: i32)291 fn set_server_id(&mut self, uuid: &Uuid, id: i32) { 292 let server = self.servers.iter_mut().find(|server| server.uuid == *uuid); 293 if let Some(s) = server { 294 s.id = Some(id); 295 } 296 } 297 get_callback_from_callback_id( &mut self, callback_id: u32, ) -> Option<&mut GattServerCallback>298 fn get_callback_from_callback_id( 299 &mut self, 300 callback_id: u32, 301 ) -> Option<&mut GattServerCallback> { 302 self.callbacks.get_by_id_mut(callback_id) 303 } 304 add_connection(&mut self, server_id: i32, conn_id: i32, address: &RawAddress)305 fn add_connection(&mut self, server_id: i32, conn_id: i32, address: &RawAddress) { 306 if self.get_conn_id_from_address(server_id, address).is_some() { 307 return; 308 } 309 310 self.connections.push(Connection { conn_id, address: *address, client_id: 0, server_id }); 311 } 312 remove_connection(&mut self, conn_id: i32)313 fn remove_connection(&mut self, conn_id: i32) { 314 self.connections.retain(|conn| conn.conn_id != conn_id); 315 } 316 get_conn_id_from_address(&self, server_id: i32, address: &RawAddress) -> Option<i32>317 fn get_conn_id_from_address(&self, server_id: i32, address: &RawAddress) -> Option<i32> { 318 return self 319 .connections 320 .iter() 321 .find(|conn| conn.server_id == server_id && conn.address == *address) 322 .map(|conn| conn.conn_id); 323 } 324 get_server_ids_from_address(&self, address: &RawAddress) -> Vec<i32>325 fn get_server_ids_from_address(&self, address: &RawAddress) -> Vec<i32> { 326 self.connections 327 .iter() 328 .filter(|conn| conn.address == *address) 329 .map(|conn| conn.server_id) 330 .collect() 331 } 332 get_address_from_conn_id(&self, conn_id: i32) -> Option<RawAddress>333 fn get_address_from_conn_id(&self, conn_id: i32) -> Option<RawAddress> { 334 self.connections.iter().find_map(|conn| (conn.conn_id == conn_id).then(|| conn.address)) 335 } 336 add_service(&mut self, server_id: i32, service: BluetoothGattService)337 fn add_service(&mut self, server_id: i32, service: BluetoothGattService) { 338 if let Some(s) = self.get_mut_by_server_id(server_id) { 339 s.services.push(service) 340 } 341 } 342 delete_service(&mut self, server_id: i32, handle: i32)343 fn delete_service(&mut self, server_id: i32, handle: i32) { 344 self.get_mut_by_server_id(server_id) 345 .map(|s: &mut Server| s.services.retain(|service| service.instance_id != handle)); 346 } 347 add_request(&mut self, request_id: i32, handle: i32)348 fn add_request(&mut self, request_id: i32, handle: i32) { 349 self.requests.push(Request { id: request_id, handle }); 350 } 351 _delete_request(&mut self, request_id: i32)352 fn _delete_request(&mut self, request_id: i32) { 353 self.requests.retain(|request| request.id != request_id); 354 } 355 get_request_handle_from_id(&self, request_id: i32) -> Option<i32>356 fn get_request_handle_from_id(&self, request_id: i32) -> Option<i32> { 357 self.requests.iter().find_map(|request| (request.id == request_id).then(|| 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( &self, client_id: i32, addr: RawAddress, handle: i32, write_type: GattWriteType, auth_req: i32, value: Vec<u8>, ) -> GattWriteRequestStatus549 fn write_characteristic( 550 &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 Into<i32> for GattDbElementType { into(self) -> i321158 fn into(self) -> i32 { 1159 self.to_u8().unwrap_or(0).into() 1160 } 1161 } 1162 1163 #[derive(Debug, FromPrimitive, ToPrimitive, Copy, Clone)] 1164 #[repr(u8)] 1165 /// GATT write type. 1166 pub enum GattWriteType { 1167 Invalid = 0, 1168 WriteNoRsp = 1, 1169 Write = 2, 1170 WritePrepare = 3, 1171 } 1172 1173 impl Default for GattWriteType { default() -> Self1174 fn default() -> Self { 1175 GattWriteType::Write 1176 } 1177 } 1178 1179 #[derive(Debug, FromPrimitive, ToPrimitive, Clone, PartialEq)] 1180 #[repr(u32)] 1181 /// Scan type configuration. 1182 pub enum ScanType { 1183 Active = 0, 1184 Passive = 1, 1185 } 1186 1187 impl Default for ScanType { default() -> Self1188 fn default() -> Self { 1189 ScanType::Active 1190 } 1191 } 1192 1193 /// Represents scanning configurations to be passed to `IBluetoothGatt::start_scan`. 1194 /// 1195 /// This configuration is general and supported on all Bluetooth hardware, irrelevant of the 1196 /// hardware filter offload (APCF or MSFT). 1197 #[derive(Debug, Clone)] 1198 pub struct ScanSettings { 1199 pub interval: i32, 1200 pub window: i32, 1201 pub scan_type: ScanType, 1202 } 1203 1204 impl ScanSettings { extract_scan_parameters(&self) -> Option<(u8, u16, u16)>1205 fn extract_scan_parameters(&self) -> Option<(u8, u16, u16)> { 1206 let scan_type = match self.scan_type { 1207 ScanType::Passive => 0x00, 1208 ScanType::Active => 0x01, 1209 }; 1210 let interval = match u16::try_from(self.interval) { 1211 Ok(i) => i, 1212 Err(e) => { 1213 println!("Invalid scan interval {}: {}", self.interval, e); 1214 return None; 1215 } 1216 }; 1217 let window = match u16::try_from(self.window) { 1218 Ok(w) => w, 1219 Err(e) => { 1220 println!("Invalid scan window {}: {}", self.window, e); 1221 return None; 1222 } 1223 }; 1224 return Some((scan_type, interval, window)); 1225 } 1226 } 1227 1228 /// Represents scan result 1229 #[derive(Debug)] 1230 pub struct ScanResult { 1231 pub name: String, 1232 pub address: RawAddress, 1233 pub addr_type: u8, 1234 pub event_type: u16, 1235 pub primary_phy: u8, 1236 pub secondary_phy: u8, 1237 pub advertising_sid: u8, 1238 pub tx_power: i8, 1239 pub rssi: i8, 1240 pub periodic_adv_int: u16, 1241 pub flags: u8, 1242 pub service_uuids: Vec<Uuid>, 1243 /// A map of 128-bit UUID and its corresponding service data. 1244 pub service_data: HashMap<String, Vec<u8>>, 1245 pub manufacturer_data: HashMap<u16, Vec<u8>>, 1246 pub adv_data: Vec<u8>, 1247 } 1248 1249 #[derive(Debug, Clone)] 1250 pub struct ScanFilterPattern { 1251 /// Specifies the starting byte position of the pattern immediately following AD Type. 1252 pub start_position: u8, 1253 1254 /// Advertising Data type (https://www.bluetooth.com/specifications/assigned-numbers/). 1255 pub ad_type: u8, 1256 1257 /// The pattern to be matched for the specified AD Type within the advertisement packet from 1258 /// the specified starting byte. 1259 pub content: Vec<u8>, 1260 } 1261 1262 #[derive(Debug, Clone)] 1263 pub struct ScanFilterAddress { 1264 pub addr_type: u8, 1265 pub bd_addr: RawAddress, 1266 } 1267 1268 #[derive(Debug, Clone)] 1269 #[repr(u8)] 1270 pub enum ScanFilterConditionType { 1271 /// [MSFT HCI Extension](https://learn.microsoft.com/en-us/windows-hardware/drivers/bluetooth/microsoft-defined-bluetooth-hci-commands-and-events). 1272 MsftConditionTypeAll = 0x0, 1273 MsftConditionTypePatterns = 0x1, 1274 MsftConditionTypeUuid = 0x2, 1275 MsftConditionTypeIrkResolution = 0x3, 1276 MsftConditionTypeAddress = 0x4, 1277 } 1278 1279 /// Represents the condition for matching advertisements. 1280 /// 1281 /// Only pattern-based matching is implemented. 1282 #[derive(Debug, Clone)] 1283 pub enum ScanFilterCondition { 1284 /// All advertisements are matched. 1285 All, 1286 1287 /// Match by pattern anywhere in the advertisement data. Multiple patterns are "OR"-ed. 1288 Patterns(Vec<ScanFilterPattern>), 1289 1290 /// Match by UUID (not implemented). 1291 Uuid, 1292 1293 /// Match if the IRK resolves an advertisement (not implemented). 1294 Irk, 1295 1296 /// Match by Bluetooth address (not implemented). 1297 BluetoothAddress(ScanFilterAddress), 1298 } 1299 1300 /// Represents a scan filter to be passed to `IBluetoothGatt::start_scan`. 1301 /// 1302 /// This filter is intentionally modelled close to the MSFT hardware offload filter. 1303 /// Reference: 1304 /// https://learn.microsoft.com/en-us/windows-hardware/drivers/bluetooth/microsoft-defined-bluetooth-hci-commands-and-events 1305 #[derive(Debug, Clone)] 1306 pub struct ScanFilter { 1307 /// Advertisements with RSSI above or equal this value is considered "found". 1308 pub rssi_high_threshold: u8, 1309 1310 /// Advertisements with RSSI below or equal this value (for a period of rssi_low_timeout) is 1311 /// considered "lost". 1312 pub rssi_low_threshold: u8, 1313 1314 /// The time in seconds over which the RSSI value should be below rssi_low_threshold before 1315 /// being considered "lost". 1316 pub rssi_low_timeout: u8, 1317 1318 /// The sampling interval in milliseconds. 1319 pub rssi_sampling_period: u8, 1320 1321 /// The condition to match advertisements with. 1322 pub condition: ScanFilterCondition, 1323 } 1324 1325 type ScannersMap = HashMap<Uuid, ScannerInfo>; 1326 1327 const DEFAULT_ASYNC_TIMEOUT_MS: u64 = 5000; 1328 1329 /// Abstraction for async GATT operations. Contains async methods for coordinating async operations 1330 /// more conveniently. 1331 struct GattAsyncIntf { 1332 scanners: Arc<Mutex<ScannersMap>>, 1333 gatt: Option<Arc<Mutex<Gatt>>>, 1334 1335 async_helper_msft_adv_monitor_add: AsyncHelper<(u8, u8)>, 1336 async_helper_msft_adv_monitor_remove: AsyncHelper<u8>, 1337 async_helper_msft_adv_monitor_enable: AsyncHelper<u8>, 1338 } 1339 1340 impl GattAsyncIntf { 1341 /// Adds an advertisement monitor. Returns monitor handle and status. msft_adv_monitor_add(&mut self, monitor: MsftAdvMonitor) -> Result<(u8, u8), ()>1342 async fn msft_adv_monitor_add(&mut self, monitor: MsftAdvMonitor) -> Result<(u8, u8), ()> { 1343 let gatt = self.gatt.as_ref().unwrap().clone(); 1344 1345 self.async_helper_msft_adv_monitor_add 1346 .call_method( 1347 move |call_id| { 1348 gatt.lock().unwrap().scanner.msft_adv_monitor_add(call_id, &monitor); 1349 }, 1350 Some(DEFAULT_ASYNC_TIMEOUT_MS), 1351 ) 1352 .await 1353 } 1354 1355 /// Removes an advertisement monitor. Returns status. msft_adv_monitor_remove(&mut self, monitor_handle: u8) -> Result<u8, ()>1356 async fn msft_adv_monitor_remove(&mut self, monitor_handle: u8) -> Result<u8, ()> { 1357 let gatt = self.gatt.as_ref().unwrap().clone(); 1358 1359 self.async_helper_msft_adv_monitor_remove 1360 .call_method( 1361 move |call_id| { 1362 gatt.lock().unwrap().scanner.msft_adv_monitor_remove(call_id, monitor_handle); 1363 }, 1364 Some(DEFAULT_ASYNC_TIMEOUT_MS), 1365 ) 1366 .await 1367 } 1368 1369 /// Enables/disables an advertisement monitor. Returns status. msft_adv_monitor_enable(&mut self, enable: bool) -> Result<u8, ()>1370 async fn msft_adv_monitor_enable(&mut self, enable: bool) -> Result<u8, ()> { 1371 let gatt = self.gatt.as_ref().unwrap().clone(); 1372 1373 self.async_helper_msft_adv_monitor_enable 1374 .call_method( 1375 move |call_id| { 1376 gatt.lock().unwrap().scanner.msft_adv_monitor_enable(call_id, enable); 1377 }, 1378 Some(DEFAULT_ASYNC_TIMEOUT_MS), 1379 ) 1380 .await 1381 } 1382 1383 /// Updates the scan state depending on the states of registered scanners: 1384 /// 1. Scan is started if there is at least 1 enabled scanner. 1385 /// 2. Always toggle the scan off and on so that we reset the scan parameters based on whether 1386 /// we have enabled scanners using hardware filtering. 1387 /// TODO(b/266752123): We can do more bookkeeping to optimize when we really need to 1388 /// toggle. Also improve toggling API into 1 operation that guarantees correct ordering. 1389 /// 3. If there is an enabled ScanType::Active scanner, prefer its scan settings. Otherwise, 1390 /// adopt the settings from any of the enabled scanners. We shouldn't just use the settings 1391 /// from |scanner_id| because it may refer to a disabled scan. 1392 /// 1393 /// Note: this does not need to be async, but declared as async for consistency in this struct. 1394 /// May be converted into real async in the future if btif supports it. update_scan(&mut self, scanner_id: u8)1395 async fn update_scan(&mut self, scanner_id: u8) { 1396 let mut has_enabled_scan = false; 1397 let mut enabled_scan_param = None; 1398 let mut enabled_active_scan_param = None; 1399 for scanner in self.scanners.lock().unwrap().values() { 1400 if !scanner.is_enabled { 1401 continue; 1402 } 1403 has_enabled_scan = true; 1404 if let Some(ss) = &scanner.scan_settings { 1405 enabled_scan_param = ss.extract_scan_parameters(); 1406 if ss.scan_type == ScanType::Active { 1407 enabled_active_scan_param = ss.extract_scan_parameters(); 1408 break; 1409 } 1410 } 1411 } 1412 1413 self.gatt.as_ref().unwrap().lock().unwrap().scanner.stop_scan(); 1414 if !has_enabled_scan { 1415 return; 1416 } 1417 1418 if let Some((scan_type, scan_interval, scan_window)) = 1419 enabled_active_scan_param.or(enabled_scan_param) 1420 { 1421 self.gatt.as_ref().unwrap().lock().unwrap().scanner.set_scan_parameters( 1422 scanner_id, 1423 scan_type, 1424 scan_interval, 1425 scan_window, 1426 1, 1427 ); 1428 } 1429 self.gatt.as_ref().unwrap().lock().unwrap().scanner.start_scan(); 1430 } 1431 } 1432 1433 pub enum GattActions { 1434 /// This disconnects all server and client connections to the device. 1435 /// Params: remote_device 1436 Disconnect(BluetoothDevice), 1437 } 1438 1439 /// Implementation of the GATT API (IBluetoothGatt). 1440 pub struct BluetoothGatt { 1441 intf: Arc<Mutex<BluetoothInterface>>, 1442 // TODO(b/254870880): Wrapping in an `Option` makes the code unnecessarily verbose. Find a way 1443 // to not wrap this in `Option` since we know that we can't function without `gatt` being 1444 // initialized anyway. 1445 gatt: Option<Arc<Mutex<Gatt>>>, 1446 1447 context_map: ContextMap, 1448 server_context_map: ServerContextMap, 1449 reliable_queue: HashSet<RawAddress>, 1450 scanner_callbacks: Callbacks<dyn IScannerCallback + Send>, 1451 scanners: Arc<Mutex<ScannersMap>>, 1452 scan_suspend_mode: SuspendMode, 1453 adv_manager: AdvertiseManager, 1454 1455 adv_mon_add_cb_sender: CallbackSender<(u8, u8)>, 1456 adv_mon_remove_cb_sender: CallbackSender<u8>, 1457 adv_mon_enable_cb_sender: CallbackSender<u8>, 1458 1459 // Used for generating random UUIDs. SmallRng is chosen because it is fast, don't use this for 1460 // cryptography. 1461 small_rng: SmallRng, 1462 1463 gatt_async: Arc<tokio::sync::Mutex<GattAsyncIntf>>, 1464 enabled: bool, 1465 } 1466 1467 impl BluetoothGatt { 1468 /// Constructs a new IBluetoothGatt implementation. new(intf: Arc<Mutex<BluetoothInterface>>, tx: Sender<Message>) -> BluetoothGatt1469 pub fn new(intf: Arc<Mutex<BluetoothInterface>>, tx: Sender<Message>) -> BluetoothGatt { 1470 let scanners = Arc::new(Mutex::new(HashMap::new())); 1471 1472 let async_helper_msft_adv_monitor_add = AsyncHelper::new("MsftAdvMonitorAdd"); 1473 let async_helper_msft_adv_monitor_remove = AsyncHelper::new("MsftAdvMonitorRemove"); 1474 let async_helper_msft_adv_monitor_enable = AsyncHelper::new("MsftAdvMonitorEnable"); 1475 BluetoothGatt { 1476 intf, 1477 gatt: None, 1478 context_map: ContextMap::new(tx.clone()), 1479 server_context_map: ServerContextMap::new(tx.clone()), 1480 reliable_queue: HashSet::new(), 1481 scanner_callbacks: Callbacks::new(tx.clone(), Message::ScannerCallbackDisconnected), 1482 scanners: scanners.clone(), 1483 scan_suspend_mode: SuspendMode::Normal, 1484 small_rng: SmallRng::from_entropy(), 1485 adv_manager: AdvertiseManager::new(tx.clone()), 1486 adv_mon_add_cb_sender: async_helper_msft_adv_monitor_add.get_callback_sender(), 1487 adv_mon_remove_cb_sender: async_helper_msft_adv_monitor_remove.get_callback_sender(), 1488 adv_mon_enable_cb_sender: async_helper_msft_adv_monitor_enable.get_callback_sender(), 1489 gatt_async: Arc::new(tokio::sync::Mutex::new(GattAsyncIntf { 1490 scanners, 1491 gatt: None, 1492 async_helper_msft_adv_monitor_add, 1493 async_helper_msft_adv_monitor_remove, 1494 async_helper_msft_adv_monitor_enable, 1495 })), 1496 enabled: false, 1497 } 1498 } 1499 init_profiles(&mut self, tx: Sender<Message>, api_tx: Sender<APIMessage>)1500 pub fn init_profiles(&mut self, tx: Sender<Message>, api_tx: Sender<APIMessage>) { 1501 self.gatt = Gatt::new(&self.intf.lock().unwrap()).map(|gatt| Arc::new(Mutex::new(gatt))); 1502 1503 let tx_clone = tx.clone(); 1504 let gatt_client_callbacks_dispatcher = GattClientCallbacksDispatcher { 1505 dispatch: Box::new(move |cb| { 1506 let tx_clone = tx_clone.clone(); 1507 topstack::get_runtime().spawn(async move { 1508 let _ = tx_clone.send(Message::GattClient(cb)).await; 1509 }); 1510 }), 1511 }; 1512 1513 let tx_clone = tx.clone(); 1514 let gatt_server_callbacks_dispatcher = GattServerCallbacksDispatcher { 1515 dispatch: Box::new(move |cb| { 1516 let tx_clone = tx_clone.clone(); 1517 topstack::get_runtime().spawn(async move { 1518 let _ = tx_clone.send(Message::GattServer(cb)).await; 1519 }); 1520 }), 1521 }; 1522 1523 let tx_clone = tx.clone(); 1524 let gatt_scanner_callbacks_dispatcher = GattScannerCallbacksDispatcher { 1525 dispatch: Box::new(move |cb| { 1526 let tx_clone = tx_clone.clone(); 1527 topstack::get_runtime().spawn(async move { 1528 let _ = tx_clone.send(Message::LeScanner(cb)).await; 1529 }); 1530 }), 1531 }; 1532 1533 let tx_clone = tx.clone(); 1534 let gatt_scanner_inband_callbacks_dispatcher = GattScannerInbandCallbacksDispatcher { 1535 dispatch: Box::new(move |cb| { 1536 let tx_clone = tx_clone.clone(); 1537 topstack::get_runtime().spawn(async move { 1538 let _ = tx_clone.send(Message::LeScannerInband(cb)).await; 1539 }); 1540 }), 1541 }; 1542 1543 let tx_clone = tx.clone(); 1544 let gatt_adv_inband_callbacks_dispatcher = GattAdvInbandCallbacksDispatcher { 1545 dispatch: Box::new(move |cb| { 1546 let tx_clone = tx_clone.clone(); 1547 topstack::get_runtime().spawn(async move { 1548 let _ = tx_clone.send(Message::LeAdvInband(cb)).await; 1549 }); 1550 }), 1551 }; 1552 1553 let tx_clone = tx.clone(); 1554 let gatt_adv_callbacks_dispatcher = GattAdvCallbacksDispatcher { 1555 dispatch: Box::new(move |cb| { 1556 let tx_clone = tx_clone.clone(); 1557 topstack::get_runtime().spawn(async move { 1558 let _ = tx_clone.send(Message::LeAdv(cb)).await; 1559 }); 1560 }), 1561 }; 1562 1563 self.gatt.as_ref().unwrap().lock().unwrap().initialize( 1564 gatt_client_callbacks_dispatcher, 1565 gatt_server_callbacks_dispatcher, 1566 gatt_scanner_callbacks_dispatcher, 1567 gatt_scanner_inband_callbacks_dispatcher, 1568 gatt_adv_inband_callbacks_dispatcher, 1569 gatt_adv_callbacks_dispatcher, 1570 ); 1571 1572 let gatt = self.gatt.clone(); 1573 let gatt_async = self.gatt_async.clone(); 1574 let api_tx_clone = api_tx.clone(); 1575 tokio::spawn(async move { 1576 gatt_async.lock().await.gatt = gatt; 1577 // TODO(b/247093293): Gatt topshim api is only usable some 1578 // time after init. Investigate why this delay is needed 1579 // and make it a blocking part before removing this. 1580 time::sleep(time::Duration::from_millis(500)).await; 1581 let _ = api_tx_clone.send(APIMessage::IsReady(BluetoothAPI::Gatt)).await; 1582 }); 1583 } 1584 1585 /// Initializes AdvertiseManager. 1586 /// 1587 /// Query |is_le_ext_adv_supported| outside this function (before locking BluetoothGatt) to 1588 /// avoid deadlock. |is_le_ext_adv_supported| can only be queried after Bluetooth is ready. 1589 /// 1590 /// TODO(b/242083290): Correctly fire IsReady message for Adv API in this function after the 1591 /// API is fully split out. For now Gatt is delayed for 500ms (see 1592 /// |BluetoothGatt::init_profiles|) which shall be enough for Bluetooth to become ready. init_adv_manager( &mut self, adapter: Arc<Mutex<Box<Bluetooth>>>, is_le_ext_adv_supported: bool, )1593 pub fn init_adv_manager( 1594 &mut self, 1595 adapter: Arc<Mutex<Box<Bluetooth>>>, 1596 is_le_ext_adv_supported: bool, 1597 ) { 1598 self.adv_manager.initialize( 1599 self.gatt.as_ref().unwrap().clone(), 1600 adapter, 1601 is_le_ext_adv_supported, 1602 ); 1603 } 1604 enable(&mut self, enabled: bool)1605 pub fn enable(&mut self, enabled: bool) { 1606 self.enabled = enabled; 1607 } 1608 1609 /// Remove a scanner callback and unregisters all scanners associated with that callback. remove_scanner_callback(&mut self, callback_id: u32) -> bool1610 pub fn remove_scanner_callback(&mut self, callback_id: u32) -> bool { 1611 let affected_scanner_ids: Vec<u8> = self 1612 .scanners 1613 .lock() 1614 .unwrap() 1615 .iter() 1616 .filter(|(_uuid, scanner)| scanner.callback_id == callback_id) 1617 .filter_map(|(_uuid, scanner)| { 1618 if let Some(scanner_id) = scanner.scanner_id { 1619 Some(scanner_id) 1620 } else { 1621 None 1622 } 1623 }) 1624 .collect(); 1625 1626 // All scanners associated with the callback must be also unregistered. 1627 for scanner_id in affected_scanner_ids { 1628 self.unregister_scanner(scanner_id); 1629 } 1630 1631 self.scanner_callbacks.remove_callback(callback_id) 1632 } 1633 1634 /// Set the suspend mode. set_scan_suspend_mode(&mut self, suspend_mode: SuspendMode)1635 pub fn set_scan_suspend_mode(&mut self, suspend_mode: SuspendMode) { 1636 if suspend_mode != self.scan_suspend_mode { 1637 self.scan_suspend_mode = suspend_mode.clone(); 1638 1639 // Notify current suspend mode to all active callbacks. 1640 self.scanner_callbacks.for_all_callbacks(|callback| { 1641 callback.on_suspend_mode_change(suspend_mode.clone()); 1642 }); 1643 } 1644 } 1645 1646 /// Enters suspend mode for LE Scan. 1647 /// 1648 /// This "pauses" all operations managed by this module to prepare for system suspend. A 1649 /// callback is triggered to let clients know that this module is in suspend mode and some 1650 /// subsequent API calls will be blocked in this mode. scan_enter_suspend(&mut self) -> BtStatus1651 pub fn scan_enter_suspend(&mut self) -> BtStatus { 1652 if self.get_scan_suspend_mode() != SuspendMode::Normal { 1653 return BtStatus::Busy; 1654 } 1655 self.set_scan_suspend_mode(SuspendMode::Suspending); 1656 1657 let scanners_to_suspend = self 1658 .scanners 1659 .lock() 1660 .unwrap() 1661 .iter() 1662 .filter_map( 1663 |(_uuid, scanner)| if scanner.is_enabled { scanner.scanner_id } else { None }, 1664 ) 1665 .collect::<Vec<_>>(); 1666 // Note: We can't simply disable the LE scanning. When a filter is offloaded 1667 // with the MSFT extension and it is monitoring a device, it sends a 1668 // `Monitor Device Event` to indicate that monitoring is stopped and this 1669 // can cause an early wake-up. Until we fix the disable + mask solution, we 1670 // must remove all monitors before suspend and re-monitor them on resume. 1671 for scanner_id in scanners_to_suspend { 1672 self.stop_scan(scanner_id); 1673 if let Some(scanner) = 1674 Self::find_scanner_by_id(&mut self.scanners.lock().unwrap(), scanner_id) 1675 { 1676 scanner.is_suspended = true; 1677 } 1678 } 1679 self.set_scan_suspend_mode(SuspendMode::Suspended); 1680 return BtStatus::Success; 1681 } 1682 1683 /// Exits suspend mode for LE Scan. 1684 /// 1685 /// To be called after system resume/wake up. This "unpauses" the operations that were "paused" 1686 /// due to suspend. A callback is triggered to let clients when this module has exited suspend 1687 /// mode. scan_exit_suspend(&mut self) -> BtStatus1688 pub fn scan_exit_suspend(&mut self) -> BtStatus { 1689 if self.get_scan_suspend_mode() != SuspendMode::Suspended { 1690 return BtStatus::Busy; 1691 } 1692 self.set_scan_suspend_mode(SuspendMode::Resuming); 1693 1694 self.scanners.lock().unwrap().retain(|_uuid, scanner| { 1695 if let (true, Some(scanner_id)) = (scanner.is_unregistered, scanner.scanner_id) { 1696 self.gatt.as_ref().unwrap().lock().unwrap().scanner.unregister(scanner_id); 1697 } 1698 !scanner.is_unregistered 1699 }); 1700 1701 let scanners_to_resume = self 1702 .scanners 1703 .lock() 1704 .unwrap() 1705 .iter() 1706 .filter_map( 1707 |(_uuid, scanner)| if scanner.is_suspended { scanner.scanner_id } else { None }, 1708 ) 1709 .collect::<Vec<_>>(); 1710 for scanner_id in scanners_to_resume { 1711 let status = self.resume_scan(scanner_id); 1712 if status != BtStatus::Success { 1713 log::error!("Failed to resume scanner {}, status={:?}", scanner_id, status); 1714 } 1715 if let Some(scanner) = 1716 Self::find_scanner_by_id(&mut self.scanners.lock().unwrap(), scanner_id) 1717 { 1718 scanner.is_suspended = false; 1719 } 1720 } 1721 1722 self.set_scan_suspend_mode(SuspendMode::Normal); 1723 1724 return BtStatus::Success; 1725 } 1726 find_scanner_by_id<'a>( scanners: &'a mut MutexGuard<ScannersMap>, scanner_id: u8, ) -> Option<&'a mut ScannerInfo>1727 fn find_scanner_by_id<'a>( 1728 scanners: &'a mut MutexGuard<ScannersMap>, 1729 scanner_id: u8, 1730 ) -> Option<&'a mut ScannerInfo> { 1731 scanners.values_mut().find(|scanner| scanner.scanner_id == Some(scanner_id)) 1732 } 1733 1734 /// The resume_scan method is used to resume scanning after system suspension. 1735 /// It assumes that scanner.filter has already had the filter data. resume_scan(&mut self, scanner_id: u8) -> BtStatus1736 fn resume_scan(&mut self, scanner_id: u8) -> BtStatus { 1737 if !self.enabled { 1738 return BtStatus::UnexpectedState; 1739 } 1740 1741 if self.get_scan_suspend_mode() != SuspendMode::Resuming { 1742 return BtStatus::Busy; 1743 } 1744 1745 let filter = { 1746 let mut scanners_lock = self.scanners.lock().unwrap(); 1747 if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) { 1748 if scanner.is_suspended { 1749 scanner.is_suspended = false; 1750 scanner.is_enabled = true; 1751 // When a scanner resumes from a suspended state, the 1752 // scanner.filter has already had the filter data. 1753 scanner.filter.clone() 1754 } else { 1755 log::warn!( 1756 "This Scanner {} is supposed to resume from suspended state", 1757 scanner_id 1758 ); 1759 return BtStatus::UnexpectedState; 1760 } 1761 } else { 1762 log::warn!("Scanner {} not found", scanner_id); 1763 return BtStatus::Fail; 1764 } 1765 }; 1766 1767 self.add_monitor_and_update_scan(scanner_id, filter) 1768 } 1769 add_child_monitor(&self, scanner_id: u8, scan_filter: ScanFilter) -> BtStatus1770 fn add_child_monitor(&self, scanner_id: u8, scan_filter: ScanFilter) -> BtStatus { 1771 let gatt_async = self.gatt_async.clone(); 1772 let scanners = self.scanners.clone(); 1773 let is_msft_supported = self.is_msft_supported(); 1774 1775 // Add and enable the monitor filter only when the MSFT extension is supported. 1776 if !is_msft_supported { 1777 log::error!("add_child_monitor: MSFT extension is not supported"); 1778 return BtStatus::Unsupported; 1779 } 1780 log::debug!( 1781 "add_child_monitor: monitoring address, scanner_id={}, filter={:?}", 1782 scanner_id, 1783 scan_filter 1784 ); 1785 1786 tokio::spawn(async move { 1787 // Add address monitor to track the specified device 1788 let mut gatt_async = gatt_async.lock().await; 1789 1790 let monitor_handle = match gatt_async.msft_adv_monitor_add((&scan_filter).into()).await 1791 { 1792 Ok((handle, 0)) => handle, 1793 _ => { 1794 log::error!("Error adding advertisement monitor"); 1795 return; 1796 } 1797 }; 1798 1799 if let Some(scanner) = 1800 Self::find_scanner_by_id(&mut scanners.lock().unwrap(), scanner_id) 1801 { 1802 // After hci complete event is received, update the monitor_handle. 1803 // The address monitor handles are needed in stop_scan(). 1804 let addr_info: MsftAdvMonitorAddress = (&scan_filter.condition).into(); 1805 1806 if scanner.addr_handle_map.contains_key(&addr_info.bd_addr) { 1807 scanner.addr_handle_map.insert(addr_info.bd_addr, Some(monitor_handle)); 1808 log::debug!( 1809 "Added addr monitor {} and updated bd_addr={} to addr filter map", 1810 monitor_handle, 1811 DisplayAddress(&addr_info.bd_addr) 1812 ); 1813 return; 1814 } else { 1815 log::debug!("add_child_monitor: bd_addr {} has been removed, removing the addr monitor {}.", 1816 DisplayAddress(&addr_info.bd_addr), 1817 monitor_handle); 1818 } 1819 } else { 1820 log::warn!( 1821 "add_child_monitor: scanner has been removed, removing the addr monitor {}", 1822 monitor_handle 1823 ); 1824 } 1825 let _res = gatt_async.msft_adv_monitor_remove(monitor_handle).await; 1826 }); 1827 1828 BtStatus::Success 1829 } 1830 remove_child_monitor(&self, _scanner_id: u8, monitor_handle: u8) -> BtStatus1831 fn remove_child_monitor(&self, _scanner_id: u8, monitor_handle: u8) -> BtStatus { 1832 let gatt_async = self.gatt_async.clone(); 1833 let is_msft_supported = self.is_msft_supported(); 1834 tokio::spawn(async move { 1835 let mut gatt_async = gatt_async.lock().await; 1836 1837 // Remove and disable the monitor only when the MSFT extension is supported. 1838 if is_msft_supported { 1839 let _res = gatt_async.msft_adv_monitor_remove(monitor_handle).await; 1840 log::debug!("Removed addr monitor {}.", monitor_handle); 1841 } 1842 }); 1843 BtStatus::Success 1844 } 1845 add_monitor_and_update_scan( &mut self, scanner_id: u8, filter: Option<ScanFilter>, ) -> BtStatus1846 fn add_monitor_and_update_scan( 1847 &mut self, 1848 scanner_id: u8, 1849 filter: Option<ScanFilter>, 1850 ) -> BtStatus { 1851 let gatt_async = self.gatt_async.clone(); 1852 let scanners = self.scanners.clone(); 1853 let is_msft_supported = self.is_msft_supported(); 1854 1855 tokio::spawn(async move { 1856 // The three operations below (monitor add, monitor enable, update scan) happen one 1857 // after another, and cannot be interleaved with other GATT async operations. 1858 // So acquire the GATT async lock in the beginning of this block and will be released 1859 // at the end of this block. 1860 // TODO(b/217274432): Consider not using async model but instead add actions when 1861 // handling callbacks. 1862 let mut gatt_async = gatt_async.lock().await; 1863 1864 // Add and enable the monitor filter only when the MSFT extension is supported. 1865 if is_msft_supported { 1866 if let Some(filter) = filter { 1867 let monitor_handle = 1868 match gatt_async.msft_adv_monitor_add((&filter).into()).await { 1869 Ok((handle, 0)) => handle, 1870 _ => { 1871 log::error!("Error adding advertisement monitor"); 1872 return; 1873 } 1874 }; 1875 1876 if let Some(scanner) = 1877 Self::find_scanner_by_id(&mut scanners.lock().unwrap(), scanner_id) 1878 { 1879 scanner.monitor_handle = Some(monitor_handle); 1880 } 1881 1882 log::debug!("Added adv pattern monitor handle = {}", monitor_handle); 1883 } 1884 1885 let has_enabled_unfiltered_scanner = scanners 1886 .lock() 1887 .unwrap() 1888 .iter() 1889 .any(|(_uuid, scanner)| scanner.is_enabled && scanner.filter.is_none()); 1890 1891 if !gatt_async 1892 .msft_adv_monitor_enable(!has_enabled_unfiltered_scanner) 1893 .await 1894 .map_or(false, |status| status == 0) 1895 { 1896 // TODO(b/266752123): 1897 // Intel controller throws "Command Disallowed" error if we tried to enable/disable 1898 // filter but it's already at the same state. This is harmless but we can improve 1899 // the state machine to avoid calling enable/disable if it's already at that state 1900 log::error!("Error updating Advertisement Monitor enable"); 1901 } 1902 } 1903 1904 gatt_async.update_scan(scanner_id).await; 1905 }); 1906 1907 BtStatus::Success 1908 } 1909 1910 /// Remove an adv_manager callback and unregisters all advertising sets associated with that callback. remove_adv_callback(&mut self, callback_id: u32) -> bool1911 pub fn remove_adv_callback(&mut self, callback_id: u32) -> bool { 1912 self.adv_manager.get_impl().unregister_callback(callback_id) 1913 } 1914 remove_client_callback(&mut self, callback_id: u32)1915 pub fn remove_client_callback(&mut self, callback_id: u32) { 1916 // Unregister client if client id exists. 1917 if let Some(client) = self.context_map.get_by_callback_id(callback_id) { 1918 if let Some(id) = client.id { 1919 self.unregister_client(id); 1920 } 1921 } 1922 1923 // Always remove callback. 1924 self.context_map.remove_callback(callback_id); 1925 } 1926 remove_server_callback(&mut self, callback_id: u32)1927 pub fn remove_server_callback(&mut self, callback_id: u32) { 1928 // Unregister server if server id exists. 1929 if let Some(server) = self.server_context_map.get_by_callback_id(callback_id) { 1930 if let Some(id) = server.id { 1931 self.unregister_server(id); 1932 } 1933 } 1934 1935 // Always remove callback. 1936 self.context_map.remove_callback(callback_id); 1937 } 1938 1939 /// Enters suspend mode for LE advertising. advertising_enter_suspend(&mut self)1940 pub fn advertising_enter_suspend(&mut self) { 1941 self.adv_manager.get_impl().enter_suspend() 1942 } 1943 1944 /// Exits suspend mode for LE advertising. advertising_exit_suspend(&mut self)1945 pub fn advertising_exit_suspend(&mut self) { 1946 self.adv_manager.get_impl().exit_suspend() 1947 } 1948 1949 /// Start an active scan on given scanner id. This will look up and assign 1950 /// the correct ScanSettings for it as well. start_active_scan(&mut self, scanner_id: u8) -> BtStatus1951 pub(crate) fn start_active_scan(&mut self, scanner_id: u8) -> BtStatus { 1952 let settings = ScanSettings { 1953 interval: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanInterval), 1954 window: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanWindow), 1955 scan_type: ScanType::Active, 1956 }; 1957 1958 self.start_scan(scanner_id, Some(settings), /*filter=*/ None) 1959 } 1960 stop_active_scan(&mut self, scanner_id: u8) -> BtStatus1961 pub(crate) fn stop_active_scan(&mut self, scanner_id: u8) -> BtStatus { 1962 self.stop_scan(scanner_id) 1963 } 1964 handle_action(&mut self, action: GattActions)1965 pub fn handle_action(&mut self, action: GattActions) { 1966 match action { 1967 GattActions::Disconnect(device) => { 1968 for client_id in self.context_map.get_client_ids_from_address(&device.address) { 1969 if let Some(conn_id) = 1970 self.context_map.get_conn_id_from_address(client_id, &device.address) 1971 { 1972 self.gatt.as_ref().unwrap().lock().unwrap().client.disconnect( 1973 client_id, 1974 &device.address, 1975 conn_id, 1976 ); 1977 } 1978 } 1979 for server_id in 1980 self.server_context_map.get_server_ids_from_address(&device.address) 1981 { 1982 if let Some(conn_id) = 1983 self.server_context_map.get_conn_id_from_address(server_id, &device.address) 1984 { 1985 self.gatt.as_ref().unwrap().lock().unwrap().server.disconnect( 1986 server_id, 1987 &device.address, 1988 conn_id, 1989 ); 1990 } 1991 } 1992 } 1993 } 1994 } 1995 handle_adv_action(&mut self, action: AdvertiserActions)1996 pub fn handle_adv_action(&mut self, action: AdvertiserActions) { 1997 self.adv_manager.get_impl().handle_action(action); 1998 } 1999 } 2000 2001 #[derive(Debug, FromPrimitive, ToPrimitive)] 2002 #[repr(u8)] 2003 /// Status of WriteCharacteristic methods. 2004 pub enum GattWriteRequestStatus { 2005 Success = 0, 2006 Fail = 1, 2007 Busy = 2, 2008 } 2009 2010 // This structure keeps track of the lifecycle of a scanner. 2011 #[derive(Debug)] 2012 struct ScannerInfo { 2013 // The callback to which events about this scanner needs to be sent to. 2014 // Another purpose of keeping track of the callback id is that when a callback is disconnected 2015 // or unregistered we need to also unregister all scanners associated with that callback to 2016 // prevent dangling unowned scanners. 2017 callback_id: u32, 2018 // If the scanner is registered successfully, this contains the scanner id, otherwise None. 2019 scanner_id: Option<u8>, 2020 // If one of scanners is enabled, we scan. 2021 is_enabled: bool, 2022 // Scan filter. 2023 filter: Option<ScanFilter>, 2024 // Adv monitor handle, if exists. 2025 monitor_handle: Option<u8>, 2026 // If suspended then we need to resume it on exit_suspend. 2027 is_suspended: bool, 2028 /// Whether the unregistration of the scanner is held. 2029 /// This flag is set when a scanner is unregistered while we're not able to do it, such as: 2030 /// - The system is suspending / suspended 2031 /// 2032 /// The scanner would be unregistered after the system exits the suspended state. 2033 is_unregistered: bool, 2034 // The scan parameters to use 2035 scan_settings: Option<ScanSettings>, 2036 // Whether the MSFT extension monitor tracking by address filter quirk will be used. 2037 addr_tracking_quirk: bool, 2038 // Stores all the monitored handles for pattern and address. 2039 addr_handle_map: HashMap<RawAddress, Option<u8>>, 2040 } 2041 2042 impl ScannerInfo { new(callback_id: u32) -> Self2043 fn new(callback_id: u32) -> Self { 2044 Self { 2045 callback_id, 2046 scanner_id: None, 2047 is_enabled: false, 2048 filter: None, 2049 monitor_handle: None, 2050 is_suspended: false, 2051 is_unregistered: false, 2052 scan_settings: None, 2053 addr_tracking_quirk: sysprop::get_bool(sysprop::PropertyBool::LeAdvMonRtlQuirk), 2054 addr_handle_map: HashMap::new(), 2055 } 2056 } 2057 } 2058 2059 impl Into<MsftAdvMonitorPattern> for &ScanFilterPattern { into(self) -> MsftAdvMonitorPattern2060 fn into(self) -> MsftAdvMonitorPattern { 2061 MsftAdvMonitorPattern { 2062 ad_type: self.ad_type, 2063 start_byte: self.start_position, 2064 pattern: self.content.clone(), 2065 } 2066 } 2067 } 2068 2069 impl Into<Vec<MsftAdvMonitorPattern>> for &ScanFilterCondition { into(self) -> Vec<MsftAdvMonitorPattern>2070 fn into(self) -> Vec<MsftAdvMonitorPattern> { 2071 match self { 2072 ScanFilterCondition::Patterns(patterns) => { 2073 patterns.iter().map(|pattern| pattern.into()).collect() 2074 } 2075 _ => vec![], 2076 } 2077 } 2078 } 2079 2080 impl Into<MsftAdvMonitorAddress> for &ScanFilterAddress { into(self) -> MsftAdvMonitorAddress2081 fn into(self) -> MsftAdvMonitorAddress { 2082 MsftAdvMonitorAddress { addr_type: self.addr_type, bd_addr: self.bd_addr } 2083 } 2084 } 2085 2086 impl Into<MsftAdvMonitorAddress> for &ScanFilterCondition { into(self) -> MsftAdvMonitorAddress2087 fn into(self) -> MsftAdvMonitorAddress { 2088 match &self { 2089 ScanFilterCondition::BluetoothAddress(addr_info) => addr_info.into(), 2090 _ => MsftAdvMonitorAddress { addr_type: 0, bd_addr: RawAddress::empty() }, 2091 } 2092 } 2093 } 2094 2095 impl Into<MsftAdvMonitor> for &ScanFilter { into(self) -> MsftAdvMonitor2096 fn into(self) -> MsftAdvMonitor { 2097 let scan_filter_condition_type = match self.condition { 2098 ScanFilterCondition::Patterns(_) => { 2099 ScanFilterConditionType::MsftConditionTypePatterns as u8 2100 } 2101 ScanFilterCondition::BluetoothAddress(_) => { 2102 ScanFilterConditionType::MsftConditionTypeAddress as u8 2103 } 2104 _ => ScanFilterConditionType::MsftConditionTypeAll as u8, 2105 }; 2106 MsftAdvMonitor { 2107 rssi_high_threshold: self.rssi_high_threshold.try_into().unwrap(), 2108 rssi_low_threshold: self.rssi_low_threshold.try_into().unwrap(), 2109 rssi_low_timeout: self.rssi_low_timeout.try_into().unwrap(), 2110 rssi_sampling_period: self.rssi_sampling_period.try_into().unwrap(), 2111 condition_type: scan_filter_condition_type, 2112 patterns: (&self.condition).into(), 2113 addr_info: (&self.condition).into(), 2114 } 2115 } 2116 } 2117 2118 impl IBluetoothGatt for BluetoothGatt { is_msft_supported(&self) -> bool2119 fn is_msft_supported(&self) -> bool { 2120 self.gatt.as_ref().unwrap().lock().unwrap().scanner.is_msft_supported() 2121 } 2122 register_scanner_callback(&mut self, callback: Box<dyn IScannerCallback + Send>) -> u322123 fn register_scanner_callback(&mut self, callback: Box<dyn IScannerCallback + Send>) -> u32 { 2124 self.scanner_callbacks.add_callback(callback) 2125 } 2126 unregister_scanner_callback(&mut self, callback_id: u32) -> bool2127 fn unregister_scanner_callback(&mut self, callback_id: u32) -> bool { 2128 self.remove_scanner_callback(callback_id) 2129 } 2130 register_scanner(&mut self, callback_id: u32) -> Uuid2131 fn register_scanner(&mut self, callback_id: u32) -> Uuid { 2132 if !self.enabled { 2133 return Uuid::empty(); 2134 } 2135 2136 let mut bytes: [u8; 16] = [0; 16]; 2137 self.small_rng.fill_bytes(&mut bytes); 2138 let uuid = Uuid::from(bytes); 2139 2140 self.scanners.lock().unwrap().insert(uuid, ScannerInfo::new(callback_id)); 2141 2142 // libbluetooth's register_scanner takes a UUID of the scanning application. This UUID does 2143 // not correspond to higher level concept of "application" so we use random UUID that 2144 // functions as a unique identifier of the scanner. 2145 self.gatt.as_ref().unwrap().lock().unwrap().scanner.register_scanner(uuid); 2146 2147 uuid 2148 } 2149 unregister_scanner(&mut self, scanner_id: u8) -> bool2150 fn unregister_scanner(&mut self, scanner_id: u8) -> bool { 2151 if self.get_scan_suspend_mode() != SuspendMode::Normal { 2152 if let Some(scanner) = 2153 Self::find_scanner_by_id(&mut self.scanners.lock().unwrap(), scanner_id) 2154 { 2155 info!("Deferred scanner unregistration due to suspending"); 2156 scanner.is_unregistered = true; 2157 return true; 2158 } else { 2159 warn!("Scanner {} not found", scanner_id); 2160 return false; 2161 } 2162 } 2163 2164 self.gatt.as_ref().unwrap().lock().unwrap().scanner.unregister(scanner_id); 2165 2166 // The unregistered scanner must also be stopped. 2167 self.stop_scan(scanner_id); 2168 2169 self.scanners 2170 .lock() 2171 .unwrap() 2172 .retain(|_uuid, scanner| scanner.scanner_id != Some(scanner_id)); 2173 2174 true 2175 } 2176 start_scan( &mut self, scanner_id: u8, settings: Option<ScanSettings>, filter: Option<ScanFilter>, ) -> BtStatus2177 fn start_scan( 2178 &mut self, 2179 scanner_id: u8, 2180 settings: Option<ScanSettings>, 2181 filter: Option<ScanFilter>, 2182 ) -> BtStatus { 2183 if !self.enabled { 2184 return BtStatus::UnexpectedState; 2185 } 2186 2187 if self.get_scan_suspend_mode() != SuspendMode::Normal { 2188 return BtStatus::Busy; 2189 } 2190 2191 // If the client is not specifying scan settings, the default one will be used. 2192 let settings = settings.unwrap_or_else(|| { 2193 // Offloaded filtering + Active scan doesn't work correctly on some QCA chips - It 2194 // behaves like "Filter policy: Accept all advertisement" and impacts the power 2195 // consumption. Thus, we by default select Passive scan if the quirk is on and the 2196 // filter is set. 2197 // OTOH the clients are still allowed to explicitly set the scan type Active, so in case 2198 // the scan response data is necessary this quirk will not cause any functionality 2199 // breakage. 2200 let scan_type = 2201 if sysprop::get_bool(sysprop::PropertyBool::LeAdvMonQcaQuirk) && filter.is_some() { 2202 ScanType::Passive 2203 } else { 2204 ScanType::default() 2205 }; 2206 ScanSettings { 2207 interval: sysprop::get_i32(sysprop::PropertyI32::LeAdvMonScanInterval), 2208 window: sysprop::get_i32(sysprop::PropertyI32::LeAdvMonScanWindow), 2209 scan_type, 2210 } 2211 }); 2212 2213 // Multiplexing scanners happens at this layer. The implementations of start_scan 2214 // and stop_scan maintains the state of all registered scanners and based on the states 2215 // update the scanning and/or filter states of libbluetooth. 2216 { 2217 let mut scanners_lock = self.scanners.lock().unwrap(); 2218 2219 if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) { 2220 scanner.is_enabled = true; 2221 scanner.filter = filter.clone(); 2222 scanner.scan_settings = Some(settings); 2223 } else { 2224 log::warn!("Scanner {} not found", scanner_id); 2225 return BtStatus::Fail; 2226 } 2227 } 2228 2229 return self.add_monitor_and_update_scan(scanner_id, filter); 2230 } 2231 stop_scan(&mut self, scanner_id: u8) -> BtStatus2232 fn stop_scan(&mut self, scanner_id: u8) -> BtStatus { 2233 if !self.enabled { 2234 return BtStatus::UnexpectedState; 2235 } 2236 2237 let scan_suspend_mode = self.get_scan_suspend_mode(); 2238 if scan_suspend_mode != SuspendMode::Normal && scan_suspend_mode != SuspendMode::Suspending 2239 { 2240 return BtStatus::Busy; 2241 } 2242 2243 let monitor_handles = { 2244 let mut scanners_lock = self.scanners.lock().unwrap(); 2245 2246 if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) { 2247 scanner.is_enabled = false; 2248 let mut handles: Vec<u8> = vec![]; 2249 2250 if let Some(handle) = scanner.monitor_handle.take() { 2251 handles.push(handle); 2252 } 2253 2254 for (_addr, handle) in scanner.addr_handle_map.drain() { 2255 if let Some(h) = handle { 2256 handles.push(h); 2257 } 2258 } 2259 handles 2260 } else { 2261 log::warn!("Scanner {} not found", scanner_id); 2262 // Clients can assume success of the removal since the scanner does not exist. 2263 return BtStatus::Success; 2264 } 2265 }; 2266 2267 let gatt_async = self.gatt_async.clone(); 2268 let scanners = self.scanners.clone(); 2269 let is_msft_supported = self.is_msft_supported(); 2270 tokio::spawn(async move { 2271 // The two operations below (monitor remove, update scan) happen one after another, and 2272 // cannot be interleaved with other GATT async operations. 2273 // So acquire the GATT async lock in the beginning of this block and will be released 2274 // at the end of this block. 2275 let mut gatt_async = gatt_async.lock().await; 2276 2277 // Remove and disable the monitor only when the MSFT extension is supported. 2278 if is_msft_supported { 2279 for handle in monitor_handles { 2280 let _res = gatt_async.msft_adv_monitor_remove(handle).await; 2281 } 2282 2283 let has_enabled_unfiltered_scanner = scanners 2284 .lock() 2285 .unwrap() 2286 .iter() 2287 .any(|(_uuid, scanner)| scanner.is_enabled && scanner.filter.is_none()); 2288 2289 if !gatt_async 2290 .msft_adv_monitor_enable(!has_enabled_unfiltered_scanner) 2291 .await 2292 .map_or(false, |status| status == 0) 2293 { 2294 log::error!("Error updating Advertisement Monitor enable"); 2295 } 2296 } 2297 2298 gatt_async.update_scan(scanner_id).await; 2299 }); 2300 2301 BtStatus::Success 2302 } 2303 get_scan_suspend_mode(&self) -> SuspendMode2304 fn get_scan_suspend_mode(&self) -> SuspendMode { 2305 self.scan_suspend_mode.clone() 2306 } 2307 2308 // Advertising 2309 register_advertiser_callback( &mut self, callback: Box<dyn IAdvertisingSetCallback + Send>, ) -> u322310 fn register_advertiser_callback( 2311 &mut self, 2312 callback: Box<dyn IAdvertisingSetCallback + Send>, 2313 ) -> u32 { 2314 self.adv_manager.get_impl().register_callback(callback) 2315 } 2316 unregister_advertiser_callback(&mut self, callback_id: u32) -> bool2317 fn unregister_advertiser_callback(&mut self, callback_id: u32) -> bool { 2318 self.adv_manager.get_impl().unregister_callback(callback_id) 2319 } 2320 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, ) -> i322321 fn start_advertising_set( 2322 &mut self, 2323 parameters: AdvertisingSetParameters, 2324 advertise_data: AdvertiseData, 2325 scan_response: Option<AdvertiseData>, 2326 periodic_parameters: Option<PeriodicAdvertisingParameters>, 2327 periodic_data: Option<AdvertiseData>, 2328 duration: i32, 2329 max_ext_adv_events: i32, 2330 callback_id: u32, 2331 ) -> i32 { 2332 self.adv_manager.get_impl().start_advertising_set( 2333 parameters, 2334 advertise_data, 2335 scan_response, 2336 periodic_parameters, 2337 periodic_data, 2338 duration, 2339 max_ext_adv_events, 2340 callback_id, 2341 ) 2342 } 2343 stop_advertising_set(&mut self, advertiser_id: i32)2344 fn stop_advertising_set(&mut self, advertiser_id: i32) { 2345 self.adv_manager.get_impl().stop_advertising_set(advertiser_id) 2346 } 2347 get_own_address(&mut self, advertiser_id: i32)2348 fn get_own_address(&mut self, advertiser_id: i32) { 2349 self.adv_manager.get_impl().get_own_address(advertiser_id); 2350 } 2351 enable_advertising_set( &mut self, advertiser_id: i32, enable: bool, duration: i32, max_ext_adv_events: i32, )2352 fn enable_advertising_set( 2353 &mut self, 2354 advertiser_id: i32, 2355 enable: bool, 2356 duration: i32, 2357 max_ext_adv_events: i32, 2358 ) { 2359 self.adv_manager.get_impl().enable_advertising_set( 2360 advertiser_id, 2361 enable, 2362 duration, 2363 max_ext_adv_events, 2364 ); 2365 } 2366 set_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData)2367 fn set_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData) { 2368 self.adv_manager.get_impl().set_advertising_data(advertiser_id, data); 2369 } 2370 set_raw_adv_data(&mut self, advertiser_id: i32, data: Vec<u8>)2371 fn set_raw_adv_data(&mut self, advertiser_id: i32, data: Vec<u8>) { 2372 self.adv_manager.get_impl().set_raw_adv_data(advertiser_id, data); 2373 } 2374 set_scan_response_data(&mut self, advertiser_id: i32, data: AdvertiseData)2375 fn set_scan_response_data(&mut self, advertiser_id: i32, data: AdvertiseData) { 2376 self.adv_manager.get_impl().set_scan_response_data(advertiser_id, data); 2377 } 2378 set_advertising_parameters( &mut self, advertiser_id: i32, parameters: AdvertisingSetParameters, )2379 fn set_advertising_parameters( 2380 &mut self, 2381 advertiser_id: i32, 2382 parameters: AdvertisingSetParameters, 2383 ) { 2384 self.adv_manager.get_impl().set_advertising_parameters(advertiser_id, parameters); 2385 } 2386 set_periodic_advertising_parameters( &mut self, advertiser_id: i32, parameters: PeriodicAdvertisingParameters, )2387 fn set_periodic_advertising_parameters( 2388 &mut self, 2389 advertiser_id: i32, 2390 parameters: PeriodicAdvertisingParameters, 2391 ) { 2392 self.adv_manager.get_impl().set_periodic_advertising_parameters(advertiser_id, parameters); 2393 } 2394 set_periodic_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData)2395 fn set_periodic_advertising_data(&mut self, advertiser_id: i32, data: AdvertiseData) { 2396 self.adv_manager.get_impl().set_periodic_advertising_data(advertiser_id, data); 2397 } 2398 set_periodic_advertising_enable( &mut self, advertiser_id: i32, enable: bool, include_adi: bool, )2399 fn set_periodic_advertising_enable( 2400 &mut self, 2401 advertiser_id: i32, 2402 enable: bool, 2403 include_adi: bool, 2404 ) { 2405 self.adv_manager.get_impl().set_periodic_advertising_enable( 2406 advertiser_id, 2407 enable, 2408 include_adi, 2409 ); 2410 } 2411 2412 // GATT Client 2413 register_client( &mut self, app_uuid: String, callback: Box<dyn IBluetoothGattCallback + Send>, eatt_support: bool, )2414 fn register_client( 2415 &mut self, 2416 app_uuid: String, 2417 callback: Box<dyn IBluetoothGattCallback + Send>, 2418 eatt_support: bool, 2419 ) { 2420 let Some(uuid) = Uuid::from_string(app_uuid.clone()) else { 2421 warn!("register_client: Uuid is malformed: {}", app_uuid); 2422 return; 2423 }; 2424 self.context_map.add(&uuid, callback); 2425 self.gatt 2426 .as_ref() 2427 .expect("GATT has not been initialized") 2428 .lock() 2429 .unwrap() 2430 .client 2431 .register_client(&uuid, eatt_support); 2432 } 2433 unregister_client(&mut self, client_id: i32)2434 fn unregister_client(&mut self, client_id: i32) { 2435 self.context_map.remove(client_id); 2436 self.gatt.as_ref().unwrap().lock().unwrap().client.unregister_client(client_id); 2437 } 2438 client_connect( &self, client_id: i32, addr: RawAddress, is_direct: bool, transport: BtTransport, opportunistic: bool, phy: LePhy, )2439 fn client_connect( 2440 &self, 2441 client_id: i32, 2442 addr: RawAddress, 2443 is_direct: bool, 2444 transport: BtTransport, 2445 opportunistic: bool, 2446 phy: LePhy, 2447 ) { 2448 self.gatt.as_ref().unwrap().lock().unwrap().client.connect( 2449 client_id, 2450 &addr, 2451 // Addr type is default PUBLIC. 2452 0, 2453 is_direct, 2454 transport.into(), 2455 opportunistic, 2456 phy.into(), 2457 ); 2458 } 2459 client_disconnect(&self, client_id: i32, addr: RawAddress)2460 fn client_disconnect(&self, client_id: i32, addr: RawAddress) { 2461 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2462 return; 2463 }; 2464 2465 self.gatt.as_ref().unwrap().lock().unwrap().client.disconnect(client_id, &addr, conn_id); 2466 } 2467 refresh_device(&self, client_id: i32, addr: RawAddress)2468 fn refresh_device(&self, client_id: i32, addr: RawAddress) { 2469 self.gatt.as_ref().unwrap().lock().unwrap().client.refresh(client_id, &addr); 2470 } 2471 discover_services(&self, client_id: i32, addr: RawAddress)2472 fn discover_services(&self, client_id: i32, addr: RawAddress) { 2473 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2474 return; 2475 }; 2476 2477 self.gatt.as_ref().unwrap().lock().unwrap().client.search_service(conn_id, None); 2478 } 2479 discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String)2480 fn discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String) { 2481 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2482 return; 2483 }; 2484 2485 let uuid = Uuid::from_string(uuid); 2486 if uuid.is_none() { 2487 return; 2488 } 2489 2490 self.gatt.as_ref().unwrap().lock().unwrap().client.search_service(conn_id, uuid); 2491 } 2492 btif_gattc_discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String)2493 fn btif_gattc_discover_service_by_uuid(&self, client_id: i32, addr: RawAddress, uuid: String) { 2494 let conn_id = match self.context_map.get_conn_id_from_address(client_id, &addr) { 2495 None => return, 2496 Some(id) => id, 2497 }; 2498 let Some(uuid) = Uuid::from_string(uuid) else { return }; 2499 2500 self.gatt 2501 .as_ref() 2502 .unwrap() 2503 .lock() 2504 .unwrap() 2505 .client 2506 .btif_gattc_discover_service_by_uuid(conn_id, &uuid); 2507 } 2508 read_characteristic(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32)2509 fn read_characteristic(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32) { 2510 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2511 return; 2512 }; 2513 2514 // TODO(b/200065274): Perform check on restricted handles. 2515 2516 self.gatt.as_ref().unwrap().lock().unwrap().client.read_characteristic( 2517 conn_id, 2518 handle as u16, 2519 auth_req, 2520 ); 2521 } 2522 read_using_characteristic_uuid( &self, client_id: i32, addr: RawAddress, uuid: String, start_handle: i32, end_handle: i32, auth_req: i32, )2523 fn read_using_characteristic_uuid( 2524 &self, 2525 client_id: i32, 2526 addr: RawAddress, 2527 uuid: String, 2528 start_handle: i32, 2529 end_handle: i32, 2530 auth_req: i32, 2531 ) { 2532 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2533 return; 2534 }; 2535 let Some(uuid) = Uuid::from_string(uuid) else { return }; 2536 2537 // TODO(b/200065274): Perform check on restricted handles. 2538 2539 self.gatt.as_ref().unwrap().lock().unwrap().client.read_using_characteristic_uuid( 2540 conn_id, 2541 &uuid, 2542 start_handle as u16, 2543 end_handle as u16, 2544 auth_req, 2545 ); 2546 } 2547 write_characteristic( &self, client_id: i32, addr: RawAddress, handle: i32, mut write_type: GattWriteType, auth_req: i32, value: Vec<u8>, ) -> GattWriteRequestStatus2548 fn write_characteristic( 2549 &self, 2550 client_id: i32, 2551 addr: RawAddress, 2552 handle: i32, 2553 mut write_type: GattWriteType, 2554 auth_req: i32, 2555 value: Vec<u8>, 2556 ) -> GattWriteRequestStatus { 2557 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2558 return GattWriteRequestStatus::Fail; 2559 }; 2560 2561 if self.reliable_queue.contains(&addr) { 2562 write_type = GattWriteType::WritePrepare; 2563 } 2564 2565 // TODO(b/200065274): Perform check on restricted handles. 2566 2567 // TODO(b/200070162): Handle concurrent write characteristic. 2568 2569 self.gatt.as_ref().unwrap().lock().unwrap().client.write_characteristic( 2570 conn_id, 2571 handle as u16, 2572 write_type.to_i32().unwrap(), 2573 auth_req, 2574 &value, 2575 ); 2576 2577 return GattWriteRequestStatus::Success; 2578 } 2579 read_descriptor(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32)2580 fn read_descriptor(&self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32) { 2581 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2582 return; 2583 }; 2584 2585 // TODO(b/200065274): Perform check on restricted handles. 2586 2587 self.gatt.as_ref().unwrap().lock().unwrap().client.read_descriptor( 2588 conn_id, 2589 handle as u16, 2590 auth_req, 2591 ); 2592 } 2593 write_descriptor( &self, client_id: i32, addr: RawAddress, handle: i32, auth_req: i32, value: Vec<u8>, )2594 fn write_descriptor( 2595 &self, 2596 client_id: i32, 2597 addr: RawAddress, 2598 handle: i32, 2599 auth_req: i32, 2600 value: Vec<u8>, 2601 ) { 2602 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2603 return; 2604 }; 2605 2606 // TODO(b/200065274): Perform check on restricted handles. 2607 2608 self.gatt.as_ref().unwrap().lock().unwrap().client.write_descriptor( 2609 conn_id, 2610 handle as u16, 2611 auth_req, 2612 &value, 2613 ); 2614 } 2615 register_for_notification( &self, client_id: i32, addr: RawAddress, handle: i32, enable: bool, )2616 fn register_for_notification( 2617 &self, 2618 client_id: i32, 2619 addr: RawAddress, 2620 handle: i32, 2621 enable: bool, 2622 ) { 2623 let conn_id = self.context_map.get_conn_id_from_address(client_id, &addr); 2624 if conn_id.is_none() { 2625 return; 2626 } 2627 2628 // TODO(b/200065274): Perform check on restricted handles. 2629 2630 if enable { 2631 self.gatt.as_ref().unwrap().lock().unwrap().client.register_for_notification( 2632 client_id, 2633 &addr, 2634 handle as u16, 2635 ); 2636 } else { 2637 self.gatt.as_ref().unwrap().lock().unwrap().client.deregister_for_notification( 2638 client_id, 2639 &addr, 2640 handle as u16, 2641 ); 2642 } 2643 } 2644 begin_reliable_write(&mut self, _client_id: i32, addr: RawAddress)2645 fn begin_reliable_write(&mut self, _client_id: i32, addr: RawAddress) { 2646 self.reliable_queue.insert(addr); 2647 } 2648 end_reliable_write(&mut self, client_id: i32, addr: RawAddress, execute: bool)2649 fn end_reliable_write(&mut self, client_id: i32, addr: RawAddress, execute: bool) { 2650 self.reliable_queue.remove(&addr); 2651 2652 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2653 return; 2654 }; 2655 2656 self.gatt 2657 .as_ref() 2658 .unwrap() 2659 .lock() 2660 .unwrap() 2661 .client 2662 .execute_write(conn_id, if execute { 1 } else { 0 }); 2663 } 2664 read_remote_rssi(&self, client_id: i32, addr: RawAddress)2665 fn read_remote_rssi(&self, client_id: i32, addr: RawAddress) { 2666 self.gatt.as_ref().unwrap().lock().unwrap().client.read_remote_rssi(client_id, &addr); 2667 } 2668 configure_mtu(&self, client_id: i32, addr: RawAddress, mtu: i32)2669 fn configure_mtu(&self, client_id: i32, addr: RawAddress, mtu: i32) { 2670 let Some(conn_id) = self.context_map.get_conn_id_from_address(client_id, &addr) else { 2671 return; 2672 }; 2673 2674 self.gatt.as_ref().unwrap().lock().unwrap().client.configure_mtu(conn_id, mtu); 2675 } 2676 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, )2677 fn connection_parameter_update( 2678 &self, 2679 _client_id: i32, 2680 addr: RawAddress, 2681 min_interval: i32, 2682 max_interval: i32, 2683 latency: i32, 2684 timeout: i32, 2685 min_ce_len: u16, 2686 max_ce_len: u16, 2687 ) { 2688 self.gatt.as_ref().unwrap().lock().unwrap().client.conn_parameter_update( 2689 &addr, 2690 min_interval, 2691 max_interval, 2692 latency, 2693 timeout, 2694 min_ce_len, 2695 max_ce_len, 2696 ); 2697 } 2698 client_set_preferred_phy( &self, client_id: i32, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, phy_options: i32, )2699 fn client_set_preferred_phy( 2700 &self, 2701 client_id: i32, 2702 addr: RawAddress, 2703 tx_phy: LePhy, 2704 rx_phy: LePhy, 2705 phy_options: i32, 2706 ) { 2707 let conn_id = self.context_map.get_conn_id_from_address(client_id, &addr); 2708 if conn_id.is_none() { 2709 return; 2710 } 2711 2712 self.gatt.as_ref().unwrap().lock().unwrap().client.set_preferred_phy( 2713 &addr, 2714 tx_phy.to_u8().unwrap(), 2715 rx_phy.to_u8().unwrap(), 2716 phy_options as u16, 2717 ); 2718 } 2719 client_read_phy(&mut self, client_id: i32, addr: RawAddress)2720 fn client_read_phy(&mut self, client_id: i32, addr: RawAddress) { 2721 self.gatt.as_ref().unwrap().lock().unwrap().client.read_phy(client_id, &addr); 2722 } 2723 2724 // GATT Server 2725 register_server( &mut self, app_uuid: String, callback: Box<dyn IBluetoothGattServerCallback + Send>, eatt_support: bool, )2726 fn register_server( 2727 &mut self, 2728 app_uuid: String, 2729 callback: Box<dyn IBluetoothGattServerCallback + Send>, 2730 eatt_support: bool, 2731 ) { 2732 let Some(uuid) = Uuid::from_string(app_uuid.clone()) else { 2733 warn!("register_server: Uuid is malformed: {}", app_uuid); 2734 return; 2735 }; 2736 self.server_context_map.add(&uuid, callback); 2737 self.gatt 2738 .as_ref() 2739 .expect("GATT has not been initialized") 2740 .lock() 2741 .unwrap() 2742 .server 2743 .register_server(&uuid, eatt_support); 2744 } 2745 unregister_server(&mut self, server_id: i32)2746 fn unregister_server(&mut self, server_id: i32) { 2747 self.server_context_map.remove(server_id); 2748 self.gatt.as_ref().unwrap().lock().unwrap().server.unregister_server(server_id); 2749 } 2750 server_connect( &self, server_id: i32, addr: RawAddress, is_direct: bool, transport: BtTransport, ) -> bool2751 fn server_connect( 2752 &self, 2753 server_id: i32, 2754 addr: RawAddress, 2755 is_direct: bool, 2756 transport: BtTransport, 2757 ) -> bool { 2758 self.gatt.as_ref().unwrap().lock().unwrap().server.connect( 2759 server_id, 2760 &addr, 2761 // Addr type is default PUBLIC. 2762 0, 2763 is_direct, 2764 transport.into(), 2765 ); 2766 2767 true 2768 } 2769 server_disconnect(&self, server_id: i32, addr: RawAddress) -> bool2770 fn server_disconnect(&self, server_id: i32, addr: RawAddress) -> bool { 2771 let conn_id = match self.server_context_map.get_conn_id_from_address(server_id, &addr) { 2772 None => return false, 2773 Some(id) => id, 2774 }; 2775 2776 self.gatt.as_ref().unwrap().lock().unwrap().server.disconnect(server_id, &addr, conn_id); 2777 2778 true 2779 } 2780 add_service(&self, server_id: i32, service: BluetoothGattService)2781 fn add_service(&self, server_id: i32, service: BluetoothGattService) { 2782 if let Some(server) = self.server_context_map.get_by_server_id(server_id) { 2783 self.gatt 2784 .as_ref() 2785 .unwrap() 2786 .lock() 2787 .unwrap() 2788 .server 2789 .add_service(server_id, &BluetoothGattService::into_db(service, &server.services)); 2790 } else { 2791 log::error!("Server id {} is not valid", server_id); 2792 } 2793 } 2794 remove_service(&self, server_id: i32, handle: i32)2795 fn remove_service(&self, server_id: i32, handle: i32) { 2796 self.gatt.as_ref().unwrap().lock().unwrap().server.delete_service(server_id, handle); 2797 } 2798 clear_services(&self, server_id: i32)2799 fn clear_services(&self, server_id: i32) { 2800 if let Some(s) = self.server_context_map.get_by_server_id(server_id) { 2801 for service in &s.services { 2802 self.gatt 2803 .as_ref() 2804 .unwrap() 2805 .lock() 2806 .unwrap() 2807 .server 2808 .delete_service(server_id, service.instance_id); 2809 } 2810 } 2811 } 2812 send_response( &self, server_id: i32, addr: RawAddress, request_id: i32, status: GattStatus, offset: i32, value: Vec<u8>, ) -> bool2813 fn send_response( 2814 &self, 2815 server_id: i32, 2816 addr: RawAddress, 2817 request_id: i32, 2818 status: GattStatus, 2819 offset: i32, 2820 value: Vec<u8>, 2821 ) -> bool { 2822 (|| { 2823 let conn_id = self.server_context_map.get_conn_id_from_address(server_id, &addr)?; 2824 let handle = self.server_context_map.get_request_handle_from_id(request_id)?; 2825 let len = value.len() as u16; 2826 2827 let data: [u8; 512] = array_utils::to_sized_array(&value); 2828 2829 self.gatt.as_ref().unwrap().lock().unwrap().server.send_response( 2830 conn_id, 2831 request_id, 2832 status as i32, 2833 &BtGattResponse { 2834 attr_value: BtGattValue { 2835 value: data, 2836 handle: handle as u16, 2837 offset: offset as u16, 2838 len, 2839 auth_req: 0 as u8, 2840 }, 2841 }, 2842 ); 2843 2844 Some(()) 2845 })() 2846 .is_some() 2847 } 2848 send_notification( &self, server_id: i32, addr: RawAddress, handle: i32, confirm: bool, value: Vec<u8>, ) -> bool2849 fn send_notification( 2850 &self, 2851 server_id: i32, 2852 addr: RawAddress, 2853 handle: i32, 2854 confirm: bool, 2855 value: Vec<u8>, 2856 ) -> bool { 2857 let conn_id = match self.server_context_map.get_conn_id_from_address(server_id, &addr) { 2858 None => return false, 2859 Some(id) => id, 2860 }; 2861 2862 self.gatt.as_ref().unwrap().lock().unwrap().server.send_indication( 2863 server_id, 2864 handle, 2865 conn_id, 2866 confirm as i32, 2867 value.as_ref(), 2868 ); 2869 2870 true 2871 } 2872 server_set_preferred_phy( &self, _server_id: i32, addr: RawAddress, tx_phy: LePhy, rx_phy: LePhy, phy_options: i32, )2873 fn server_set_preferred_phy( 2874 &self, 2875 _server_id: i32, 2876 addr: RawAddress, 2877 tx_phy: LePhy, 2878 rx_phy: LePhy, 2879 phy_options: i32, 2880 ) { 2881 self.gatt.as_ref().unwrap().lock().unwrap().server.set_preferred_phy( 2882 &addr, 2883 tx_phy.to_u8().unwrap_or_default(), 2884 rx_phy.to_u8().unwrap_or_default(), 2885 phy_options as u16, 2886 ); 2887 } 2888 server_read_phy(&self, server_id: i32, addr: RawAddress)2889 fn server_read_phy(&self, server_id: i32, addr: RawAddress) { 2890 self.gatt.as_ref().unwrap().lock().unwrap().server.read_phy(server_id, &addr); 2891 } 2892 } 2893 2894 #[btif_callbacks_dispatcher(dispatch_gatt_client_callbacks, GattClientCallbacks)] 2895 pub(crate) trait BtifGattClientCallbacks { 2896 #[btif_callback(RegisterClient)] register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid)2897 fn register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid); 2898 2899 #[btif_callback(Connect)] connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress)2900 fn connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress); 2901 2902 #[btif_callback(Disconnect)] disconnect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress)2903 fn disconnect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress); 2904 2905 #[btif_callback(SearchComplete)] search_complete_cb(&mut self, conn_id: i32, status: GattStatus)2906 fn search_complete_cb(&mut self, conn_id: i32, status: GattStatus); 2907 2908 #[btif_callback(RegisterForNotification)] register_for_notification_cb( &mut self, conn_id: i32, registered: i32, status: GattStatus, handle: u16, )2909 fn register_for_notification_cb( 2910 &mut self, 2911 conn_id: i32, 2912 registered: i32, 2913 status: GattStatus, 2914 handle: u16, 2915 ); 2916 2917 #[btif_callback(Notify)] notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams)2918 fn notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams); 2919 2920 #[btif_callback(ReadCharacteristic)] read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)2921 fn read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams); 2922 2923 #[btif_callback(WriteCharacteristic)] write_characteristic_cb( &mut self, conn_id: i32, status: GattStatus, handle: u16, len: u16, value: *const u8, )2924 fn write_characteristic_cb( 2925 &mut self, 2926 conn_id: i32, 2927 status: GattStatus, 2928 handle: u16, 2929 len: u16, 2930 value: *const u8, 2931 ); 2932 2933 #[btif_callback(ReadDescriptor)] read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)2934 fn read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams); 2935 2936 #[btif_callback(WriteDescriptor)] write_descriptor_cb( &mut self, conn_id: i32, status: GattStatus, handle: u16, len: u16, value: *const u8, )2937 fn write_descriptor_cb( 2938 &mut self, 2939 conn_id: i32, 2940 status: GattStatus, 2941 handle: u16, 2942 len: u16, 2943 value: *const u8, 2944 ); 2945 2946 #[btif_callback(ExecuteWrite)] execute_write_cb(&mut self, conn_id: i32, status: GattStatus)2947 fn execute_write_cb(&mut self, conn_id: i32, status: GattStatus); 2948 2949 #[btif_callback(ReadRemoteRssi)] read_remote_rssi_cb( &mut self, client_id: i32, addr: RawAddress, rssi: i32, status: GattStatus, )2950 fn read_remote_rssi_cb( 2951 &mut self, 2952 client_id: i32, 2953 addr: RawAddress, 2954 rssi: i32, 2955 status: GattStatus, 2956 ); 2957 2958 #[btif_callback(ConfigureMtu)] configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32)2959 fn configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32); 2960 2961 #[btif_callback(Congestion)] congestion_cb(&mut self, conn_id: i32, congested: bool)2962 fn congestion_cb(&mut self, conn_id: i32, congested: bool); 2963 2964 #[btif_callback(GetGattDb)] get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, count: i32)2965 fn get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, count: i32); 2966 2967 #[btif_callback(PhyUpdated)] phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)2968 fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus); 2969 2970 #[btif_callback(ConnUpdated)] conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )2971 fn conn_updated_cb( 2972 &mut self, 2973 conn_id: i32, 2974 interval: u16, 2975 latency: u16, 2976 timeout: u16, 2977 status: GattStatus, 2978 ); 2979 2980 #[btif_callback(ServiceChanged)] service_changed_cb(&mut self, conn_id: i32)2981 fn service_changed_cb(&mut self, conn_id: i32); 2982 2983 #[btif_callback(ReadPhy)] read_phy_cb( &mut self, client_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )2984 fn read_phy_cb( 2985 &mut self, 2986 client_id: i32, 2987 addr: RawAddress, 2988 tx_phy: u8, 2989 rx_phy: u8, 2990 status: GattStatus, 2991 ); 2992 } 2993 2994 impl BtifGattClientCallbacks for BluetoothGatt { register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid)2995 fn register_client_cb(&mut self, status: GattStatus, client_id: i32, app_uuid: Uuid) { 2996 self.context_map.set_client_id(&app_uuid, client_id); 2997 2998 let client = self.context_map.get_by_uuid(&app_uuid); 2999 match client { 3000 Some(c) => { 3001 let cbid = c.cbid; 3002 self.context_map.get_callback_from_callback_id(cbid).and_then( 3003 |cb: &mut GattClientCallback| { 3004 cb.on_client_registered(status, client_id); 3005 Some(()) 3006 }, 3007 ); 3008 } 3009 None => { 3010 warn!("Warning: Client not registered for UUID {}", DisplayUuid(&app_uuid)); 3011 } 3012 } 3013 } 3014 connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress)3015 fn connect_cb(&mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress) { 3016 if status == GattStatus::Success { 3017 self.context_map.add_connection(client_id, conn_id, &addr); 3018 } 3019 3020 let Some(client) = self.context_map.get_by_client_id(client_id) else { return }; 3021 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3022 cb.on_client_connection_state(status, client_id, status == GattStatus::Success, addr); 3023 } 3024 } 3025 disconnect_cb( &mut self, conn_id: i32, status: GattStatus, client_id: i32, addr: RawAddress, )3026 fn disconnect_cb( 3027 &mut self, 3028 conn_id: i32, 3029 status: GattStatus, 3030 client_id: i32, 3031 addr: RawAddress, 3032 ) { 3033 let Some(client) = self.context_map.get_by_client_id(client_id) else { return }; 3034 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3035 cb.on_client_connection_state(status, client_id, false, addr); 3036 } 3037 self.context_map.remove_connection(client_id, conn_id); 3038 } 3039 search_complete_cb(&mut self, conn_id: i32, _status: GattStatus)3040 fn search_complete_cb(&mut self, conn_id: i32, _status: GattStatus) { 3041 // Gatt DB is ready! 3042 self.gatt.as_ref().unwrap().lock().unwrap().client.get_gatt_db(conn_id); 3043 } 3044 register_for_notification_cb( &mut self, _conn_id: i32, _registered: i32, _status: GattStatus, _handle: u16, )3045 fn register_for_notification_cb( 3046 &mut self, 3047 _conn_id: i32, 3048 _registered: i32, 3049 _status: GattStatus, 3050 _handle: u16, 3051 ) { 3052 // No-op. 3053 } 3054 notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams)3055 fn notify_cb(&mut self, conn_id: i32, data: BtGattNotifyParams) { 3056 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3057 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3058 cb.on_notify(data.bda, data.handle as i32, data.value[0..data.len as usize].to_vec()); 3059 } 3060 } 3061 read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)3062 fn read_characteristic_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams) { 3063 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3064 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3065 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3066 cb.on_characteristic_read( 3067 addr, 3068 status, 3069 data.handle as i32, 3070 data.value.value[0..data.value.len as usize].to_vec(), 3071 ); 3072 } 3073 } 3074 write_characteristic_cb( &mut self, conn_id: i32, mut status: GattStatus, handle: u16, _len: u16, _value: *const u8, )3075 fn write_characteristic_cb( 3076 &mut self, 3077 conn_id: i32, 3078 mut status: GattStatus, 3079 handle: u16, 3080 _len: u16, 3081 _value: *const u8, 3082 ) { 3083 // TODO(b/200070162): Design how to handle concurrent write characteristic to the same 3084 // peer. 3085 3086 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3087 let Some(client) = self.context_map.get_client_by_conn_id_mut(conn_id) else { return }; 3088 3089 if client.is_congested { 3090 if status == GattStatus::Congested { 3091 status = GattStatus::Success; 3092 } 3093 client.congestion_queue.push((addr, status, handle as i32)); 3094 return; 3095 } 3096 3097 let cbid = client.cbid; 3098 if let Some(cb) = self.context_map.get_callback_from_callback_id(cbid) { 3099 cb.on_characteristic_write(addr, status, handle as i32); 3100 } 3101 } 3102 read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams)3103 fn read_descriptor_cb(&mut self, conn_id: i32, status: GattStatus, data: BtGattReadParams) { 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_descriptor_read( 3108 addr, 3109 status, 3110 data.handle as i32, 3111 data.value.value[0..data.value.len as usize].to_vec(), 3112 ); 3113 } 3114 } 3115 write_descriptor_cb( &mut self, conn_id: i32, status: GattStatus, handle: u16, _len: u16, _value: *const u8, )3116 fn write_descriptor_cb( 3117 &mut self, 3118 conn_id: i32, 3119 status: GattStatus, 3120 handle: u16, 3121 _len: u16, 3122 _value: *const u8, 3123 ) { 3124 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3125 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3126 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3127 cb.on_descriptor_write(addr, status, handle as i32); 3128 } 3129 } 3130 execute_write_cb(&mut self, conn_id: i32, status: GattStatus)3131 fn execute_write_cb(&mut self, conn_id: i32, status: GattStatus) { 3132 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3133 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3134 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3135 cb.on_execute_write(addr, status); 3136 } 3137 } 3138 read_remote_rssi_cb( &mut self, client_id: i32, addr: RawAddress, rssi: i32, status: GattStatus, )3139 fn read_remote_rssi_cb( 3140 &mut self, 3141 client_id: i32, 3142 addr: RawAddress, 3143 rssi: i32, 3144 status: GattStatus, 3145 ) { 3146 let Some(client) = self.context_map.get_by_client_id(client_id) else { return }; 3147 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3148 cb.on_read_remote_rssi(addr, rssi, status); 3149 } 3150 } 3151 configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32)3152 fn configure_mtu_cb(&mut self, conn_id: i32, status: GattStatus, mtu: i32) { 3153 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3154 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3155 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3156 cb.on_configure_mtu(addr, mtu, status); 3157 } 3158 } 3159 congestion_cb(&mut self, conn_id: i32, congested: bool)3160 fn congestion_cb(&mut self, conn_id: i32, congested: bool) { 3161 if let Some(client) = self.context_map.get_client_by_conn_id_mut(conn_id) { 3162 client.is_congested = congested; 3163 if !client.is_congested { 3164 let cbid = client.cbid; 3165 let mut congestion_queue: Vec<(RawAddress, GattStatus, i32)> = vec![]; 3166 client.congestion_queue.retain(|v| { 3167 congestion_queue.push(v.clone()); 3168 false 3169 }); 3170 3171 self.context_map.get_callback_from_callback_id(cbid).and_then( 3172 |cb: &mut GattClientCallback| { 3173 for callback in congestion_queue.iter() { 3174 cb.on_characteristic_write(callback.0.clone(), callback.1, callback.2); 3175 } 3176 Some(()) 3177 }, 3178 ); 3179 } 3180 } 3181 } 3182 get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, _count: i32)3183 fn get_gatt_db_cb(&mut self, conn_id: i32, elements: Vec<BtGattDbElement>, _count: i32) { 3184 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3185 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3186 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3187 cb.on_search_complete( 3188 addr, 3189 BluetoothGattService::from_db(elements, true), 3190 GattStatus::Success, 3191 ); 3192 } 3193 } 3194 phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)3195 fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus) { 3196 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3197 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3198 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3199 cb.on_phy_update( 3200 addr, 3201 LePhy::from_u8(tx_phy).unwrap(), 3202 LePhy::from_u8(rx_phy).unwrap(), 3203 status, 3204 ); 3205 } 3206 } 3207 read_phy_cb( &mut self, client_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )3208 fn read_phy_cb( 3209 &mut self, 3210 client_id: i32, 3211 addr: RawAddress, 3212 tx_phy: u8, 3213 rx_phy: u8, 3214 status: GattStatus, 3215 ) { 3216 let Some(client) = self.context_map.get_by_client_id(client_id) else { return }; 3217 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3218 cb.on_phy_read( 3219 addr, 3220 LePhy::from_u8(tx_phy).unwrap(), 3221 LePhy::from_u8(rx_phy).unwrap(), 3222 status, 3223 ); 3224 } 3225 } 3226 conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )3227 fn conn_updated_cb( 3228 &mut self, 3229 conn_id: i32, 3230 interval: u16, 3231 latency: u16, 3232 timeout: u16, 3233 status: GattStatus, 3234 ) { 3235 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3236 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3237 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3238 cb.on_connection_updated(addr, interval as i32, latency as i32, timeout as i32, status); 3239 } 3240 } 3241 service_changed_cb(&mut self, conn_id: i32)3242 fn service_changed_cb(&mut self, conn_id: i32) { 3243 let Some(addr) = self.context_map.get_address_by_conn_id(conn_id) else { return }; 3244 let Some(client) = self.context_map.get_client_by_conn_id(conn_id) else { return }; 3245 if let Some(cb) = self.context_map.get_callback_from_callback_id(client.cbid) { 3246 cb.on_service_changed(addr); 3247 } 3248 } 3249 } 3250 3251 #[btif_callbacks_dispatcher(dispatch_gatt_server_callbacks, GattServerCallbacks)] 3252 pub(crate) trait BtifGattServerCallbacks { 3253 #[btif_callback(RegisterServer)] register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid)3254 fn register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid); 3255 3256 #[btif_callback(Connection)] connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress)3257 fn connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress); 3258 3259 #[btif_callback(ServiceAdded)] service_added_cb( &mut self, status: GattStatus, server_id: i32, elements: Vec<BtGattDbElement>, _count: usize, )3260 fn service_added_cb( 3261 &mut self, 3262 status: GattStatus, 3263 server_id: i32, 3264 elements: Vec<BtGattDbElement>, 3265 _count: usize, 3266 ); 3267 3268 #[btif_callback(ServiceDeleted)] service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32)3269 fn service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32); 3270 3271 #[btif_callback(RequestReadCharacteristic)] request_read_characteristic_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3272 fn request_read_characteristic_cb( 3273 &mut self, 3274 conn_id: i32, 3275 trans_id: i32, 3276 addr: RawAddress, 3277 handle: i32, 3278 offset: i32, 3279 is_long: bool, 3280 ); 3281 3282 #[btif_callback(RequestReadDescriptor)] request_read_descriptor_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3283 fn request_read_descriptor_cb( 3284 &mut self, 3285 conn_id: i32, 3286 trans_id: i32, 3287 addr: RawAddress, 3288 handle: i32, 3289 offset: i32, 3290 is_long: bool, 3291 ); 3292 3293 #[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, )3294 fn request_write_characteristic_cb( 3295 &mut self, 3296 conn_id: i32, 3297 trans_id: i32, 3298 addr: RawAddress, 3299 handle: i32, 3300 offset: i32, 3301 need_rsp: bool, 3302 is_prep: bool, 3303 data: Vec<u8>, 3304 len: usize, 3305 ); 3306 3307 #[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, )3308 fn request_write_descriptor_cb( 3309 &mut self, 3310 conn_id: i32, 3311 trans_id: i32, 3312 addr: RawAddress, 3313 handle: i32, 3314 offset: i32, 3315 need_rsp: bool, 3316 is_prep: bool, 3317 data: Vec<u8>, 3318 len: usize, 3319 ); 3320 3321 #[btif_callback(RequestExecWrite)] request_exec_write_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, exec_write: i32, )3322 fn request_exec_write_cb( 3323 &mut self, 3324 conn_id: i32, 3325 trans_id: i32, 3326 addr: RawAddress, 3327 exec_write: i32, 3328 ); 3329 3330 #[btif_callback(IndicationSent)] indication_sent_cb(&mut self, conn_id: i32, status: GattStatus)3331 fn indication_sent_cb(&mut self, conn_id: i32, status: GattStatus); 3332 3333 #[btif_callback(Congestion)] congestion_cb(&mut self, conn_id: i32, congested: bool)3334 fn congestion_cb(&mut self, conn_id: i32, congested: bool); 3335 3336 #[btif_callback(MtuChanged)] mtu_changed_cb(&mut self, conn_id: i32, mtu: i32)3337 fn mtu_changed_cb(&mut self, conn_id: i32, mtu: i32); 3338 3339 #[btif_callback(PhyUpdated)] phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)3340 fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus); 3341 3342 #[btif_callback(ReadPhy)] read_phy_cb( &mut self, server_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )3343 fn read_phy_cb( 3344 &mut self, 3345 server_id: i32, 3346 addr: RawAddress, 3347 tx_phy: u8, 3348 rx_phy: u8, 3349 status: GattStatus, 3350 ); 3351 3352 #[btif_callback(ConnUpdated)] conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )3353 fn conn_updated_cb( 3354 &mut self, 3355 conn_id: i32, 3356 interval: u16, 3357 latency: u16, 3358 timeout: u16, 3359 status: GattStatus, 3360 ); 3361 3362 #[btif_callback(SubrateChanged)] subrate_chg_cb( &mut self, conn_id: i32, subrate_factor: u16, latency: u16, cont_num: u16, timeout: u16, status: GattStatus, )3363 fn subrate_chg_cb( 3364 &mut self, 3365 conn_id: i32, 3366 subrate_factor: u16, 3367 latency: u16, 3368 cont_num: u16, 3369 timeout: u16, 3370 status: GattStatus, 3371 ); 3372 } 3373 3374 impl BtifGattServerCallbacks for BluetoothGatt { register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid)3375 fn register_server_cb(&mut self, status: GattStatus, server_id: i32, app_uuid: Uuid) { 3376 self.server_context_map.set_server_id(&app_uuid, server_id); 3377 3378 let cbid = self.server_context_map.get_by_uuid(&app_uuid).map(|server| server.cbid); 3379 match cbid { 3380 Some(cbid) => { 3381 if let Some(cb) = 3382 self.server_context_map.get_callback_from_callback_id(cbid).as_mut() 3383 { 3384 cb.on_server_registered(status, server_id) 3385 } 3386 } 3387 None => { 3388 warn!("Warning: No callback found for UUID {}", DisplayUuid(&app_uuid)); 3389 } 3390 } 3391 } 3392 connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress)3393 fn connection_cb(&mut self, conn_id: i32, server_id: i32, connected: i32, addr: RawAddress) { 3394 let is_connected = connected != 0; 3395 if is_connected { 3396 self.server_context_map.add_connection(server_id, conn_id, &addr); 3397 } else { 3398 self.server_context_map.remove_connection(conn_id); 3399 } 3400 3401 let cbid = self.server_context_map.get_by_server_id(server_id).map(|server| server.cbid); 3402 match cbid { 3403 Some(cbid) => { 3404 if let Some(cb) = 3405 self.server_context_map.get_callback_from_callback_id(cbid).as_mut() 3406 { 3407 cb.on_server_connection_state(server_id, is_connected, addr); 3408 } 3409 } 3410 None => { 3411 warn!("Warning: No callback found for server ID {}", server_id); 3412 } 3413 } 3414 } 3415 service_added_cb( &mut self, status: GattStatus, server_id: i32, elements: Vec<BtGattDbElement>, _count: usize, )3416 fn service_added_cb( 3417 &mut self, 3418 status: GattStatus, 3419 server_id: i32, 3420 elements: Vec<BtGattDbElement>, 3421 _count: usize, 3422 ) { 3423 for service in BluetoothGattService::from_db(elements, false) { 3424 if status == GattStatus::Success { 3425 self.server_context_map.add_service(server_id, service.clone()); 3426 } 3427 3428 let cbid = 3429 self.server_context_map.get_by_server_id(server_id).map(|server| server.cbid); 3430 match cbid { 3431 Some(cbid) => { 3432 if let Some(cb) = 3433 self.server_context_map.get_callback_from_callback_id(cbid).as_mut() 3434 { 3435 cb.on_service_added(status, service); 3436 } 3437 } 3438 None => { 3439 warn!("Warning: No callback found for server ID {}", server_id); 3440 } 3441 } 3442 } 3443 } 3444 service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32)3445 fn service_deleted_cb(&mut self, status: GattStatus, server_id: i32, handle: i32) { 3446 if status == GattStatus::Success { 3447 self.server_context_map.delete_service(server_id, handle); 3448 } 3449 3450 let cbid = self 3451 .server_context_map 3452 .get_by_server_id(server_id) 3453 .and_then(|server| Some(server.cbid)); 3454 3455 if let Some(cbid) = cbid { 3456 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3457 cb.on_service_removed(status, handle); 3458 } 3459 } 3460 } 3461 request_read_characteristic_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3462 fn request_read_characteristic_cb( 3463 &mut self, 3464 conn_id: i32, 3465 trans_id: i32, 3466 addr: RawAddress, 3467 handle: i32, 3468 offset: i32, 3469 is_long: bool, 3470 ) { 3471 self.server_context_map.add_request(trans_id, handle); 3472 3473 if let Some(cbid) = 3474 self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid) 3475 { 3476 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3477 cb.on_characteristic_read_request(addr, trans_id, offset, is_long, handle); 3478 } 3479 } 3480 } 3481 request_read_descriptor_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, handle: i32, offset: i32, is_long: bool, )3482 fn request_read_descriptor_cb( 3483 &mut self, 3484 conn_id: i32, 3485 trans_id: i32, 3486 addr: RawAddress, 3487 handle: i32, 3488 offset: i32, 3489 is_long: bool, 3490 ) { 3491 self.server_context_map.add_request(trans_id, handle); 3492 3493 if let Some(cbid) = 3494 self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid) 3495 { 3496 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3497 cb.on_descriptor_read_request(addr, trans_id, offset, is_long, handle); 3498 } 3499 } 3500 } 3501 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, )3502 fn request_write_characteristic_cb( 3503 &mut self, 3504 conn_id: i32, 3505 trans_id: i32, 3506 addr: RawAddress, 3507 handle: i32, 3508 offset: i32, 3509 need_rsp: bool, 3510 is_prep: bool, 3511 data: Vec<u8>, 3512 len: usize, 3513 ) { 3514 self.server_context_map.add_request(trans_id, handle); 3515 3516 if let Some(cbid) = 3517 self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid) 3518 { 3519 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3520 cb.on_characteristic_write_request( 3521 addr, trans_id, offset, len as i32, is_prep, need_rsp, handle, data, 3522 ); 3523 } 3524 } 3525 } 3526 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, )3527 fn request_write_descriptor_cb( 3528 &mut self, 3529 conn_id: i32, 3530 trans_id: i32, 3531 addr: RawAddress, 3532 handle: i32, 3533 offset: i32, 3534 need_rsp: bool, 3535 is_prep: bool, 3536 data: Vec<u8>, 3537 len: usize, 3538 ) { 3539 self.server_context_map.add_request(trans_id, handle); 3540 3541 if let Some(cbid) = 3542 self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid) 3543 { 3544 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3545 cb.on_descriptor_write_request( 3546 addr, trans_id, offset, len as i32, is_prep, need_rsp, handle, data, 3547 ); 3548 } 3549 } 3550 } 3551 request_exec_write_cb( &mut self, conn_id: i32, trans_id: i32, addr: RawAddress, exec_write: i32, )3552 fn request_exec_write_cb( 3553 &mut self, 3554 conn_id: i32, 3555 trans_id: i32, 3556 addr: RawAddress, 3557 exec_write: i32, 3558 ) { 3559 self.server_context_map.add_request(trans_id, 0); 3560 3561 if let Some(cbid) = 3562 self.server_context_map.get_by_conn_id(conn_id).map(|server| server.cbid) 3563 { 3564 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3565 cb.on_execute_write(addr, trans_id, exec_write != 0); 3566 } 3567 } 3568 } 3569 indication_sent_cb(&mut self, conn_id: i32, mut status: GattStatus)3570 fn indication_sent_cb(&mut self, conn_id: i32, mut status: GattStatus) { 3571 (|| { 3572 let address = self.server_context_map.get_address_from_conn_id(conn_id)?; 3573 let server = self.server_context_map.get_mut_by_conn_id(conn_id)?; 3574 3575 if server.is_congested { 3576 if status == GattStatus::Congested { 3577 status = GattStatus::Success; 3578 } 3579 3580 server.congestion_queue.push((address, status)); 3581 return None; 3582 } 3583 3584 let cbid = server.cbid; 3585 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3586 cb.on_notification_sent(address, status); 3587 } 3588 3589 Some(()) 3590 })(); 3591 } 3592 congestion_cb(&mut self, conn_id: i32, congested: bool)3593 fn congestion_cb(&mut self, conn_id: i32, congested: bool) { 3594 if let Some(server) = self.server_context_map.get_mut_by_conn_id(conn_id) { 3595 server.is_congested = congested; 3596 if !server.is_congested { 3597 let cbid = server.cbid; 3598 let congestion_queue: Vec<_> = server.congestion_queue.drain(..).collect(); 3599 3600 if let Some(cb) = 3601 self.server_context_map.get_callback_from_callback_id(cbid).as_mut() 3602 { 3603 for callback in congestion_queue { 3604 cb.on_notification_sent(callback.0.clone(), callback.1); 3605 } 3606 } 3607 } 3608 } 3609 } 3610 mtu_changed_cb(&mut self, conn_id: i32, mtu: i32)3611 fn mtu_changed_cb(&mut self, conn_id: i32, mtu: i32) { 3612 (|| { 3613 let address = self.server_context_map.get_address_from_conn_id(conn_id)?; 3614 let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid; 3615 3616 if let Some(cb) = 3617 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut() 3618 { 3619 cb.on_mtu_changed(address, mtu); 3620 } 3621 3622 Some(()) 3623 })(); 3624 } 3625 phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus)3626 fn phy_updated_cb(&mut self, conn_id: i32, tx_phy: u8, rx_phy: u8, status: GattStatus) { 3627 (|| { 3628 let address = self.server_context_map.get_address_from_conn_id(conn_id)?; 3629 let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid; 3630 3631 if let Some(cb) = 3632 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut() 3633 { 3634 cb.on_phy_update( 3635 address, 3636 LePhy::from_u8(tx_phy).unwrap_or_default(), 3637 LePhy::from_u8(rx_phy).unwrap_or_default(), 3638 status, 3639 ); 3640 } 3641 3642 Some(()) 3643 })(); 3644 } 3645 read_phy_cb( &mut self, server_id: i32, addr: RawAddress, tx_phy: u8, rx_phy: u8, status: GattStatus, )3646 fn read_phy_cb( 3647 &mut self, 3648 server_id: i32, 3649 addr: RawAddress, 3650 tx_phy: u8, 3651 rx_phy: u8, 3652 status: GattStatus, 3653 ) { 3654 if let Some(cbid) = 3655 self.server_context_map.get_by_server_id(server_id).map(|server| server.cbid) 3656 { 3657 if let Some(cb) = self.server_context_map.get_callback_from_callback_id(cbid).as_mut() { 3658 cb.on_phy_read( 3659 addr, 3660 LePhy::from_u8(tx_phy).unwrap_or_default(), 3661 LePhy::from_u8(rx_phy).unwrap_or_default(), 3662 status, 3663 ); 3664 } 3665 } 3666 } 3667 conn_updated_cb( &mut self, conn_id: i32, interval: u16, latency: u16, timeout: u16, status: GattStatus, )3668 fn conn_updated_cb( 3669 &mut self, 3670 conn_id: i32, 3671 interval: u16, 3672 latency: u16, 3673 timeout: u16, 3674 status: GattStatus, 3675 ) { 3676 (|| { 3677 let address = self.server_context_map.get_address_from_conn_id(conn_id)?; 3678 let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid; 3679 3680 if let Some(cb) = 3681 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut() 3682 { 3683 cb.on_connection_updated( 3684 address, 3685 interval as i32, 3686 latency as i32, 3687 timeout as i32, 3688 status, 3689 ); 3690 } 3691 3692 Some(()) 3693 })(); 3694 } 3695 subrate_chg_cb( &mut self, conn_id: i32, subrate_factor: u16, latency: u16, cont_num: u16, timeout: u16, status: GattStatus, )3696 fn subrate_chg_cb( 3697 &mut self, 3698 conn_id: i32, 3699 subrate_factor: u16, 3700 latency: u16, 3701 cont_num: u16, 3702 timeout: u16, 3703 status: GattStatus, 3704 ) { 3705 (|| { 3706 let address = self.server_context_map.get_address_from_conn_id(conn_id)?; 3707 let server_cbid = self.server_context_map.get_by_conn_id(conn_id)?.cbid; 3708 3709 if let Some(cb) = 3710 self.server_context_map.get_callback_from_callback_id(server_cbid).as_mut() 3711 { 3712 cb.on_subrate_change( 3713 address, 3714 subrate_factor as i32, 3715 latency as i32, 3716 cont_num as i32, 3717 timeout as i32, 3718 status, 3719 ); 3720 } 3721 3722 Some(()) 3723 })(); 3724 } 3725 } 3726 3727 #[btif_callbacks_dispatcher(dispatch_le_scanner_callbacks, GattScannerCallbacks)] 3728 pub(crate) trait BtifGattScannerCallbacks { 3729 #[btif_callback(OnScannerRegistered)] on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus)3730 fn on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus); 3731 3732 #[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>, )3733 fn on_scan_result( 3734 &mut self, 3735 event_type: u16, 3736 addr_type: u8, 3737 bda: RawAddress, 3738 primary_phy: u8, 3739 secondary_phy: u8, 3740 advertising_sid: u8, 3741 tx_power: i8, 3742 rssi: i8, 3743 periodic_adv_int: u16, 3744 adv_data: Vec<u8>, 3745 ); 3746 3747 #[btif_callback(OnTrackAdvFoundLost)] on_track_adv_found_lost(&mut self, adv_track_info: AdvertisingTrackInfo)3748 fn on_track_adv_found_lost(&mut self, adv_track_info: AdvertisingTrackInfo); 3749 } 3750 3751 #[btif_callbacks_dispatcher(dispatch_le_scanner_inband_callbacks, GattScannerInbandCallbacks)] 3752 pub(crate) trait BtifGattScannerInbandCallbacks { 3753 #[btif_callback(RegisterCallback)] inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8)3754 fn inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8); 3755 3756 #[btif_callback(StatusCallback)] inband_status_callback(&mut self, scanner_id: u8, btm_status: u8)3757 fn inband_status_callback(&mut self, scanner_id: u8, btm_status: u8); 3758 3759 #[btif_callback(EnableCallback)] inband_enable_callback(&mut self, action: u8, btm_status: u8)3760 fn inband_enable_callback(&mut self, action: u8, btm_status: u8); 3761 3762 #[btif_callback(FilterParamSetupCallback)] inband_filter_param_setup_callback( &mut self, scanner_id: u8, available_space: u8, action_type: u8, btm_status: u8, )3763 fn inband_filter_param_setup_callback( 3764 &mut self, 3765 scanner_id: u8, 3766 available_space: u8, 3767 action_type: u8, 3768 btm_status: u8, 3769 ); 3770 3771 #[btif_callback(FilterConfigCallback)] inband_filter_config_callback( &mut self, filter_index: u8, filter_type: u8, available_space: u8, action: u8, btm_status: u8, )3772 fn inband_filter_config_callback( 3773 &mut self, 3774 filter_index: u8, 3775 filter_type: u8, 3776 available_space: u8, 3777 action: u8, 3778 btm_status: u8, 3779 ); 3780 3781 #[btif_callback(MsftAdvMonitorAddCallback)] inband_msft_adv_monitor_add_callback( &mut self, call_id: u32, monitor_handle: u8, status: u8, )3782 fn inband_msft_adv_monitor_add_callback( 3783 &mut self, 3784 call_id: u32, 3785 monitor_handle: u8, 3786 status: u8, 3787 ); 3788 3789 #[btif_callback(MsftAdvMonitorRemoveCallback)] inband_msft_adv_monitor_remove_callback(&mut self, call_id: u32, status: u8)3790 fn inband_msft_adv_monitor_remove_callback(&mut self, call_id: u32, status: u8); 3791 3792 #[btif_callback(MsftAdvMonitorEnableCallback)] inband_msft_adv_monitor_enable_callback(&mut self, call_id: u32, status: u8)3793 fn inband_msft_adv_monitor_enable_callback(&mut self, call_id: u32, status: u8); 3794 3795 #[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, )3796 fn inband_start_sync_callback( 3797 &mut self, 3798 status: u8, 3799 sync_handle: u16, 3800 advertising_sid: u8, 3801 address_type: u8, 3802 address: RawAddress, 3803 phy: u8, 3804 interval: u16, 3805 ); 3806 3807 #[btif_callback(SyncReportCallback)] inband_sync_report_callback( &mut self, sync_handle: u16, tx_power: i8, rssi: i8, status: u8, data: Vec<u8>, )3808 fn inband_sync_report_callback( 3809 &mut self, 3810 sync_handle: u16, 3811 tx_power: i8, 3812 rssi: i8, 3813 status: u8, 3814 data: Vec<u8>, 3815 ); 3816 3817 #[btif_callback(SyncLostCallback)] inband_sync_lost_callback(&mut self, sync_handle: u16)3818 fn inband_sync_lost_callback(&mut self, sync_handle: u16); 3819 3820 #[btif_callback(SyncTransferCallback)] inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress)3821 fn inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress); 3822 } 3823 3824 impl BtifGattScannerInbandCallbacks for BluetoothGatt { inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8)3825 fn inband_register_callback(&mut self, app_uuid: Uuid, scanner_id: u8, btm_status: u8) { 3826 log::debug!( 3827 "Callback received: {:#?}", 3828 GattScannerInbandCallbacks::RegisterCallback(app_uuid, scanner_id, btm_status) 3829 ); 3830 } 3831 inband_status_callback(&mut self, scanner_id: u8, btm_status: u8)3832 fn inband_status_callback(&mut self, scanner_id: u8, btm_status: u8) { 3833 log::debug!( 3834 "Callback received: {:#?}", 3835 GattScannerInbandCallbacks::StatusCallback(scanner_id, btm_status) 3836 ); 3837 } 3838 inband_enable_callback(&mut self, action: u8, btm_status: u8)3839 fn inband_enable_callback(&mut self, action: u8, btm_status: u8) { 3840 log::debug!( 3841 "Callback received: {:#?}", 3842 GattScannerInbandCallbacks::EnableCallback(action, btm_status) 3843 ); 3844 } 3845 inband_filter_param_setup_callback( &mut self, scanner_id: u8, available_space: u8, action_type: u8, btm_status: u8, )3846 fn inband_filter_param_setup_callback( 3847 &mut self, 3848 scanner_id: u8, 3849 available_space: u8, 3850 action_type: u8, 3851 btm_status: u8, 3852 ) { 3853 log::debug!( 3854 "Callback received: {:#?}", 3855 GattScannerInbandCallbacks::FilterParamSetupCallback( 3856 scanner_id, 3857 available_space, 3858 action_type, 3859 btm_status 3860 ) 3861 ); 3862 } 3863 inband_filter_config_callback( &mut self, filter_index: u8, filter_type: u8, available_space: u8, action: u8, btm_status: u8, )3864 fn inband_filter_config_callback( 3865 &mut self, 3866 filter_index: u8, 3867 filter_type: u8, 3868 available_space: u8, 3869 action: u8, 3870 btm_status: u8, 3871 ) { 3872 log::debug!( 3873 "Callback received: {:#?}", 3874 GattScannerInbandCallbacks::FilterConfigCallback( 3875 filter_index, 3876 filter_type, 3877 available_space, 3878 action, 3879 btm_status, 3880 ) 3881 ); 3882 } 3883 inband_msft_adv_monitor_add_callback( &mut self, call_id: u32, monitor_handle: u8, status: u8, )3884 fn inband_msft_adv_monitor_add_callback( 3885 &mut self, 3886 call_id: u32, 3887 monitor_handle: u8, 3888 status: u8, 3889 ) { 3890 (self.adv_mon_add_cb_sender.lock().unwrap())(call_id, (monitor_handle, status)); 3891 } 3892 inband_msft_adv_monitor_remove_callback(&mut self, call_id: u32, status: u8)3893 fn inband_msft_adv_monitor_remove_callback(&mut self, call_id: u32, status: u8) { 3894 (self.adv_mon_remove_cb_sender.lock().unwrap())(call_id, status); 3895 } 3896 inband_msft_adv_monitor_enable_callback(&mut self, call_id: u32, status: u8)3897 fn inband_msft_adv_monitor_enable_callback(&mut self, call_id: u32, status: u8) { 3898 (self.adv_mon_enable_cb_sender.lock().unwrap())(call_id, status); 3899 } 3900 inband_start_sync_callback( &mut self, status: u8, sync_handle: u16, advertising_sid: u8, address_type: u8, address: RawAddress, phy: u8, interval: u16, )3901 fn inband_start_sync_callback( 3902 &mut self, 3903 status: u8, 3904 sync_handle: u16, 3905 advertising_sid: u8, 3906 address_type: u8, 3907 address: RawAddress, 3908 phy: u8, 3909 interval: u16, 3910 ) { 3911 log::debug!( 3912 "Callback received: StartSyncCallback({}, {}, {}, {}, {}, {}, {})", 3913 status, 3914 sync_handle, 3915 advertising_sid, 3916 address_type, 3917 DisplayAddress(&address), 3918 phy, 3919 interval 3920 ); 3921 } 3922 inband_sync_report_callback( &mut self, sync_handle: u16, tx_power: i8, rssi: i8, status: u8, data: Vec<u8>, )3923 fn inband_sync_report_callback( 3924 &mut self, 3925 sync_handle: u16, 3926 tx_power: i8, 3927 rssi: i8, 3928 status: u8, 3929 data: Vec<u8>, 3930 ) { 3931 log::debug!( 3932 "Callback received: {:#?}", 3933 GattScannerInbandCallbacks::SyncReportCallback( 3934 sync_handle, 3935 tx_power, 3936 rssi, 3937 status, 3938 data 3939 ) 3940 ); 3941 } 3942 inband_sync_lost_callback(&mut self, sync_handle: u16)3943 fn inband_sync_lost_callback(&mut self, sync_handle: u16) { 3944 log::debug!( 3945 "Callback received: {:#?}", 3946 GattScannerInbandCallbacks::SyncLostCallback(sync_handle,) 3947 ); 3948 } 3949 inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress)3950 fn inband_sync_transfer_callback(&mut self, status: u8, address: RawAddress) { 3951 log::debug!( 3952 "Callback received: SyncTransferCallback({}, {})", 3953 status, 3954 DisplayAddress(&address) 3955 ); 3956 } 3957 } 3958 3959 impl BtifGattScannerCallbacks for BluetoothGatt { on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus)3960 fn on_scanner_registered(&mut self, uuid: Uuid, scanner_id: u8, status: GattStatus) { 3961 log::debug!( 3962 "on_scanner_registered UUID = {}, scanner_id = {}, status = {}", 3963 DisplayUuid(&uuid), 3964 scanner_id, 3965 status 3966 ); 3967 3968 let mut scanners_lock = self.scanners.lock().unwrap(); 3969 let scanner_info = scanners_lock.get_mut(&uuid); 3970 3971 if let Some(info) = scanner_info { 3972 info.scanner_id = Some(scanner_id); 3973 if let Some(cb) = self.scanner_callbacks.get_by_id_mut(info.callback_id) { 3974 cb.on_scanner_registered(uuid, scanner_id, status); 3975 } else { 3976 log::warn!("There is no callback for scanner UUID {}", DisplayUuid(&uuid)); 3977 } 3978 } else { 3979 log::warn!( 3980 "Scanner registered callback for non-existent scanner info, UUID = {}", 3981 DisplayUuid(&uuid) 3982 ); 3983 } 3984 3985 if status != GattStatus::Success { 3986 log::error!("Error registering scanner UUID {}", DisplayUuid(&uuid)); 3987 scanners_lock.remove(&uuid); 3988 } 3989 } 3990 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>, )3991 fn on_scan_result( 3992 &mut self, 3993 event_type: u16, 3994 addr_type: u8, 3995 address: RawAddress, 3996 primary_phy: u8, 3997 secondary_phy: u8, 3998 advertising_sid: u8, 3999 tx_power: i8, 4000 rssi: i8, 4001 periodic_adv_int: u16, 4002 adv_data: Vec<u8>, 4003 ) { 4004 self.scanner_callbacks.for_all_callbacks(|callback| { 4005 callback.on_scan_result(ScanResult { 4006 name: adv_parser::extract_name(adv_data.as_slice()), 4007 address, 4008 addr_type, 4009 event_type, 4010 primary_phy, 4011 secondary_phy, 4012 advertising_sid, 4013 tx_power, 4014 rssi, 4015 periodic_adv_int, 4016 flags: adv_parser::extract_flags(adv_data.as_slice()), 4017 service_uuids: adv_parser::extract_service_uuids(adv_data.as_slice()), 4018 service_data: adv_parser::extract_service_data(adv_data.as_slice()), 4019 manufacturer_data: adv_parser::extract_manufacturer_data(adv_data.as_slice()), 4020 adv_data: adv_data.clone(), 4021 }); 4022 }); 4023 } 4024 on_track_adv_found_lost(&mut self, track_adv_info: AdvertisingTrackInfo)4025 fn on_track_adv_found_lost(&mut self, track_adv_info: AdvertisingTrackInfo) { 4026 let addr = track_adv_info.advertiser_address; 4027 let display_addr = DisplayAddress(&addr); 4028 let mut binding = self.scanners.lock().unwrap(); 4029 let mut corresponding_scanner: Option<&mut ScannerInfo> = 4030 binding.values_mut().find_map(|scanner| { 4031 if scanner.monitor_handle == Some(track_adv_info.monitor_handle) { 4032 Some(scanner) 4033 } else { 4034 None 4035 } 4036 }); 4037 if corresponding_scanner.is_none() { 4038 corresponding_scanner = binding.values_mut().find_map(|scanner| { 4039 if scanner.addr_handle_map.contains_key(&addr) { 4040 Some(scanner) 4041 } else { 4042 None 4043 } 4044 }); 4045 } 4046 4047 let corresponding_scanner = match corresponding_scanner { 4048 Some(scanner) => scanner, 4049 None => { 4050 log::warn!("No scanner having monitor handle {}", track_adv_info.monitor_handle); 4051 return; 4052 } 4053 }; 4054 let scanner_id = match corresponding_scanner.scanner_id { 4055 Some(scanner_id) => scanner_id, 4056 None => { 4057 log::warn!("No scanner id having monitor handle {}", track_adv_info.monitor_handle); 4058 return; 4059 } 4060 }; 4061 4062 let controller_need_separate_pattern_and_address = 4063 corresponding_scanner.addr_tracking_quirk; 4064 4065 let mut address_monitor_succeed: bool = false; 4066 if controller_need_separate_pattern_and_address { 4067 if track_adv_info.advertiser_state == 0x01 { 4068 if corresponding_scanner.addr_handle_map.contains_key(&addr) { 4069 log::debug!( 4070 "on_track_adv_found_lost: this addr {} is already handled, just return", 4071 display_addr 4072 ); 4073 return; 4074 } 4075 log::debug!( 4076 "on_track_adv_found_lost: state == 0x01, adding addr {} to map", 4077 display_addr 4078 ); 4079 corresponding_scanner.addr_handle_map.insert(addr, None); 4080 4081 let scan_filter_addr = ScanFilterAddress { 4082 addr_type: track_adv_info.advertiser_address_type, 4083 bd_addr: addr, 4084 }; 4085 4086 if let Some(saved_filter) = corresponding_scanner.filter.clone() { 4087 let scan_filter = ScanFilter { 4088 rssi_high_threshold: saved_filter.rssi_high_threshold, 4089 rssi_low_threshold: saved_filter.rssi_low_threshold, 4090 rssi_low_timeout: saved_filter.rssi_low_timeout, 4091 rssi_sampling_period: saved_filter.rssi_sampling_period, 4092 condition: ScanFilterCondition::BluetoothAddress(scan_filter_addr), 4093 }; 4094 self.add_child_monitor(scanner_id, scan_filter); 4095 address_monitor_succeed = true; 4096 } 4097 } else { 4098 if let Some(handle) = corresponding_scanner.monitor_handle { 4099 if handle == track_adv_info.monitor_handle { 4100 log::info!("pattern filter lost, addr={}", display_addr); 4101 return; 4102 } 4103 } 4104 4105 if corresponding_scanner.addr_handle_map.remove(&addr).is_some() { 4106 log::debug!( 4107 "on_track_adv_found_lost: removing addr = {} from map", 4108 display_addr 4109 ); 4110 self.remove_child_monitor(scanner_id, track_adv_info.monitor_handle); 4111 } 4112 } 4113 } 4114 4115 self.scanner_callbacks.for_all_callbacks(|callback| { 4116 let adv_data = 4117 [&track_adv_info.adv_packet[..], &track_adv_info.scan_response[..]].concat(); 4118 4119 let scan_result = ScanResult { 4120 name: adv_parser::extract_name(adv_data.as_slice()), 4121 address: addr, 4122 addr_type: track_adv_info.advertiser_address_type, 4123 event_type: 0, /* not used */ 4124 primary_phy: LePhy::Phy1m as u8, 4125 secondary_phy: 0, /* not used */ 4126 advertising_sid: 0xff, /* not present */ 4127 /* A bug in libbluetooth that uses u8 for TX power. 4128 * TODO(b/261482382): Fix the data type in C++ layer to use i8 instead of u8. */ 4129 tx_power: track_adv_info.tx_power as i8, 4130 rssi: track_adv_info.rssi, 4131 periodic_adv_int: 0, /* not used */ 4132 flags: adv_parser::extract_flags(adv_data.as_slice()), 4133 service_uuids: adv_parser::extract_service_uuids(adv_data.as_slice()), 4134 service_data: adv_parser::extract_service_data(adv_data.as_slice()), 4135 manufacturer_data: adv_parser::extract_manufacturer_data(adv_data.as_slice()), 4136 adv_data, 4137 }; 4138 4139 if track_adv_info.advertiser_state == 0x01 { 4140 if !controller_need_separate_pattern_and_address || address_monitor_succeed { 4141 callback.on_advertisement_found(scanner_id, scan_result); 4142 } 4143 } else { 4144 callback.on_advertisement_lost(scanner_id, scan_result); 4145 } 4146 }); 4147 } 4148 } 4149 4150 impl BtifGattAdvCallbacks for BluetoothGatt { on_advertising_set_started( &mut self, reg_id: i32, advertiser_id: u8, tx_power: i8, status: AdvertisingStatus, )4151 fn on_advertising_set_started( 4152 &mut self, 4153 reg_id: i32, 4154 advertiser_id: u8, 4155 tx_power: i8, 4156 status: AdvertisingStatus, 4157 ) { 4158 self.adv_manager.get_impl().on_advertising_set_started( 4159 reg_id, 4160 advertiser_id, 4161 tx_power, 4162 status, 4163 ); 4164 } 4165 on_advertising_enabled(&mut self, adv_id: u8, enabled: bool, status: AdvertisingStatus)4166 fn on_advertising_enabled(&mut self, adv_id: u8, enabled: bool, status: AdvertisingStatus) { 4167 self.adv_manager.get_impl().on_advertising_enabled(adv_id, enabled, status); 4168 } 4169 on_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus)4170 fn on_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus) { 4171 self.adv_manager.get_impl().on_advertising_data_set(adv_id, status); 4172 } 4173 on_scan_response_data_set(&mut self, adv_id: u8, status: AdvertisingStatus)4174 fn on_scan_response_data_set(&mut self, adv_id: u8, status: AdvertisingStatus) { 4175 self.adv_manager.get_impl().on_scan_response_data_set(adv_id, status); 4176 } 4177 on_advertising_parameters_updated( &mut self, adv_id: u8, tx_power: i8, status: AdvertisingStatus, )4178 fn on_advertising_parameters_updated( 4179 &mut self, 4180 adv_id: u8, 4181 tx_power: i8, 4182 status: AdvertisingStatus, 4183 ) { 4184 self.adv_manager.get_impl().on_advertising_parameters_updated(adv_id, tx_power, status); 4185 } 4186 on_periodic_advertising_parameters_updated( &mut self, adv_id: u8, status: AdvertisingStatus, )4187 fn on_periodic_advertising_parameters_updated( 4188 &mut self, 4189 adv_id: u8, 4190 status: AdvertisingStatus, 4191 ) { 4192 self.adv_manager.get_impl().on_periodic_advertising_parameters_updated(adv_id, status); 4193 } 4194 on_periodic_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus)4195 fn on_periodic_advertising_data_set(&mut self, adv_id: u8, status: AdvertisingStatus) { 4196 self.adv_manager.get_impl().on_periodic_advertising_data_set(adv_id, status); 4197 } 4198 on_periodic_advertising_enabled( &mut self, adv_id: u8, enabled: bool, status: AdvertisingStatus, )4199 fn on_periodic_advertising_enabled( 4200 &mut self, 4201 adv_id: u8, 4202 enabled: bool, 4203 status: AdvertisingStatus, 4204 ) { 4205 self.adv_manager.get_impl().on_periodic_advertising_enabled(adv_id, enabled, status); 4206 } 4207 on_own_address_read(&mut self, adv_id: u8, addr_type: u8, address: RawAddress)4208 fn on_own_address_read(&mut self, adv_id: u8, addr_type: u8, address: RawAddress) { 4209 self.adv_manager.get_impl().on_own_address_read(adv_id, addr_type, address); 4210 } 4211 } 4212 4213 #[cfg(test)] 4214 mod tests { 4215 struct TestBluetoothGattCallback { 4216 id: String, 4217 } 4218 4219 impl TestBluetoothGattCallback { new(id: String) -> TestBluetoothGattCallback4220 fn new(id: String) -> TestBluetoothGattCallback { 4221 TestBluetoothGattCallback { id } 4222 } 4223 } 4224 4225 impl IBluetoothGattCallback for TestBluetoothGattCallback { on_client_registered(&mut self, _status: GattStatus, _client_id: i32)4226 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, )4227 fn on_client_connection_state( 4228 &mut self, 4229 _status: GattStatus, 4230 _client_id: i32, 4231 _connected: bool, 4232 _addr: RawAddress, 4233 ) { 4234 } 4235 on_phy_update( &mut self, _addr: RawAddress, _tx_phy: LePhy, _rx_phy: LePhy, _status: GattStatus, )4236 fn on_phy_update( 4237 &mut self, 4238 _addr: RawAddress, 4239 _tx_phy: LePhy, 4240 _rx_phy: LePhy, 4241 _status: GattStatus, 4242 ) { 4243 } 4244 on_phy_read( &mut self, _addr: RawAddress, _tx_phy: LePhy, _rx_phy: LePhy, _status: GattStatus, )4245 fn on_phy_read( 4246 &mut self, 4247 _addr: RawAddress, 4248 _tx_phy: LePhy, 4249 _rx_phy: LePhy, 4250 _status: GattStatus, 4251 ) { 4252 } 4253 on_search_complete( &mut self, _addr: RawAddress, _services: Vec<BluetoothGattService>, _status: GattStatus, )4254 fn on_search_complete( 4255 &mut self, 4256 _addr: RawAddress, 4257 _services: Vec<BluetoothGattService>, 4258 _status: GattStatus, 4259 ) { 4260 } 4261 on_characteristic_read( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, _value: Vec<u8>, )4262 fn on_characteristic_read( 4263 &mut self, 4264 _addr: RawAddress, 4265 _status: GattStatus, 4266 _handle: i32, 4267 _value: Vec<u8>, 4268 ) { 4269 } 4270 on_characteristic_write( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, )4271 fn on_characteristic_write( 4272 &mut self, 4273 _addr: RawAddress, 4274 _status: GattStatus, 4275 _handle: i32, 4276 ) { 4277 } 4278 on_execute_write(&mut self, _addr: RawAddress, _status: GattStatus)4279 fn on_execute_write(&mut self, _addr: RawAddress, _status: GattStatus) {} 4280 on_descriptor_read( &mut self, _addr: RawAddress, _status: GattStatus, _handle: i32, _value: Vec<u8>, )4281 fn on_descriptor_read( 4282 &mut self, 4283 _addr: RawAddress, 4284 _status: GattStatus, 4285 _handle: i32, 4286 _value: Vec<u8>, 4287 ) { 4288 } 4289 on_descriptor_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32)4290 fn on_descriptor_write(&mut self, _addr: RawAddress, _status: GattStatus, _handle: i32) {} 4291 on_notify(&mut self, _addr: RawAddress, _handle: i32, _value: Vec<u8>)4292 fn on_notify(&mut self, _addr: RawAddress, _handle: i32, _value: Vec<u8>) {} 4293 on_read_remote_rssi(&mut self, _addr: RawAddress, _rssi: i32, _status: GattStatus)4294 fn on_read_remote_rssi(&mut self, _addr: RawAddress, _rssi: i32, _status: GattStatus) {} 4295 on_configure_mtu(&mut self, _addr: RawAddress, _mtu: i32, _status: GattStatus)4296 fn on_configure_mtu(&mut self, _addr: RawAddress, _mtu: i32, _status: GattStatus) {} 4297 on_connection_updated( &mut self, _addr: RawAddress, _interval: i32, _latency: i32, _timeout: i32, _status: GattStatus, )4298 fn on_connection_updated( 4299 &mut self, 4300 _addr: RawAddress, 4301 _interval: i32, 4302 _latency: i32, 4303 _timeout: i32, 4304 _status: GattStatus, 4305 ) { 4306 } 4307 on_service_changed(&mut self, _addr: RawAddress)4308 fn on_service_changed(&mut self, _addr: RawAddress) {} 4309 } 4310 4311 impl RPCProxy for TestBluetoothGattCallback { get_object_id(&self) -> String4312 fn get_object_id(&self) -> String { 4313 self.id.clone() 4314 } 4315 } 4316 4317 use super::*; 4318 4319 #[test] test_uuid_from_string()4320 fn test_uuid_from_string() { 4321 let uuid = Uuid::from_string("abcdef"); 4322 assert!(uuid.is_none()); 4323 4324 let uuid = Uuid::from_string("0123456789abcdef0123456789abcdef"); 4325 assert!(uuid.is_some()); 4326 let expected: [u8; 16] = [ 4327 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 4328 0xcd, 0xef, 4329 ]; 4330 assert_eq!(Uuid::from(expected), uuid.unwrap()); 4331 } 4332 4333 #[test] test_context_map_clients()4334 fn test_context_map_clients() { 4335 let (tx, _rx) = crate::Stack::create_channel(); 4336 let mut map = ContextMap::new(tx.clone()); 4337 4338 // Add client 1. 4339 let callback1 = Box::new(TestBluetoothGattCallback::new(String::from("Callback 1"))); 4340 let uuid1 = Uuid::from_string("00000000000000000000000000000001").unwrap(); 4341 map.add(&uuid1, callback1); 4342 let found = map.get_by_uuid(&uuid1); 4343 assert!(found.is_some()); 4344 assert_eq!( 4345 "Callback 1", 4346 match found { 4347 Some(c) => { 4348 let cbid = c.cbid; 4349 map.callbacks 4350 .get_by_id(cbid) 4351 .and_then(|cb| Some(cb.get_object_id())) 4352 .unwrap_or(String::new()) 4353 } 4354 None => String::new(), 4355 } 4356 ); 4357 4358 // Add client 2. 4359 let callback2 = Box::new(TestBluetoothGattCallback::new(String::from("Callback 2"))); 4360 let uuid2 = Uuid::from_string("00000000000000000000000000000002").unwrap(); 4361 map.add(&uuid2, callback2); 4362 let found = map.get_by_uuid(&uuid2); 4363 assert!(found.is_some()); 4364 assert_eq!( 4365 "Callback 2", 4366 match found { 4367 Some(c) => { 4368 let cbid = c.cbid; 4369 map.callbacks 4370 .get_by_id(cbid) 4371 .and_then(|cb| Some(cb.get_object_id())) 4372 .unwrap_or(String::new()) 4373 } 4374 None => String::new(), 4375 } 4376 ); 4377 4378 // Set client ID and get by client ID. 4379 map.set_client_id(&uuid1, 3); 4380 let found = map.get_by_client_id(3); 4381 assert!(found.is_some()); 4382 4383 // Remove client 1. 4384 map.remove(3); 4385 let found = map.get_by_uuid(&uuid1); 4386 assert!(found.is_none()); 4387 } 4388 4389 #[test] test_context_map_connections()4390 fn test_context_map_connections() { 4391 let (tx, _rx) = crate::Stack::create_channel(); 4392 let mut map = ContextMap::new(tx.clone()); 4393 let client_id = 1; 4394 4395 map.add_connection(client_id, 3, &RawAddress::from_string("aa:bb:cc:dd:ee:ff").unwrap()); 4396 map.add_connection(client_id, 4, &RawAddress::from_string("11:22:33:44:55:66").unwrap()); 4397 4398 let found = map.get_conn_id_from_address( 4399 client_id, 4400 &RawAddress::from_string("aa:bb:cc:dd:ee:ff").unwrap(), 4401 ); 4402 assert!(found.is_some()); 4403 assert_eq!(3, found.unwrap()); 4404 4405 let found = map.get_conn_id_from_address( 4406 client_id, 4407 &RawAddress::from_string("11:22:33:44:55:66").unwrap(), 4408 ); 4409 assert!(found.is_some()); 4410 assert_eq!(4, found.unwrap()); 4411 } 4412 } 4413