Skip to content

Commit

Permalink
ble(client): add scan timout
Browse files Browse the repository at this point in the history
  • Loading branch information
gen2thomas committed Feb 5, 2024
1 parent 3ac63bf commit 59a2afa
Show file tree
Hide file tree
Showing 5 changed files with 517 additions and 74 deletions.
191 changes: 118 additions & 73 deletions platforms/bleclient/ble_client_adaptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,112 +11,165 @@ import (
"gobot.io/x/gobot/v2"
)

var (
currentAdapter *bluetooth.Adapter
bleMutex sync.Mutex
)
type bleAdaptorConfiguration struct {
scanTimeout time.Duration
debug bool
}

// Adaptor represents a client connection to a BLE Peripheral
// Adaptor represents a Client Connection to a BLE Peripheral
type Adaptor struct {
name string
address string
AdapterName string
name string
identifier string
clientCfg *bleAdaptorConfiguration

addr bluetooth.Address
adpt *bluetooth.Adapter
device *bluetooth.Device
btAdpt *btAdapter
btDevice *btDevice
characteristics map[string]bluetooth.DeviceCharacteristic

connected bool
withoutResponses bool
connected bool
rssi int

btAdptCreator btAdptCreatorFunc
mutex *sync.Mutex
}

// NewAdaptor returns a new Bluetooth LE client adaptor given an address
func NewAdaptor(address string) *Adaptor {
return &Adaptor{
name: gobot.DefaultName("BLEClient"),
address: address,
AdapterName: "default",
connected: false,
withoutResponses: false,
characteristics: make(map[string]bluetooth.DeviceCharacteristic),
// NewAdaptor returns a new Adaptor given an identifier. The identifier can be the address or the name.
//
// Supported options:
//
// "WithAdaptorDebug"
// "WithAdaptorScanTimeout"
func NewAdaptor(identifier string, opts ...bleAdaptorOptionApplier) *Adaptor {

Check failure on line 42 in platforms/bleclient/ble_client_adaptor.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleAdaptorOptionApplier
cfg := bleAdaptorConfiguration{
scanTimeout: 10 * time.Minute,
}

a := Adaptor{
name: gobot.DefaultName("BLEClient"),
identifier: identifier,
clientCfg: &cfg,
characteristics: make(map[string]bluetooth.DeviceCharacteristic),
btAdptCreator: newBtAdapter,
mutex: &sync.Mutex{},
}

for _, o := range opts {
o.apply(a.clientCfg)
}

return &a
}

// Name returns the name for the adaptor
func (a *Adaptor) Name() string { return a.name }
// WithAdaptorDebug switch on some debug messages.
func WithAdaptorDebug() bleAdaptorDebugOption {

Check failure on line 64 in platforms/bleclient/ble_client_adaptor.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleAdaptorDebugOption
return bleAdaptorDebugOption(true)

Check failure on line 65 in platforms/bleclient/ble_client_adaptor.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleAdaptorDebugOption
}

// WithAdaptorScanTimeout substitute the default scan timeout of 10 min.
func WithAdaptorScanTimeout(timeout time.Duration) bleAdaptorScanTimeoutOption {

Check failure on line 69 in platforms/bleclient/ble_client_adaptor.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleAdaptorScanTimeoutOption
return bleAdaptorScanTimeoutOption(timeout)

Check failure on line 70 in platforms/bleclient/ble_client_adaptor.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleAdaptorScanTimeoutOption
}

// Name returns the name for the adaptor and after the connection is done, the name of the device
func (a *Adaptor) Name() string {
if a.btDevice != nil {
return a.btDevice.Name()
}
return a.name
}

// SetName sets the name for the adaptor
func (a *Adaptor) SetName(n string) { a.name = n }

// Address returns the Bluetooth LE address for the adaptor
func (a *Adaptor) Address() string { return a.address }
// Address returns the Bluetooth LE address of the device if connected, otherwise the identifier
func (a *Adaptor) Address() string {
if a.btDevice != nil {
return a.btDevice.Address()
}

return a.identifier
}

// RSSI returns the Bluetooth LE RSSI value at the moment of connecting the adaptor
func (a *Adaptor) RSSI() int { return a.rssi }

// WithoutResponses sets if the adaptor should expect responses after
// writing characteristics for this device
func (a *Adaptor) WithoutResponses(use bool) { a.withoutResponses = use }
// writing characteristics for this device (has no effect at the moment).
func (a *Adaptor) WithoutResponses(bool) {}

// Connect initiates a connection to the BLE peripheral. Returns true on successful connection.
// Connect initiates a connection to the BLE peripheral.
func (a *Adaptor) Connect() error {
bleMutex.Lock()
defer bleMutex.Unlock()
a.mutex.Lock()
defer a.mutex.Unlock()

var err error
// enable adaptor
a.adpt, err = getBLEAdapter(a.AdapterName)
if err != nil {
return fmt.Errorf("can't get adapter %s: %w", a.AdapterName, err)
}

// handle address
a.addr.Set(a.Address())
if a.clientCfg.debug {
fmt.Println("[Connect]: enable adaptor...")
}

// scan for the address
ch := make(chan bluetooth.ScanResult, 1)
err = a.adpt.Scan(func(adapter *bluetooth.Adapter, result bluetooth.ScanResult) {
if result.Address.String() == a.Address() {
if err := a.adpt.StopScan(); err != nil {
panic(err)
}
a.SetName(result.LocalName())
ch <- result
// for re-connect, the adapter is already known
if a.btAdpt == nil {
a.btAdpt = a.btAdptCreator(bluetooth.DefaultAdapter)
if err := a.btAdpt.Enable(); err != nil {
return fmt.Errorf("can't get adapter default: %w", err)
}
})
}

if a.clientCfg.debug {
fmt.Printf("[Connect]: scan %s for the identifier '%s'...\n", a.clientCfg.scanTimeout, a.identifier)
}

result, err := a.btAdpt.Scan(a.identifier, a.clientCfg.scanTimeout)
if err != nil {
return err
}

// wait to connect to peripheral device
result := <-ch
a.device, err = a.adpt.Connect(result.Address, bluetooth.ConnectionParams{})
if a.clientCfg.debug {
fmt.Printf("[Connect]: connect to peripheral device with address %s...\n", result.Address)
}

dev, err := a.btAdpt.Connect(result.Address, result.LocalName())
if err != nil {
return err
}

// get all services/characteristics
srvcs, err := a.device.DiscoverServices(nil)
a.rssi = int(result.RSSI)
a.btDevice = dev

if a.clientCfg.debug {
fmt.Println("[Connect]: get all services/characteristics...")
}
services, err := a.btDevice.DiscoverServices(nil)
if err != nil {
return err
}
for _, srvc := range srvcs {
chars, err := srvc.DiscoverCharacteristics(nil)
for _, service := range services {
if a.clientCfg.debug {
fmt.Printf("[Connect]: service found: %s\n", service)
}
chars, err := service.DiscoverCharacteristics(nil)
if err != nil {
log.Println(err)
continue
}
for _, char := range chars {
if a.clientCfg.debug {
fmt.Printf("[Connect]: characteristic found: %s\n", char)
}
a.characteristics[char.UUID().String()] = char
}
}

if a.clientCfg.debug {
fmt.Println("[Connect]: connected")
}
a.connected = true
return nil
}

// Reconnect attempts to reconnect to the BLE peripheral. If it has an active connection
// it will first close that connection and then establish a new connection.
// Returns true on Successful reconnection
func (a *Adaptor) Reconnect() error {
if a.connected {
if err := a.Disconnect(); err != nil {
Expand All @@ -126,10 +179,17 @@ func (a *Adaptor) Reconnect() error {
return a.Connect()
}

// Disconnect terminates the connection to the BLE peripheral. Returns true on successful disconnect.
// Disconnect terminates the connection to the BLE peripheral.
func (a *Adaptor) Disconnect() error {
err := a.device.Disconnect()
if a.clientCfg.debug {
fmt.Println("[Disconnect]: disconnect...")
}
err := a.btDevice.Disconnect()
time.Sleep(500 * time.Millisecond)
a.connected = false
if a.clientCfg.debug {
fmt.Println("[Disconnect]: disconnected")
}
return err
}

Expand Down Expand Up @@ -197,18 +257,3 @@ func (a *Adaptor) Subscribe(cUUID string, f func([]byte, error)) error {

return fmt.Errorf("Unknown characteristic: %s", cUUID)
}

// getBLEAdapter is singleton for bluetooth adapter connection
func getBLEAdapter(impl string) (*bluetooth.Adapter, error) { //nolint:unparam // TODO: impl is unused, maybe an error
if currentAdapter != nil {
return currentAdapter, nil
}

currentAdapter = bluetooth.DefaultAdapter
err := currentAdapter.Enable()
if err != nil {
return nil, err
}

return currentAdapter, nil
}
30 changes: 30 additions & 0 deletions platforms/bleclient/ble_client_adaptor_options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package bleclient

import "time"

// bleClientAdaptorOptionApplier needs to be implemented by each configurable option type
type bleClientAdaptorOptionApplier interface {
apply(cfg *bleClientAdaptorConfiguration)

Check failure on line 7 in platforms/bleclient/ble_client_adaptor_options.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleClientAdaptorConfiguration
}

// bleClientAdaptorDebug is the type for applying the debug switch on or off.
type bleClientAdaptorDebugOption bool

// bleClientAdaptorScanTimeoutOption is the type for applying another timeout than the default 10 min.
type bleClientAdaptorScanTimeoutOption time.Duration

func (o bleClientAdaptorDebugOption) String() string {
return "debug option for BLE client adaptors"
}

func (o bleClientAdaptorScanTimeoutOption) String() string {
return "scan timeout option for BLE client adaptors"
}

func (o bleClientAdaptorDebugOption) apply(cfg *bleClientAdaptorConfiguration) {

Check failure on line 24 in platforms/bleclient/ble_client_adaptor_options.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleClientAdaptorConfiguration
cfg.debug = bool(o)
}

func (o bleClientAdaptorScanTimeoutOption) apply(cfg *bleClientAdaptorConfiguration) {

Check failure on line 28 in platforms/bleclient/ble_client_adaptor_options.go

View workflow job for this annotation

GitHub Actions / lint

undefined: bleClientAdaptorConfiguration
cfg.scanTimeout = time.Duration(o)
}
27 changes: 27 additions & 0 deletions platforms/bleclient/ble_client_adaptor_options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package bleclient

import (
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestWithClientAdaptorDebug(t *testing.T) {
// This is a general test, that options are applied by using the TestWithClientAdaptorDebug() option.
// All other configuration options can also be tested by With..(val).apply(cfg).
// arrange & act
a := NewAdaptor("address", WithClientAdaptorDebug())
// assert
assert.True(t, a.clientCfg.debug)
}

func TestWithClientAdaptorScanTimeout(t *testing.T) {
// arrange
newTimeout := 2 * time.Second
cfg := &bleClientAdaptorConfiguration{scanTimeout: 10 * time.Second}
// act
WithClientAdaptorScanTimeout(newTimeout).apply(cfg)
// assert
assert.Equal(t, newTimeout, cfg.scanTimeout)
}
Loading

0 comments on commit 59a2afa

Please sign in to comment.