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 Jan 29, 2024
1 parent 915d0c8 commit 5df431b
Show file tree
Hide file tree
Showing 6 changed files with 523 additions and 77 deletions.
2 changes: 1 addition & 1 deletion platforms/adaptors/pwmpinsadaptoroptions.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package adaptors

import "time"

// pwmPinOptionApplier needs to be implemented by each configurable option type
// PwmPinsOptionApplier needs to be implemented by each configurable option type
type PwmPinsOptionApplier interface {
apply(cfg *pwmPinsConfiguration)
}
Expand Down
191 changes: 118 additions & 73 deletions platforms/ble/ble_client_adaptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@ import (
"gobot.io/x/gobot/v2"
)

var (
currentAdapter *bluetooth.Adapter
bleMutex sync.Mutex
)

// BLEConnector is the interface that a BLE ClientAdaptor must implement
type BLEConnector interface {
gobot.Adaptor
Expand All @@ -30,107 +25,165 @@ type BLEConnector interface {
WithoutResponses(use bool)
}

type bleClientAdaptorConfiguration struct {
scanTimeout time.Duration
debug bool
}

// ClientAdaptor represents a Client Connection to a BLE Peripheral
type ClientAdaptor struct {
name string
address string
AdapterName string
name string
identifier string
clientCfg *bleClientAdaptorConfiguration

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
}

// NewClientAdaptor returns a new ClientAdaptor given an address
func NewClientAdaptor(address string) *ClientAdaptor {
return &ClientAdaptor{
name: gobot.DefaultName("BLEClient"),
address: address,
AdapterName: "default",
connected: false,
withoutResponses: false,
characteristics: make(map[string]bluetooth.DeviceCharacteristic),
// NewClientAdaptor returns a new ClientAdaptor given an identifier. The identifier can be the address or the name.
//
// Supported options:
//
// "WithClientAdaptorDebug"
// "WithClientAdaptorScanTimeout"
func NewClientAdaptor(identifier string, opts ...bleClientAdaptorOptionApplier) *ClientAdaptor {
cfg := bleClientAdaptorConfiguration{
scanTimeout: 10 * time.Minute,
}

b := ClientAdaptor{
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(b.clientCfg)
}

return &b
}

// WithClientAdaptorDebug switch on some debug messages.
func WithClientAdaptorDebug() bleClientAdaptorDebugOption {
return bleClientAdaptorDebugOption(true)
}

// WithClientAdaptorScanTimeout substitute the default scan timeout of 10 min.
func WithClientAdaptorScanTimeout(timeout time.Duration) bleClientAdaptorScanTimeoutOption {
return bleClientAdaptorScanTimeoutOption(timeout)
}

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

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

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

return b.identifier
}

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

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

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

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

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

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

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

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

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

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

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

if b.clientCfg.debug {
fmt.Println("[Connect]: get all services/characteristics...")
}
services, err := b.btDevice.DiscoverServices(nil)
if err != nil {
return err
}
for _, srvc := range srvcs {
chars, err := srvc.DiscoverCharacteristics(nil)
for _, service := range services {
if b.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 b.clientCfg.debug {
fmt.Printf("[Connect]: characteristic found: %s\n", char)
}
b.characteristics[char.UUID().String()] = char
}
}

if b.clientCfg.debug {
fmt.Println("[Connect]: connected")
}
b.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 (b *ClientAdaptor) Reconnect() error {
if b.connected {
if err := b.Disconnect(); err != nil {
Expand All @@ -140,10 +193,17 @@ func (b *ClientAdaptor) Reconnect() error {
return b.Connect()
}

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

Expand Down Expand Up @@ -211,18 +271,3 @@ func (b *ClientAdaptor) 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/ble/ble_client_adaptor_options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ble

import "time"

// bleClientAdaptorOptionApplier needs to be implemented by each configurable option type
type bleClientAdaptorOptionApplier interface {
apply(cfg *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) {
cfg.debug = bool(o)
}

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

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 := NewClientAdaptor("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 5df431b

Please sign in to comment.