From e4200f5e1de821d364b9f0fe094518a30c0633df Mon Sep 17 00:00:00 2001 From: Szymon Lesisz Date: Wed, 29 Oct 2025 14:36:52 +0100 Subject: [PATCH] Add DeviceId from str conversion --- bluez-async/src/device.rs | 30 ++++++++++++++++++++++++++++++ bluez-async/src/lib.rs | 3 +++ 2 files changed, 33 insertions(+) diff --git a/bluez-async/src/device.rs b/bluez-async/src/device.rs index 27c6ed7..44ce400 100644 --- a/bluez-async/src/device.rs +++ b/bluez-async/src/device.rs @@ -3,6 +3,7 @@ use dbus::Path; use dbus::arg::{PropMap, RefArg, Variant, cast}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::convert::TryFrom; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use uuid::Uuid; @@ -41,6 +42,23 @@ impl From for Path<'static> { } } +impl FromStr for DeviceId { + type Err = BluetoothError; + + fn from_str(s: &str) -> Result { + if !s.starts_with("hci") { + return Err(BluetoothError::DeviceIdParseError(s.to_string())); + } + + let path = Path::new(format!("/org/bluez/{}", s)) + .map_err(|_| BluetoothError::DeviceIdParseError(s.to_string()))?; + + Ok(DeviceId { + object_path: path.into_static(), + }) + } +} + impl Display for DeviceId { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( @@ -296,6 +314,18 @@ mod tests { assert_eq!(device_id.to_string(), "hci0/dev_11_22_33_44_55_66"); } + #[test] + fn from_string() { + let device_id = DeviceId::from_str("hci0/dev_11_22_33_44_55_66"); + assert_eq!(device_id.unwrap().to_string(), "hci0/dev_11_22_33_44_55_66"); + + let invalid_id = DeviceId::from_str("dev_11_22_33_44_55_66"); + assert_eq!( + invalid_id.unwrap_err().to_string(), + "Error parsing DeviceId string: dev_11_22_33_44_55_66" + ); + } + #[test] fn service_data() { let uuid = uuid_from_u32(0x11223344); diff --git a/bluez-async/src/lib.rs b/bluez-async/src/lib.rs index 1e8d6ec..3365580 100644 --- a/bluez-async/src/lib.rs +++ b/bluez-async/src/lib.rs @@ -96,6 +96,9 @@ pub enum BluetoothError { /// Error parsing a `Modalias` from a string. #[error(transparent)] ModaliasParseError(#[from] ParseModaliasError), + /// Error parsing DeviceId from a string. + #[error("Error parsing DeviceId string: {0}")] + DeviceIdParseError(String), } /// Error type for futures representing tasks spawned by this crate.