Skip to content

feat: add SetConnectionStateHandler with a disconnect reason - #518

Merged
deadprogram merged 3 commits into
devfrom
connection-state
Oct 27, 2026
Merged

deadprogram merged 3 commits into
devfrom
connection-state

Conversation

@acouvreur

@acouvreur acouvreur commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Replaces #444. It follows the suggestion on #443 to pass a struct instead of a new argument.

This adds SetConnectionStateHandler, whose handler gets a ConnectionState instead of a bool.

type ConnectionState struct {
	Connected bool
	Err       error
}

SetConnectHandler keeps its signature, so existing programs still build. It is deprecated and marked //go:fix inline, so go fix ./... rewrites callers to the new method. The rewrite needs Go 1.26 or later, where go fix runs the inline analyzer. Older Go versions still build the code but do not rewrite it.

// before
adapter.SetConnectHandler(onConnect)

// after go fix
adapter.SetConnectionStateHandler(func(device bluetooth.Device, state bluetooth.ConnectionState) {
	if onConnect != nil {
		onConnect(device, state.Connected)
	}
})

The nil check keeps SetConnectHandler(nil) a no-op, which some programs use to clear the handler.

BLEAdapter gets SetConnectionStateHandler and keeps SetConnectHandler.

Err says why the device disconnected. It is nil when the device connected, when this side ended the connection, or when the platform gives no reason.

Platform Err on disconnect
nRF SoftDevice DisconnectReason, the HCI code of BLE_GAP_EVT_DISCONNECTED
HCI (NINA, CYW43439, HCI UART, ESP32) DisconnectReason, from the Disconnection Complete event
macOS the CoreBluetooth error of didDisconnectPeripheral
Windows, Linux, Web Bluetooth nil, the platform gives no reason

A caller can check the code with errors.As.

var reason bluetooth.DisconnectReason
if errors.As(state.Err, &reason) && reason == bluetooth.DisconnectTimeout {
	// reconnect
}

Why this shape

  1. A struct can get new fields later without another breaking change. Go does this for hook arguments in net/http/httptrace, for example DNSDoneInfo and WroteRequestInfo. grpc passes SubConnState to its state listener, with the state and a ConnectionError that is nil unless the connection failed.
  2. The device stays its own argument, like http.Server.ConnState func(net.Conn, ConnState), Android onConnectionStateChange(gatt, status, newState) and Nordic's onDeviceDisconnected(device, reason).
  3. Err is nil when this side ended the connection, as in CoreBluetooth didDisconnectPeripheral. So state.Err != nil means the same on every platform. Nordic and HCI report reason 0x16 in that case, which becomes nil.
  4. A typed reason lets a caller tell a timeout from a remote disconnect, like Nordic's REASON_TIMEOUT and REASON_TERMINATE_PEER_USER, or Kable's State.Disconnected(status). DisconnectReason follows AttributeProtocolError. It lives in ble/ with an alias in the root package, and has the codes from Core Specification v5.4, Vol 1, Part F, Table 1.1.
  5. A new method instead of a new signature keeps existing programs building, and //go:fix inline lets go fix move them over.

Next steps

On Linux, BlueZ 5.83 added a Disconnected(reason, message) signal to org.bluez.Device1 (bluez@8b08f90). A follow-up can use it when it is there.

Tests

Check Result
go test and go vet on Windows pass
go vet and the changed examples for Linux and js/wasm pass
tinygo builds for pca10040-s132v6, pca10056-s140v7, microbit-v2-s113v7, microbit-s110v8, circuitplay-bluefruit, nano-rp2040, badger2040-w, xiao-esp32c3 pass
go fix on a program that calls SetConnectHandler with a func literal, a named func, a variable and nil rewritten, builds
Windows 11 with a real peripheral the handler gets Connected: true with a nil Err

How to verify

The reason path is not tested on hardware yet.

On nRF52

  1. Flash the advertisement example, for example tinygo flash -target=pca10056-s140v7 -monitor ./examples/advertisement.
  2. Connect from a phone with nRF Connect, then disconnect from the phone. Expect reason: HCI error 0x13 (Remote User Terminated Connection).
  3. Connect again and take the phone out of range. Expect reason: HCI error 0x08 (Connection Timeout).

On macOS, connect to a peripheral from a program with a connection state handler, then power off the peripheral. Expect a non-nil Err. Call Disconnect instead and expect a nil Err.

@acouvreur
acouvreur requested review from deadprogram and removed request for deadprogram October 17, 2026 20:13
@acouvreur
acouvreur marked this pull request as ready for review October 17, 2026 20:31
@acouvreur
acouvreur requested a review from deadprogram October 17, 2026 20:31
@deadprogram deadprogram added this to the 0.18.0 milestone Oct 27, 2026
SetConnectionStateHandler takes a handler that gets a ConnectionState. It
holds whether the device is connected and, when it disconnected, the reason.

Nordic and HCI adapters report the HCI reason code as a DisconnectReason.
macOS passes the CoreBluetooth error. The reason is nil when this side
ended the connection, and on Windows, Linux and the web, which give none.

SetConnectHandler keeps its signature and is deprecated, so existing
programs still build. go fix rewrites its callers, and a nil handler
stays a no-op.
@acouvreur acouvreur changed the title feat!: pass a ConnectionState to the connect handler feat: add SetConnectionStateHandler with a disconnect reason Oct 27, 2026
@deadprogram

Copy link
Copy Markdown
Member

Thanks, this looks good.

  1. Please add SetConnectionStateHandler to the BLEAdapter interface in adapter.go. Keep SetConnectHandler there too.
  2. AttributeProtocolError is in ble/ with an alias in the root package. Can DisconnectReason follow the same pattern?
  3. Please note in the description that the go fix rewrite needs Go 1.26.

DisconnectReason and its codes now live in ble with aliases in the root
package, like AttributeProtocolError.

@deadprogram deadprogram left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking good now @acouvreur thanks for keeping backwards compat now squash/merging.

@deadprogram
deadprogram merged commit 59f1b88 into dev Oct 27, 2026
6 checks passed
@deadprogram
deadprogram deleted the connection-state branch October 27, 2026 21:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants