@@ -122,20 +122,28 @@ impl Device {
122122 /// # Panics
123123 /// This functions panics if the BLE device does not have the expected badge characteristic.
124124 pub async fn write ( & self , payload : PayloadBuffer ) -> Result < ( ) > {
125- // Connect and discover services
126125 self . peripheral
127126 . connect ( )
128127 . await
129128 . context ( "bluetooth device connect" ) ?;
130- if let Err ( error) = self . peripheral . discover_services ( ) . await {
129+
130+ let result = self . write_connected ( payload) . await ;
131+ if result. is_ok ( ) {
131132 self . peripheral
132133 . disconnect ( )
133134 . await
134135 . context ( "bluetooth device disconnect" ) ?;
135- return Err ( error. into ( ) ) ;
136136 }
137137
138- // Get characteristics
138+ result
139+ }
140+
141+ async fn write_connected ( & self , payload : PayloadBuffer ) -> Result < ( ) > {
142+ // Get characteristic
143+ self . peripheral
144+ . discover_services ( )
145+ . await
146+ . context ( "discovering services" ) ?;
139147 let characteristics = self . peripheral . characteristics ( ) ;
140148 let badge_char = characteristics. iter ( ) . find ( |c| c. uuid == BADGE_CHAR_UUID ) ;
141149
@@ -160,24 +168,12 @@ impl Device {
160168 anyhow:: ensure!( data. len( ) <= 8192 , "payload too long (max 8192 bytes)" ) ;
161169
162170 for chunk in data. chunks ( BLE_CHAR_CHUNK_SIZE ) {
163- let write_result = self
164- . peripheral
171+ self . peripheral
165172 . write ( badge_char, chunk, WriteType :: WithoutResponse )
166- . await ;
167-
168- if let Err ( error) = write_result {
169- self . peripheral
170- . disconnect ( )
171- . await
172- . context ( "bluetooth device disconnect" ) ?;
173- return Err ( anyhow:: anyhow!( "Error writing payload chunk: {:?}" , error) ) ;
174- }
173+ . await
174+ . context ( "writing payload chunk" ) ?;
175175 }
176176
177- self . peripheral
178- . disconnect ( )
179- . await
180- . context ( "bluetooth device disconnect" ) ?;
181177 Ok ( ( ) )
182178 }
183179}
0 commit comments