diff --git a/gap_windows.go b/gap_windows.go index a884b46..742ef33 100644 --- a/gap_windows.go +++ b/gap_windows.go @@ -1,6 +1,7 @@ package bluetooth import ( + "context" "errors" "fmt" "unsafe" @@ -275,6 +276,9 @@ func (a *Adapter) StopScan() error { // Device is a connection to a remote peripheral. type Device struct { + ctx context.Context + cancel context.CancelFunc + Address Address // the MAC address of the device device *bluetooth.BluetoothLEDevice @@ -343,7 +347,18 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err return Device{}, err } - device := Device{address, bleDevice, newSession} + ctx, cancel := context.WithCancel(context.Background()) + + device := Device{ + ctx: ctx, + cancel: cancel, + + Address: address, + + device: bleDevice, + session: newSession, + } + if a.connectHandler != nil { a.connectHandler(device, true) } @@ -357,6 +372,8 @@ func (d Device) Disconnect() error { defer d.device.Release() defer d.session.Release() + d.cancel() + if err := d.session.Close(); err != nil { return err } diff --git a/gattc_windows.go b/gattc_windows.go index cde3fcf..e384db3 100644 --- a/gattc_windows.go +++ b/gattc_windows.go @@ -107,6 +107,11 @@ func (d Device) DiscoverServices(filterUUIDs []UUID) ([]DeviceService, error) { } } + go func() { + <-d.ctx.Done() + srv.Close() + }() + services = append(services, DeviceService{ uuidWrapper: serviceUuid, service: srv,