A github mirror of https://bitbucket.org/OscarAcena/pygattlib
https://github.com/robhogan/pygattlib.git
Description =========== This is a Python library to use the GATT Protocol for Bluetooth LE devices. It is a wrapper around the implementation used by gatttool in bluez package. It does not call other binaries to do its job :) Installation ============ There are many ways of installing this library: using Python Pip, using the Debian package, or manually compiling it. Python pip
DiscoveryService provided. You need
to create an instance of it, indicating the Bluetooth device you want
to use. Then call the method discover, with a timeout. It will
return a dictionary with the address and name of all devices that
responded the discovery.
Note: it is very likely that you will need admin permissions to do
a discovery, so run this script using sudo (or something similar).
As example:
from gattlib import DiscoveryService
service = DiscoveryService("hci0")
devices = service.discover(2)
for address, name in devices.items():
print "name: {}, address: {}".format(name, address)
Reading data
async method used.
NOTE: It is important to maintain the Python process alive, or the
response will never arrive. You can wait on that response object, or you
can do other things meanwhile.
The following is an example of response waiting:
from gattlib import GATTRequester, GATTResponse
req = GATTRequester("00:11:22:33:44:55")
response = GATTResponse()
req.readbyhandle_async(0x15, response)
while not response.received():
time.sleep(0.1)
steps = response.received()[0]
And then, an example that inherits from GATTResponse to be notified
when the response arrives:
from gattlib import GATTRequester, GATTResponse
class NotifyYourName(GATTResponse):
def on_response(self, name):
print "your name is: {}".format(name)
response = NotifyYourName()
req = GATTRequester("00:11:22:33:44:55")
req.readbyhandle_async(0x15, response)
while True:
# here, do other interesting things
sleep(1)
Writing data
write_by_handle to send the
data. As a note, data must be a string, but you can convert it from
bytearray or something similar. See the following example:
from gattlib import GATTRequester
req = GATTRequester("00:11:22:33:44:55")
req.writebyhandle(0x10, str(bytearray([14, 4, 56])))