@@ -122,20 +122,28 @@ impl Device {
122
122
/// # Panics
123
123
/// This functions panics if the BLE device does not have the expected badge characteristic.
124
124
pub async fn write ( & self , payload : PayloadBuffer ) -> Result < ( ) > {
125
- // Connect and discover services
126
125
self . peripheral
127
126
. connect ( )
128
127
. await
129
128
. 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 ( ) {
131
132
self . peripheral
132
133
. disconnect ( )
133
134
. await
134
135
. context ( "bluetooth device disconnect" ) ?;
135
- return Err ( error. into ( ) ) ;
136
136
}
137
137
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" ) ?;
139
147
let characteristics = self . peripheral . characteristics ( ) ;
140
148
let badge_char = characteristics. iter ( ) . find ( |c| c. uuid == BADGE_CHAR_UUID ) ;
141
149
@@ -160,24 +168,12 @@ impl Device {
160
168
anyhow:: ensure!( data. len( ) <= 8192 , "payload too long (max 8192 bytes)" ) ;
161
169
162
170
for chunk in data. chunks ( BLE_CHAR_CHUNK_SIZE ) {
163
- let write_result = self
164
- . peripheral
171
+ self . peripheral
165
172
. 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" ) ?;
175
175
}
176
176
177
- self . peripheral
178
- . disconnect ( )
179
- . await
180
- . context ( "bluetooth device disconnect" ) ?;
181
177
Ok ( ( ) )
182
178
}
183
179
}
0 commit comments