Skip to content
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

Handle bluez connection call with cancellable context #297

Closed
wants to merge 16 commits into from
Closed
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
4 changes: 4 additions & 0 deletions gap.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ func NewDuration(interval time.Duration) Duration {
return Duration(uint64(interval / (625 * time.Microsecond)))
}

func (d Duration) AsTimeDuration() time.Duration {
return time.Duration(d) * (625 * time.Microsecond)
}

// Connection is a numeric identifier that indicates a connection handle.
type Connection uint16

Expand Down
48 changes: 40 additions & 8 deletions gap_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
package bluetooth

import (
"context"
"errors"
"fmt"
"strings"
"sync/atomic"
"time"

"github.com/godbus/dbus/v5"
"github.com/godbus/dbus/v5/prop"
Expand Down Expand Up @@ -195,9 +197,14 @@ func (a *Adapter) Scan(callback func(*Adapter, ScanResult)) error {
devices[path] = device
}

// Instruct BlueZ to start discovering.
err = a.adapter.Call("org.bluez.Adapter1.StartDiscovery", 0).Err
if err != nil {
// Instruct BlueZ to start discovering if it isn't already.
if disc, err := a.adapter.GetProperty("org.bluez.Adapter1.Discovering"); disc.Value().(bool) == false && err == nil {
err = a.adapter.Call("org.bluez.Adapter1.StartDiscovery", 0).Err
if err != nil {
return err
}
defer a.adapter.Call("org.bluez.Adapter1.StopDiscovery", 0)
} else if err != nil {
return err
}

Expand Down Expand Up @@ -345,6 +352,7 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err
// were connected between the two calls the signal wouldn't be picked up.
signal := make(chan *dbus.Signal)
a.bus.Signal(signal)
defer close(signal)
defer a.bus.RemoveSignal(signal)
propertiesChangedMatchOptions := []dbus.MatchOption{dbus.WithMatchInterface("org.freedesktop.DBus.Properties")}
a.bus.AddMatchSignal(propertiesChangedMatchOptions...)
Expand All @@ -358,14 +366,23 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err

// Connect to the device, if not already connected.
if !connected.Value().(bool) {
if params.ConnectionTimeout <= 0 {
params.ConnectionTimeout = NewDuration(30 * time.Second)
}

// Start connecting (async).
err := device.device.Call("org.bluez.Device1.Connect", 0).Err
ctx, cancelConnect := context.WithCancel(context.Background())
time.AfterFunc(params.ConnectionTimeout.AsTimeDuration(), cancelConnect)
err := device.device.CallWithContext(ctx, "org.bluez.Device1.Connect", 0).Err
if err != nil {
return Device{}, fmt.Errorf("bluetooth: failed to connect: %w", err)
}

// Wait until the device has connected.
connectChan := make(chan struct{})
// Wait until the device has connected or the connection attempt times out.
connectChan := make(chan error)
defer close(connectChan)
cancelTimeout := make(chan bool)
defer close(cancelTimeout)
go func() {
for sig := range signal {
switch sig.Name {
Expand All @@ -379,12 +396,27 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err
}
changes := sig.Body[1].(map[string]dbus.Variant)
if connected, ok := changes["Connected"].Value().(bool); ok && connected {
close(connectChan)
connectChan <- nil
}
}
}
}()
<-connectChan
go func() {
select {
case <-cancelTimeout:
case <-time.After(params.ConnectionTimeout.AsTimeDuration()):
connected, err := device.device.GetProperty("org.bluez.Device1.Connected")
if !connected.Value().(bool) || err != nil {
connectChan <- fmt.Errorf("connection timeout exceeded: %w", err)
} else {
connectChan <- nil
}
}
}()
err = <-connectChan
if err != nil {
return Device{}, err
}
}

return device, nil
Expand Down
4 changes: 3 additions & 1 deletion gap_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ func (a *Adapter) StopScan() error {

// Device is a connection to a remote peripheral.
type Device struct {
Address Address // the MAC address of the device

device *bluetooth.BluetoothLEDevice
session *genericattributeprofile.GattSession
}
Expand Down Expand Up @@ -238,7 +240,7 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err
return Device{}, err
}

return Device{bleDevice, newSession}, nil
return Device{address, bleDevice, newSession}, nil
}

// Disconnect from the BLE device. This method is non-blocking and does not
Expand Down
24 changes: 23 additions & 1 deletion gattc_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package bluetooth

import (
"errors"
"path"
"sort"
"strings"
"time"
Expand Down Expand Up @@ -242,6 +243,9 @@ func (c DeviceCharacteristic) EnableNotifications(callback func(buf []byte)) err
return errDupNotif
}

// Figure out the path of the device that this characteristic belongs to
devicePath := dbus.ObjectPath(path.Dir(path.Dir(string(c.characteristic.Path()))))

// Start watching for changes in the Value property.
c.property = make(chan *dbus.Signal)
c.adapter.bus.Signal(c.property)
Expand All @@ -257,12 +261,24 @@ func (c DeviceCharacteristic) EnableNotifications(callback func(buf []byte)) err
for sig := range c.property {
if sig.Name == "org.freedesktop.DBus.Properties.PropertiesChanged" {
interfaceName := sig.Body[0].(string)

if interfaceName == "org.bluez.Device1" && sig.Path == devicePath {
changes := sig.Body[1].(map[string]dbus.Variant)

if connected, ok := changes["Connected"].Value().(bool); ok && !connected {
c.EnableNotifications(nil)
return
}
}

if interfaceName != "org.bluez.GattCharacteristic1" {
continue
}

if sig.Path != c.characteristic.Path() {
continue
}

changes := sig.Body[1].(map[string]dbus.Variant)
if value, ok := changes["Value"].Value().([]byte); ok {
callback(value)
Expand All @@ -278,8 +294,14 @@ func (c DeviceCharacteristic) EnableNotifications(callback func(buf []byte)) err
return nil
}

err := c.adapter.bus.RemoveMatchSignal(c.propertiesChangedMatchOption)
err := c.characteristic.Call("org.bluez.GattCharacteristic1.StopNotify", 0).Err
if err != nil {
return err
}

err = c.adapter.bus.RemoveMatchSignal(c.propertiesChangedMatchOption)
c.adapter.bus.RemoveSignal(c.property)
close(c.property)
c.property = nil
return err
}
Expand Down
Loading