Skip to content
Merged
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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,16 @@ func main() {
must("enable BLE stack", adapter.Enable())

ctx, cancel := context.WithCancel(context.Background())
adapter.SetConnectHandler(func(device bluetooth.Device, connected bool) {
if connected {
adapter.SetConnectionStateHandler(func(device bluetooth.Device, state bluetooth.ConnectionState) {
if state.Connected {
println("device connected:", device.Address.String())
return
}

println("device disconnected:", device.Address.String())
if state.Err != nil {
println("reason:", state.Err.Error())
}
cancel()
})

Expand Down
29 changes: 27 additions & 2 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,41 @@ type BLEAdapter interface {
Reset() error
Scan(callback func(*Adapter, ScanResult)) (err error)
SetConnectHandler(c func(device Device, connected bool))
SetConnectionStateHandler(c func(device Device, state ConnectionState))
StopScan() error
}

// SetConnectHandler sets a handler function to be called whenever the adapter connects
// ConnectionState is passed to the connect handler when a device connects or
// disconnects.
type ConnectionState struct {
// Connected is true when the device connected, and false when it disconnected.
Connected bool

// Err is why the device disconnected. It is nil when Connected is true,
// when this side ended the connection, or when the platform gives no reason.
Err error
}

// SetConnectionStateHandler sets a handler function to be called whenever the adapter connects
// or disconnects. You must call this before you call adapter.Connect() for centrals
// or advertisement.Start() for peripherals in order for it to work.
func (a *Adapter) SetConnectHandler(c func(device Device, connected bool)) {
func (a *Adapter) SetConnectionStateHandler(c func(device Device, state ConnectionState)) {
a.connectHandler = c
}

// SetConnectHandler sets a handler that only gets whether the device is connected.
//
// Deprecated: Use SetConnectionStateHandler, and run go fix to update callers.
//
//go:fix inline
func (a *Adapter) SetConnectHandler(c func(device Device, connected bool)) {
a.SetConnectionStateHandler(func(device Device, state ConnectionState) {
if c != nil {
c(device, state.Connected)
}
})
}

// DCSupplyStage selects a regulator stage. The two stages are in series,
// because REG0 supplies VDD from VDDH and VDD is the input to REG1.
// See nRF52840 Product Specification v1.11 section 5.4, Power management.
Expand Down
2 changes: 1 addition & 1 deletion adapter_cyw43439.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type Adapter struct {
var DefaultAdapter = &Adapter{
hciAdapter: hciAdapter{
isDefault: true,
connectHandler: func(device Device, connected bool) {
connectHandler: func(device Device, state ConnectionState) {
return
},
connectedDevices: make([]Device, 0, maxConnections),
Expand Down
6 changes: 3 additions & 3 deletions adapter_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type Adapter struct {
// used to allow multiple callers to call Connect concurrently.
connectMap sync.Map

connectHandler func(device Device, connected bool)
connectHandler func(device Device, state ConnectionState)
}

// DefaultAdapter is the default adapter on the system.
Expand All @@ -37,7 +37,7 @@ var DefaultAdapter = &Adapter{
pm: cbgo.NewPeripheralManager(nil),
connectMap: sync.Map{},

connectHandler: func(device Device, connected bool) {
connectHandler: func(device Device, state ConnectionState) {
return
},
}
Expand Down Expand Up @@ -167,7 +167,7 @@ func (cmd *centralManagerDelegate) DidDisconnectPeripheral(cmgr cbgo.CentralMana
addr := Address{}
uuid, _ := ParseUUID(id)
addr.UUID = uuid
cmd.a.connectHandler(Device{Address: addr}, false)
cmd.a.connectHandler(Device{Address: addr}, ConnectionState{Err: err})

// like with DidConnectPeripheral, check if we have a chan allocated for this and send through the peripheral
// this will only be true if the receiving side is still waiting for a connection to complete
Expand Down
2 changes: 1 addition & 1 deletion adapter_espradio.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type Adapter struct {
var DefaultAdapter = &Adapter{
hciAdapter: hciAdapter{
isDefault: true,
connectHandler: func(device Device, connected bool) {
connectHandler: func(device Device, state ConnectionState) {
return
},
connectedDevices: make([]Device, 0, maxConnections),
Expand Down
2 changes: 1 addition & 1 deletion adapter_hci.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type hciAdapter struct {
scanning bool
scanType ScanType

connectHandler func(device Device, connected bool)
connectHandler func(device Device, state ConnectionState)

connectedDevices []Device
notificationsStarted bool
Expand Down
2 changes: 1 addition & 1 deletion adapter_hci_uart.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ type Adapter struct {
var DefaultAdapter = &Adapter{
hciAdapter: hciAdapter{
isDefault: true,
connectHandler: func(device Device, connected bool) {
connectHandler: func(device Device, state ConnectionState) {
return
},
connectedDevices: make([]Device, 0, maxConnections),
Expand Down
4 changes: 2 additions & 2 deletions adapter_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ var errNotEnabled = errors.New("bluetooth: adapter is not enabled, call Enable f
// Adapter represents the WebBluetooth adapter accessed via navigator.bluetooth.
type Adapter struct {
bluetooth js.Value
connectHandler func(device Device, connected bool)
connectHandler func(device Device, state ConnectionState)

// devices holds the BluetoothDevice objects returned by Scan, keyed by
// device ID, because Connect needs them again.
Expand All @@ -39,7 +39,7 @@ type Adapter struct {
//
// Make sure to call Enable() before using it to initialize the adapter.
var DefaultAdapter = &Adapter{
connectHandler: func(device Device, connected bool) {},
connectHandler: func(device Device, state ConnectionState) {},
}

// Enable configures the BLE stack. It must be called before any
Expand Down
4 changes: 2 additions & 2 deletions adapter_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Adapter struct {
address string
defaultAdvertisement *Advertisement

connectHandler func(device Device, connected bool)
connectHandler func(device Device, state ConnectionState)
}

// NewAdapter creates a new Adapter with the given ID.
Expand All @@ -34,7 +34,7 @@ type Adapter struct {
func NewAdapter(id string) *Adapter {
return &Adapter{
id: id,
connectHandler: func(device Device, connected bool) {},
connectHandler: func(device Device, state ConnectionState) {},
}
}

Expand Down
2 changes: 1 addition & 1 deletion adapter_ninafw.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type Adapter struct {
var DefaultAdapter = &Adapter{
hciAdapter: hciAdapter{
isDefault: true,
connectHandler: func(device Device, connected bool) {
connectHandler: func(device Device, state ConnectionState) {
return
},
connectedDevices: make([]Device, 0, maxConnections),
Expand Down
5 changes: 3 additions & 2 deletions adapter_nrf51.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func handleEvent() {
Address: Address{makeMACAddress(connectEvent.peer_addr)},
connectionHandle: gapEvent.conn_handle,
}
DefaultAdapter.connectHandler(device, true)
DefaultAdapter.connectHandler(device, ConnectionState{Connected: true})
case C.BLE_GAP_EVT_DISCONNECTED:
if defaultAdvertisement.isAdvertising.Get() != 0 {
// The advertisement was running but was automatically stopped
Expand All @@ -63,7 +63,8 @@ func handleEvent() {
device := Device{
connectionHandle: gapEvent.conn_handle,
}
DefaultAdapter.connectHandler(device, false)
reason := gapEvent.params.unionfield_disconnected().reason
DefaultAdapter.connectHandler(device, ConnectionState{Err: disconnectError(uint8(reason))})
case C.BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
// Respond with the default PPCP connection parameters by passing
// nil:
Expand Down
7 changes: 4 additions & 3 deletions adapter_nrf528xx-full.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ func handleEvent() {
println("evt: connected in peripheral role")
}
currentConnection.handle.Reg = uint16(gapEvent.conn_handle)
DefaultAdapter.connectHandler(device, true)
DefaultAdapter.connectHandler(device, ConnectionState{Connected: true})
case C.BLE_GAP_ROLE_CENTRAL:
if debug {
println("evt: connected in central role")
}
connectionAttempt.connectionHandle = gapEvent.conn_handle
connectionAttempt.state.Set(2) // connection was successful
DefaultAdapter.connectHandler(device, true)
DefaultAdapter.connectHandler(device, ConnectionState{Connected: true})
default:
if debug {
println("evt: connected in unknown role")
Expand Down Expand Up @@ -74,7 +74,8 @@ func handleEvent() {
device := Device{
connectionHandle: gapEvent.conn_handle,
}
DefaultAdapter.connectHandler(device, false)
reason := gapEvent.params.unionfield_disconnected().reason
DefaultAdapter.connectHandler(device, ConnectionState{Err: disconnectError(uint8(reason))})
case C.BLE_GAP_EVT_CONN_PARAM_UPDATE:
if debug {
// Print connection parameters for easy debugging.
Expand Down
5 changes: 3 additions & 2 deletions adapter_nrf528xx-peripheral.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func handleEvent() {
Address: Address{makeMACAddress(connectEvent.peer_addr)},
connectionHandle: gapEvent.conn_handle,
}
DefaultAdapter.connectHandler(device, true)
DefaultAdapter.connectHandler(device, ConnectionState{Connected: true})
case C.BLE_GAP_EVT_DISCONNECTED:
if debug {
println("evt: disconnected, reason", gapEvent.params.unionfield_disconnected().reason)
Expand All @@ -54,7 +54,8 @@ func handleEvent() {
device := Device{
connectionHandle: gapEvent.conn_handle,
}
DefaultAdapter.connectHandler(device, false)
reason := gapEvent.params.unionfield_disconnected().reason
DefaultAdapter.connectHandler(device, ConnectionState{Err: disconnectError(uint8(reason))})
case C.BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
// We need to respond with sd_ble_gap_data_length_update. Setting
// both parameters to nil will make sure we send the default values.
Expand Down
4 changes: 2 additions & 2 deletions adapter_sd.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@ type Adapter struct {
scanning bool
charWriteHandlers []charWriteHandler

connectHandler func(device Device, connected bool)
connectHandler func(device Device, state ConnectionState)
}

// DefaultAdapter is the default adapter on the current system. On Nordic chips,
// it will return the SoftDevice interface.
//
// Make sure to call Enable() before using it to initialize the adapter.
var DefaultAdapter = &Adapter{isDefault: true,
connectHandler: func(device Device, connected bool) {
connectHandler: func(device Device, state ConnectionState) {
return
}}

Expand Down
22 changes: 22 additions & 0 deletions adapter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package bluetooth

import (
"reflect"
"testing"
)

func TestSetConnectHandler(t *testing.T) {
a := &Adapter{}
var got []bool
a.SetConnectHandler(func(d Device, connected bool) { got = append(got, connected) })

a.connectHandler(Device{}, ConnectionState{Connected: true})
a.connectHandler(Device{}, ConnectionState{Err: DisconnectTimeout})

if want := []bool{true, false}; !reflect.DeepEqual(got, want) {
t.Errorf("handler got %v, want %v", got, want)
}

a.SetConnectHandler(nil)
a.connectHandler(Device{}, ConnectionState{Connected: true})
}
4 changes: 2 additions & 2 deletions adapter_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var _ BLEAdapter = (*Adapter)(nil)
type Adapter struct {
watcher *advertisement.BluetoothLEAdvertisementWatcher

connectHandler func(device Device, connected bool)
connectHandler func(device Device, state ConnectionState)

defaultAdvertisement *Advertisement
}
Expand All @@ -28,7 +28,7 @@ type Adapter struct {
//
// Make sure to call Enable() before using it to initialize the adapter.
var DefaultAdapter = &Adapter{
connectHandler: func(device Device, connected bool) {
connectHandler: func(device Device, state ConnectionState) {
return
},
}
Expand Down
20 changes: 20 additions & 0 deletions ble.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,26 @@ type (
// AttributeProtocolError represents an ATT error code as defined in the
// Bluetooth Core Specification, Section 3.4.1.1 (ATT_ERROR_RSP), Table 3.4.
AttributeProtocolError = ble.AttributeProtocolError

// DisconnectReason is the HCI error code that Nordic and HCI adapters report when
// a device disconnects. See Bluetooth Core Specification v5.4, Vol 1, Part F, Table 1.1.
DisconnectReason = ble.DisconnectReason
)

// HCI error codes that end a connection, from Vol 1, Part F, Table 1.1.
const (
DisconnectAuthenticationFailure = ble.DisconnectAuthenticationFailure
DisconnectKeyMissing = ble.DisconnectKeyMissing
DisconnectTimeout = ble.DisconnectTimeout
DisconnectRemoteUser = ble.DisconnectRemoteUser
DisconnectRemoteLowResources = ble.DisconnectRemoteLowResources
DisconnectRemotePowerOff = ble.DisconnectRemotePowerOff
DisconnectUnsupportedRemoteFeature = ble.DisconnectUnsupportedRemoteFeature
DisconnectResponseTimeout = ble.DisconnectResponseTimeout
DisconnectInstantPassed = ble.DisconnectInstantPassed
DisconnectUnacceptableParameters = ble.DisconnectUnacceptableParameters
DisconnectMICFailure = ble.DisconnectMICFailure
DisconnectFailedToEstablish = ble.DisconnectFailedToEstablish
)

// ATT error codes from the Bluetooth Core Specification, Table 3.4.
Expand Down
54 changes: 54 additions & 0 deletions ble/disconnect.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package ble

import "encoding/hex"

// DisconnectReason is the HCI error code that Nordic and HCI adapters report when
// a device disconnects. See Bluetooth Core Specification v5.4, Vol 1, Part F, Table 1.1.
type DisconnectReason uint8

// HCI error codes that end a connection, from Vol 1, Part F, Table 1.1.
const (
DisconnectAuthenticationFailure DisconnectReason = 0x05
DisconnectKeyMissing DisconnectReason = 0x06
DisconnectTimeout DisconnectReason = 0x08
DisconnectRemoteUser DisconnectReason = 0x13
DisconnectRemoteLowResources DisconnectReason = 0x14
DisconnectRemotePowerOff DisconnectReason = 0x15
DisconnectUnsupportedRemoteFeature DisconnectReason = 0x1A
DisconnectResponseTimeout DisconnectReason = 0x22
DisconnectInstantPassed DisconnectReason = 0x28
DisconnectUnacceptableParameters DisconnectReason = 0x3B
DisconnectMICFailure DisconnectReason = 0x3D
DisconnectFailedToEstablish DisconnectReason = 0x3E

disconnectLocalHost DisconnectReason = 0x16
)

var disconnectReasonNames = map[DisconnectReason]string{
DisconnectAuthenticationFailure: "Authentication Failure",
DisconnectKeyMissing: "PIN or Key Missing",
DisconnectTimeout: "Connection Timeout",
DisconnectRemoteUser: "Remote User Terminated Connection",
DisconnectRemoteLowResources: "Remote Device Terminated Connection due to Low Resources",
DisconnectRemotePowerOff: "Remote Device Terminated Connection due to Power Off",
disconnectLocalHost: "Connection Terminated By Local Host",
DisconnectUnsupportedRemoteFeature: "Unsupported Remote Feature",
DisconnectResponseTimeout: "LL Response Timeout",
DisconnectInstantPassed: "Instant Passed",
DisconnectUnacceptableParameters: "Unacceptable Connection Parameters",
DisconnectMICFailure: "Connection Terminated due to MIC Failure",
DisconnectFailedToEstablish: "Connection Failed to be Established",
}

// Code returns the raw HCI error code.
func (r DisconnectReason) Code() uint8 {
return uint8(r)
}

func (r DisconnectReason) Error() string {
name, ok := disconnectReasonNames[r]
if !ok {
name = "Unknown"
}
return "HCI error 0x" + hex.EncodeToString([]byte{uint8(r)}) + " (" + name + ")"
}
19 changes: 19 additions & 0 deletions ble/disconnect_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package ble

import "testing"

func TestDisconnectReasonError(t *testing.T) {
tests := []struct {
reason DisconnectReason
want string
}{
{DisconnectTimeout, "HCI error 0x08 (Connection Timeout)"},
{DisconnectRemoteUser, "HCI error 0x13 (Remote User Terminated Connection)"},
{0x01, "HCI error 0x01 (Unknown)"},
}
for _, tt := range tests {
if got := tt.reason.Error(); got != tt.want {
t.Errorf("DisconnectReason(%#x).Error() = %q, want %q", tt.reason.Code(), got, tt.want)
}
}
}
Loading
Loading