hybridgroup.gobot/platforms/bleclient/ble_client_adaptor.go

260 lines
6.4 KiB
Go
Raw Permalink Normal View History

package bleclient
2015-06-08 03:38:19 +08:00
import (
"fmt"
2016-03-03 14:00:05 +08:00
"log"
"sync"
"time"
"tinygo.org/x/bluetooth"
"gobot.io/x/gobot/v2"
2015-06-08 03:38:19 +08:00
)
2024-02-12 00:01:24 +08:00
type configuration struct {
scanTimeout time.Duration
sleepAfterDisconnect time.Duration
debug bool
}
2024-02-12 00:01:24 +08:00
// Adaptor represents a Client Connection to a BLE Peripheral
type Adaptor struct {
2024-02-12 00:01:24 +08:00
name string
identifier string
cfg *configuration
2024-02-12 00:01:24 +08:00
btAdpt *btAdapter
btDevice *btDevice
characteristics map[string]bluetoothExtCharacteristicer
2024-02-12 00:01:24 +08:00
connected bool
rssi int
btAdptCreator btAdptCreatorFunc
mutex *sync.Mutex
2015-06-08 03:38:19 +08:00
}
2024-02-12 00:01:24 +08:00
// 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 ...optionApplier) *Adaptor {
cfg := configuration{
scanTimeout: 10 * time.Minute,
sleepAfterDisconnect: 500 * time.Millisecond,
}
a := Adaptor{
name: gobot.DefaultName("BLEClient"),
identifier: identifier,
cfg: &cfg,
characteristics: make(map[string]bluetoothExtCharacteristicer),
btAdptCreator: newBtAdapter,
mutex: &sync.Mutex{},
}
for _, o := range opts {
o.apply(a.cfg)
2015-06-08 03:38:19 +08:00
}
2024-02-12 00:01:24 +08:00
return &a
}
// WithDebug switch on some debug messages.
func WithDebug() debugOption {
return debugOption(true)
2015-06-08 03:38:19 +08:00
}
2024-02-12 00:01:24 +08:00
// WithScanTimeout substitute the default scan timeout of 10 min.
func WithScanTimeout(timeout time.Duration) scanTimeoutOption {
return scanTimeoutOption(timeout)
}
// 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 }
2024-02-12 00:01:24 +08:00
// 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 }
2015-06-08 03:38:19 +08:00
// WithoutResponses sets if the adaptor should expect responses after
2024-02-12 00:01:24 +08:00
// writing characteristics for this device (has no effect at the moment).
func (a *Adaptor) WithoutResponses(bool) {}
2024-02-12 00:01:24 +08:00
// Connect initiates a connection to the BLE peripheral.
func (a *Adaptor) Connect() error {
2024-02-12 00:01:24 +08:00
a.mutex.Lock()
defer a.mutex.Unlock()
var err error
2015-06-08 03:38:19 +08:00
2024-02-12 00:01:24 +08:00
if a.cfg.debug {
fmt.Println("[Connect]: enable adaptor...")
}
2024-02-12 00:01:24 +08:00
// for re-connect, the adapter is already known
if a.btAdpt == nil {
a.btAdpt = a.btAdptCreator(bluetooth.DefaultAdapter, a.cfg.debug)
if err := a.btAdpt.enable(); err != nil {
return fmt.Errorf("can't get adapter default: %w", err)
}
2024-02-12 00:01:24 +08:00
}
if a.cfg.debug {
fmt.Printf("[Connect]: scan %s for the identifier '%s'...\n", a.cfg.scanTimeout, a.identifier)
}
2015-06-08 03:38:19 +08:00
2024-02-12 00:01:24 +08:00
result, err := a.btAdpt.scan(a.identifier, a.cfg.scanTimeout)
if err != nil {
return err
}
2024-02-12 00:01:24 +08:00
if a.cfg.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
}
2024-02-12 00:01:24 +08:00
a.rssi = int(result.RSSI)
a.btDevice = dev
if a.cfg.debug {
fmt.Println("[Connect]: get all services/characteristics...")
}
services, err := a.btDevice.discoverServices(nil)
if err != nil {
return err
}
2024-02-12 00:01:24 +08:00
for _, service := range services {
if a.cfg.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 {
2024-02-12 00:01:24 +08:00
if a.cfg.debug {
fmt.Printf("[Connect]: characteristic found: %s\n", char)
}
c := char // to prevent implicit memory aliasing in for loop, before go 1.22
a.characteristics[char.UUID().String()] = &c
}
}
2015-06-08 03:38:19 +08:00
2024-02-12 00:01:24 +08:00
if a.cfg.debug {
fmt.Println("[Connect]: connected")
}
a.connected = true
return nil
2015-06-08 03:38:19 +08:00
}
// 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.
func (a *Adaptor) Reconnect() error {
if a.connected {
if err := a.Disconnect(); err != nil {
return err
}
2015-06-08 03:38:19 +08:00
}
return a.Connect()
2015-06-08 03:38:19 +08:00
}
2024-02-12 00:01:24 +08:00
// Disconnect terminates the connection to the BLE peripheral.
func (a *Adaptor) Disconnect() error {
2024-02-12 00:01:24 +08:00
if a.cfg.debug {
fmt.Println("[Disconnect]: disconnect...")
}
err := a.btDevice.disconnect()
time.Sleep(a.cfg.sleepAfterDisconnect)
a.connected = false
if a.cfg.debug {
fmt.Println("[Disconnect]: disconnected")
}
return err
2015-06-08 03:38:19 +08:00
}
// Finalize finalizes the BLEAdaptor
func (a *Adaptor) Finalize() error {
return a.Disconnect()
2015-06-08 03:38:19 +08:00
}
2024-02-12 00:01:24 +08:00
// ReadCharacteristic returns bytes from the BLE device for the requested characteristic UUID.
// The UUID can be given as 16-bit or 128-bit (with or without dashes) value.
func (a *Adaptor) ReadCharacteristic(cUUID string) ([]byte, error) {
if !a.connected {
2024-02-12 00:01:24 +08:00
return nil, fmt.Errorf("cannot read from BLE device until connected")
2015-06-30 00:47:18 +08:00
}
2015-06-08 03:38:19 +08:00
2024-02-12 00:01:24 +08:00
cUUID, err := convertUUID(cUUID)
if err != nil {
return nil, err
}
2024-02-12 00:01:24 +08:00
if chara, ok := a.characteristics[cUUID]; ok {
return readFromCharacteristic(chara)
}
2024-02-12 00:01:24 +08:00
return nil, fmt.Errorf("unknown characteristic: %s", cUUID)
2015-06-08 03:38:19 +08:00
}
2024-02-12 00:01:24 +08:00
// WriteCharacteristic writes bytes to the BLE device for the requested characteristic UUID.
// The UUID can be given as 16-bit or 128-bit (with or without dashes) value.
func (a *Adaptor) WriteCharacteristic(cUUID string, data []byte) error {
if !a.connected {
2024-02-12 00:01:24 +08:00
return fmt.Errorf("cannot write to BLE device until connected")
}
2024-02-12 00:01:24 +08:00
cUUID, err := convertUUID(cUUID)
if err != nil {
return err
}
2024-02-12 00:01:24 +08:00
if chara, ok := a.characteristics[cUUID]; ok {
return writeToCharacteristicWithoutResponse(chara, data)
}
2024-02-12 00:01:24 +08:00
return fmt.Errorf("unknown characteristic: %s", cUUID)
}
2024-02-12 00:01:24 +08:00
// Subscribe subscribes to notifications from the BLE device for the requested characteristic UUID.
// The UUID can be given as 16-bit or 128-bit (with or without dashes) value.
func (a *Adaptor) Subscribe(cUUID string, f func(data []byte)) error {
if !a.connected {
2024-02-12 00:01:24 +08:00
return fmt.Errorf("cannot subscribe to BLE device until connected")
}
2024-02-12 00:01:24 +08:00
cUUID, err := convertUUID(cUUID)
if err != nil {
return err
}
2024-02-12 00:01:24 +08:00
if chara, ok := a.characteristics[cUUID]; ok {
return enableNotificationsForCharacteristic(chara, f)
}
2024-02-12 00:01:24 +08:00
return fmt.Errorf("unknown characteristic: %s", cUUID)
2016-03-03 14:00:05 +08:00
}