Simplify error handling of BLE writing

This commit is contained in:
Lilian 2024-07-31 23:48:30 +02:00 committed by Martin Michaelis
parent 925fb45617
commit ba41bf3a65

View file

@ -122,20 +122,28 @@ impl Device {
/// # Panics /// # Panics
/// This functions panics if the BLE device does not have the expected badge characteristic. /// This functions panics if the BLE device does not have the expected badge characteristic.
pub async fn write(&self, payload: PayloadBuffer) -> Result<()> { pub async fn write(&self, payload: PayloadBuffer) -> Result<()> {
// Connect and discover services
self.peripheral self.peripheral
.connect() .connect()
.await .await
.context("bluetooth device connect")?; .context("bluetooth device connect")?;
if let Err(error) = self.peripheral.discover_services().await {
let result = self.write_connected(payload).await;
if result.is_ok() {
self.peripheral self.peripheral
.disconnect() .disconnect()
.await .await
.context("bluetooth device disconnect")?; .context("bluetooth device disconnect")?;
return Err(error.into());
} }
// Get characteristics result
}
async fn write_connected(&self, payload: PayloadBuffer) -> Result<()> {
// Get characteristic
self.peripheral
.discover_services()
.await
.context("discovering services")?;
let characteristics = self.peripheral.characteristics(); let characteristics = self.peripheral.characteristics();
let badge_char = characteristics.iter().find(|c| c.uuid == BADGE_CHAR_UUID); let badge_char = characteristics.iter().find(|c| c.uuid == BADGE_CHAR_UUID);
@ -160,24 +168,12 @@ impl Device {
anyhow::ensure!(data.len() <= 8192, "payload too long (max 8192 bytes)"); anyhow::ensure!(data.len() <= 8192, "payload too long (max 8192 bytes)");
for chunk in data.chunks(BLE_CHAR_CHUNK_SIZE) { for chunk in data.chunks(BLE_CHAR_CHUNK_SIZE) {
let write_result = self self.peripheral
.peripheral
.write(badge_char, chunk, WriteType::WithoutResponse) .write(badge_char, chunk, WriteType::WithoutResponse)
.await;
if let Err(error) = write_result {
self.peripheral
.disconnect()
.await .await
.context("bluetooth device disconnect")?; .context("writing payload chunk")?;
return Err(anyhow::anyhow!("Error writing payload chunk: {:?}", error));
}
} }
self.peripheral
.disconnect()
.await
.context("bluetooth device disconnect")?;
Ok(()) Ok(())
} }
} }