Skip to content

Commit baba482

Browse files
authored
Fix device disconnect for windows (#368)
1 parent 7042cf1 commit baba482

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

gap_windows.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package bluetooth
22

33
import (
4+
"context"
45
"errors"
56
"fmt"
67
"unsafe"
@@ -275,6 +276,9 @@ func (a *Adapter) StopScan() error {
275276

276277
// Device is a connection to a remote peripheral.
277278
type Device struct {
279+
ctx context.Context
280+
cancel context.CancelFunc
281+
278282
Address Address // the MAC address of the device
279283

280284
device *bluetooth.BluetoothLEDevice
@@ -343,7 +347,18 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err
343347
return Device{}, err
344348
}
345349

346-
device := Device{address, bleDevice, newSession}
350+
ctx, cancel := context.WithCancel(context.Background())
351+
352+
device := Device{
353+
ctx: ctx,
354+
cancel: cancel,
355+
356+
Address: address,
357+
358+
device: bleDevice,
359+
session: newSession,
360+
}
361+
347362
if a.connectHandler != nil {
348363
a.connectHandler(device, true)
349364
}
@@ -357,6 +372,8 @@ func (d Device) Disconnect() error {
357372
defer d.device.Release()
358373
defer d.session.Release()
359374

375+
d.cancel()
376+
360377
if err := d.session.Close(); err != nil {
361378
return err
362379
}

gattc_windows.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ func (d Device) DiscoverServices(filterUUIDs []UUID) ([]DeviceService, error) {
107107
}
108108
}
109109

110+
go func() {
111+
<-d.ctx.Done()
112+
srv.Close()
113+
}()
114+
110115
services = append(services, DeviceService{
111116
uuidWrapper: serviceUuid,
112117
service: srv,

0 commit comments

Comments
 (0)