py9b/py9b/link/ble.py

113 lines
3.0 KiB
Python
Raw Normal View History

2018-10-15 12:10:00 +00:00
"""BLE link using BlueGiga adapter via PyGatt/BGAPI"""
from __future__ import absolute_import
import pygatt
from .base import BaseLink, LinkTimeoutException, LinkOpenException
2018-10-15 12:10:00 +00:00
from binascii import hexlify
SCAN_TIMEOUT = 3
2019-05-21 19:09:08 +00:00
try:
2019-10-18 14:11:14 +00:00
import queue
2019-05-21 19:09:08 +00:00
except ImportError:
2019-10-18 14:11:14 +00:00
import Queue as queue
2019-10-20 06:49:22 +00:00
class Fifo:
2019-10-18 14:11:14 +00:00
def __init__(self):
self.q = queue.Queue()
2019-10-20 06:49:22 +00:00
def write(self, data): # put bytes
2019-10-18 14:11:14 +00:00
for b in data:
self.q.put(b)
2019-10-20 06:49:22 +00:00
def read(self, size=1, timeout=None): # but read string
res = ""
2019-10-18 14:11:14 +00:00
for i in xrange(size):
res += chr(self.q.get(True, timeout))
return res
2019-05-17 05:05:32 +00:00
2019-10-20 06:49:22 +00:00
# _cccd_uuid = '00002902-0000-1000-8000-00805f9b34fb'
_rx_char_uuid = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
_tx_char_uuid = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
_write_chunk_size = 20 # as in android dumps
2019-05-17 05:05:32 +00:00
class BLELink(BaseLink):
2019-10-18 14:11:14 +00:00
def __init__(self, *args, **kwargs):
super(BLELink, self).__init__(*args, **kwargs)
self._adapter = None
self._dev = None
self._wr_handle = None
self._rx_fifo = Fifo()
def __enter__(self):
self._adapter = pygatt.GATTToolBackend()
self._adapter.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
2019-10-20 06:49:22 +00:00
def _make_rx_cb(self): # this is a closure :)
2019-10-18 14:11:14 +00:00
def rx_cb(handle, value):
self._rx_fifo.write(value)
2019-10-20 06:49:22 +00:00
return rx_cb
2019-10-18 14:11:14 +00:00
def scan(self):
res = []
self._adapter.reset()
devices = self._adapter.scan(timeout=SCAN_TIMEOUT)
for dev in devices:
2019-10-20 06:49:22 +00:00
if dev["name"] and dev["name"].startswith(
(u"MISc", u"NBSc", u"JP2", u"Seg")
):
res.append((dev["name"], dev["address"]))
2019-10-18 14:11:14 +00:00
return res
def open(self, port):
try:
2019-10-20 06:49:22 +00:00
self._dev = self._adapter.connect(
port, address_type=pygatt.BLEAddressType.random
)
2019-10-18 14:11:14 +00:00
self._dev.subscribe(_tx_char_uuid, callback=self._make_rx_cb())
self._wr_handle = self._dev.get_handle(_rx_char_uuid)
except pygatt.exceptions.NotConnectedError:
raise LinkOpenException
def close(self):
if self._dev:
self._dev.disconnect()
self._dev = None
if self._adapter:
self._adapter.stop()
def read(self, size):
try:
data = self._rx_fifo.read(size, timeout=self.timeout)
except queue.Empty:
raise LinkTimeoutException
if self.dump:
2019-10-20 06:49:22 +00:00
print("<", hexlify(data).upper())
2019-10-18 14:11:14 +00:00
return data
def write(self, data):
if self.dump:
2019-10-20 06:49:22 +00:00
print(">", hexlify(data).upper())
2019-10-18 14:11:14 +00:00
size = len(data)
ofs = 0
while size:
chunk_sz = min(size, _write_chunk_size)
2019-10-20 06:49:22 +00:00
self._dev.char_write_handle(
self._wr_handle, bytearray(data[ofs : ofs + chunk_sz])
)
2019-10-18 14:11:14 +00:00
ofs += chunk_sz
size -= chunk_sz
2019-05-17 05:05:32 +00:00
2019-10-20 06:49:22 +00:00
__all__ = ["BLELink"]