ble

package
v2.23.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: GPL-3.0 Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Zaparoo Core Copyright (c) 2026 The Zaparoo Project Contributors. SPDX-License-Identifier: GPL-3.0-or-later

This file is part of Zaparoo Core.

Zaparoo Core is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

Zaparoo Core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with Zaparoo Core. If not, see <http://www.gnu.org/licenses/>.

Package ble is a thin layer over the operating system's Bluetooth Low Energy stack. It exposes the two roles Core needs: a peripheral (GATT server plus advertising, used by the app transport) and a central (scan, connect, subscribe, used by reader drivers). Linux is served by BlueZ over D-Bus and Windows by the WinRT Bluetooth API; other platforms report ErrUnsupported.

Index

Constants

View Source
const (
	FlagRead                 = "read"
	FlagWrite                = "write"
	FlagWriteWithoutResponse = "write-without-response"
	FlagNotify               = "notify"
	// FlagEncryptRead is read over an encrypted link only. A phone that
	// reads it over a plain one pairs first and then retries the read.
	FlagEncryptRead = "encrypt-read"
)

Characteristic flags, as BlueZ names them.

View Source
const DefaultCallTimeout = 3 * time.Second

DefaultCallTimeout bounds a single D-Bus round trip.

Variables

View Source
var (
	// ErrUnsupported is returned on platforms without an implementation.
	ErrUnsupported = errors.New("bluetooth: not supported on this platform")
	// ErrUnavailable is returned when the system's Bluetooth service cannot
	// be reached: on Linux, the system bus or bluetoothd.
	ErrUnavailable = errors.New("bluetooth: system bluetooth service not reachable")
	// ErrNoAdapter is returned when the Bluetooth service is running but no
	// adapter is plugged in.
	ErrNoAdapter = errors.New("bluetooth: no bluetooth adapter")
	// ErrPoweredOff is returned when the adapter is switched off. Core
	// never switches one on unless asked to with WithPowerOn: the adapter
	// may be off on purpose, and it is shared with the device's gamepads.
	ErrPoweredOff = errors.New("bluetooth: adapter is powered off")
	// ErrRoleUnsupported is returned when the adapter cannot take the
	// requested role.
	ErrRoleUnsupported = errors.New("bluetooth: adapter does not support this role")
	// ErrNotFound is returned when a remote device, service, or
	// characteristic is not present.
	ErrNotFound = errors.New("bluetooth: not found")
)

Functions

func NormalizeAddress

func NormalizeAddress(address string) (string, error)

NormalizeAddress validates a Bluetooth address and returns it in the upper-case colon form BlueZ uses.

func SupportsRole

func SupportsRole(roles []Role, role Role) bool

SupportsRole reports whether roles allows role. An empty list means the adapter did not say, which callers treat as "try it".

Types

type Adapter

type Adapter interface {
	// Address is the controller's own Bluetooth address.
	Address() string
	// Roles lists what the controller supports; empty when BlueZ did not
	// report it.
	Roles() []Role
	// Peripheral returns the GATT server and advertising side.
	Peripheral() (Peripheral, error)
	// Central returns the scanning and connecting side.
	Central() (Central, error)
	// Gone is closed when the adapter disappears or the bus connection
	// drops, so owners can start over.
	Gone() <-chan struct{}
	// Close releases the bus connection. Everything obtained from the
	// adapter stops working.
	Close() error
}

Adapter is one local Bluetooth controller.

func Open

func Open(ctx context.Context, opts ...Option) (Adapter, error)

Open connects to bluetoothd on a private bus connection and selects an adapter: the lowest-numbered powered one, or the lowest-numbered one at all when none is powered. A powered-off choice is reported as ErrPoweredOff, or switched on with WithPowerOn.

type Advertisement struct {
	LocalName    string
	ServiceUUIDs []string
}

Advertisement describes what the peripheral broadcasts. It is always a connectable advertisement.

type Application

type Application struct {
	Services []Service
}

Application is the set of local services registered together.

type BondWindow

type BondWindow interface {
	// Keep marks a peer whose bond should survive Close: one that went on
	// to finish Core's pairing.
	Keep(peer Peer)
	// Close stops accepting bonds and removes the bonds made during the
	// window by peers that were not kept.
	Close(ctx context.Context) error
}

BondWindow is an open bonding window.

type Bonder

type Bonder interface {
	// AllowBonding makes the adapter accept bonding from peers that have
	// used Core's service, until the window is closed.
	AllowBonding(ctx context.Context) (BondWindow, error)
}

Bonder is implemented by peripherals that can let a phone bond while Core's own pairing is open.

type Central

type Central interface {
	// Scan reports the LE devices in range that match filter until ctx
	// ends or the adapter is gone, after which the channel is closed. A
	// consumer that falls behind loses the oldest updates, not the scan.
	Scan(ctx context.Context, filter ScanFilter) (<-chan ScanResult, error)
	// Find returns the device with the given address. One bluetoothd
	// already knows is returned at once, in range or not, and connecting
	// to it waits for it to advertise: bluetoothd does that with a scan
	// that only listens for that one device, which is slower to notice it
	// than a full scan but asks almost nothing of the controller. Only a
	// device bluetoothd has never seen is scanned for, until it is heard
	// or ctx ends.
	Find(ctx context.Context, address string) (Device, error)
}

Central is the scanning and connecting side of an adapter.

type Characteristic

type Characteristic struct {
	UUID  string
	Flags []string
}

Characteristic describes one characteristic of a local service.

type Device

type Device interface {
	Address() string
	// Connect connects and waits for service discovery to finish.
	Connect(ctx context.Context) error
	Disconnect(ctx context.Context) error
	// Characteristic looks up a characteristic of a resolved service.
	Characteristic(serviceUUID, charUUID string) (RemoteCharacteristic, error)
	// Disconnected is closed once the connection has ended.
	Disconnected() <-chan struct{}
}

Device is a remote peripheral.

type GoneCauser

type GoneCauser interface {
	// GoneCause returns why Gone was closed, wrapping one of this package's
	// errors where the reason is known. It is nil while the adapter is
	// still there, after an ordinary Close, and when nothing is known.
	GoneCause() error
}

GoneCauser is implemented by adapters that can open without a usable radio and only find that out when a role is used. On Windows that is every adapter, so its owner cannot tell a missing radio from a broken one by whether Open worked.

type KeyReloader

type KeyReloader interface {
	// ReloadLongTermKeys loads the stored keys and reports how many. It
	// sends nothing when there are none.
	ReloadLongTermKeys(ctx context.Context) (int, error)
}

KeyReloader is implemented by adapters that can hand the controller the LE long-term keys the system keeps on disk. On Linux that works around BlueZ 5.61 to 5.63, which can fail to load them at boot, leaving every bonded phone unable to reconnect.

type Option

type Option func(*options)

Option configures Open.

func WithBusAddress

func WithBusAddress(addr string) Option

WithBusAddress connects to the bus at addr instead of the system bus. Tests use it to point the layer at a private bus hosting a fake bluetoothd.

func WithCallTimeout

func WithCallTimeout(d time.Duration) Option

WithCallTimeout overrides DefaultCallTimeout.

func WithPowerOn

func WithPowerOn() Option

WithPowerOn powers the adapter on if it is off. Only a caller acting on an explicit user choice should ask for this; a background retry must not keep switching a radio back on that the user turned off.

type Peer

type Peer struct {
	// Path is the BlueZ Device1 object path, unique per connection.
	Path string
	// Address is the peer's Bluetooth address as BlueZ reports it, which
	// for phones is usually a rotating private address.
	Address string
}

Peer identifies a remote central connected to the local GATT server.

type Peripheral

type Peripheral interface {
	// Serve registers the application and advertisement, then blocks until
	// ctx ends or the adapter is gone. Both are unregistered on return.
	Serve(ctx context.Context, app Application, adv Advertisement, h PeripheralHandler) error
	// Notify sends value to peer on the characteristic. Where the stack
	// cannot address one peer (BlueZ), or peer is the zero value, it goes
	// to every subscriber, so callers tag the payload if they need the
	// others to ignore it.
	Notify(peer Peer, charUUID string, value []byte) error
	// Disconnect drops a peer's connection.
	Disconnect(ctx context.Context, peer Peer) error
	// SetAdvertising stops or resumes advertising without ending Serve or
	// any connection. It holds across Serve calls on this peripheral, so it
	// may be set before Serve starts. Advertising is on until it is
	// switched off.
	SetAdvertising(on bool)
}

Peripheral is the GATT server and advertising side of an adapter.

type PeripheralHandler

type PeripheralHandler interface {
	// OnWrite is called once per write to a characteristic. mtu is the
	// negotiated ATT MTU when BlueZ reports it, otherwise 0.
	OnWrite(peer Peer, charUUID string, value []byte, mtu int)
	// OnRead returns the value a peer reads from a characteristic.
	OnRead(peer Peer, charUUID string) ([]byte, error)
	// OnSubscribe reports notification subscriptions. BlueZ does not say
	// which peer subscribed, so peer is zero-valued.
	OnSubscribe(peer Peer, charUUID string, subscribed bool)
	// OnDisconnect is called when a peer's connection ends.
	OnDisconnect(peer Peer)
}

PeripheralHandler receives GATT server events. Calls for one peer may arrive out of order because BlueZ delivers each one on its own goroutine; consumers must tolerate that.

type RemoteCharacteristic

type RemoteCharacteristic interface {
	// Subscribe enables notifications and streams their values until ctx
	// ends or the device disconnects, after which the channel is closed.
	Subscribe(ctx context.Context) (<-chan []byte, error)
	// Read reads the characteristic's current value from the device.
	Read(ctx context.Context) ([]byte, error)
	// MTU is the ATT MTU negotiated for the link, or 0 when BlueZ does not
	// report it (versions before 5.62).
	MTU(ctx context.Context) (int, error)
	// Write writes the value, with or without waiting for the peripheral's
	// acknowledgement.
	Write(ctx context.Context, value []byte, withResponse bool) error
}

RemoteCharacteristic is one characteristic on a connected device.

type Role

type Role string

Role is a BLE link-layer role an adapter can take.

const (
	// RoleCentral scans and initiates connections.
	RoleCentral Role = "central"
	// RolePeripheral advertises and accepts connections.
	RolePeripheral Role = "peripheral"
)

type ScanFilter

type ScanFilter struct {
	// ServiceUUIDs keeps only devices advertising at least one of these.
	ServiceUUIDs []string
}

ScanFilter narrows a scan. The zero value reports every LE device.

type ScanResult

type ScanResult struct {
	// ManufacturerData is keyed by Bluetooth company identifier.
	ManufacturerData map[uint16][]byte
	// ServiceData is keyed by service UUID.
	ServiceData  map[string][]byte
	Address      string
	Name         string
	ServiceUUIDs []string
	// RSSI is the last signal strength in dBm, valid when HasRSSI. A
	// device BlueZ only remembers from an earlier scan has none.
	RSSI    int16
	HasRSSI bool
}

ScanResult is what is known about one remote device while scanning. A device is reported when it is first heard and again when bluetoothd learns something new about it; repeats of the same advertisement are not reported, so RSSI is a first reading, not a running one.

type Service

type Service struct {
	UUID            string
	Characteristics []Characteristic
	// Handle, when not zero, asks the stack to place the service at this
	// ATT handle. A phone caches a bonded device's handles and is told
	// only where the new ones are when they move, so it keeps reading the
	// old ones. BlueZ otherwise places a service after every one it has
	// held since it started, which moves it on every restart.
	Handle  uint16
	Primary bool
}

Service describes one local GATT service.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL