Describe the bug
When concurrent async calls (e.g, discover_services) are made on the same Peripheral from different tasks, the later call‘s Future will overwrites the earlier call’s Future (e.g, code), after the first finished one resolved the Future, the second one will have no Future to resolve, then panic at code.
Code to reproduce
use btleplug::{
api::{Central, Manager as _, Peripheral},
platform::Manager,
};
use std::{sync::Arc, time::Duration};
use tokio::time::sleep;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let manager = Manager::new().await?;
let adapter_list = manager.adapters().await?;
let adapter = adapter_list.into_iter().next().expect("No BLE adapter found");
println!("Scanning for peripherals...");
adapter.start_scan(btleplug::api::ScanFilter::default()).await?;
sleep(Duration::from_secs(2)).await;
let peripherals = adapter.peripherals().await?;
if peripherals.is_empty() {
println!("No peripherals found. Please make sure a BLE device is nearby.");
return Ok(());
}
let peripheral = Arc::new(peripherals.into_iter().next().unwrap());
if !peripheral.is_connected().await? {
println!("Connecting to peripheral...");
peripheral.connect().await?;
}
let task1 = tokio::spawn({
let peripheral = peripheral.clone();
async move {
println!("Task 1: Calling discover_services...");
match peripheral.discover_services().await {
Ok(_) => println!("Task 1: Success"),
Err(e) => println!("Task 1: Failed with error: {:?}", e),
}
}
});
let task2 = tokio::spawn({
let peripheral = peripheral.clone();
async move {
sleep(Duration::from_millis(5)).await;
println!("Task 2: Calling discover_services...");
match peripheral.discover_services().await {
Ok(_) => println!("Task 2: Success"),
Err(e) => println!("Task 2: Failed with error: {:?}", e),
}
}
});
tokio::try_join!(task1, task2)?;
Ok(())
}
Describe the bug
When concurrent async calls (e.g, discover_services) are made on the same Peripheral from different tasks, the later call‘s Future will overwrites the earlier call’s Future (e.g, code), after the first finished one resolved the Future, the second one will have no Future to resolve, then panic at code.
Code to reproduce