@@ -3,6 +3,7 @@ package bluetooth
33import (
44 "errors"
55 "fmt"
6+ "slices"
67 "syscall"
78 "unsafe"
89
@@ -196,6 +197,13 @@ func (s DeviceService) DiscoverCharacteristics(filterUUIDs []UUID) ([]DeviceChar
196197 }
197198
198199 var characteristics []DeviceCharacteristic
200+
201+ if len (filterUUIDs ) > 0 {
202+ // The caller wants to get a list of characteristics in a specific
203+ // order.
204+ characteristics = make ([]DeviceCharacteristic , len (filterUUIDs ))
205+ }
206+
199207 for i := uint32 (0 ); i < characteristicsSize ; i ++ {
200208 c , err := charVector .GetAt (i )
201209 if err != nil {
@@ -217,33 +225,53 @@ func (s DeviceService) DiscoverCharacteristics(filterUUIDs []UUID) ([]DeviceChar
217225
218226 // only include characteristics that are included in the input filter
219227 if len (filterUUIDs ) > 0 {
220- found := false
221- for _ , uuid := range filterUUIDs {
228+ for j , uuid := range filterUUIDs {
229+ if characteristics [j ] != (DeviceCharacteristic {}) {
230+ // To support multiple identical characteristics, we
231+ // need to ignore the characteristics that are already
232+ // found. See:
233+ // https://github.com/tinygo-org/bluetooth/issues/131
234+ continue
235+ }
222236 if characteristicUUID .String () == uuid .String () {
223237 // One of the characteristics we're looking for.
224- found = true
238+ characteristics [ j ] = s . makeCharacteristic ( characteristicUUID , characteristic , properties )
225239 break
226240 }
227241 }
228- if ! found {
229- continue
230- }
242+ } else {
243+ // The caller wants to get all characteristics, in any order.
244+ characteristics = append ( characteristics , s . makeCharacteristic ( characteristicUUID , characteristic , properties ))
231245 }
246+ }
232247
233- characteristics = append (characteristics , DeviceCharacteristic {
234- uuidWrapper : characteristicUUID ,
248+ if slices .Contains (characteristics , (DeviceCharacteristic {})) {
249+ return nil , errors .New ("bluetooth: did not find all requested characteristic" )
250+ }
251+
252+ return characteristics , nil
253+ }
254+
255+ // Small helper to create a DeviceCharacteristic object.
256+ func (s DeviceService ) makeCharacteristic (uuid UUID , characteristic * genericattributeprofile.GattCharacteristic , properties genericattributeprofile.GattCharacteristicProperties ) DeviceCharacteristic {
257+ char := DeviceCharacteristic {
258+ deviceCharacteristic : & deviceCharacteristic {
259+ uuidWrapper : uuid ,
235260 service : s ,
236261 characteristic : characteristic ,
237262 properties : properties ,
238- })
263+ },
239264 }
240-
241- return characteristics , nil
265+ return char
242266}
243267
244268// DeviceCharacteristic is a BLE characteristic on a connected peripheral
245269// device.
246270type DeviceCharacteristic struct {
271+ * deviceCharacteristic
272+ }
273+
274+ type deviceCharacteristic struct {
247275 uuidWrapper
248276
249277 characteristic * genericattributeprofile.GattCharacteristic
0 commit comments