コード例 #1
0
def device_inquiry_with_with_rssi(sock):
    # save current filter
    old_filter = sock.getsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, flt)

    duration = 4
    max_responses = 255
    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
    bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)

    results = []

    while True:
        pkt = sock.recv(255)
        ptype, event, plen = struct.unpack("BBB", pkt[:3])
        print("Event: {}".format(event))
        if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                rssi = bluetooth.byte_to_signed_int(
                    bluetooth.get_byte(pkt[1 + 13 * nrsp + i]))
                results.append((addr, rssi))
                print("[{}] RSSI: {}".format(addr, rssi))

                rssi = (pkt[-1])
                print(addr, rssi)
        elif event == bluez.EVT_INQUIRY_COMPLETE:
            break
        elif event == bluez.EVT_CMD_STATUS:
            status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
            if status:
                print("Uh oh...")
                printpacket(pkt[3:7])
                break
        elif event == bluez.EVT_INQUIRY_RESULT:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                results.append((addr, -1))
                print("[{}] (no RRSI)".format(addr))
                rssi = (pkt[-1])
                print(addr, rssi)
        else:
            print("Unrecognized packet type 0x{:02x}.".format(ptype))

    # restore old filter
    sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, old_filter)

    return results
コード例 #2
0
ファイル: fetch_rssi.py プロジェクト: Cleanshooter/fetch_rssi
def fetch_rssi(socket, bdaddr):
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    socket.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
    
    cmd_pkt = struct.pack("????")
    bluez.hci_send_cmd(socket, bluez.OGF_LINK_CTL, bluez.OCF_READ_RSSI, cmd_pkt)

    pkt = socket.recv(255)
    ptype, event, plen = struct.unpack("BBB", pkt[:3])
    if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
        pkt = pkt[3:]
        nrsp = bluetooth.get_byte(pkt[0])
        for i in range(nrsp):
            addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
            rssi = bluetooth.byte_to_signed_int(
                    bluetooth.get_byte(pkt[1+13*nrsp+i]))
            results.append( ( addr, rssi ) )
            print("[%s] RSSI: [%d]" % (addr, rssi))
    elif event == bluez.EVT_CMD_STATUS:
        status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
        if status != 0:
            print("uh oh...")
            done = True
    elif event == bluez.EVT_INQUIRY_RESULT:
        pkt = pkt[3:]
        nrsp = bluetooth.get_byte(pkt[0])
        for i in range(nrsp):
            addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
            results.append( ( addr, -1 ) )
            print("[%s] (no RRSI)" % addr)
    else:
        print("unrecognized packet type 0x%02x" % ptype)
    print("event ", event)
コード例 #3
0
    def _device_inquiry_with_with_rssi(self, sock):
        """inquiry blutooth devices with rssi"""
        # save current filter
        old_filter = sock.getsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, 14)

        # perform a device inquiry on bluetooth device #0
        # The inquiry should last 8 * 1.28 = 10.24 seconds
        # before the inquiry is performed, bluez should flush its cache of
        # previously discovered devices
        flt = bluez.hci_filter_new()
        bluez.hci_filter_all_events(flt)
        bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
        sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, flt)

        duration = 4
        max_responses = 255
        cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration,
                              max_responses)
        bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY,
                           cmd_pkt)

        results = []

        done = False
        while not done:
            pkt = sock.recv(255)
            ptype, event, plen = struct.unpack("BBB", pkt[:3])
            if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
                pkt = pkt[3:]
                nrsp = bluetooth.get_byte(pkt[0])
                for i in range(nrsp):
                    addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                    rssi = bluetooth.byte_to_signed_int(
                        bluetooth.get_byte(pkt[1 + 13 * nrsp + i]))
                    results.append(
                        (addr, rssi, str(datetime.datetime.utcnow())))

            elif event == bluez.EVT_INQUIRY_COMPLETE:
                done = True
            elif event == bluez.EVT_CMD_STATUS:
                status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
                if status != 0:
                    print("uh oh...")
                    self._print_packet(pkt[3:7])
                    done = True
            elif event == bluez.EVT_INQUIRY_RESULT:
                pkt = pkt[3:]
                nrsp = bluetooth.get_byte(pkt[0])
                for i in range(nrsp):
                    addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                    results.append((addr, -1, str(datetime.datetime.utcnow())))
            else:
                print("unrecognized packet type 0x%02x" % ptype)

        # restore old filter
        sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, old_filter)

        return results
コード例 #4
0
ファイル: br.py プロジェクト: rhnvrm/iot-hackerearth
def device_inquiry_with_with_rssi(sock):
    # save current filter
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )

    duration = 4
    max_responses = 255
    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
    bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)

    results = []

    done = False
    while not done:
        pkt = sock.recv(255)
        ptype, event, plen = struct.unpack("BBB", pkt[:3])
        if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                rssi = bluetooth.byte_to_signed_int(
                        bluetooth.get_byte(pkt[1+13*nrsp+i]))
                name = bluetooth.lookup_name( addr )
                results.append( ( addr, rssi, name) )
                print("[%s]  RSSI: [%d] NAME: [%s]" % (addr,  rssi, name))
        elif event == bluez.EVT_INQUIRY_COMPLETE:
            done = True
        elif event == bluez.EVT_CMD_STATUS:
            status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
            if status != 0:
                print("uh oh...")
                printpacket(pkt[3:7])
                done = True
        elif event == bluez.EVT_INQUIRY_RESULT:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                results.append( ( addr, -1 ) )
                print("[%s] (no RRSI)" % addr)
        else:
            if(testing): print("unrecognized packet type 0x%02x" % ptype)
        if(testing): print("event ", event)


    # restore old filter
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )

    return results
def device_inquiry_with_with_rssi(sock):
    # save current filter
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
    #filter

    duration = 4
    max_responses = 255
    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
    bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)
    #send command

    results = []

    done = False
    while not done:
        pkt = sock.recv(255)
        ptype, event, plen = struct.unpack("BBB", pkt[:3])
        if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                rssi = bluetooth.byte_to_signed_int(
                        bluetooth.get_byte(pkt[1+13*nrsp+i]))
                        results.append( ( addr, rssi ) )# store rssi and mac
                print("[%s] RSSI: [%d]" % (addr, rssi))
        elif event == bluez.EVT_INQUIRY_COMPLETE:
            #scanning complete
            done = True
コード例 #6
0
ファイル: rssi.py プロジェクト: EdWard680/goose
def get_rssis(addrs):
    try:
        sock = bt.hci_open_dev()
    except:
        print("error accessing bluetooth device...")
        sys.exit(1)

    try:
        mode = read_inquiry_mode(sock)
    except Exception as e:
        print("error reading inquiry mode.  ")
        print("Are you sure this a bluetooth 1.2 device?")
        print(e)
        sys.exit(1)

    if mode != 1:
        try:
            result = write_inquiry_mode(sock, 1)
        except Exception as e:
            print("error writing inquiry mode.  Are you sure you're root?")
            print(e)
            sys.exit(1)
        if result != 0:
            print("error while setting inquiry mode")

    # save current filter
    old_filter = sock.getsockopt(bt.SOL_HCI, bt.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bt should flush its cache of
    # previously discovered devices
    flt = bt.hci_filter_new()
    bt.hci_filter_all_events(flt)
    bt.hci_filter_set_ptype(flt, bt.HCI_EVENT_PKT)
    sock.setsockopt(bt.SOL_HCI, bt.HCI_FILTER, flt)

    while True:
        duration = 4
        max_responses = 255
        cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration,
                              max_responses)
        bt.hci_send_cmd(sock, bt.OGF_LINK_CTL, bt.OCF_INQUIRY, cmd_pkt)

        results = []

        done = False
        while not done:
            pkt = sock.recv(255)
            ptype, event, plen = struct.unpack("BBB", pkt[:3])
            if event == bt.EVT_INQUIRY_RESULT_WITH_RSSI:
                pkt = pkt[3:]
                nrsp = bluetooth.get_byte(pkt[0])
                for i in range(nrsp):
                    addr = bt.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                    if addr in addrs:
                        rssi = bluetooth.byte_to_signed_int(
                            bluetooth.get_byte(pkt[1 + 13 * nrsp + i]))
                        yield (addr, rssi)
            elif event == bt.EVT_INQUIRY_COMPLETE:
                done = True
            elif event == bt.EVT_CMD_STATUS:
                status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
                if status != 0:
                    print("uh oh...")
                    printpacket(pkt[3:7])
                    done = True
                    sock.setsockopt(bt.SOL_HCI, bt.HCI_FILTER, old_filter)
                    sys.exit(1)

    # restore old filter
    sock.setsockopt(bt.SOL_HCI, bt.HCI_FILTER, old_filter)
コード例 #7
0
def device_inquiry_with_with_rssi(sock):
    # save current filter
    old_filter = sock.getsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, flt)

    duration = 1
    max_responses = 255
    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
    while True:
        bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY,
                           cmd_pkt)
        results = []

        done = False
        while not done:
            pkt = sock.recv(255)
            ptype, event, plen = struct.unpack("BBB", pkt[:3])
            if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
                pkt = pkt[3:]
                nrsp = bluetooth.get_byte(pkt[0])
                for i in range(nrsp):
                    addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                    rssi = bluetooth.byte_to_signed_int(
                        bluetooth.get_byte(pkt[1 + 13 * nrsp + i]))
                    #     results.append( ( addr, rssi ) )
                    if "98:00" in str(addr) or "30:6A" in str(
                            addr) or 'D4' in str(addr):
                        print("[%s] RSSI: [%d]" % (addr, rssi))
                        #send request to server
                        #serialize json
                        params = {'id': id, 'address': addr, 'rssi': rssi}
                        a = requests.post(
                            'http://76339ea5.ngrok.io/read_points',
                            json=params,
                            headers={'Connection': 'close'})
                        requests.map([a])
            elif event == bluez.EVT_INQUIRY_COMPLETE:
                done = True
            elif event == bluez.EVT_CMD_STATUS:
                status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
                if status != 0:
                    print("uh oh...")
                    printpacket(pkt[3:7])
                    done = True
            elif event == bluez.EVT_INQUIRY_RESULT:
                pkt = pkt[3:]
                nrsp = bluetooth.get_byte(pkt[0])
                for i in range(nrsp):
                    addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                    results.append((addr, -1))
                    print("[%s] (no RRSI)" % addr)
            else:
                print("unrecognized packet type 0x%02x" % ptype)

    # restore old filter
    sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, old_filter)

    return results
コード例 #8
0
    def device_inquiry_with_with_rssi(self, sock):
        # save current filter
        old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

        # perform a device inquiry on bluetooth device #0
        # The inquiry should last 8 * 1.28 = 10.24 seconds
        # before the inquiry is performed, bluez should flush its cache of
        # previously discovered devices
        flt = bluez.hci_filter_new()
        bluez.hci_filter_all_events(flt)
        bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
        sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )

        duration = 1
        max_responses = 255
        cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
        bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)

        results = []

        done = False
        while not done:
            pkt = sock.recv(255)
            ptype, event, plen = struct.unpack("BBB", pkt[:3])
            if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
                pkt = pkt[3:]
                nrsp = bluetooth.get_byte(pkt[0])
                for i in range(nrsp):
                    addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                    rssi = bluetooth.byte_to_signed_int(
                        bluetooth.get_byte(pkt[1+13*nrsp+i]))
                    results.append( ( addr, rssi ) )
                    #print("[%s] RSSI: [%d]" % (addr, rssi))

                    # If we found the target device print it 
                    if addr == self.target_Address:
                        print("Found The Target: [%s] " % (addr))
                        print("Target's RSSI   : [%s] " % (rssi))

                        # Set the RSSI if we have our target
                        # Set that we found it as well.
                        # Then break out, since we do not need
                        # to search any more.
                        self.setRSSI(rssi)
                        self.setFoundDevice(True)
                        break
            elif event == bluez.EVT_INQUIRY_COMPLETE:
                done = True
            elif event == bluez.EVT_CMD_STATUS:
                status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
                if status != 0:
                    print("uh oh...")
                    printpacket(pkt[3:7])
                    done = True
            elif event == bluez.EVT_INQUIRY_RESULT:
                pkt = pkt[3:]
                nrsp = bluetooth.get_byte(pkt[0])
                for i in range(nrsp):
                    addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                    results.append( ( addr, -1 ) )
                    print("[%s] (no RRSI)" % addr)
            else:
                print("unrecognized packet type 0x%02x" % ptype)
                self.printpacket(pkt)
                
           # print("event ", event)

        # restore old filter
        sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )

        return results
コード例 #9
0
def device_inquiry_with_with_rssi(sock):
    global  Send_Flag
    #Get GPS Coordinate 
    report = session.next()
    
    # save current filter
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )

    duration = 4
    max_responses = 255
    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
    bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)

    results = []

    done = False
    while not done:
        pkt = sock.recv(255)
        ptype, event, plen = struct.unpack("BBB", pkt[:3])
        if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                rssi = bluetooth.byte_to_signed_int(
                        bluetooth.get_byte(pkt[1+13*nrsp+i]))
                results.append( ( addr, rssi ) )
                #Compare device addr is connected device
                if addr == dev_addr:
                    power = (abs(rssi)-59)/(10*2.0)
                    meter = pow(10, power)
                    print("[%s] RSSI: [%d]" % (addr, rssi))
                    print("Distance: [%.2f]" % meter)
                    if meter > 0.5:
                        #buzzer warning
                        GPIO.output(23, GPIO.HIGH)
                        time.sleep(1)
                        GPIO.output(23, GPIO.LOW)
                        time.sleep(1)
                        #change GPS coordinate
                        loc = wgs2bd(report.lat,report.lon)
                        #Send GPS Info E-mail
                        if os.path.exists('/home/pi/MarkPoint.html'):
                            Send_Flag = 0
                        else:
                            Send_Flag = 1
                            #Generate HTML File
                            generate(loc[0],loc[1])
                        if Send_Flag:
                            Send_Flag = 0
                            yag = yagmail.SMTP(user = '******', password = '******', host = 'smtp.qq.com')
                            yag.send(to = [mail_addr],subject = 'GPS Map',contents = ['GPS Coordinate','/home/pi/MarkPoint.html'])
        
        elif event == bluez.EVT_INQUIRY_COMPLETE:
            done = True
        elif event == bluez.EVT_CMD_STATUS:
            status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
            if status != 0:
                print("uh oh...")
                printpacket(pkt[3:7])
                done = True
        elif event == bluez.EVT_INQUIRY_RESULT:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                results.append( ( addr, -1 ) )
                print("[%s] (no RRSI)" % addr)
        #else:
        #    print("unrecognized packet type 0x%02x" % ptype)
        #print("event ", event)
        
    # restore old filter
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )

    return results
コード例 #10
0
ファイル: _bluetooth.py プロジェクト: mkhlz/signalum
def device_inquiry_with_with_rssi(sock, show_name=False, show_extra_info=False, color=True, ret_table=False):
    global LOADING_HANDLER
    
    # save current filter
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )

    duration = 1
    max_responses = 255
    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
    # TODO Optimize code for performance
    # update the global device name dictionary before sending hci cmd(which changes mode)
    headers =["Name", "MAC Address", "RSSI"]
    data = []
    results = []
    if show_extra_info or show_name:
        devices = bluetooth.discover_devices(lookup_names=True, lookup_class=True)
        if show_name:
            update_dict = {i[0]: i[1] for i in devices}
            NAME_DICT.update(update_dict)
        if show_extra_info:
            update_dict = {i[0]: i[2] for i in devices}
            CLASS_DICT.update(update_dict)
            headers.extend(["Major Dev Class", "Minor Dev Class", "Services"])
            populate_info_dict()
    bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)
            


    done = False
    while not done:
        pkt = sock.recv(255)
        ptype, event, plen = struct.unpack("BBB", pkt[:3])
        if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                # get human readable addr
                addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                rssi = bluetooth.byte_to_signed_int(
                        bluetooth.get_byte(pkt[1+13*nrsp+i]))
                # retrieve device name, or assign address as name
                try:
                    name = NAME_DICT[addr]
                except:
                    name = addr
                results.append( ( addr, rssi, name ) )
                if color:
                    data.append([name, addr, rssi_to_colour_str(rssi)])
                else:
                    data.append([name, addr, rssi])
                if show_extra_info:
                    extra_info = get_device_extra(addr)
                    # extend last data list with extra info
                    data[-1].extend(extra_info)
        elif event == bluez.EVT_INQUIRY_COMPLETE:
            done = True
        elif event == bluez.EVT_CMD_STATUS:
            status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
            if status != 0:
                print("uh oh...")
                printpacket(pkt[3:7])
                done = True
        elif event == bluez.EVT_INQUIRY_RESULT:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
                results.append( ( addr, -1 , "UNK") )
                print("[%s] (no RRSI)" % addr)
        else:
            logging.debug("unrecognized packet type 0x%02x" % ptype)
        logging.debug("event %s", event)

    # restore old filter
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
    # if ordered to return a table by analyze_all, ignore other sequence
    if ret_table:
        if len(results) < 1:
            return ( (None, headers ))
        return( (data, headers) )
    else:
        # print all the data at once since blessings clears the screen just before
        if len(results)>= 1:
            # terminate concurrent loading handler
            if bool(LOADING_HANDLER):
                LOADING_HANDLER.terminate()
            show_header("BLUETOOTH")
            print(tabulate(data, headers=headers, disable_numparse=True))
        else:
            # LOADING_HANDLER = spin(before="Searching",
            #                    after="\nNo devices found in nearby range")
            LOADING_HANDLER.terminate()
            LOADING_HANDLER = spin(before="No BT devices in nearby range")
        return results
コード例 #11
0
def device_inquiry(sock, cycle_period, hash_addrs, log_out, device_queue):

    # save current filter
    old_filter = sock.getsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    filtr = bluez.hci_filter_new()
    bluez.hci_filter_all_events(filtr)
    bluez.hci_filter_set_ptype(filtr, bluez.HCI_EVENT_PKT)
    sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, filtr)

    max_responses = 255
    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, int(cycle_period / 1.25),
                          max_responses)
    bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)

    #While still scanning
    done = False
    while not done:
        sock.settimeout(5)
        try:
            pkt = sock.recv(255)
        except:
            break
        ptype, event, plen = struct.unpack("BBB", pkt[:3])
        #Enquiry result with rssi
        if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                if (hash_addrs):
                    addr = hashlib.sha224(addr.replace(":", "")).hexdigest()
                rssi = bluetooth.byte_to_signed_int(
                    bluetooth.get_byte(pkt[1 + 13 * nrsp + i]))
                register_device(addr, rssi, log_out, device_queue)

        #Enquiry result without rssi
        elif event == bluez.EVT_INQUIRY_RESULT:
            pkt = pkt[3:]
            nrsp = bluetooth.get_byte(pkt[0])
            for i in range(nrsp):
                addr = bluez.ba2str(pkt[1 + 6 * i:1 + 6 * i + 6])
                if (hash_addrs):
                    addr = hashlib.sha224(addr.replace(":", "")).hexdigest()
                register_device(addr, None, log_out, device_queue)

        #On finish
        elif event == bluez.EVT_INQUIRY_COMPLETE:
            done = True

        #Status update?
        elif event == bluez.EVT_CMD_STATUS:
            status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
            if status != 0:
                done = True

    # restore old filter
    sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, old_filter)
    return
コード例 #12
0
ファイル: inquire.py プロジェクト: terbo/sigmon
  def device_inquiry_with_with_rssi(self, sock,verbose=False):
    # save current filter
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    # perform a device inquiry on bluetooth device #0
    # The inquiry should last 8 * 1.28 = 10.24 seconds
    # before the inquiry is performed, bluez should flush its cache of
    # previously discovered devices
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )

    cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, self.duration, self.max_responses)
    bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)

    results = []

    done = False
    
    while not done:
      pkt = sock.recv(255)
      ptype, event, plen = struct.unpack("BBB", pkt[:3])
      if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
        pkt = pkt[3:]
        nrsp = bluetooth.get_byte(pkt[0])
        for i in range(nrsp):
          addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
          rssi = bluetooth.byte_to_signed_int(
              bluetooth.get_byte(pkt[1+13*nrsp+i]))
          devclass_raw = struct.unpack ("BBB",
                  pkt[1+8*nrsp+3*i:1+8*nrsp+3*i+3])
          devclass = (devclass_raw[2] << 16) | \
                 (devclass_raw[1] << 8) | \
                 devclass_raw[0]
          try:
            name = bluetooth.lookup_name(addr)
          except:
            name = 'unknown'
          time = datetime.datetime.now().isoformat()
          results.append( [time, addr, name, rssi, devclass] )
          if verbose:
            print("%s,%s,%s,%s,%s" % (time,addr,name, rssi, devclass))
      elif event == bluez.EVT_INQUIRY_COMPLETE:
        done = True
      elif event == bluez.EVT_CMD_STATUS:
        status, ncmd, opcode = struct.unpack("BBH", pkt[3:7])
        if status != 0:
          print("uh oh...")
          printpacket(pkt[3:7])
          done = True
      elif event == bluez.EVT_INQUIRY_RESULT:
        pkt = pkt[3:]
        nrsp = bluetooth.get_byte(pkt[0])
        for i in range(nrsp):
          addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] )
          results.append( ( addr, -1 ) )
          if verbose:
            print("[%s] (no RRSI)" % addr)
      else:
        print("unrecognized packet type 0x%02x" % ptype)
      if verbose:
        print("event ", event)

    # restore old filter
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )

    return results
コード例 #13
0
try:
    sock = bluez.hci_open_dev(dev_id)
except:
    print('Error accessing bluetooth device.')
    sys.exit(1)

pkt = sock.recv(255)
ptype, event, plen = struct.unpack("BBB", pkt[:3])
print("Event: {}".format(event))


if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
    pkt = pkt[3:]
    nrsp = bluetooth.get_byte(pkt[0])
    for i in range(nrsp):
        addr = bluez.ba2str(pkt[1+6*i:1+6*i+6])
        rssi = bluetooth.byte_to_signed_int(
               bluetooth.get_byte(pkt[1 + 13 * nrsp + i]))
        results.append((addr, rssi))
        print("[{}] RSSI: {}".format(addr, rssi))

# https://github.com/pybluez/pybluez/blob/d7f36702bba2abc8ea41977b2eea56a17431ac6d/examples/advanced/inquiry-with-rssi.py#L18

# https://www.icode9.com/content-1-572771.

# https://www.cnblogs.com/wuyida/archive/2013/03/27/6300007.html

# https://github.com/ewenchou/bluetooth-proximity/blob/master/bt_proximity/bt_rssi.py

コード例 #14
0
# The inquiry should last 8 * 1.28 = 10.24 seconds
# before the inquiry is performed, bluez should flush its cache of
# previously discovered devices
flt = bluez.hci_filter_new()
bluez.hci_filter_all_events(flt)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )

duration = 4
max_responses = 255
cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses)
bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt)


nearby_devices = bluetooth.discover_devices()

for bdaddr in nearby_devices:

    #if target_name == bluetooth.lookup_name( bdaddr ):
        #target_address = bdaddr
        #break
    pkt = sock.recv(255)
    rssi = bluetooth.byte_to_signed_int(bluetooth.get_byte(pkt[1+13*nrsp+i])) 
    print bdaddr 

#if target_address is not None:
    #print "found target bluetooth device with address ", target_address
#else:
    #print "could not find target bluetooth device nearby"