Skip to content

Fix device disconnect for windows #368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion gap_windows.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bluetooth

import (
"context"
"errors"
"fmt"
"unsafe"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
Expand All @@ -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
}
Expand Down
5 changes: 5 additions & 0 deletions gattc_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading