gatt

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

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

Go to latest
Published: Oct 6, 2016 License: BSD-3-Clause Imports: 12 Imported by: 23

README

Package gatt provides a Bluetooth Low Energy GATT implementation.

Gatt (Generic Attribute Profile) is the protocol used to write BLE peripherals (servers) and centrals (clients).

As a peripheral, you can create services, characteristics, and descriptors, advertise, accept connections, and handle requests.

As a central, you can scan, connect, discover services, and make requests.

SETUP

gatt supports both Linux and OS X.
On Linux:

To gain complete and exclusive control of the HCI device, gatt uses HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW. Those who must use an older kernel may patch in these relevant commits from Marcel Holtmann:

Bluetooth: Introduce new HCI socket channel for user operation
Bluetooth: Introduce user channel flag for HCI devices
Bluetooth: Refactor raw socket filter into more readable code

Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the device no other program may access it.

Before starting a gatt program, make sure that your BLE device is down:

sudo hciconfig
sudo hciconfig hci0 down  # or whatever hci device you want to use

If you have BlueZ 5.14+ (or aren't sure), stop the built-in bluetooth server, which interferes with gatt, e.g.:

sudo service bluetooth stop

Because gatt programs administer network devices, they must either be run as root, or be granted appropriate capabilities:

sudo <executable>
# OR
sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
<executable>

Usage

Please see godoc.org for documentation.

Examples

Build and run the examples on a native environment (Linux or OS X)

Go is a compiled language, which means to run the examples you need to build them first.

# Build the sample server.
go build examples/server.go
# Start the sample server.
sudo ./server

Alternatively, you can use "go run" to build and run the examples in a single step:

# Build and run the sample server.
sudo go run examples/server.go

Discoverer and explorer demonstrates central (client) functions:

# Discover surrounding peripherals.
sudo go run examples/discoverer.go

# Connect to and explorer a peripheral device.
sudo go run examples/explorer.go <peripheral ID>
Cross-compile and deploy to a target device
# Build and run the server example on a ARMv5 target device.
GOARCH=arm GOARM=5 GOOS=linux go build examples/server.go
cp server <target device>
# Start the server on the target device
sudo ./server

See the server.go, discoverer.go, and explorer.go in the examples/ directory for writing server or client programs that run on Linux and OS X.

Users, especially on Linux platforms, seeking finer-grained control over the devices can see the examples/server_lnx.go for the usage of Option, which are platform specific.

See the rest of the docs for other options and finer-grained control.

Note

Note that some BLE central devices, particularly iOS, may aggressively cache results from previous connections. If you change your services or characteristics, you may need to reboot the other device to pick up the changes. This is a common source of confusion and apparent bugs. For an OS X central, see http://stackoverflow.com/questions/20553957.

Known Issues

Currently OS X vesion does not support subscribing to indications. Please check #32 for the status of this issue.

REFERENCES

gatt started life as a port of bleno, to which it is indebted: https://github.com/sandeepmistry/bleno. If you are having problems with gatt, particularly around installation, issues filed with bleno might also be helpful references.

To try out your GATT server, it is useful to experiment with a generic BLE client. LightBlue is a good choice. It is available free for both iOS and OS X.

gatt is similar to bleno and noble, which offer BLE GATT implementations for node.js.

Gatt is released under a BSD-style license.

Documentation

Overview

Package gatt provides a Bluetooth Low Energy gatt implementation.

Gatt (Generic Attribute Profile) is the protocol used to write BLE peripherals (servers) and centrals (clients).

STATUS

This package is a work in progress. The API will change.

As a peripheral, you can create services, characteristics, and descriptors, advertise, accept connections, and handle requests. As a central, you can scan, connect, discover services, and make requests.

SETUP

gatt supports both Linux and OS X.

On Linux: To gain complete and exclusive control of the HCI device, gatt uses HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW. Those who must use an older kernel may patch in these relevant commits from Marcel Holtmann:

Bluetooth: Introduce new HCI socket channel for user operation
Bluetooth: Introduce user channel flag for HCI devices
Bluetooth: Refactor raw socket filter into more readable code

Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the device no other program may access it.

Before starting a gatt program, make sure that your BLE device is down:

sudo hciconfig
sudo hciconfig hci0 down  # or whatever hci device you want to use

If you have BlueZ 5.14+ (or aren't sure), stop the built-in bluetooth server, which interferes with gatt, e.g.:

sudo service bluetooth stop

Because gatt programs administer network devices, they must either be run as root, or be granted appropriate capabilities:

sudo <executable>
# OR
sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
<executable>

USAGE

# Start a simple server.
sudo go run example/server.go

# Discover surrounding peripherals.
sudo go run example/discoverer.go

# Connect to and explorer a peripheral device.
sudo go run example/explorer.go <peripheral ID>

See the server.go, discoverer.go, and explorer.go in the examples/ directory for writing server or client programs that run on Linux and OS X.

Users, especially on Linux platforms, seeking finer-grained control over the devices can see the examples/server_lnx.go for the usage of Option, which are platform specific.

See the rest of the docs for other options and finer-grained control.

Note that some BLE central devices, particularly iOS, may aggressively cache results from previous connections. If you change your services or characteristics, you may need to reboot the other device to pick up the changes. This is a common source of confusion and apparent bugs. For an OS X central, see http://stackoverflow.com/questions/20553957.

REFERENCES

gatt started life as a port of bleno, to which it is indebted: https://github.com/sandeepmistry/bleno. If you are having problems with gatt, particularly around installation, issues filed with bleno might also be helpful references.

To try out your GATT server, it is useful to experiment with a generic BLE client. LightBlue is a good choice. It is available free for both iOS and OS X.

Index

Examples

Constants

View Source
const (
	StatusSuccess         = 0
	StatusInvalidOffset   = 1
	StatusUnexpectedError = 2
)

Supported statuses for GATT characteristic read/write operations. These correspond to att constants in the BLE spec

View Source
const MaxEIRPacketLength = 31

MaxEIRPacketLength is the maximum allowed AdvertisingPacket and ScanResponsePacket length.

Variables

View Source
var ErrEIRPacketTooLong = errors.New("max packet length is 31")

ErrEIRPacketTooLong is the error returned when an AdvertisingPacket or ScanResponsePacket is too long.

View Source
var (
	ErrInvalidLength = errors.New("invalid length")
)

Functions

func UUIDContains

func UUIDContains(s []UUID, u UUID) bool

UUIDContains returns a boolean reporting whether u is in the slice s.

Types

type AdvPacket

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

AdvPacket is an utility to help crafting advertisment or scan response data.

func (*AdvPacket) AppendField

func (a *AdvPacket) AppendField(typ byte, b []byte) *AdvPacket

AppendField appends a BLE advertising packet field. TODO: refuse to append field if it'd make the packet too long.

func (*AdvPacket) AppendFlags

func (a *AdvPacket) AppendFlags(f byte) *AdvPacket

AppendFlags appends a flag field to the packet.

func (*AdvPacket) AppendManufacturerData

func (a *AdvPacket) AppendManufacturerData(id uint16, b []byte) *AdvPacket

AppendManufacturerData appends a manufacturer data field to the packet.

func (*AdvPacket) AppendName

func (a *AdvPacket) AppendName(n string) *AdvPacket

AppendFlags appends a name field to the packet. If the name fits in the space, it will be append as a complete name field, otherwise a short name field.

func (*AdvPacket) AppendUUIDFit

func (a *AdvPacket) AppendUUIDFit(uu []UUID) bool

AppendUUIDFit appends a BLE advertised service UUID packet field if it fits in the packet, and reports whether the UUID fit.

func (*AdvPacket) Bytes

func (a *AdvPacket) Bytes() [31]byte

Bytes returns an 31-byte array, which contains up to 31 bytes of the packet.

func (*AdvPacket) Len

func (a *AdvPacket) Len() int

Len returns the length of the packets with a maximum of 31.

type Advertisement struct {
	LocalName        string
	ManufacturerData []byte
	ServiceData      []ServiceData
	Services         []UUID
	OverflowService  []UUID
	TxPowerLevel     int
	Connectable      bool
	SolicitedService []UUID
	Raw              []byte
}

This is borrowed from core bluetooth. Embedded/Linux folks might be interested in more details.

type Central

type Central interface {
	ID() string   // ID returns platform specific ID of the remote central device.
	Close() error // Close disconnects the connection.
	MTU() int     // MTU returns the current connection mtu.
}

Central is the interface that represent a remote central device.

type Characteristic

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

A Characteristic is a BLE characteristic.

func NewCharacteristic

func NewCharacteristic(u UUID, s *Service, props Property, h uint16, vh uint16) *Characteristic

NewCharacteristic creates and returns a Characteristic.

func (*Characteristic) AddDescriptor

func (c *Characteristic) AddDescriptor(u UUID) *Descriptor

AddDescriptor adds a descriptor to a characteristic. AddDescriptor panics if the characteristic already contains another descriptor with the same UUID.

func (*Characteristic) Descriptor

func (c *Characteristic) Descriptor() *Descriptor

Descriptor returns the Descriptor of the characteristic.

func (*Characteristic) Descriptors

func (c *Characteristic) Descriptors() []*Descriptor

Descriptors returns the contained descriptors of this characteristic.

func (*Characteristic) EndHandle

func (c *Characteristic) EndHandle() uint16

EndHandle returns the End Handle of the characteristic.

func (*Characteristic) Handle

func (c *Characteristic) Handle() uint16

Handle returns the Handle of the characteristic.

func (*Characteristic) HandleNotify

func (c *Characteristic) HandleNotify(h NotifyHandler)

HandleNotify makes the characteristic support notify requests, and routes notification requests to h. HandleNotify must be called before the containing service is added to a server.

func (*Characteristic) HandleNotifyFunc

func (c *Characteristic) HandleNotifyFunc(f func(r Request, n Notifier))

HandleNotifyFunc calls HandleNotify(NotifyHandlerFunc(f)).

func (*Characteristic) HandleRead

func (c *Characteristic) HandleRead(h ReadHandler)

HandleRead makes the characteristic support read requests, and routes read requests to h. HandleRead must be called before the containing service is added to a server. HandleRead panics if the characteristic has been configured with a static value.

func (*Characteristic) HandleReadFunc

func (c *Characteristic) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest))

HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).

func (*Characteristic) HandleWrite

func (c *Characteristic) HandleWrite(h WriteHandler)

HandleWrite makes the characteristic support write and write-no-response requests, and routes write requests to h. The WriteHandler does not differentiate between write and write-no-response requests; it is handled automatically. HandleWrite must be called before the containing service is added to a server.

func (*Characteristic) HandleWriteFunc

func (c *Characteristic) HandleWriteFunc(f func(r Request, data []byte) (status byte))

HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).

func (*Characteristic) Name

func (c *Characteristic) Name() string

Name returns the specificatin name of the characteristic. If the UUID is not assigned, Name returns empty string.

func (*Characteristic) Properties

func (c *Characteristic) Properties() Property

Properties returns the properties of this characteristic.

func (*Characteristic) Service

func (c *Characteristic) Service() *Service

Service returns the containing service of this characteristic.

func (*Characteristic) SetDescriptor

func (c *Characteristic) SetDescriptor(cccd *Descriptor)

SetDescriptor sets the Descriptor of the characteristic.

func (*Characteristic) SetDescriptors

func (c *Characteristic) SetDescriptors(descs []*Descriptor)

SetDescriptors sets the list of Descriptor of the characteristic.

func (*Characteristic) SetEndHandle

func (c *Characteristic) SetEndHandle(endh uint16)

SetEndHandle sets the End Handle of the characteristic.

func (*Characteristic) SetHandle

func (c *Characteristic) SetHandle(h uint16)

SetHandle sets the Handle of the characteristic.

func (*Characteristic) SetVHandle

func (c *Characteristic) SetVHandle(vh uint16)

SetVHandle sets the Value Handle of the characteristic.

func (*Characteristic) SetValue

func (c *Characteristic) SetValue(b []byte)

SetValue makes the characteristic support read requests, and returns a static value. SetValue must be called before the containing service is added to a server. SetValue panics if the characteristic has been configured with a ReadHandler.

func (*Characteristic) UUID

func (c *Characteristic) UUID() UUID

UUID returns the UUID of the characteristic.

func (*Characteristic) VHandle

func (c *Characteristic) VHandle() uint16

VHandle returns the Value Handle of the characteristic.

type Descriptor

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

Descriptor is a BLE descriptor

func NewDescriptor

func NewDescriptor(u UUID, h uint16, char *Characteristic) *Descriptor

NewDescriptor creates and returns a Descriptor.

func (*Descriptor) Characteristic

func (d *Descriptor) Characteristic() *Characteristic

Characteristic returns the containing characteristic of the descriptor.

func (*Descriptor) Handle

func (d *Descriptor) Handle() uint16

Handle returns the Handle of the descriptor.

func (*Descriptor) HandleRead

func (d *Descriptor) HandleRead(h ReadHandler)

HandleRead makes the descriptor support read requests, and routes read requests to h. HandleRead must be called before the containing service is added to a server. HandleRead panics if the descriptor has been configured with a static value.

func (*Descriptor) HandleReadFunc

func (d *Descriptor) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest))

HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).

func (*Descriptor) HandleWrite

func (d *Descriptor) HandleWrite(h WriteHandler)

HandleWrite makes the descriptor support write and write-no-response requests, and routes write requests to h. The WriteHandler does not differentiate between write and write-no-response requests; it is handled automatically. HandleWrite must be called before the containing service is added to a server.

func (*Descriptor) HandleWriteFunc

func (d *Descriptor) HandleWriteFunc(f func(r Request, data []byte) (status byte))

HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).

func (*Descriptor) Name

func (d *Descriptor) Name() string

Name returns the specificatin name of the descriptor. If the UUID is not assigned, returns an empty string.

func (*Descriptor) SetHandle

func (d *Descriptor) SetHandle(h uint16)

SetHandle sets the Handle of the descriptor.

func (*Descriptor) SetValue

func (d *Descriptor) SetValue(b []byte)

SetValue makes the descriptor support read requests, and returns a static value. SetValue must be called before the containing service is added to a server. SetValue panics if the descriptor has already configured with a ReadHandler.

func (*Descriptor) UUID

func (d *Descriptor) UUID() UUID

UUID returns the UUID of the descriptor.

type Device

type Device interface {
	Init(stateChanged func(Device, State)) error

	// Advertise advertise AdvPacket
	Advertise(a *AdvPacket) error

	// AdvertiseNameAndServices advertises device name, and specified service UUIDs.
	// It tres to fit the UUIDs in the advertising packet as much as possible.
	// If name doesn't fit in the advertising packet, it will be put in scan response.
	AdvertiseNameAndServices(name string, ss []UUID) error

	// AdvertiseIBeaconData advertise iBeacon with given manufacturer data.
	AdvertiseIBeaconData(b []byte) error

	// AdvertisingIbeacon advertises iBeacon with specified parameters.
	AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error

	// StopAdvertising stops advertising.
	StopAdvertising() error

	// RemoveAllServices removes all services that are currently in the database.
	RemoveAllServices() error

	// Add Service add a service to database.
	AddService(s *Service) error

	// SetServices set the specified service to the database.
	// It removes all currently added services, if any.
	SetServices(ss []*Service) error

	// Scan discovers surounding remote peripherals that have the Service UUID specified in ss.
	// If ss is set to nil, all devices scanned are reported.
	// dup specifies weather duplicated advertisement should be reported or not.
	// When a remote peripheral is discovered, the PeripheralDiscovered Handler is called.
	Scan(ss []UUID, dup bool)

	// StopScanning stops scanning.
	StopScanning()

	// Stop calls OS specific close calls
	Stop() error

	// Connect connects to a remote peripheral.
	Connect(p Peripheral)

	// CancelConnection disconnects a remote peripheral.
	CancelConnection(p Peripheral)

	// Handle registers the specified handlers.
	Handle(h ...Handler)

	// Option sets the options specified.
	Option(o ...Option) error
}

Device defines the interface for a BLE device. Since an interface can't define fields(properties). To implement the callback support for cerntain events, deviceHandler is defined and implementation of Device on different platforms should embed it in order to keep have keep compatible in API level. Package users can use the Handler to set these handlers.

func NewDevice

func NewDevice(opts ...Option) (Device, error)

type Handler

type Handler func(Device)

A Handler is a self-referential function, which registers the options specified. See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.

func CentralConnected

func CentralConnected(f func(Central)) Handler

CentralConnected returns a Handler, which sets the specified function to be called when a device connects to the server.

func CentralDisconnected

func CentralDisconnected(f func(Central)) Handler

CentralDisconnected returns a Handler, which sets the specified function to be called when a device disconnects from the server.

func PeripheralConnected

func PeripheralConnected(f func(Peripheral, error)) Handler

PeripheralConnected returns a Handler, which sets the specified function to be called when a remote peripheral device connects.

func PeripheralDisconnected

func PeripheralDisconnected(f func(Peripheral, error)) Handler

PeripheralDisconnected returns a Handler, which sets the specified function to be called when a remote peripheral device disconnects.

func PeripheralDiscovered

func PeripheralDiscovered(f func(Peripheral, *Advertisement, int)) Handler

PeripheralDiscovered returns a Handler, which sets the specified function to be called when a remote peripheral device is found during scan procedure.

type Notifier

type Notifier interface {
	// Write sends data to the central.
	Write(data []byte) (int, error)

	// Done reports whether the central has requested not to
	// receive any more notifications with this notifier.
	Done() bool

	// Cap returns the maximum number of bytes that may be sent
	// in a single notification.
	Cap() int
}

A Notifier provides a means for a GATT server to send notifications about value changes to a connected device. Notifiers are provided by NotifyHandlers.

type NotifyHandler

type NotifyHandler interface {
	ServeNotify(r Request, n Notifier)
}

A NotifyHandler handles GATT notification requests. Notifications can be sent using the provided notifier.

type NotifyHandlerFunc

type NotifyHandlerFunc func(r Request, n Notifier)

NotifyHandlerFunc is an adapter to allow the use of ordinary functions as NotifyHandlers. If f is a function with the appropriate signature, NotifyHandlerFunc(f) is a NotifyHandler that calls f.

func (NotifyHandlerFunc) ServeNotify

func (f NotifyHandlerFunc) ServeNotify(r Request, n Notifier)

ServeNotify calls f(r, n).

type Option

type Option func(Device) error

An Option is a self-referential function, which sets the option specified. Most Options are platform-specific, which gives more fine-grained control over the device at a cost of losing portibility. See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.

func LnxDeviceID

func LnxDeviceID(n int, chk bool) Option

LnxDeviceID specifies which HCI device to use. If n is set to -1, all the available HCI devices will be probed. If chk is set to true, LnxDeviceID checks the LE support in the feature list of the HCI device. This is to filter devices that does not support LE. In case some LE driver that doesn't correctly set the LE support in its feature list, user can turn off the check. This option can only be used with NewDevice on Linux implementation.

Example
NewDevice(LnxDeviceID(-1, true)) // Can only be used with NewDevice.
Output:

func LnxMaxConnections

func LnxMaxConnections(n int) Option

LnxMaxConnections is an optional parameter. If set, it overrides the default max connections supported. This option can only be used with NewDevice on Linux implementation.

Example
NewDevice(LnxMaxConnections(1)) // Can only be used with NewDevice.
Output:

func LnxSendHCIRawCommand

func LnxSendHCIRawCommand(c cmd.CmdParam, rsp io.Writer) Option

LnxSendHCIRawCommand sends a raw command to the HCI device This option can be used with NewDevice or Option on Linux implementation.

Example (CustomCommand)
// customCmd implements cmd.CmdParam as a fake vendor command.
//
//  type customCmd struct{ ConnectionHandle uint16 }
//
//  func (c customCmd) Opcode() int { return 0xFC01 }
//  func (c customCmd) Len() int    { return 3 }
//  func (c customCmd) Marshal(b []byte) {
//  	[]byte{
// 	 	byte(c.ConnectionHandle),
//  		byte(c.ConnectionHandle >> 8),
//  		0xff,
//  	}
//  }
// Send a custom vendor command without checking response.
c := &customCmd{ConnectionHandle: 0x40}
d, _ := NewDevice()
d.Option(LnxSendHCIRawCommand(c, nil)) // Can only be used with Option
Output:

Example (PredefinedCommand)
// Send a predefined command of cmd package.
c := &cmd.LESetScanResponseData{
	ScanResponseDataLength: 8,
	ScanResponseData:       [31]byte{0x07, 0x09, 'G', 'o', 'p', 'h', 'e', 'r'},
}
rsp := bytes.NewBuffer(nil)
d, _ := NewDevice()
d.Option(LnxSendHCIRawCommand(c, rsp)) // Can only be used with Option
// Check the return status
if rsp.Bytes()[0] != 0x00 {
	// Handle errors
}
Output:

func LnxSetAdvertisingData

func LnxSetAdvertisingData(c *cmd.LESetAdvertisingData) Option

LnxSetAdvertisingData sets the advertising data to the HCI device. This option can be used with NewDevice or Option on Linux implementation.

func LnxSetAdvertisingEnable

func LnxSetAdvertisingEnable(en bool) Option

LnxSetAdvertisingEnable sets the advertising data to the HCI device. This option can be used with Option on Linux implementation.

Example
d, _ := NewDevice()
d.Option(LnxSetAdvertisingEnable(true)) // Can only be used with Option.
Output:

func LnxSetAdvertisingParameters

func LnxSetAdvertisingParameters(c *cmd.LESetAdvertisingParameters) Option

LnxSetAdvertisingParameters sets the advertising parameters to the HCI device. This option can be used with NewDevice or Option on Linux implementation.

Example
o := LnxSetAdvertisingParameters(&cmd.LESetAdvertisingParameters{
	AdvertisingIntervalMin:  0x800,     // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
	AdvertisingIntervalMax:  0x800,     // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
	AdvertisingType:         0x00,      // [0x00]: ADV_IND, 0x01: DIRECT(HIGH), 0x02: SCAN, 0x03: NONCONN, 0x04: DIRECT(LOW)
	OwnAddressType:          0x00,      // [0x00]: public, 0x01: random
	DirectAddressType:       0x00,      // [0x00]: public, 0x01: random
	DirectAddress:           [6]byte{}, // Public or Random Address of the device to be connected
	AdvertisingChannelMap:   0x7,       // [0x07] 0x01: ch37, 0x02: ch38, 0x04: ch39
	AdvertisingFilterPolicy: 0x00,
})
d, _ := NewDevice(o) // Can be used with NewDevice.
d.Option(o)          // Or dynamically with Option.
Output:

func LnxSetScanResponseData

func LnxSetScanResponseData(c *cmd.LESetScanResponseData) Option

LnxSetScanResponseData sets the scan response data to the HXI device. This option can be used with NewDevice or Option on Linux implementation.

Example
// Manually crafting a scan response data packet with a name field.
o := LnxSetScanResponseData(&cmd.LESetScanResponseData{
	ScanResponseDataLength: 8,
	ScanResponseData:       [31]byte{0x07, 0x09, 'G', 'o', 'p', 'h', 'e', 'r'},
})
d, _ := NewDevice(o)
d.Option(o)
Output:

type Peripheral

type Peripheral interface {
	// Device returns the underlying device.
	Device() Device

	// ID is the platform specific unique ID of the remote peripheral, e.g. MAC for Linux, Peripheral UUID for MacOS.
	ID() string

	// Name returns the name of the remote peripheral.
	// This can be the advertised name, if exists, or the GAP device name, which takes priority
	Name() string

	// Services returnns the services of the remote peripheral which has been discovered.
	Services() []*Service

	// DiscoverServices discover the specified services of the remote peripheral.
	// If the specified services is set to nil, all the available services of the remote peripheral are returned.
	DiscoverServices(s []UUID) ([]*Service, error)

	// DiscoverIncludedServices discovers the specified included services of a service.
	// If the specified services is set to nil, all the included services of the service are returned.
	DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error)

	// DiscoverCharacteristics discovers the specified characteristics of a service.
	// If the specified characterstics is set to nil, all the characteristic of the service are returned.
	DiscoverCharacteristics(c []UUID, s *Service) ([]*Characteristic, error)

	// DiscoverDescriptors discovers the descriptors of a characteristic.
	// If the specified descriptors is set to nil, all the descriptors of the characteristic are returned.
	DiscoverDescriptors(d []UUID, c *Characteristic) ([]*Descriptor, error)

	// ReadCharacteristic retrieves the value of a specified characteristic.
	ReadCharacteristic(c *Characteristic) ([]byte, error)

	// ReadLongCharacteristic retrieves the value of a specified characteristic that is longer than the
	// MTU.
	ReadLongCharacteristic(c *Characteristic) ([]byte, error)

	// ReadDescriptor retrieves the value of a specified characteristic descriptor.
	ReadDescriptor(d *Descriptor) ([]byte, error)

	// WriteCharacteristic writes the value of a characteristic.
	WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error

	// WriteDescriptor writes the value of a characteristic descriptor.
	WriteDescriptor(d *Descriptor, b []byte) error

	// SetNotifyValue sets notifications for the value of a specified characteristic.
	SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error

	// SetIndicateValue sets indications for the value of a specified characteristic.
	SetIndicateValue(c *Characteristic, f func(*Characteristic, []byte, error)) error

	// ReadRSSI retrieves the current RSSI value for the remote peripheral.
	ReadRSSI() int

	// SetMTU sets the mtu for the remote peripheral.
	SetMTU(mtu uint16) error
}

Peripheral is the interface that represent a remote peripheral device.

type Property

type Property int
const (
	CharBroadcast   Property = 0x01 // may be brocasted
	CharRead        Property = 0x02 // may be read
	CharWriteNR     Property = 0x04 // may be written to, with no reply
	CharWrite       Property = 0x08 // may be written to, with a reply
	CharNotify      Property = 0x10 // supports notifications
	CharIndicate    Property = 0x20 // supports Indications
	CharSignedWrite Property = 0x40 // supports signed write
	CharExtended    Property = 0x80 // supports extended properties
)

Characteristic property flags (spec 3.3.3.1)

func (Property) String

func (p Property) String() (result string)

type ReadHandler

type ReadHandler interface {
	ServeRead(resp ResponseWriter, req *ReadRequest)
}

A ReadHandler handles GATT read requests.

type ReadHandlerFunc

type ReadHandlerFunc func(resp ResponseWriter, req *ReadRequest)

ReadHandlerFunc is an adapter to allow the use of ordinary functions as ReadHandlers. If f is a function with the appropriate signature, ReadHandlerFunc(f) is a ReadHandler that calls f.

func (ReadHandlerFunc) ServeRead

func (f ReadHandlerFunc) ServeRead(resp ResponseWriter, req *ReadRequest)

ServeRead returns f(r, maxlen, offset).

type ReadRequest

type ReadRequest struct {
	Request
	Cap    int // maximum allowed reply length
	Offset int // request value offset
}

A ReadRequest is a characteristic read request from a connected device.

type Request

type Request struct {
	Central Central
}

A Request is the context for a request from a connected central device. TODO: Replace this with more general context, such as: http://godoc.org/golang.org/x/net/context

type ResponseWriter

type ResponseWriter interface {
	// Write writes data to return as the characteristic value.
	Write([]byte) (int, error)

	// SetStatus reports the result of the read operation. See the Status* constants.
	SetStatus(byte)
}

type Service

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

A Service is a BLE service.

func NewService

func NewService(u UUID) *Service

NewService creates and initialize a new Service using u as it's UUID.

func (*Service) AddCharacteristic

func (s *Service) AddCharacteristic(u UUID) *Characteristic

AddCharacteristic adds a characteristic to a service. AddCharacteristic panics if the service already contains another characteristic with the same UUID.

func (*Service) Characteristics

func (s *Service) Characteristics() []*Characteristic

Characteristic returns the contained characteristic of this service.

func (*Service) EndHandle

func (s *Service) EndHandle() uint16

EndHandle returns the End Handle of the service.

func (*Service) Handle

func (s *Service) Handle() uint16

Handle returns the Handle of the service.

func (*Service) Name

func (s *Service) Name() string

Name returns the specificatin name of the service according to its UUID. If the UUID is not assigne, Name returns an empty string.

func (*Service) SetCharacteristics

func (s *Service) SetCharacteristics(chars []*Characteristic)

SetCharacteristics sets the Characteristics of the service.

func (*Service) SetEndHandle

func (s *Service) SetEndHandle(endh uint16)

SetEndHandle sets the End Handle of the service.

func (*Service) SetHandle

func (s *Service) SetHandle(h uint16)

SetHandle sets the Handle of the service.

func (*Service) UUID

func (s *Service) UUID() UUID

UUID returns the UUID of the service.

type ServiceData

type ServiceData struct {
	UUID UUID
	Data []byte
}

FIXME: check the unmarshalling of this data structure.

type State

type State int
const (
	StateUnknown      State = 0
	StateResetting    State = 1
	StateUnsupported  State = 2
	StateUnauthorized State = 3
	StatePoweredOff   State = 4
	StatePoweredOn    State = 5
)

func (State) String

func (s State) String() string

type UUID

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

A UUID is a BLE UUID.

func MustParseUUID

func MustParseUUID(s string) UUID

MustParseUUID parses a standard-format UUID string, like ParseUUID, but panics in case of error.

func ParseUUID

func ParseUUID(s string) (UUID, error)

ParseUUID parses a standard-format UUID string, such as "1800" or "34DA3AD1-7110-41A1-B1EF-4430F509CDE7".

func UUID16

func UUID16(i uint16) UUID

UUID16 converts a uint16 (such as 0x1800) to a UUID.

func (UUID) Bytes

func (u UUID) Bytes() []byte

func (UUID) Equal

func (u UUID) Equal(v UUID) bool

Equal returns a boolean reporting whether v represent the same UUID as u.

func (UUID) Len

func (u UUID) Len() int

Len returns the length of the UUID, in bytes. BLE UUIDs are either 2 or 16 bytes.

func (UUID) String

func (u UUID) String() string

String hex-encodes a UUID.

type WriteHandler

type WriteHandler interface {
	ServeWrite(r Request, data []byte) (status byte)
}

A WriteHandler handles GATT write requests. Write and WriteNR requests are presented identically; the server will ensure that a response is sent if appropriate.

type WriteHandlerFunc

type WriteHandlerFunc func(r Request, data []byte) byte

WriteHandlerFunc is an adapter to allow the use of ordinary functions as WriteHandlers. If f is a function with the appropriate signature, WriteHandlerFunc(f) is a WriteHandler that calls f.

func (WriteHandlerFunc) ServeWrite

func (f WriteHandlerFunc) ServeWrite(r Request, data []byte) byte

ServeWrite returns f(r, data).

Directories

Path Synopsis
examples
option
Package option wraps the platform specific options to help users creating cross-platform programs.
Package option wraps the platform specific options to help users creating cross-platform programs.
service
Package service provides a collection of sample services for demostrating purpose.
Package service provides a collection of sample services for demostrating purpose.
cmd
evt

Jump to

Keyboard shortcuts

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