def wait_notification(self): print "Listening for communications" logger.debug("Listening for communications") #self.received.wait() while True: if self.connectionManager.isConnected(): continue logger.debug("Connection Lost, re-connecting subscribe") self.connectionManager.connect() for i in self.handles: bleServiceManager.bleServiceWriteToHandle(connectionManager, int(i, 16), self.configVal)
def wait_notification(self): print "Listening for communications" logger.debug("Listening for communications") #self.received.wait() while True: if self.connectionManager.isConnected(): continue logger.debug("Connection Lost, re-connecting subscribe") self.connectionManager.connect() for i in self.handles: bleServiceManager.bleServiceWriteToHandle( connectionManager, int(i, 16), self.configVal)
def bleServiceWrite(address, adapter, addressType, securityLevel, handles, inputs, maxTries=5): """ Used by command line tool to wrtie data to a device handle :param address: Address of target BTLE device :param adapter: Host adapter (Empty string to use host's default adapter) :param addressType: Type of address you want to connect to [public | random] :param securityLevel: Security level [low | medium | high] :param handles: List of handles to write to :param inputs: List of strings to write to handles :param maxTries: Maximum number of times to attempt each write operation. Default: 5 :type address: str :type adapter: str :type addressType: str :type securityLevel: str :type handles: list of base 10 ints :type inputs: list of strings :type maxTries: int :return: list of (handle, data, input) :rtype: list of tuples (int, str, str) """ connectionManager = bleConnectionManager.BLEConnectionManager(address, adapter, addressType, securityLevel) connectionManager.connect() #print "Input:",input handleData = [] for inputVal in inputs: for handle in handles: if handle is not None: tries = 0 while True: try: if not connectionManager.isConnected(): connectionManager.connect() data = bleServiceManager.bleServiceWriteToHandle(connectionManager, int(handle, 16), inputVal) break except RuntimeError as e: if "Invalid handle" in str(e): data = -1 break elif "Attribute can't" in str(e): data = -2 break else: if tries >= maxTries: logger.debug("%s Tries exceeded, throwing Runtime error and aborting write" % maxTries) raise RuntimeError(e) else: logger.debug("Error: %s Trying Again" % e) tries += 1 handleData.append((handle, data, inputVal)) return handleData
def gatt_write(conn, handle, message, fuzz_positions, num_iterations): '''Make a single write to a handle using bleSuite''' current_message = message if fuzz_positions: for position in fuzz_positions: if position * 2 >= len(current_message): print "Fuzz position beyond length of message" return current_message = current_message[0:position*2] + \ binascii.hexlify(chr(random.randint(0, 255))) + \ current_message[position*2:] for _ in range(num_iterations): print "writing {} ({}) to handle {}".format( current_message, repr(current_message.decode('hex')), handle) if not conn.isConnected: print "Connection lost, reconnecting" conn.connect() try: bleServiceWriteToHandle(conn, int(handle, 16), current_message.decode('hex')) except Exception as e: print e conn.connect()
def gatt_write(conn, handle, message, fuzz_positions, num_iterations): '''Make a single write to a handle using bleSuite''' current_message = message if fuzz_positions: for position in fuzz_positions: if position*2 >= len(current_message): print "Fuzz position beyond length of message" return current_message = current_message[0:position*2] + \ binascii.hexlify(chr(random.randint(0, 255))) + \ current_message[position*2:] for _ in range(num_iterations): print "writing {} ({}) to handle {}".format(current_message, repr(current_message.decode('hex')), handle) if not conn.isConnected: print "Connection lost, reconnecting" conn.connect() try: bleServiceWriteToHandle(conn, int(handle, 16), current_message.decode('hex')) except Exception as e: print e conn.connect()
def bleHandleSubscribe(address, handles, adapter, addressType, securityLevel, mode): """ Used by command line tool to enable specified handles' notify mode and listen until user interrupts. :param address: Address of target BTLE device :param handles: List of handle descriptors to write 0100 (enable notification) to :param adapter: Host adapter (Empty string to use host's default adapter) :param addressType: Type of address you want to connect to [public | random] :param securityLevel: Security level [low | medium | high] :param mode: Mode to set for characteristic configuration (0=off,1=notifications,2=indications, 3=notifications and inidications) :type address: str :type handles: list of base 10 ints :type adapter: str :type addressType: str :type securityLevel: str :type mode: int :return: """ logger.debug("Beginning Subscribe Function") if address is None: raise Exception( "%s Bluetooth address is not valid. Please supply a valid Bluetooth address value." % address) if mode == 0: configVal = str(bytearray([00, 00])) elif mode == 1: configVal = str(bytearray([01, 00])) elif mode == 2: configVal = str(bytearray([02, 00])) elif mode == 3: configVal = str(bytearray([03, 00])) else: raise Exception( "%s is not a valid mode. Please supply a value between 0 and 3 (inclusive)" % mode) class Requester(GATTRequester): def __init__(self, *args): GATTRequester.__init__(self, *args) def on_notification(self, originHandle, data): print "\nNotification on Handle" print "=======================" print format(originHandle, "#8x") utils.printHelper.printDataAndHex([data], False) #self.wakeup.set() def on_indication(self, originHandle, data): print "\nIndication on Handle" print "=======================" print format(originHandle, "#8x") utils.printHelper.printDataAndHex([data], False) #self.wakeup.set() class ReceiveNotification(object): def __init__(self, connectionManager, handles, configVal): logger.debug("Initializing receiver") self.connectionManager = connectionManager self.configVal = configVal self.handles = handles self.wait_notification() def connect(self): logger.debug("Connecting...") sys.stdout.flush() self.connectionManager.connect() #self.requester.connect(True) logger.debug("OK!") def wait_notification(self): print "Listening for communications" logger.debug("Listening for communications") #self.received.wait() while True: if self.connectionManager.isConnected(): continue logger.debug("Connection Lost, re-connecting subscribe") self.connectionManager.connect() for i in self.handles: bleServiceManager.bleServiceWriteToHandle( connectionManager, int(i, 16), self.configVal) #print "About to try to receive" connectionManager = bleConnectionManager.BLEConnectionManager( address, adapter, addressType, securityLevel, createRequester=False) #Special requester that has an overridden on_notification handler requester = Requester(address, False) connectionManager.setRequester(requester) connectionManager.connect() for handle in handles: logger.debug("Writing %s to handle %s" % (configVal, handle)) try: bleServiceManager.bleServiceWriteToHandle(connectionManager, int(handle, 16), configVal) except RuntimeError as e: if "Invalid handle" in str(e): data = -1 elif "Attribute can't be read" in str(e): data = -2 else: raise RuntimeError(e) ReceiveNotification(connectionManager, handles, configVal)
def bleServiceWrite(address, adapter, addressType, securityLevel, handles, inputs, maxTries=5): """ Used by command line tool to wrtie data to a device handle :param address: Address of target BTLE device :param adapter: Host adapter (Empty string to use host's default adapter) :param addressType: Type of address you want to connect to [public | random] :param securityLevel: Security level [low | medium | high] :param handles: List of handles to write to :param inputs: List of strings to write to handles :param maxTries: Maximum number of times to attempt each write operation. Default: 5 :type address: str :type adapter: str :type addressType: str :type securityLevel: str :type handles: list of base 10 ints :type inputs: list of strings :type maxTries: int :return: list of (handle, data, input) :rtype: list of tuples (int, str, str) """ connectionManager = bleConnectionManager.BLEConnectionManager( address, adapter, addressType, securityLevel) connectionManager.connect() #print "Input:",input handleData = [] for inputVal in inputs: for handle in handles: if handle is not None: tries = 0 while True: try: if not connectionManager.isConnected(): connectionManager.connect() data = bleServiceManager.bleServiceWriteToHandle( connectionManager, int(handle, 16), inputVal) break except RuntimeError as e: if "Invalid handle" in str(e): data = -1 break elif "Attribute can't" in str(e): data = -2 break else: if tries >= maxTries: logger.debug( "%s Tries exceeded, throwing Runtime error and aborting write" % maxTries) raise RuntimeError(e) else: logger.debug("Error: %s Trying Again" % e) tries += 1 handleData.append((handle, data, inputVal)) return handleData
def bleServiceWriteToHandle(self, handle, data): return bleServiceManager.bleServiceWriteToHandle(self.cm, handle, data)
def write(self, handle, data): bleServiceManager.bleServiceWriteToHandle(self.cm, handle, data)
def bleHandleSubscribe(address, handles, adapter, addressType, securityLevel, mode): """ Used by command line tool to enable specified handles' notify mode and listen until user interrupts. :param address: Address of target BTLE device :param handles: List of handle descriptors to write 0100 (enable notification) to :param adapter: Host adapter (Empty string to use host's default adapter) :param addressType: Type of address you want to connect to [public | random] :param securityLevel: Security level [low | medium | high] :param mode: Mode to set for characteristic configuration (0=off,1=notifications,2=indications, 3=notifications and inidications) :type address: str :type handles: list of base 10 ints :type adapter: str :type addressType: str :type securityLevel: str :type mode: int :return: """ logger.debug("Beginning Subscribe Function") if address is None: raise Exception("%s Bluetooth address is not valid. Please supply a valid Bluetooth address value." % address) if mode == 0: configVal = str(bytearray([00, 00])) elif mode == 1: configVal = str(bytearray([01, 00])) elif mode == 2: configVal = str(bytearray([02, 00])) elif mode == 3: configVal = str(bytearray([03, 00])) else: raise Exception("%s is not a valid mode. Please supply a value between 0 and 3 (inclusive)" % mode) class Requester(GATTRequester): def __init__(self, *args): GATTRequester.__init__(self, *args) def on_notification(self, originHandle, data): print "\nNotification on Handle" print "=======================" print format(originHandle, "#8x") utils.printHelper.printDataAndHex([data], False) #self.wakeup.set() def on_indication(self, originHandle, data): print "\nIndication on Handle" print "=======================" print format(originHandle, "#8x") utils.printHelper.printDataAndHex([data], False) #self.wakeup.set() class ReceiveNotification(object): def __init__(self, connectionManager, handles, configVal): logger.debug("Initializing receiver") self.connectionManager = connectionManager self.configVal = configVal self.handles = handles self.wait_notification() def connect(self): logger.debug("Connecting...") sys.stdout.flush() self.connectionManager.connect() #self.requester.connect(True) logger.debug("OK!") def wait_notification(self): print "Listening for communications" logger.debug("Listening for communications") #self.received.wait() while True: if self.connectionManager.isConnected(): continue logger.debug("Connection Lost, re-connecting subscribe") self.connectionManager.connect() for i in self.handles: bleServiceManager.bleServiceWriteToHandle(connectionManager, int(i, 16), self.configVal) #print "About to try to receive" connectionManager = bleConnectionManager.BLEConnectionManager(address, adapter, addressType, securityLevel, createRequester=False) #Special requester that has an overridden on_notification handler requester = Requester(address, False) connectionManager.setRequester(requester) connectionManager.connect() for handle in handles: logger.debug("Writing %s to handle %s" % (configVal, handle)) try: bleServiceManager.bleServiceWriteToHandle(connectionManager, int(handle, 16), configVal) except RuntimeError as e: if "Invalid handle" in str(e): data = -1 elif "Attribute can't be read" in str(e): data = -2 else: raise RuntimeError(e) ReceiveNotification(connectionManager, handles, configVal)