2024-02-05 01:50:43 +08:00
|
|
|
package bleclient
|
2015-06-08 03:38:19 +08:00
|
|
|
|
|
|
|
import (
|
2020-10-25 17:17:11 +08:00
|
|
|
"fmt"
|
2016-03-03 14:00:05 +08:00
|
|
|
"log"
|
2017-01-24 20:36:16 +08:00
|
|
|
"sync"
|
2020-10-26 05:21:20 +08:00
|
|
|
"time"
|
2016-07-14 01:16:58 +08:00
|
|
|
|
2020-10-25 17:17:11 +08:00
|
|
|
"tinygo.org/x/bluetooth"
|
2023-11-16 03:51:52 +08:00
|
|
|
|
|
|
|
"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
|
|
|
|
}
|
2017-01-24 20:36:16 +08:00
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
// Adaptor represents a Client Connection to a BLE Peripheral
|
2024-02-05 01:50:43 +08:00
|
|
|
type Adaptor struct {
|
2024-02-12 00:01:24 +08:00
|
|
|
name string
|
|
|
|
identifier string
|
|
|
|
cfg *configuration
|
2016-12-29 00:53:41 +08:00
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
btAdpt *btAdapter
|
|
|
|
btDevice *btDevice
|
|
|
|
characteristics map[string]bluetoothExtCharacteristicer
|
2016-12-29 00:53:41 +08:00
|
|
|
|
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
|
|
|
|
}
|
2017-01-15 00:45:48 +08:00
|
|
|
|
|
|
|
// SetName sets the name for the adaptor
|
2024-02-05 01:50:43 +08:00
|
|
|
func (a *Adaptor) SetName(n string) { a.name = n }
|
2016-12-29 00:53:41 +08:00
|
|
|
|
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
|
|
|
|
2018-02-18 15:47:28 +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) {}
|
2017-06-08 19:41:59 +08:00
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
// Connect initiates a connection to the BLE peripheral.
|
2024-02-05 01:50:43 +08:00
|
|
|
func (a *Adaptor) Connect() error {
|
2024-02-12 00:01:24 +08:00
|
|
|
a.mutex.Lock()
|
|
|
|
defer a.mutex.Unlock()
|
2017-01-24 20:36:16 +08:00
|
|
|
|
2023-06-13 01:51:25 +08:00
|
|
|
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...")
|
|
|
|
}
|
2020-10-25 17:17:11 +08:00
|
|
|
|
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)
|
2020-10-25 17:17:11 +08:00
|
|
|
}
|
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)
|
2016-12-29 01:06:45 +08:00
|
|
|
if err != nil {
|
2020-10-25 17:17:11 +08:00
|
|
|
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())
|
2023-05-19 20:16:22 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-12-29 00:53:41 +08:00
|
|
|
}
|
2016-12-29 01:29:46 +08:00
|
|
|
|
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)
|
2023-06-13 01:51:25 +08:00
|
|
|
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)
|
2020-10-25 17:17:11 +08:00
|
|
|
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
|
2020-10-25 17:17:11 +08:00
|
|
|
}
|
2016-12-29 00:53:41 +08:00
|
|
|
}
|
2015-06-08 03:38:19 +08:00
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
if a.cfg.debug {
|
|
|
|
fmt.Println("[Connect]: connected")
|
|
|
|
}
|
2024-02-05 01:50:43 +08:00
|
|
|
a.connected = true
|
2023-06-13 01:51:25 +08:00
|
|
|
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.
|
2024-02-05 01:50:43 +08:00
|
|
|
func (a *Adaptor) Reconnect() error {
|
|
|
|
if a.connected {
|
|
|
|
if err := a.Disconnect(); err != nil {
|
2023-06-13 01:51:25 +08:00
|
|
|
return err
|
|
|
|
}
|
2015-06-08 03:38:19 +08:00
|
|
|
}
|
2024-02-05 01:50:43 +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.
|
2024-02-05 01:50:43 +08:00
|
|
|
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")
|
|
|
|
}
|
2023-06-13 01:51:25 +08:00
|
|
|
return err
|
2015-06-08 03:38:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Finalize finalizes the BLEAdaptor
|
2024-02-05 01:50:43 +08:00
|
|
|
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.
|
2024-02-05 01:50:43 +08:00
|
|
|
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
|
|
|
|
}
|
2015-06-30 06:25:59 +08:00
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
if chara, ok := a.characteristics[cUUID]; ok {
|
|
|
|
return readFromCharacteristic(chara)
|
2020-10-25 17:17:11 +08:00
|
|
|
}
|
|
|
|
|
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.
|
2024-02-05 01:50:43 +08:00
|
|
|
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")
|
2016-07-04 23:00:36 +08:00
|
|
|
}
|
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
cUUID, err := convertUUID(cUUID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-10-25 19:09:53 +08:00
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
if chara, ok := a.characteristics[cUUID]; ok {
|
|
|
|
return writeToCharacteristicWithoutResponse(chara, data)
|
2016-07-04 23:00:36 +08:00
|
|
|
}
|
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
return fmt.Errorf("unknown characteristic: %s", cUUID)
|
2016-07-04 23:00:36 +08:00
|
|
|
}
|
|
|
|
|
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 {
|
2024-02-05 01:50:43 +08:00
|
|
|
if !a.connected {
|
2024-02-12 00:01:24 +08:00
|
|
|
return fmt.Errorf("cannot subscribe to BLE device until connected")
|
2016-07-08 17:44:45 +08:00
|
|
|
}
|
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
cUUID, err := convertUUID(cUUID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2017-04-05 17:47:28 +08:00
|
|
|
}
|
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
if chara, ok := a.characteristics[cUUID]; ok {
|
|
|
|
return enableNotificationsForCharacteristic(chara, f)
|
2017-04-05 17:47:28 +08:00
|
|
|
}
|
|
|
|
|
2024-02-12 00:01:24 +08:00
|
|
|
return fmt.Errorf("unknown characteristic: %s", cUUID)
|
2016-03-03 14:00:05 +08:00
|
|
|
}
|