Skip to content

Commit 5c19f86

Browse files
authored
fix: Darwin services ordering in DiscoverServices (#417)
* fix: Darwin services ordering in DiscoverServices The services will now appear on the expected order * remove pointer
1 parent d737f9b commit 5c19f86

1 file changed

Lines changed: 34 additions & 18 deletions

File tree

gattc_darwin.go

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package bluetooth
22

33
import (
44
"errors"
5+
"slices"
56
"time"
67

78
"github.com/tinygo-org/cbgo"
@@ -24,33 +25,34 @@ func (d Device) DiscoverServices(uuids []UUID) ([]DeviceService, error) {
2425
select {
2526
case <-d.servicesChan:
2627
svcs := []DeviceService{}
28+
29+
if len(uuids) > 0 {
30+
// The caller wants to get a list of services in a specific
31+
// order.
32+
svcs = make([]DeviceService, len(uuids))
33+
}
34+
2735
for _, dsvc := range d.prph.Services() {
2836
dsvcuuid, _ := ParseUUID(dsvc.UUID().String())
29-
// add if in our original list
37+
38+
// only include services that are included in the input filter
3039
if len(uuids) > 0 {
31-
found := false
32-
for _, uuid := range uuids {
40+
for j, uuid := range uuids {
3341
if dsvcuuid.String() == uuid.String() {
34-
// one of the services we're looking for.
35-
found = true
36-
break
42+
// One of the services we're looking for.
43+
svcs[j] = d.makeService(dsvcuuid, dsvc)
3744
}
3845
}
39-
if !found {
40-
continue
41-
}
46+
} else {
47+
// The caller wants to get all services, in any order.
48+
svcs = append(svcs, d.makeService(dsvcuuid, dsvc))
4249
}
50+
}
4351

44-
svc := DeviceService{
45-
deviceService: &deviceService{
46-
uuidWrapper: dsvcuuid,
47-
device: d,
48-
service: dsvc,
49-
},
50-
}
51-
svcs = append(svcs, svc)
52-
d.services[svc.uuidWrapper] = svc
52+
if slices.Contains(svcs, (DeviceService{})) {
53+
return nil, errors.New("bluetooth: did not find all requested services")
5354
}
55+
5456
return svcs, nil
5557
case <-time.NewTimer(10 * time.Second).C:
5658
return nil, errors.New("timeout on DiscoverServices")
@@ -61,6 +63,20 @@ func (d Device) DiscoverServices(uuids []UUID) ([]DeviceService, error) {
6163
// struct method of the same name.
6264
type uuidWrapper = UUID
6365

66+
// Small helper to create a DeviceService object.
67+
func (d Device) makeService(dsvcuuid uuidWrapper, dsvc cbgo.Service) DeviceService {
68+
svc := DeviceService{
69+
deviceService: &deviceService{
70+
uuidWrapper: dsvcuuid,
71+
device: d,
72+
service: dsvc,
73+
},
74+
}
75+
// Cache the service in the device's services map, so that we can find it
76+
d.services[svc.uuidWrapper] = svc
77+
return svc
78+
}
79+
6480
// DeviceService is a BLE service on a connected peripheral device.
6581
type DeviceService struct {
6682
*deviceService // embdedded as pointer to enable returning by []value in DiscoverServices

0 commit comments

Comments
 (0)