gatt: github.com/paypal/gatt Index | Examples | Files | Directories

package gatt

import "github.com/paypal/gatt"

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

Package Files

adv.go attr.go central.go central_linux.go common.go const.go device.go device_linux.go doc.go known_uuid.go l2cap_writer_linux.go option_linux.go peripheral.go peripheral_linux.go uuid.go

Constants

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

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

const MaxEIRPacketLength = 31

MaxEIRPacketLength is the maximum allowed AdvertisingPacket and ScanResponsePacket length.

Variables

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

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

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

type AdvPacket Uses

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

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

func (*AdvPacket) AppendField Uses

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 Uses

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

AppendFlags appends a flag field to the packet.

func (*AdvPacket) AppendManufacturerData Uses

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

AppendManufacturerData appends a manufacturer data field to the packet.

func (*AdvPacket) AppendName Uses

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 Uses

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 Uses

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

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

func (*AdvPacket) Len Uses

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
}

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

type Central Uses

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 Uses

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

A Characteristic is a BLE characteristic.

func NewCharacteristic Uses

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

NewCharacteristic creates and returns a Characteristic.

func (*Characteristic) AddDescriptor Uses

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 Uses

func (c *Characteristic) Descriptor() *Descriptor

Descriptor returns the Descriptor of the characteristic.

func (*Characteristic) Descriptors Uses

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

Descriptors returns the contained descriptors of this characteristic.

func (*Characteristic) EndHandle Uses

func (c *Characteristic) EndHandle() uint16

EndHandle returns the End Handle of the characteristic.

func (*Characteristic) Handle Uses

func (c *Characteristic) Handle() uint16

Handle returns the Handle of the characteristic.

func (*Characteristic) HandleNotify Uses

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 Uses

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

HandleNotifyFunc calls HandleNotify(NotifyHandlerFunc(f)).

func (*Characteristic) HandleRead Uses

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 Uses

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

HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).

func (*Characteristic) HandleWrite Uses

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 Uses

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

HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).

func (*Characteristic) Name Uses

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 Uses

func (c *Characteristic) Properties() Property

Properties returns the properties of this characteristic.

func (*Characteristic) Service Uses

func (c *Characteristic) Service() *Service

Service returns the containing service of this characteristic.

func (*Characteristic) SetDescriptor Uses

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

SetDescriptor sets the Descriptor of the characteristic.

func (*Characteristic) SetDescriptors Uses

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

SetDescriptors sets the list of Descriptor of the characteristic.

func (*Characteristic) SetEndHandle Uses

func (c *Characteristic) SetEndHandle(endh uint16)

SetEndHandle sets the End Handle of the characteristic.

func (*Characteristic) SetHandle Uses

func (c *Characteristic) SetHandle(h uint16)

SetHandle sets the Handle of the characteristic.

func (*Characteristic) SetVHandle Uses

func (c *Characteristic) SetVHandle(vh uint16)

SetVHandle sets the Value Handle of the characteristic.

func (*Characteristic) SetValue Uses

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 Uses

func (c *Characteristic) UUID() UUID

UUID returns the UUID of the characteristic.

func (*Characteristic) VHandle Uses

func (c *Characteristic) VHandle() uint16

VHandle returns the Value Handle of the characteristic.

type Descriptor Uses

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

Descriptor is a BLE descriptor

func NewDescriptor Uses

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

NewDescriptor creates and returns a Descriptor.

func (*Descriptor) Characteristic Uses

func (d *Descriptor) Characteristic() *Characteristic

Characteristic returns the containing characteristic of the descriptor.

func (*Descriptor) Handle Uses

func (d *Descriptor) Handle() uint16

Handle returns the Handle of the descriptor.

func (*Descriptor) HandleRead Uses

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 Uses

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

HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).

func (*Descriptor) HandleWrite Uses

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 Uses

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

HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).

func (*Descriptor) Name Uses

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 Uses

func (d *Descriptor) SetHandle(h uint16)

SetHandle sets the Handle of the descriptor.

func (*Descriptor) SetValue Uses

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 Uses

func (d *Descriptor) UUID() UUID

UUID returns the UUID of the descriptor.

type Device Uses

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()

    // 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 Uses

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

type Handler Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

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

type NotifyHandlerFunc Uses

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 Uses

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

ServeNotify calls f(r, n).

type Option Uses

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 Uses

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.

Code:

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

func LnxMaxConnections Uses

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.

Code:

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

func LnxSendHCIRawCommand Uses

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.

Code:

// 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

Code:

// 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
}

func LnxSetAdvertisingData Uses

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 Uses

func LnxSetAdvertisingEnable(en bool) Option

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

Code:

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

func LnxSetAdvertisingParameters Uses

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.

Code:

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.

func LnxSetScanResponseData Uses

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.

Code:

// 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)

type Peripheral Uses

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 Uses

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 Uses

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

type ReadHandler Uses

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

A ReadHandler handles GATT read requests.

type ReadHandlerFunc Uses

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 Uses

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

ServeRead returns f(r, maxlen, offset).

type ReadRequest Uses

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 Uses

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 Uses

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 Uses

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

A Service is a BLE service.

func NewService Uses

func NewService(u UUID) *Service

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

func (*Service) AddCharacteristic Uses

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 Uses

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

Characteristic returns the contained characteristic of this service.

func (*Service) EndHandle Uses

func (s *Service) EndHandle() uint16

EndHandle returns the End Handle of the service.

func (*Service) Handle Uses

func (s *Service) Handle() uint16

Handle returns the Handle of the service.

func (*Service) Name Uses

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 Uses

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

SetCharacteristics sets the Characteristics of the service.

func (*Service) SetEndHandle Uses

func (s *Service) SetEndHandle(endh uint16)

SetEndHandle sets the End Handle of the service.

func (*Service) SetHandle Uses

func (s *Service) SetHandle(h uint16)

SetHandle sets the Handle of the service.

func (*Service) UUID Uses

func (s *Service) UUID() UUID

UUID returns the UUID of the service.

type ServiceData Uses

type ServiceData struct {
    UUID UUID
    Data []byte
}

FIXME: check the unmarshalling of this data structure.

type State Uses

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 Uses

func (s State) String() string

type UUID Uses

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

A UUID is a BLE UUID.

func MustParseUUID Uses

func MustParseUUID(s string) UUID

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

func ParseUUID Uses

func ParseUUID(s string) (UUID, error)

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

func UUID16 Uses

func UUID16(i uint16) UUID

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

func (UUID) Equal Uses

func (u UUID) Equal(v UUID) bool

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

func (UUID) Len Uses

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 Uses

func (u UUID) String() string

String hex-encodes a UUID.

type WriteHandler Uses

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 Uses

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 Uses

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

ServeWrite returns f(r, data).

Directories

PathSynopsis
examples/optionPackage option wraps the platform specific options to help users creating cross-platform programs.
examples/servicePackage service provides a collection of sample services for demostrating purpose.
linux
linux/cmd
linux/evt
linux/gioctl
linux/socket
linux/util
xpc

Package gatt imports 12 packages (graph) and is imported by 11 packages. Updated 2017-07-19. Refresh now. Tools for package owners.