class BluezBleInterface(BleInterface): def __init__(self, *args, **kwargs): super(BluezBleInterface, self).__init__(*args, **kwargs) self._addr = kwargs.get('addr') self._log.info("Started interface {0}.".format(self)) def __del__(self): self._disconnect() def _connect(self, addr): self._log.info("BLE %s connecting ..." % addr) self.requester = GATTRequester(addr, False) self.requester.connect(True) chars = self.requester.discover_characteristics() self.characteristic = {} for char in chars: self.characteristic[char['uuid']] = char['value_handle'] self._log.info("BLE %s connected OK" % self._addr) def _disconnect(self): self.requester.disconnect() def _read_uuid(self, reg, type='float'): value = self.requester.read_by_uuid(reg)[0] if type == 'float': return struct.unpack('H', value)[0] * 1.0 elif type == 'string': try: value = value.decode("utf-8") except AttributeError: pass return value else: return value def _write_uuid(self, reg, value, type='float'): if type == 'string': value = struct.pack('B', value) self.requester.write_by_handle(self.characteristic[reg], value)
import time from bluetooth.ble import GATTRequester # # the MAC address of the BLE device. Replace 'D8:80:39:FC:7B:F5' with the address of your device. # grq = GATTRequester('D8:80:39:FC:7B:F5', False) grq.connect() print("Waiting to connect...") while not grq.is_connected(): time.sleep(1) print("Connected.") characteristics = grq.discover_characteristics() # # the UUID of the service on the BLE device. # sample_uuid = '59c889e0-5364-11e7-b114-b2f933d5fe66' # find the handle for the characteristic. vh_sample = None for c12c in characteristics: if c12c['uuid'] == sample_uuid: vh_sample = c12c['value_handle'] print("Characteristic value handle is %d." % vh_sample) break assert (vh_sample is not None)