Gatt is a Go package for building Bluetooth Low Energy peripherals

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

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.

Issues
  • Linux: Failed to discover services, err: invalid length

    Linux: Failed to discover services, err: invalid length

    When trying to connect to a specific peripheral under Linux, I get the error Failed to discover services, err: invalid length.

    First I receive these messages:

    2016/07/05 00:42:51 Request 0x02 got a mismatched response: 0x08
    2016/07/05 00:42:51 ignore l2cap signal:[ 0C 00 05 00 12 01 08 00 06 00 06 00 00 00 F4 01 ]
    2016/07/05 00:42:51 Request 0x10 got a mismatched response: 0x03
    

    And then the main error:

    Failed to discover services, err: invalid length
    

    I am able to connect using Noble, so I know it is not a hardware issue per se. Also, the same gatt code works on OSX, just not Linux. Anyone else run into anything like this?

    opened by deadprogram 22
  • Feature/go hci v3

    Feature/go hci v3

    v3.1 addresses most of the comments so far, and reworks the following items.

    • advertiser interface between hci, server, l2cap.
    • few more doc comments
    • move hci/l2cap to internal packages: linux/
    • remove conn.go: SetPrivateData()/PrivateData()

    However, the following interface between server and l2cap is left as is.

    • conn.go: io.ReadWriterCloser()

    Currently, we set the boundary between generic and platform code around l2cap. But I'm planing to add another abstraction layer between them - roles(peripheral/central). This should pave the way to support other platforms which provide BLE API around role level, such as apple core bluetooth, and android framework. In this case, we'll shift more code to the linux/.

    Note: It requires linux kernel v3.14+ for the new USER_CHANNEL of HCI socket. When a device is opened with user channel, it requires exclusive usage of the HCI interface. So the HCI interface must be in "DOWN" status, or -EBUSY is returned.

    ex: sudo hciconfig hci0 down

    Revision history: v0: 9225a4f v1: dc97e44 v2: 8602eff

    opened by roylee17 13
  • scan doesn't work on Intel Edison

    scan doesn't work on Intel Edison

    From https://github.com/paypal/gatt/pull/20, I expected gatt works on Intel Edison, but not worked.

    [email protected]:~/src/github.com/paypal/gatt/examples# go run discoverer.go 
    2015/06/03 04:14:11 dev: hci0 up
    2015/06/03 04:14:11 dev: hci0 down
    2015/06/03 04:14:11 dev: hci0 can't bind to hci user channel, err: invalid argument.
    2015/06/03 04:14:11 dev: hci0 opened
    State: PoweredOn
    scanning...
    

    examples/discover.go starts scanning but nothing happen.

    My environment is below. To avoid cross compiling issue, I have started from self build on Intel Edison.

    - go version go1.4.2 linux/386
    - Linux edison 3.10.17-poky-edison+ #1 SMP PREEMPT Wed Apr 29 03:54:01 CEST 2015 i686 GNU/Linux
    - image: edison-image-ww18-15
    

    Thanks!

    opened by shirou 10
  • Hangs on Beaglebone Black/Arch Linux

    Hangs on Beaglebone Black/Arch Linux

    The gatt_server example hangs after calling srv.AdvertiseAndServe().

    $ uname -a
    Linux bbb_001 3.14.4-1-ARCH #1 SMP Sun May 18 18:32:31 MDT 2014 armv7l GNU/Linux
    
    $ go version
    go version go1.3 linux/arm
    

    I can see the Peripheral name using LightBlue but not the characteristics. The sample server never prints an output to stdout, just hangs there.

    I'm using the plugable USB dongle:

    $ hciconfig
    hci0:   Type: BR/EDR  Bus: USB
        BD Address: 00:02:72:C5:C1:80  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING PSCAN 
        RX bytes:2701 acl:11 sco:0 events:151 errors:0
        TX bytes:1825 acl:14 sco:0 commands:105 errors:0
    
    lsusb
    Bus 002 Device 002: ID 0a5c:21e8 Broadcom Corp. BCM20702A0 Bluetooth 4.0
    
    opened by leoneu 8
  • BLE, scanning interval

    BLE, scanning interval

    Hi everyone. I would like use this library to my project but i have problem with scan interval. I would like scanning all ble devices in range ma scanner(raspberry pi) online. My device emit advertising packet every 350ms, but in my simple application i see this packet every 2-4 s. have any idea why ?

    opened by wopol 7
  • Native linux bluetooth device enumeration and info

    Native linux bluetooth device enumeration and info

    Just wanted to sync up with the other work going on here.

    Over the weekend I completed a basic replacement for the bluez methods:

    • hci_for_each_dev
    • hci_devinfo

    Just wanted to know if there was already work happening in this area? And whether I should make a pull request so you can decide whether you want this functionality.

    I am working on integrating mainly client functions at the moment.

    cc @roylee17

    opened by wolfeidau 6
  • Unhandled LE LTK Request while connection to IOS

    Unhandled LE LTK Request while connection to IOS

    Hi , I'm using the "sample.go" on a RPI 3.18 I can connect to mac / os and inquire services / characteristics and exchange data. But while connecting to very simple IOS app , the IOS app sends an LTK request and the sample.go shows on screen : "hci: unhandled LE event: LE LTK Request" on the IOS side, the app is exiting with an "Error Domain=CBErrorDomain Code=6 "The connection has timed out unexpectedly." UserInfo=0x174072280" I tried also with a few apps ( LightBlue, BLE diag tool) and all of them are giving the same result. On IOS I couldn't found an alternate method of connecting. Thanks Henrique

    opened by hmatulis 5
  • add Getter/Setter of the service, characteristic, and descriptor.

    add Getter/Setter of the service, characteristic, and descriptor.

    From previous issue, I found noble uses two tiny C programs to read/write HCI and L2CAP, and works on Intel Edison(kernel 3.10). So that, I created noblechild which provides almost same interface to paypal/gatt via noble's C programs. Currently, noblechild can read/write attributes. But I have to make some changes to paypal/gatt.

    This PR includes some setter/getter functions to use unexported variables in Server, Characteristic, and Descriptor. No other functions are changes. Would you please merge this PR?

    Thank you!

    opened by shirou 4
  • Increasing buffer size on responses channel

    Increasing buffer size on responses channel

    Because of "Dequeue request loop" returning message into the channel (req.rspc <- r) this may deadlock if another response has been already pushed by other routine to the channel.
    It does locks consistently with devices that send a lot of notifications. Adding extra buffer in channel reserves space for that extra command to be returned.

    opened by demon-xxi 4
  • Added Indications Support for Linux implementation

    Added Indications Support for Linux implementation

    Please review my changes and consider merging into your repo.

    Added new method Peripheral.SetIndicateValue to subscribe for gatt indications similar to notifications. For Indications though we need to send acknowledgment which is done by

    p.l2c.Write([]byte{attOpHandleCnf})
    

    Current pr contains only linux implementation. Darwin version needs more investigation as seems less documented and uses some hard-coded values instead of constants.

    opened by demon-xxi 4
  • mac fix, updating examples

    mac fix, updating examples

    The project was not building on mac, as header file being included was named incorrectly. Also a few fixes to one of the example programs as it was crashing if the flag was not provided.

    opened by acmacalister 4
  • Can't run on MacOS Big Sur

    Can't run on MacOS Big Sur

    when I run the example/discover.go, I got this output in console:

    Unhandled event: xpc.Dict{"kCBMsgArgs":xpc.Dict{"kCBMsgArgRequiresTCC":1}, "kCBMsgId":3}

    then I search the "kCBMsgId" in "HandleXpcEvent" function, and do not find the handler of kCBMsgId=3. My question is what the exactly handler of kCBMsgId=3?

    opened by johnnyeven 1
  • Avoid slice bounds out of range

    Avoid slice bounds out of range

    Fixed the following panic when scaning.

    panic: runtime error: slice bounds out of range [2:1]
    
    goroutine 18803 [running]:
    github.com/paypal/gatt.(*Advertisement).unmarshall(0x2711ef0, 0x2761160, 0xe, 0xe, 0x115b94, 0x2492018)
    	/home/pi/.go/src/github.com/paypal/gatt/adv.go:99 +0x8c4
    github.com/paypal/gatt.(*device).Init.func3(0x24599e0)
    	/home/pi/.go/src/github.com/paypal/gatt/device_linux.go:97 +0x50
    github.com/paypal/gatt/linux.(*HCI).handleAdvertisement(0x248e040, 0x2796b93, 0xc, 0xc)
    	/home/pi/.go/src/github.com/paypal/gatt/linux/hci.go:262 +0x214
    created by github.com/paypal/gatt/linux.(*HCI).handleLEMeta
    	/home/pi/.go/src/github.com/paypal/gatt/linux/hci.go:359 +0x114
    
    opened by dki1110 0
  • Support on openwrt?

    Support on openwrt?

    Hi,

    Thanks for the library. I am trying to run this on MIPS based platform with bluez-util v 5.49. When it's initiating, it can't create a new device and fails with file descriptor in bad state. I made sure I am not running any other Bluetooth daemon at the backend(hciconfig hci0 down;service bluetoothd stop;dbus stop). But when I enable dbus, I can use bluetoothctl utility to discover Bluetooth devices around me. Am I missing any dependency which I can add to fix this?

    Thanks, Aditya

    opened by Aditya23456 0
  • Code gets stuck inside DiscoverServices() method

    Code gets stuck inside DiscoverServices() method

    I used paypal/gatt package to create and connect a bluetooth server and peripheral device . I created a service exactly like the one described in examples folder. The service which I created is advertised correctly. When I am trying to connect to this service using a peripheral device which is written using paypal/gatt I am getting a random failure. Upon checking logs I realized that it is getting stuck in DiscoverServices() method. In DiscoverServices()[present in peripheral_linux.go] there is call to sendReq() method. When the channel gets value the control goes to loop() function in same file.There it is calling the Read and Write methods. It seems like write is happening properly but the code is getting stuck inside Read()[present in l2cap.go]. When I debugged I could see that the read is getting value from handleL2CAP()[hci.go] which is called by handlePacket()[hci.go].

    opened by lidiyag 1
Owner
PayPal
PayPal
Bluetooth Low Energy for Go

Bluetooth Low Energy for Go (based od CC2541) Description Bluetooth Low Enery (HM10) module for Go Installation go get github.com/MarinX/goble Exampl

Marin Basic 44 Jun 5, 2022
This package provides support for using Bluetooth with gokrazy!

This package provides support for using Bluetooth with gokrazy! Note that general purpose Bluetooth would depend on userland utilities such as bluez w

null 12 Jun 13, 2022
πŸ¦– Streaming-Serverless Framework for Low-latency Edge Computing applications, running atop QUIC protocol, engaging 5G technology.

YoMo YoMo is an open-source Streaming Serverless Framework for building Low-latency Edge Computing applications. Built atop QUIC Transport Protocol an

YoMo 1.1k Jun 22, 2022
Project Flogo is an open source ecosystem of opinionated event-driven capabilities to simplify building efficient & modern serverless functions, microservices & edge apps.

Project Flogo is an Open Source ecosystem for event-driven apps Ecosystem | Core | Flows | Streams | Flogo Rules | Go Developers | When to use Flogo |

TIBCO Software Inc. 2k Jun 23, 2022
A project outputs Bluetooth Low Energy (BLE) sensors data in InfluxDB line protocol formatA project outputs Bluetooth Low Energy (BLE) sensors data in InfluxDB line protocol format

Intro This project outputs Bluetooth Low Energy (BLE) sensors data in InfluxDB line protocol format. It integrates nicely with the Telegraf execd inpu

Marc Venturini 1 Apr 15, 2022
Go package for interacting with the "ELK" Bluetooth Low Energy RGB LED Controller

Go interactions for the ELK-BLEDOM RGB LED Controller This repository contains information on the common (and cheap) ELK-BLEDOM Bluetooth Low Energy R

Fergus 4 Apr 19, 2022
Bluetooth Low Energy for Go

Bluetooth Low Energy for Go (based od CC2541) Description Bluetooth Low Enery (HM10) module for Go Installation go get github.com/MarinX/goble Exampl

Marin Basic 44 Jun 5, 2022
This package provides support for using Bluetooth with gokrazy!

This package provides support for using Bluetooth with gokrazy! Note that general purpose Bluetooth would depend on userland utilities such as bluez w

null 12 Jun 13, 2022
Package bright-golang is a client for the Bright App energy monitoring API.

Go client library for the Bright API Package bright-golang is a client for the Bright App energy monitoring API. Not all the API endpoints are impleme

Robin Kearney 0 Jan 5, 2022
Cross-platform Bluetooth API for Go and TinyGo.

Go Bluetooth is a cross-platform package for using Bluetooth Low Energy hardware from the Go programming language.

TinyGo 401 Jun 26, 2022
HyperKit: an easy-to-use bridge between LedFX, WLED, Bluetooth, HomeKit, and AirPlay2

HyperKit HyperKit is an easy-to-use bridge between LedFX, WLED, Bluetooth, HomeKit, and AirPlay2. HyperKit Functionality: Custom HomeKit Menu Integrat

Carter Peel 4 Feb 27, 2022
Bampf is a simple 3D arcade style game. Collect Energy Cores in order to finish a level. Teleport (bampf) to safety or use cloaking abilities to avoid Sentinels.

Bampf Bampf is a simple 3D arcade style game. Collect energy cores in order to finish a level. Teleport (bampf) to safety or use cloaking abilities to

null 39 Apr 7, 2021
NKN-ESI (or nESI) is an NKN based Energy Services Interface (ESI).

nkn-esi NKN-ESI (or nESI) is an NKN based Energy Services Interface (ESI). An ESI supports a distributed marketplace for energy services on the electr

Elijah J. Passmore 2 Mar 18, 2022
Loosely inspired by Terry A. Davis's gw, orgone is a command line Orgone energy accumulator

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚

cat K. 2 Jun 19, 2022
Kepler (Kubernetes-based Efficient Power Level Exporter) uses eBPF to probe energy related system stats and exports as Prometheus metrics

kepler Kepler (Kubernetes Efficient Power Level Exporter) uses eBPF to probe energy related system stats and exports as Prometheus metrics Architectur

Sustainable Computing 78 Jun 22, 2022
Package socket provides a low-level network connection type which integrates with Go's runtime network poller to provide asynchronous I/O and deadline support. MIT Licensed.

socket Package socket provides a low-level network connection type which integrates with Go's runtime network poller to provide asynchronous I/O and d

Matt Layher 41 May 9, 2022
DiscordGo: a Go package that provides low level bindings to the Discord chat client API

DiscordGo DiscordGo is a Go package that provides low level bindings to the Discord chat client API. DiscordGo has nearly complete support for all of

Владислав Π§Π΅Ρ€Π½ΠΈΠΊΠΎΠ² 1 Dec 14, 2021
Tiny go package for fetching high and low value of a stock for any given period range using kite connect historical data APIs.

Tiny go package for fetching high and low value of stock for any given period range using Kite connect Historical data APIs.

Rakesh R 1 Apr 27, 2022
A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities.

ozzo-dbx Summary Description Requirements Installation Supported Databases Getting Started Connecting to Database Executing Queries Binding Parameters

Ozzo Framework 551 Jun 3, 2022
β™ͺ A low-level library to play sound on multiple platforms β™ͺ

Oto (音) A low-level library to play sound. This package offers io.WriteCloser to play PCM sound. Platforms Windows macOS Linux FreeBSD OpenBSD Android

Hajime Hoshi 1k Jun 25, 2022
Low-level key/value store in pure Go.

Description Package slowpoke is a simple key/value store written using Go's standard library only. Keys are stored in memory (with persistence), value

Vadim Kulibaba 99 Mar 13, 2022
High performance, distributed and low latency publish-subscribe platform.

Emitter: Distributed Publish-Subscribe Platform Emitter is a distributed, scalable and fault-tolerant publish-subscribe platform built with MQTT proto

emitter 3.3k Jun 26, 2022
The X Go Binding is a low-level API to communicate with the X server. It is modeled on XCB and supports many X extensions.

Note that this project is largely unmaintained as I don't have the time to do or support more development. Please consider using this fork instead: ht

Andrew Gallant 444 Jun 18, 2022
🐜🐜🐜 ants is a high-performance and low-cost goroutine pool in Go, inspired by fasthttp./ ants ζ˜―δΈ€δΈͺι«˜ζ€§θƒ½δΈ”δ½ŽζŸθ€—ηš„ goroutine 池。

A goroutine pool for Go English | ???? δΈ­ζ–‡ ?? Introduction Library ants implements a goroutine pool with fixed capacity, managing and recycling a massi

Andy Pan 8.6k Jun 26, 2022
A simple low bandwidth simulator written in go

NETSNAIL 0.8 ABOUT Netsnail is a simple network proxy that simulates low bandwidth. RUNNING Usage of netsnail: -d=0: the delay on data transfe

Per Arneng 23 May 19, 2021
Automatic Linux privesc via exploitation of low-hanging fruit

Traitor Automatically exploit low-hanging fruit to pop a root shell. Linux privilege escalation made easy! Traitor packages up a bunch of methods to e

Liam Galvin 5.2k Jun 30, 2022
πŸ¦– Streaming-Serverless Framework for Low-latency Edge Computing applications, running atop QUIC protocol, engaging 5G technology.

YoMo YoMo is an open-source Streaming Serverless Framework for building Low-latency Edge Computing applications. Built atop QUIC Transport Protocol an

YoMo 1.1k Jun 22, 2022
The High Code Framework (low-code for devs)

hof - the high code framework The hof tool tries to remove redundent development activities by using high level designs, code generation, and diff3 wh

_Hofstadter 232 Jun 21, 2022
TalariaDB is a distributed, highly available, and low latency time-series database for Presto

TalariaDB is a distributed, highly available, and low latency time-series database that stores real-time data. It's built on top of Badger DB.

Grab 97 Jun 18, 2022