Skip to content

Commit 8260f2f

Browse files
aykevldeadprogram
authored andcommitted
linux: do not randomize order of returned discovered services/chars
Previously the list of services and characteristics wasn't sorted, and because of the way Go maps work they were in fact randomized. This commit fixes the sorting for services and characteristics, which both suffered from the same lack of sorting. This fixes #135.
1 parent 5717af5 commit 8260f2f

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

gattc_linux.go

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ package bluetooth
55

66
import (
77
"errors"
8+
"sort"
89
"strings"
910
"time"
1011

12+
"github.com/godbus/dbus/v5"
1113
"github.com/muka/go-bluetooth/bluez"
1214
"github.com/muka/go-bluetooth/bluez/profile/gatt"
1315
)
@@ -70,15 +72,20 @@ func (d *Device) DiscoverServices(uuids []UUID) ([]DeviceService, error) {
7072
if err != nil {
7173
return nil, err
7274
}
75+
objects := make([]string, 0, len(list))
7376
for objectPath := range list {
74-
if !strings.HasPrefix(string(objectPath), string(d.device.Path())+"/service") {
77+
objects = append(objects, string(objectPath))
78+
}
79+
sort.Strings(objects)
80+
for _, objectPath := range objects {
81+
if !strings.HasPrefix(objectPath, string(d.device.Path())+"/service") {
7582
continue
7683
}
77-
suffix := string(objectPath)[len(d.device.Path()+"/"):]
84+
suffix := objectPath[len(d.device.Path()+"/"):]
7885
if len(strings.Split(suffix, "/")) != 1 {
7986
continue
8087
}
81-
service, err := gatt.NewGattService1(objectPath)
88+
service, err := gatt.NewGattService1(dbus.ObjectPath(objectPath))
8289
if err != nil {
8390
return nil, err
8491
}
@@ -160,15 +167,20 @@ func (s *DeviceService) DiscoverCharacteristics(uuids []UUID) ([]DeviceCharacter
160167
if err != nil {
161168
return nil, err
162169
}
170+
objects := make([]string, 0, len(list))
163171
for objectPath := range list {
164-
if !strings.HasPrefix(string(objectPath), string(s.service.Path())+"/char") {
172+
objects = append(objects, string(objectPath))
173+
}
174+
sort.Strings(objects)
175+
for _, objectPath := range objects {
176+
if !strings.HasPrefix(objectPath, string(s.service.Path())+"/char") {
165177
continue
166178
}
167-
suffix := string(objectPath)[len(s.service.Path()+"/"):]
179+
suffix := objectPath[len(s.service.Path()+"/"):]
168180
if len(strings.Split(suffix, "/")) != 1 {
169181
continue
170182
}
171-
characteristic, err := gatt.NewGattCharacteristic1(objectPath)
183+
characteristic, err := gatt.NewGattCharacteristic1(dbus.ObjectPath(objectPath))
172184
if err != nil {
173185
return nil, err
174186
}

0 commit comments

Comments
 (0)