Exemplo n.º 1
0
 def on_att_event(self, connection_handle, data):
     from blesuite.pybt.att import ATT_PDU_OPCODE_BY_NAME
     if data.opcode == 0x1b:  #notification
         print("\nNotification on Handle %s" % hex(data.gatt_handle))
         print("=======================")
         #print format(originHandle, "#8x")
         print_helper.print_data_and_hex([data.value], False)
     elif data.opcode == 0x1d:  #indication
         print("\nIndication on Handle %s" % hex(data.gatt_handle))
         print("=======================")
         print_helper.print_data_and_hex([data.value], False)
Exemplo n.º 2
0
    def print_device_structure(self):
        """ Print device information, maintaining hierarchy of device, services, characteristics.

        :return:
        """
        print "\nDevice"
        print "======="
        print self.address, "\n"
        print "\nDevice Details"
        print "==============="
        for info in self.device_information:
            print info[0].upper() + ":"
            print "\tUUID:", info[1]
            if info[2] is not None:
                print "\tHandle:", "".join("{:02x}".format(ord(c))
                                           for c in info[2])
            else:
                print "\tHandle:"
            for val in info[3]:
                print_data_and_hex(val, False, prefix="\t")
        print "Services and Characteristics"
        print "============================="
        for service in self.services:
            print service.uuid, " start:", format(service.start, '#8x'), " end:", format(service.end, '#8x'),\
                  "type: ", service.get_type_string()
            for incl in service.includes:
                print "\tIncluded Service - Handle:", incl.handle, "Handles of included service:", \
                    format(incl.included_service_att_handle, '#8x'),\
                    "end group handle:", format(incl.included_service_end_group_handle, '#8x'), " Service UUID:", \
                    incl.included_service_uuid, " type: ", incl.get_type_string()
            for characteristic in service.characteristics:
                print "\t", characteristic.uuid, " value_handle:", format(characteristic.value_handle, '#8x'),\
                    " declaration handle:", format(characteristic.handle, '#8x'), " properties:", \
                    format(characteristic.gatt_properties, '#4x'), " permissions:", \
                    characteristic.calculate_permission(), " type: ", characteristic.get_type_string()
                for descriptor in characteristic.descriptors:
                    print "\t\tUUID:", descriptor.uuid
                    if descriptor.type is None:
                        print "\t\t\tType:"
                    else:
                        print "\t\t\tType: " + descriptor.type_string
                    print "\t\t\thandle:", format(descriptor.handle, '#8x')
                    #print "Raw:", descriptor.lastReadValue
                    if descriptor.value is not None:
                        if isinstance(descriptor.value, list):
                            for val in descriptor.value:
                                print_data_and_hex(val, False, prefix="\t\t\t")
                        else:
                            print_data_and_hex(descriptor.value,
                                               False,
                                               prefix="\t\t\t")

            print ""
        print "=============================\n"
Exemplo n.º 3
0
def process_args(args):
    """
    Process command line tool arguments parsed by argparse
    and call appropriate bleSuite functions.

    :param args: parser.parse_args()
    :return:
    """

    command = args.command[0]
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)

    timeout = args.timeout[0] * 1000 # convert seconds to ms

    if command == 'spoof':
        import bdaddr
        if args.address[0] == "":
            print "Please specify an address to spoof."
        else:
            logger.debug("About to spoof to address %s for adapter %s" % (args.address[0], args.adapter[0]))
            ret = bdaddr.bdaddr(("hci"+str(args.adapter[0])), args.address[0])
            if ret == -1:
                raise ValueError('Spoofing failed. Your device may not be supported.')

    if command == 'scan':
        print "BTLE Scan beginning"
        with BLEConnectionManager(args.adapter[0], 'central') as connection_manager:
            discovered = connection_manager.scan(timeout)

            print "Discovered:"
            for i in discovered.keys():
                print "\t", i, "(public)" if discovered[i][0] == 0 else "(random)"
                for h, j in enumerate(discovered[i][1]):
                    gap = connection_manager.decode_gap_data(str(discovered[i][1][h]))
                    info = connection_manager.generate_gap_data_dict(gap)
                    for k in info.keys():
                        print "\t\t", k + ":"
                        print "\t\t\t", info[k]

    if command == 'smartscan':
        print "BTLE Smart Scan beginning"
        device = ble_run_smart_scan(args.address[0], args.adapter[0],
                                    args.address_type[0], skip_device_info_query=args.skip_device_info_query,
                                    attempt_read=args.smart_read,
                                    timeout=timeout)

    if command == 'servicescan':
        print "BTLE Scanning Services"
        ble_service_scan(args.address[0], args.adapter[0],
                         args.address_type[0])

    if command == 'read':
        if len(args.handles) <= 0 and len(args.uuids) <= 0:
            print "ERROR: No handles or UUIDs supplied for read operation."
            return
        print "Reading value from handle or UUID"
        if args.async:
            uuidData, handleData = ble_service_read_async(args.address[0], args.adapter[0],
                                                          args.address_type[0],
                                                          args.handles, args.uuids,
                                                          timeout=timeout)
            for dataTuple in handleData:
                print "\nHandle:", "0x" + dataTuple[0]
                print_data_and_hex(dataTuple[1], False)
                '''
                if isinstance(dataTuple[1][0], str):
                    utils.print_helper.print_data_and_hex(dataTuple[1], False)
                else:
                    utils.print_helper.print_data_and_hex(dataTuple[1][1], False)'''
            for dataTuple in uuidData:
                print "\nUUID:", dataTuple[0]
                print_data_and_hex(dataTuple[1], False)
                '''
                if isinstance(dataTuple[1][0], str):
                    utils.print_helper.print_data_and_hex(dataTuple[1], False)
                else:
                    utils.print_helper.print_data_and_hex(dataTuple[1][1].received(), True)'''
        else:
            uuidData, handleData = ble_service_read(args.address[0], args.adapter[0],
                                                    args.address_type[0],
                                                    args.handles, args.uuids, timeout=timeout)
            for dataTuple in handleData:
                print "\nHandle:", "0x" + dataTuple[0]
                print_data_and_hex(dataTuple[1], False)
            for dataTuple in uuidData:
                print "\nUUID:", dataTuple[0]
                print_data_and_hex(dataTuple[1], False)

    if command == 'write':
        if len(args.handles) <= 0:
            print "ERROR: No handles supplied for write operation. Note: Write operation does not support use of UUIDs."
            return
        print "Writing value to handle"
        if args.async:
            logger.debug("Async Write")
            if len(args.data) > 0:
                handleData = ble_service_write_async(args.address[0], args.adapter[0],
                                                     args.address_type[0],
                                                     args.handles, args.data,
                                                     timeout=timeout)
            elif args.payload_delimiter[0] == 'EOF':
                logger.debug("Payload Delimiter: EOF")
                dataSet = []
                for dataFile in args.files:
                    if dataFile is None:
                        continue
                    logger.debug("Reading file: %s", dataFile)
                    f = open(dataFile, 'r')
                    dataSet.append(f.read())
                    f.close()
                logger.debug("Sending data set: %s" % dataSet)
                handleData = ble_service_write_async(args.addr[0], args.adapter[0],
                                                     args.address_type[0],
                                                     args.handles, dataSet,
                                                     timeout=timeout)
                logger.debug("Received data: %s" % handleData)
                '''for dataTuple in handleData:
                    print "\nHandle:", "0x" + dataTuple[0]
                    utils.print_helper.print_data_and_hex(dataTuple[1], False)'''
            else:
                logger.debug("Payload Delimiter: %s", args.payload_delimiter[0])
                dataSet = []
                for dataFile in args.files:
                    if dataFile is None:
                        continue
                    f = open(dataFile, 'r')
                    data = f.read()
                    f.close()
                    data = data.split(args.payload_delimiter[0])
                    dataSet.extend(data)

                logger.debug("Sending dataSet: %s" % dataSet)

                handleData = ble_service_write_async(args.address[0], args.adapter[0],
                                                     args.address_type[0],
                                                     args.handles, dataSet,
                                                     timeout=timeout)
            for dataTuple in handleData:
                print "\nHandle:", "0x" + dataTuple[0]
                print "Input:"
                utils.print_helper.print_data_and_hex(dataTuple[2], False, prefix="\t")
                print "Output:"
                #if tuple[1][0] is a string, it means our cmdLineToolWrapper removed the GattResponse object
                #due to a timeout, else we grab the GattResponse and its response data
                if isinstance(dataTuple[1][0], str):
                    utils.print_helper.print_data_and_hex(dataTuple[1], False, prefix="\t")
                else:
                    utils.print_helper.print_data_and_hex(dataTuple[1][1].received(), False, prefix="\t")
        else:
            logger.debug("Sync Write")
            print args.data
            if len(args.data) > 0:
                handleData = ble_service_write(args.address[0], args.adapter[0],
                                               args.address_type[0],
                                               args.handles, args.data, timeout=timeout)

                '''for dataTuple in handleData:
                    print "\nHandle:", "0x" + dataTuple[0]
                    utils.print_helper.print_data_and_hex(dataTuple[1], False)'''

            elif args.payload_delimiter[0] == 'EOF':
                logger.debug("Payload Delimiter: EOF")
                dataSet = []
                for dataFile in args.files:
                    if dataFile is None:
                        continue
                    logger.debug("Reading file: %s", dataFile)
                    f = open(dataFile, 'r')
                    dataSet.append(f.read())
                    f.close()
                logger.debug("Sending data set: %s" % dataSet)
                handleData = ble_service_write(args.address[0], args.adapter[0],
                                               args.address_type[0],
                                               args.handles, dataSet, timeout=timeout)
                logger.debug("Received data: %s" % handleData)
                '''for dataTuple in handleData:
                    print "\nHandle:", "0x" + dataTuple[0]
                    utils.print_helper.print_data_and_hex(dataTuple[1], False)'''
            else:
                logger.debug("Payload Delimiter: %s", args.payload_delimiter[0])
                dataSet = []
                for dataFile in args.files:
                    if dataFile is None:
                        continue
                    f = open(dataFile, 'r')
                    data = f.read()
                    f.close()
                    data = data.split(args.payload_delimiter[0])
                    dataSet.extend(data)
                logger.debug("Sending dataSet: %s" % dataSet)
                handleData = ble_service_write(args.address[0], args.adapter[0],
                                               args.address_type[0],
                                               args.handles, dataSet, timeout=timeout)
            for dataTuple in handleData:
                print "\nHandle:", "0x" + dataTuple[0]
                print "Input:"
                print_data_and_hex([dataTuple[2]], False, prefix="\t")
                print "Output:"
                print_data_and_hex(dataTuple[1], False, prefix="\t")

    if command == 'subscribe':
        print "Subscribing to device"
        if args.subscribe_timeout[0] is not None:
            timeout = args.subscribe_timeout[0] * 1000
        else:
            timeout = None
        ble_handle_subscribe(args.address[0], args.handles, args.adapter[0],
                             args.address_type[0], args.mode[0], timeout)

    return