@@ -3,6 +3,7 @@ use dbus::Path;
33use dbus:: arg:: { PropMap , RefArg , Variant , cast} ;
44use serde:: { Deserialize , Serialize } ;
55use std:: collections:: HashMap ;
6+ use std:: convert:: TryFrom ;
67use std:: fmt:: { self , Display , Formatter } ;
78use std:: str:: FromStr ;
89use uuid:: Uuid ;
@@ -41,6 +42,23 @@ impl From<DeviceId> for Path<'static> {
4142 }
4243}
4344
45+ impl FromStr for DeviceId {
46+ type Err = BluetoothError ;
47+
48+ fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
49+ if !s. starts_with ( "hci" ) {
50+ return Err ( BluetoothError :: DeviceIdParseError ( s. to_string ( ) ) ) ;
51+ }
52+
53+ let path = Path :: new ( format ! ( "/org/bluez/{}" , s) )
54+ . map_err ( |_| BluetoothError :: DeviceIdParseError ( s. to_string ( ) ) ) ?;
55+
56+ Ok ( DeviceId {
57+ object_path : path. into_static ( ) ,
58+ } )
59+ }
60+ }
61+
4462impl Display for DeviceId {
4563 fn fmt ( & self , f : & mut Formatter < ' _ > ) -> fmt:: Result {
4664 write ! (
@@ -296,6 +314,18 @@ mod tests {
296314 assert_eq ! ( device_id. to_string( ) , "hci0/dev_11_22_33_44_55_66" ) ;
297315 }
298316
317+ #[ test]
318+ fn from_string ( ) {
319+ let device_id = DeviceId :: from_str ( "hci0/dev_11_22_33_44_55_66" ) ;
320+ assert_eq ! ( device_id. unwrap( ) . to_string( ) , "hci0/dev_11_22_33_44_55_66" ) ;
321+
322+ let invalid_id = DeviceId :: from_str ( "dev_11_22_33_44_55_66" ) ;
323+ assert_eq ! (
324+ invalid_id. unwrap_err( ) . to_string( ) ,
325+ "Error parsing DeviceId string: dev_11_22_33_44_55_66"
326+ ) ;
327+ }
328+
299329 #[ test]
300330 fn service_data ( ) {
301331 let uuid = uuid_from_u32 ( 0x11223344 ) ;
0 commit comments