bluetooth

package module
v0.0.0-...-f91f73e Latest Latest
Warning

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

Go to latest
Published: May 31, 2020 License: BSD-3-Clause Imports: 6 Imported by: 0

README

Go Bluetooth

CircleCI GoDoc

This package attempts to build a cross-platform Bluetooth Low Energy module for Go. It currently supports the following systems:

Windows Linux Nordic chips
Scanning
Advertisement
Local services
Local characteristics

Baremetal support

As you can see above, there is support for some chips from Nordic Semiconductors. At the moment the following chips are supported:

  • The nRF52832 with the S132 SoftDevice (version 6).
  • The nRF52840 with the S140 SoftDevice (version 7).
  • The nRF51822 with the S110 SoftDevice (version 8). This SoftDevice does not support all features (e.g. scanning).

These chips are supported through TinyGo.

The SoftDevice is a binary blob that implements the BLE stack. There are other (open source) BLE stacks, but the SoftDevices are pretty solid and have all the qualifications you might need. Other BLE stacks might be added in the future.

Flashing the SoftDevice

Flashing the SoftDevice can be tricky. If you have nrfjprog installed, you can erase the flash and flash the new BLE firmware using the following commands. Replace the path to the hex file with the correct SoftDevice, for example s132_nrf52_6.1.1/s132_nrf52_6.1.1_softdevice.hex for S132 version 6.

nrfjprog -f nrf52 --eraseall
nrfjprog -f nrf52 --program path/to/softdevice.hex

After that, don't reset the board but instead flash a new program to it. For example, you can flash the Heart Rate Sensor example using tinygo (modify the -target flag as needed for your board):

tinygo flash -target=pca10040-s132v6 ./examples/heartrate

Flashing will normally reset the board.

For boards that use the CMSIS-DAP interface (such as the BBC micro:bit), this works a bit different. Flashing the SoftDevice is done by simply copying the .hex file to the device, for example (on Linux):

cp path/to/softdevice.hex /media/yourusername/MICROBIT/

Flashing will then need to be done a bit differently, using the CMSIS-DAP interface instead of the mass-storage interface normally used by TinyGo:

tinygo flash -target=microbit-s110v8 -programmer=cmsis-dap ./examples/heartrate

License

This project is licensed under the BSD 3-clause license, see the LICENSE file for details.

The SoftDevices from Nordic are licensed under a different license, check the license file in the SoftDevice source directory.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMalformedAdvertisement = errors.New("bluetooth: malformed advertisement packet")
)

Functions

This section is empty.

Types

type Adapter

type Adapter struct {
	// contains filtered or unexported fields
}

func DefaultAdapter

func DefaultAdapter() (*Adapter, error)

DefaultAdapter returns the default adapter on the current system. On Linux, it will return the first adapter available.

func (*Adapter) AddService

func (a *Adapter) AddService(s *Service) error

AddService creates a new service with the characteristics listed in the Service struct.

TODO: add support for characteristics on Linux.

func (*Adapter) Enable

func (a *Adapter) Enable() error

Enable configures the BLE stack. It must be called before any Bluetooth-related calls (unless otherwise indicated).

The Linux implementation is a no-op.

func (*Adapter) NewAdvertisement

func (a *Adapter) NewAdvertisement() *Advertisement

NewAdvertisement creates a new advertisement instance but does not configure it.

func (*Adapter) Scan

func (a *Adapter) Scan(callback func(*Adapter, ScanResult)) error

Scan starts a BLE scan. It is stopped by a call to StopScan. A common pattern is to cancel the scan when a particular device has been found.

On Linux with BlueZ, incoming packets cannot be observed directly. Instead, existing devices are watched for property changes. This closely simulates the behavior as if the actual packets were observed, but it has flaws: it is possible some events are missed and perhaps even possible that some events are duplicated.

func (*Adapter) SetEventHandler

func (a *Adapter) SetEventHandler(handler func(Event))

SetEventHandler sets the callback that gets called on incoming events.

Warning: must only be called when the Bluetooth stack has not yet been initialized!

func (*Adapter) StopScan

func (a *Adapter) StopScan() error

StopScan stops any in-progress scan. It can be called from within a Scan callback to stop the current scan. If no scan is in progress, an error will be returned.

type AdvertiseInterval

type AdvertiseInterval uint32

AdvertiseInterval is the advertisement interval in 0.625µs units.

func NewAdvertiseInterval

func NewAdvertiseInterval(intervalMillis uint32) AdvertiseInterval

NewAdvertiseInterval returns a new advertisement interval, based on an interval in milliseconds.

type AdvertiseOptions

type AdvertiseOptions struct {
	Interval AdvertiseInterval
}

AdvertiseOptions configures everything related to BLE advertisements.

type Advertisement struct {
	// contains filtered or unexported fields
}

Advertisement encapsulates a single advertisement instance.

func (*Advertisement) Configure

func (a *Advertisement) Configure(broadcastData, scanResponseData []byte, options *AdvertiseOptions) error

Configure this advertisement.

func (*Advertisement) Start

func (a *Advertisement) Start() error

Start advertisement. May only be called after it has been configured.

type AdvertisementFields

type AdvertisementFields struct {
	// The LocalName part of the advertisement (either the complete local name
	// or the shortened local name).
	LocalName string
}

AdvertisementFields contains advertisement fields in structured form.

type AdvertisementPayload

type AdvertisementPayload interface {
	// LocalName is the (complete or shortened) local name of the device.
	// Please note that many devices do not broadcast a local name, but may
	// broadcast other data (e.g. manufacturer data or service UUIDs) with which
	// they may be identified.
	LocalName() string

	// Bytes returns the raw advertisement packet, if available. It returns nil
	// if this data is not available.
	Bytes() []byte
}

AdvertisementPayload contains information obtained during a scan (see ScanResult). It is provided as an interface as there are two possible implementations: an implementation that works with raw data (usually on low-level BLE stacks) and an implementation that works with structured data.

type Characteristic

type Characteristic struct {
	// contains filtered or unexported fields
}

Characteristic is a single characteristic in a service. It has an UUID and a value.

func (*Characteristic) Handle

func (c *Characteristic) Handle() uint16

Handle returns the numeric handle for this characteristic. This is used internally in the Bluetooth stack to identify this characteristic.

type CharacteristicConfig

type CharacteristicConfig struct {
	Handle *Characteristic
	UUID
	Value      []byte
	Flags      CharacteristicPermissions
	WriteEvent func(client Connection, offset int, value []byte)
}

CharacteristicConfig contains some parameters for the configuration of a single characteristic.

The Handle field may be nil. If it is set, it points to a characteristic handle that can be used to access the characteristic at a later time.

type CharacteristicPermissions

type CharacteristicPermissions uint8

CharacteristicPermissions lists a number of basic permissions/capabilities that clients have regarding this characteristic. For example, if you want to allow clients to read the value of this characteristic (a common scenario), set the Read permission.

const (
	CharacteristicBroadcastPermission CharacteristicPermissions = 1 << iota
	CharacteristicReadPermission
	CharacteristicWriteWithoutResponsePermission
	CharacteristicWritePermission
	CharacteristicNotifyPermission
	CharacteristicIndicatePermission
)

Characteristic permission bitfields.

func (CharacteristicPermissions) Broadcast

func (p CharacteristicPermissions) Broadcast() bool

Broadcast returns whether broadcasting of the value is permitted.

func (CharacteristicPermissions) Read

Read returns whether reading of the value is permitted.

func (CharacteristicPermissions) Write

func (p CharacteristicPermissions) Write() bool

Write returns whether writing of the value with Write Request is permitted.

func (CharacteristicPermissions) WriteWithoutResponse

func (p CharacteristicPermissions) WriteWithoutResponse() bool

WriteWithoutResponse returns whether writing of the value with Write Command is permitted.

type ConnectEvent

type ConnectEvent struct {
	GAPEvent
}

ConnectEvent occurs when a remote device connects to this device.

type Connection

type Connection uint16

Connection is a numeric identifier that indicates a connection handle.

type DisconnectEvent

type DisconnectEvent struct {
	GAPEvent
}

DisconnectEvent occurs when a remote device disconnects from this device.

type Event

type Event interface{}

Event is a global Bluetooth stack event.

type GAPEvent

type GAPEvent struct {
	Connection Connection
}

GAPEvent is a base (embeddable) event for all GAP events.

type MAC

type MAC [6]byte

MAC represents a MAC address, in little endian format.

func ParseMAC

func ParseMAC(s string) (mac MAC, err error)

ParseMAC parses the given MAC address, which must be in 11:22:33:AA:BB:CC format. If it cannot be parsed, an error is returned.

func (MAC) String

func (mac MAC) String() string

String returns a human-readable version of this MAC address, such as 11:22:33:AA:BB:CC.

type ScanResult

type ScanResult struct {
	// MAC address of the scanned device.
	Address MAC

	// RSSI the last time a packet from this device has been received.
	RSSI int16

	// The data obtained from the advertisement data, which may contain many
	// different properties.
	// Warning: this data may only stay valid until the next event arrives. If
	// you need any of the fields to stay alive until after the callback
	// returns, copy them.
	AdvertisementPayload
}

ScanResult contains information from when an advertisement packet was received. It is passed as a parameter to the callback of the Scan method.

type Service

type Service struct {
	UUID
	Characteristics []CharacteristicConfig
	// contains filtered or unexported fields
}

Service is a GATT service to be used in AddService.

type UUID

type UUID [4]uint32

UUID is a single UUID as used in the Bluetooth stack. It is represented as a [4]uint32 instead of a [16]byte for efficiency.

func New16BitUUID

func New16BitUUID(shortUUID uint16) UUID

New16BitUUID returns a new 128-bit UUID based on a 16-bit UUID.

Note: only use registered UUIDs. See https://www.bluetooth.com/specifications/gatt/services/ for a list.

func NewUUID

func NewUUID(uuid [16]byte) UUID

NewUUID returns a new UUID based on the 128-bit (or 16-byte) input.

func (UUID) Bytes

func (uuid UUID) Bytes() [16]byte

Bytes returns a 16-byte array containing the raw UUID.

func (UUID) Is16Bit

func (uuid UUID) Is16Bit() bool

Is16Bit returns whether this UUID is a 16-bit BLE UUID.

func (UUID) Is32Bit

func (uuid UUID) Is32Bit() bool

Is32Bit returns whether this UUID is a 32-bit BLE UUID.

func (UUID) Replace16BitComponent

func (uuid UUID) Replace16BitComponent(component uint16) UUID

Replace16BitComponent returns a new UUID where bits 16..32 have been replaced with the bits given in the argument. These bits are the same bits that vary in the 16-bit compressed UUID form.

This is especially useful for the Nordic SoftDevice, because it is able to store custom UUIDs more efficiently when only these bits vary between them.

func (UUID) String

func (uuid UUID) String() string

String returns a human-readable version of this UUID, such as 00001234-0000-1000-8000-00805F9B34FB.

Directories

Path Synopsis
examples
advertisement command
heartrate command
ledcolor command
scanner command
Package winbt provides a thin layer over the WinRT Bluetooth interfaces.
Package winbt provides a thin layer over the WinRT Bluetooth interfaces.

Jump to

Keyboard shortcuts

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