コード例 #1
0
def hci_cc(adapter: int, ps4btaddr: str) -> None:
    import bluetooth._bluetooth as _bt

    try:
        hci_sock = _bt.hci_open_dev(adapter)

        # Get bytes from bluetooth address
        baps4addr = bytearray.fromhex(ps4btaddr.replace(":", ""))
        baps4addr.reverse()
        # HCI CONNECT
        # BLUETOOTH SPECIFICATION Version 5.0 | Vol 2, Part E page 774
        # https://github.com/pauloborges/bluez/blob/master/tools/hcitool.c => cmd_cc
        # https://github.com/pauloborges/bluez/blob/master/lib/hci.c => hci_create_connection
        cmd_pkt = bytes(
            baps4addr
        ) + bytes([  # Target BTADDR on 6 bytes reverse order,
            0x18,
            0xCC,  # pkt_type HCI_DM1 | HCI_DM3 | HCI_DM5 | HCI_DH1 | HCI_DH3 | HCI_DH5
            0x02,  # pscan_rep_mode
            0x00,  # pscan_mode (reserved)
            0x00,
            0x00,  # clock_offset
            0x01
        ])  # role_switch

        # Send HCI request
        _bt.hci_send_req(hci_sock, _bt.OGF_LINK_CTL, _bt.OCF_CREATE_CONN,
                         _bt.EVT_CONN_COMPLETE, 1000, cmd_pkt)
        hci_sock.close()

    except _bt.error as e:
        raise BluetoothError(*e.args)
コード例 #2
0
def bcm_write_local_bdaddr(adapter: int, dsbtaddr: str) -> None:
    import bluetooth._bluetooth as _bt

    try:
        # Open hci socket
        hci_sock = _bt.hci_open_dev(adapter)

        # Get bytes from bluetooth address
        baddrtospoof = bytearray.fromhex(dsbtaddr.replace(":", ""))
        baddrtospoof.reverse()

        # Send HCI request
        cmd_pkt = bytes(baddrtospoof)

        # BCM WRITE ADDR command
        # https://github.com/pauloborges/bluez/blob/master/tools/bdaddr.c
        _bt.hci_send_req(
            hci_sock,
            _bt.OGF_VENDOR_CMD,
            0x0001,  #OCF_BCM_WRITE_BD_ADDR
            0x00000000,
            1000,
            cmd_pkt)

        hci_sock.close()

    except _bt.error as e:
        raise BluetoothError(*e.args)
コード例 #3
0
    def getRSSI(self):
        """Detects whether the device is near by or not"""
        addr = self.address
		
        # Open hci socket
        hci_sock = bt.hci_open_dev()
        hci_fd = hci_sock.fileno()

        # Connect to device (to whatever you like)
        bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
        bt_sock.settimeout(10)
        result = bt_sock.connect_ex((addr, 1))	# PSM 1 - Service Discovery

        try:
            # Get ConnInfo
            reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
            request = array.array("c", reqstr )
            handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
            handle = struct.unpack("8xH14x", request.tostring())[0]

            # Get RSSI
            cmd_pkt=struct.pack('H', handle)
            rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                         bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
            rssi = struct.unpack('b', rssi[3])[0]

            # Close sockets
            bt_sock.close()
            hci_sock.close()

            return rssi

        except Exception, e:
            return None
コード例 #4
0
def get_RSSI(addr):
    # Open an hci socket
    hci_sock = bluez.hci_open_dev()
    hci_fd = hci_sock.fileno()

    # Try to open a connection to remote BT device
    try:
        bt_sock = bluez.SDPSession()
        bt_sock.connect(addr)
    except:
        bt_sock.close()
        hci_sock.close()
        return None
    # Get handle to ACL connection to remote BT device
    reqstr = struct.pack("6sB17s", bluez.str2ba(addr), bluez.ACL_LINK,
                         "\0" * 17)
    request = array.array("c", reqstr)
    fcntl.ioctl(hci_fd, bluez.HCIGETCONNINFO, request, 1)
    handle = struct.unpack("8xH14x", request.tostring())[0]

    # Get RSSI
    cmd_pkt = struct.pack('H', handle)
    RSSI = bluez.hci_send_req(hci_sock, bluez.OGF_STATUS_PARAM,
                              bluez.OCF_READ_RSSI, bluez.EVT_CMD_COMPLETE, 4,
                              cmd_pkt)
    RSSI = struct.unpack('b', RSSI[3])[0]

    bt_sock.close()
    hci_sock.close()
    return RSSI
コード例 #5
0
def bluetooth_rssi(addr):
    # Open hci socket
    hci_sock = bt.hci_open_dev()
    hci_fd = hci_sock.fileno()

    # Connect to device (to whatever you like)
    bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bt_sock.settimeout(10)
    result = bt_sock.connect_ex((addr, 1))	# PSM 1 - Service Discovery

    try:
        # Get ConnInfo
        reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
        request = array.array("c", reqstr )
        handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
        handle = struct.unpack("8xH14x", request.tostring())[0]

        # Get RSSI
        cmd_pkt=struct.pack('H', handle)
        rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                     bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
        rssi = struct.unpack('b', rssi[3])[0]

        # Close sockets
        bt_sock.close()
        hci_sock.close()

        return rssi

    except:
        return None
コード例 #6
0
    def get_rssi(self):
        """Gets the current RSSI value.
        @return: The RSSI value (float) or None if the device connection fails
                 (i.e. the device is nowhere nearby).
        """
        try:
            self.connect()
            if not self.connected:
                return -99

            if self.cmd_pkt is None:
                self.prep_cmd_pkt()
            # Send command to request RSSI
            rssi = bt.hci_send_req(self.hci_sock, bt.OGF_STATUS_PARAM,
                                   bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4,
                                   self.cmd_pkt)

            rssi_int = rssi[3]
            rssi_bytes = rssi_int.to_bytes((rssi_int.bit_length() + 7) // 8,
                                           'big')
            rssi = struct.unpack('b', rssi_bytes)[0]

            return rssi
        except IOError:
            # Happens if connection fails (e.g. device is not in range)
            self.connected = False

            return -99
        except struct.error:
            # Invalid RSSI value returned

            return None
コード例 #7
0
    def getRSSI(self):
        """Detects whether the device is near by or not using RSSI"""
        addr = self.address
		
        # Open hci socket
        hci_sock = bt.hci_open_dev()
        hci_fd = hci_sock.fileno()

        # Connect to device (to whatever you like)
        bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
        bt_sock.settimeout(10)
        result = bt_sock.connect_ex((addr, 1))	# PSM 1 - Service Discovery

        try:
            # Get ConnInfo
            reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
            request = array.array("c", reqstr )
            handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
            handle = struct.unpack("8xH14x", request.tostring())[0]

            # Get RSSI
            cmd_pkt=struct.pack('H', handle)
            rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                         bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
            rssi = struct.unpack('b', rssi[3])[0]

            # Close sockets
            bt_sock.close()
            hci_sock.close()

            return rssi

        except Exception, e:
            #self.logger.error("<Bluetooth> (getRSSI) %s" % (repr(e)))
            return None
コード例 #8
0
    def request_rssi(self):
        """Request the current RSSI value.
        @return: The RSSI value or None if the device connection fails
                 (i.e. the device is not in range).
        """
        try:
            # If socket is closed, return nothing
            if self.closed:
                return None
            # Only do connection if not already connected
            if not self.connected:
                self.connect()
            # Command packet prepared each iteration to allow disconnect to trigger IOError
            self.prep_cmd_pkt()

            # print('cmd packet is {}'.format(self.cmd_pkt))
            # Send command to request RSSI
            rssi = bt.hci_send_req(
                self.hci_sock, bt.OGF_STATUS_PARAM,
                bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, self.cmd_pkt)

            if len(rssi) < 4:
                print('RSSI IS NONE')
                return None

            rssi = struct.unpack('b', rssi[3].to_bytes(1, 'big'))
            return rssi
        except IOError:
            # Happens if connection fails (e.g. device is not in range)
            self.connected = False
            # Socket recreated to allow device to successfully reconnect
            self.bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
            return None
コード例 #9
0
def bluetooth_rssi(addr):
    # Open hci socket
    hci_sock = bt.hci_open_dev()
    hci_fd = hci_sock.fileno()

    # Connect to device (to whatever you like)
    bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bt_sock.settimeout(10)
    result = bt_sock.connect_ex((addr, 1))  # PSM 1 - Service Discovery

    try:
        # Get ConnInfo
        reqstr = struct.pack('6sB17s', bt.str2ba(addr), bt.ACL_LINK, '\0' * 17)
        request = array.array('c', reqstr )
        handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
        handle = struct.unpack('8xH14x', request.tostring())[0]

        # Get RSSI
        cmd_pkt=struct.pack('H', handle)
        rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                     bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
        rssi = struct.unpack('b', rssi[3])[0]

        # Close sockets
        bt_sock.close()
        hci_sock.close()

        return rssi

    except:
        return None
コード例 #10
0
ファイル: bt_rssi.py プロジェクト: 8tm/scripts
    def get_rssi(self):
        """Gets the current RSSI value.

        @return: The RSSI value (float) or None if the device connection fails
                 (i.e. the device is nowhere nearby).
        """
        try:
            # Only do connection if not already connected
            if not self.connected:
                self.connect()
            if self.cmd_pkt is None:
                self.prep_cmd_pkt()
            # Send command to request RSSI
            rssi = bt.hci_send_req(
                self.hci_sock, bt.OGF_STATUS_PARAM,
                bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, self.cmd_pkt)
            if sys.version_info < (3, 0, 0):
                rssi = struct.unpack('b', rssi[3])[0]
            else:
                rssi = struct.unpack('b', rssi[3].to_bytes(1, 'big'))[0]
            return rssi
        except IOError:
            # Happens if connection fails (e.g. device is not in range)
            self.connected = False
            return None
コード例 #11
0
ファイル: bt_rssi.py プロジェクト: Alieff/bluetooth-proximity
    def get_rssi(self):
        """Gets the current RSSI value.

        @return: The RSSI value (float) or None if the device connection fails
                 (i.e. the device is nowhere nearby).
        """
        try:
            # Only do connection if not already connected
            if not self.connected:
                self.connect()
            if self.cmd_pkt is None:
                self.prep_cmd_pkt()
            # Send command to request RSSI
            rssi = bt.hci_send_req(
                self.hci_sock, bt.OGF_STATUS_PARAM,
                bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, self.cmd_pkt)
            # print("RSSI:")
            if len(rssi) != 4: # case when the pair just turned off the bluetooth
                return None
            rssi = struct.unpack('4b',rssi)
            return rssi[3]
        except IOError:
            # Happens if connection fails (e.g. device is not in range)
            self.connected = False
            return None
コード例 #12
0
def get_RSSI(addr):
    # Open an hci socket
    hci_sock = bluez.hci_open_dev()
    hci_fd = hci_sock.fileno ()

    # Try to open a connection to remote BT device
    try:
        bt_sock = bluez.SDPSession ()
        bt_sock.connect(addr)
    except:
        bt_sock.close()
        hci_sock.close()
        return None
    # Get handle to ACL connection to remote BT device
    reqstr = struct.pack ("6sB17s", bluez.str2ba (addr),
            bluez.ACL_LINK, "\0" * 17)
    request = array.array ("c", reqstr)
    fcntl.ioctl (hci_fd, bluez.HCIGETCONNINFO, request, 1)
    handle = struct.unpack ("8xH14x", request.tostring ())[0]

    # Get RSSI
    cmd_pkt=struct.pack('H', handle)
    RSSI = bluez.hci_send_req(hci_sock, bluez.OGF_STATUS_PARAM,
                           bluez.OCF_READ_RSSI,
                           bluez.EVT_CMD_COMPLETE, 4, cmd_pkt)
    RSSI = struct.unpack('b', RSSI[3])[0]

    bt_sock.close()
    hci_sock.close()
    return RSSI
コード例 #13
0
    def get_rssi(self):
        """Gets the current RSSI value.

        @return: The RSSI value (float) or None if the device connection fails
                 (i.e. the device is nowhere nearby).
        """
        try:
            # Only do connection if not already connected
            if not self.connected:
                self.connect()
            if self.cmd_pkt is None:
                self.prep_cmd_pkt()
            # Send command to request RSSI
            rssi = bt.hci_send_req(self.hci_sock, bt.OGF_STATUS_PARAM,
                                   bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4,
                                   self.cmd_pkt)
            #print(rssi)
            #uint8_t status = get_u8(data);
            #+       uint16_t handle = get_le16(data + 1);
            #+       int8_t rssi = get_s8(data + 3);
            (rssi, ) = struct.unpack('xxxb', rssi)
            return rssi
        except IOError:
            # Happens if connection fails (e.g. device is not in range)
            self.connected = False
            return None
コード例 #14
0
 def get_rssi(self):
     """Gets the current RSSI value.
     @return: The RSSI value (float) or None if the device connection fails
              (i.e. the device is nowhere nearby).
     """
     try:
         # Only do connection if not already connected
         if not self.connected:
             self.connect()
         if self.cmd_pkt is None:
             self.prep_cmd_pkt()
         # Send command to request RSSI
         rssi = bt.hci_send_req(
             self.hci_sock, bt.OGF_STATUS_PARAM,
             bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, self.cmd_pkt)
         
         retVal = None
         if rssi[3] > 0 and rssi[3] <= 256:
             retVal = -(256 - rssi[3])
         if rssi[3] == 0:
             retVal = rssi[3]
             
         print("rssi %d retval " % rssi[3],retVal)
         return retVal
     except IOError:
         # Happens if connection fails (e.g. device is not in range)
         self.connected = False
         return None
コード例 #15
0
ファイル: bluez.py プロジェクト: ygl-rg/AIRi
def setupSCO():
    # check voice settings. switch to S16 LE mono 8kHz CVSD if needed
    hci_sock = bt.hci_open_dev()
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL,
                               bt.OCF_READ_VOICE_SETTING, bt.EVT_CMD_COMPLETE,
                               3)
    status, voice_setting = struct.unpack("<BH", response)
    if voice_setting != 0x60:
        new_vs = struct.pack("<H", 0x60)
        bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, bt.OCF_WRITE_VOICE_SETTING,
                        bt.EVT_CMD_COMPLETE, 1, new_vs)

    # determine the maximun packet size
    response = bt.hci_send_req(hci_sock, bt.OGF_INFO_PARAM,
                               bt.OCF_READ_BUFFER_SIZE, bt.EVT_CMD_COMPLETE, 8)
    status, acl_mtu, sco_mtu, acl_nbufs, sco_nbufs = struct.unpack(
        ">BHBHH", response)
    return acl_mtu, sco_mtu, acl_nbufs, sco_nbufs
コード例 #16
0
ファイル: bluez.py プロジェクト: manuelnaranjo/AIRi
def setupSCO():
    # check voice settings. switch to S16 LE mono 8kHz CVSD if needed
    hci_sock=bt.hci_open_dev()
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 
            bt.OCF_READ_VOICE_SETTING, bt.EVT_CMD_COMPLETE, 3)
    status, voice_setting = struct.unpack("<BH", response)
    if voice_setting != 0x60:
        new_vs = struct.pack("<H", 0x60)
        bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 
            bt.OCF_WRITE_VOICE_SETTING, 
            bt.EVT_CMD_COMPLETE, 1, new_vs)

    # determine the maximun packet size
    response = bt.hci_send_req(hci_sock, bt.OGF_INFO_PARAM, 
    bt.OCF_READ_BUFFER_SIZE, bt.EVT_CMD_COMPLETE, 8)
    status, acl_mtu, sco_mtu, acl_nbufs, sco_nbufs = struct.unpack(
                ">BHBHH", response)
    return acl_mtu, sco_mtu, acl_nbufs, sco_nbufs
コード例 #17
0
ファイル: test3.py プロジェクト: Eragon666/netcentric-2
def write_flush_timeout( addr, timeout ):
    hci_sock = bt.hci_open_dev()
    # get the ACL connection handle to the remote device
    handle = __get_acl_conn_handle(hci_sock, addr)
    pkt = struct.pack("HH", handle, bt.htobs(timeout))
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 
        0x0028, bt.EVT_CMD_COMPLETE, 3, pkt)
    status = struct.unpack("B", response[0])[0]
    rhandle = struct.unpack("H", response[1:3])[0]
    assert rhandle == handle 
    assert status == 0
コード例 #18
0
def write_flush_timeout(addr, timeout):
    hci_sock = bt.hci_open_dev()
    # get the ACL connection handle to the remote device
    handle = __get_acl_conn_handle(hci_sock, addr)
    pkt = struct.pack("HH", handle, bt.htobs(timeout))
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 0x0028,
                               bt.EVT_CMD_COMPLETE, 3, pkt)
    status = struct.unpack("B", response[0])[0]
    rhandle = struct.unpack("H", response[1:3])[0]
    assert rhandle == handle
    assert status == 0
コード例 #19
0
ファイル: test3.py プロジェクト: Eragon666/netcentric-2
def read_flush_timeout( addr ):
    hci_sock = bt.hci_open_dev()
    # get the ACL connection handle to the remote device
    handle = __get_acl_conn_handle(hci_sock, addr)
    pkt = struct.pack("H", handle)
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 
        0x0027, bt.EVT_CMD_COMPLETE, 5, pkt)
    status = struct.unpack("B", response[0])[0]
    rhandle = struct.unpack("H", response[1:3])[0]
    assert rhandle == handle
    assert status == 0
    fto = struct.unpack("H", response[3:5])[0]
    return fto
コード例 #20
0
def read_flush_timeout(addr):
    hci_sock = bt.hci_open_dev()
    # get the ACL connection handle to the remote device
    handle = __get_acl_conn_handle(hci_sock, addr)
    pkt = struct.pack("H", handle)
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 0x0027,
                               bt.EVT_CMD_COMPLETE, 5, pkt)
    status = struct.unpack("B", response[0])[0]
    rhandle = struct.unpack("H", response[1:3])[0]
    assert rhandle == handle
    assert status == 0
    fto = struct.unpack("H", response[3:5])[0]
    return fto
コード例 #21
0
ファイル: BLEconnect.py プロジェクト: kw123/piBeacon
def tryToConnect(MAC,BLEtimeout,devId):

	ret	 = {"signal": -999, "txPower": -999,"flag0ok":0,"byte2":0}
	try:
		for ii in range(5):	 # wait until (wifi) sending is finsihed
			if os.path.isfile(G.homeDir + "temp/sending"):
				#print "delaying hci"
				time.sleep(0.5)
			else:
				 break

		hci_sock = bt.hci_open_dev(devId)
		hci_fd	 = hci_sock.fileno()

		# Connect to device (to whatever you like)
		bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
		bt_sock.settimeout(BLEtimeout)

		try:
			result	= bt_sock.connect_ex((MAC, 1))	# PSM 1 - Service Discovery
			reqstr = struct.pack("6sB17s", bt.str2ba(MAC), bt.ACL_LINK, "\0" * 17)
			request = array.array("c", reqstr)
			handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
			handle = struct.unpack("8xH14x", request.tostring())[0]
			cmd_pkt=struct.pack('H', handle)
			# Send command to request RSSI
			rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM, bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
			bt_sock.close()
			hci_sock.close()
			flag0ok	  = struct.unpack('b', rssi[0])[0]
			txPower	  = struct.unpack('b', rssi[1])[0]
			byte2	  = struct.unpack('b', rssi[2])[0]
			signal	  = struct.unpack('b', rssi[3])[0]
			#print MAC, test0, txPower, test2, signal
			ret["flag0ok"]	= flag0ok
			ret["byte2"]	= byte2
			if flag0ok == 0 and not (txPower == signal and signal == 0 ):
				ret["signal"]	= signal
				ret["txPower"]	= txPower
		except IOError:
			# Happens if connection fails (e.g. device is not in range)
			bt_sock.close()
			hci_sock.close()

	except	Exception, e:
			U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
			print  u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)
コード例 #22
0
def tryToConnect(MAC,BLEtimeout,devId):

	ret	 = {"signal": -999, "txPower": -999,"flag0ok":0,"byte2":0}
	try:
		for ii in range(5):	 # wait until (wifi) sending is finsihed
			if os.path.isfile(G.homeDir + "temp/sending"):
				#print "delaying hci"
				time.sleep(0.5)
			else:
				 break

		hci_sock = bt.hci_open_dev(devId)
		hci_fd	 = hci_sock.fileno()

		# Connect to device (to whatever you like)
		bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
		bt_sock.settimeout(BLEtimeout)

		try:
			result	= bt_sock.connect_ex((MAC, 1))	# PSM 1 - Service Discovery
			reqstr = struct.pack("6sB17s", bt.str2ba(MAC), bt.ACL_LINK, "\0" * 17)
			request = array.array("c", reqstr)
			handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
			handle = struct.unpack("8xH14x", request.tostring())[0]
			cmd_pkt=struct.pack('H', handle)
			# Send command to request RSSI
			rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM, bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
			bt_sock.close()
			hci_sock.close()
			flag0ok	  = struct.unpack('b', rssi[0])[0]
			txPower	  = struct.unpack('b', rssi[1])[0]
			byte2	  = struct.unpack('b', rssi[2])[0]
			signal	  = struct.unpack('b', rssi[3])[0]
			#print MAC, test0, txPower, test2, signal
			ret["flag0ok"]	= flag0ok
			ret["byte2"]	= byte2
			if flag0ok == 0 and not (txPower == signal and signal == 0 ):
				ret["signal"]	= signal
				ret["txPower"]	= txPower
		except IOError:
			# Happens if connection fails (e.g. device is not in range)
			bt_sock.close()
			hci_sock.close()

	except	Exception, e:
			U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
			print  u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)
コード例 #23
0
def bluetooth_rssi(addr):
    # Open hci socket
    hci_sock = bt.hci_open_dev()
    hci_fd = hci_sock.fileno()

    # Connect to device (to whatever you like)
    bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bt_sock.settimeout(5)
    #

    try:
        #Get result
        result = bt_sock.connect((addr, 1))  # PSM 1 - Service Discovery

        # Get ConnInfo
        #Construct request to bit value
        reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
        #request into array
        request = array.array("c", reqstr)
        #hamdler creation
        handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
        #unback request to handler
        handle = struct.unpack("8xH14x", request.tostring())[0]

        # Get RSSI
        #Handler into command body
        cmd_pkt = struct.pack('H', handle)

        #recive request
        result = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                                 bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4,
                                 cmd_pkt)
        #get rssi to
        rssi = struct.unpack('b', result[3])[0]

        # Close sockets
        bt_sock.close()
        hci_sock.close()

        return rssi

    except:
        #print("Error")
        return None
コード例 #24
0
 def get_rssi(self):
     #Gets the RSSI value
     try:
         # Only do connection if not already connected
         if not self.connected:
             self.connect()
         if self.cmd_pkt is None:
             self.prepare_command()
         # Send command to request RSSI
         rssi = bt.hci_send_req(self.hci_sock, bt.OGF_STATUS_PARAM,
                                bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4,
                                self.cmd_pkt)
         rssi = struct.unpack('b', rssi[3:4])[0]
         return rssi
     except IOError as ioerr:
         # Happens if connection fails
         #LOGGER.debug("I/O error: {0}".format(ioerr))
         self.connected = False
         return None
コード例 #25
0
ファイル: bluetooth-near.py プロジェクト: pavelpy/BNNB
 def get_rssi(self):
     try:
         # noinspection PyPep8Naming
         READ_RSSI_RP_SIZE = 4
         if not self._connected:
             self.connect()
         if self._cmd_pkt is None:
             self._prep_cmd_pkt()
         _rssi = bt.hci_send_req(self._hci_sock, bt.OGF_STATUS_PARAM,
                                 bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE,
                                 READ_RSSI_RP_SIZE, self._cmd_pkt)
         _rssi = struct.unpack('b', _rssi[3].to_bytes(1, 'big'))
         _rssi = _rssi[0]
         if _rssi is not None:
             return float(_rssi)
         self._connected = False
         return None
     except IOError:
         self._connected = False
         return None
コード例 #26
0
def hci_read_local_version_compid(adapter: int) -> int:
    import bluetooth._bluetooth as _bt

    try:
        hci_sock = _bt.hci_open_dev(adapter)
        res = _bt.hci_send_req(hci_sock, _bt.OGF_INFO_PARAM,
                               _bt.OCF_READ_LOCAL_VERSION,
                               _bt.EVT_CONN_COMPLETE, 9)
        hci_sock.close()
        # Check first byte.
        # See read_local_version_rp.status
        # 0 if OK or ERRNO if an error has been raised
        if res[0]:
            # Invalid response
            return -1

        return int.from_bytes(res[5:7], byteorder='little', signed=False)

    except _bt.error as e:
        raise BluetoothError(*e.args)
コード例 #27
0
ファイル: bluetooth-near.py プロジェクト: pavelpy/BNNB
 def get_tx_power(self):
     try:
         # noinspection PyPep8Naming
         READ_TRANSMIT_POWER_LEVEL_RP_SIZE = 4
         if not self._connected:
             self.connect()
         if self._cmd_pkt is None:
             self._prep_cmd_pkt()
         _tx_power = bt.hci_send_req(self._hci_sock, bt.OGF_HOST_CTL,
                                     bt.OCF_READ_TRANSMIT_POWER_LEVEL,
                                     bt.EVT_CMD_COMPLETE,
                                     READ_TRANSMIT_POWER_LEVEL_RP_SIZE,
                                     self._cmd_pkt)
         _tx_power = struct.unpack('b', _tx_power[3].to_bytes(1, 'big'))[0]
         if _tx_power is not None:
             return float(_tx_power)
         self._connected = False
         return None
     except IOError:
         self._connected = False
         return None
コード例 #28
0
ファイル: linux.py プロジェクト: yeiyeiyei/beacontools
def send_req(socket, group_field, command_field, event, rlen, params, timeout):
    """Send hci request to device."""
    return bluez.hci_send_req(socket, group_field, command_field, event, rlen, params, timeout)
コード例 #29
0
ファイル: bdaddr.py プロジェクト: Cergoo/junk
baddr = sys.argv[1].split(":")

# Open hci socket
sock = bt.hci_open_dev(0)

# CSR vendor command to change address
cmd = [ "\xc2", "\x02", "\x00", "\x0c", "\x00", "\x11",
        "\x47", "\x03", "\x70", "\x00", "\x00", "\x01",
        "\x00", "\x04", "\x00", "\x00", "\x00", "\x00",
        "\x00", "\x00", "\x00", "\x00", "\x00", "\x00",
        "\x00" ]

# Set new addr in hex
cmd[17] = baddr[3].decode("hex")
cmd[19] = baddr[5].decode("hex")
cmd[20] = baddr[4].decode("hex")
cmd[21] = baddr[2].decode("hex")
cmd[23] = baddr[1].decode("hex")
cmd[24] = baddr[0].decode("hex")

# Send HCI request
bt.hci_send_req(sock,
                bt.OGF_VENDOR_CMD,
                0,
                bt.EVT_VENDOR,
                2000,
                "".join(cmd))

sock.close()
print "Dont forget to reset your device"
コード例 #30
0
# Split bluetooth address into it's bytes
baddr = sys.argv[1].split(":")

# Open hci socket
sock = bt.hci_open_dev(1)

# CSR vendor command to change address
cmd = [
    b"\xc2", b"\x02", b"\x00", b"\x0c", b"\x00", b"\x11", b"\x47", b"\x03",
    b"\x70", b"\x00", b"\x00", b"\x01", b"\x00", b"\x04", b"\x00", b"\x00",
    b"\x00", b"\x00", b"\x00", b"\x00", b"\x00", b"\x00", b"\x00", b"\x00",
    b"\x00"
]

# Set new addr in hex
decode_hex = codecs.getdecoder("hex_codec")

cmd[17] = decode_hex(baddr[3])[0]
cmd[19] = decode_hex(baddr[5])[0]
cmd[20] = decode_hex(baddr[4])[0]
cmd[21] = decode_hex(baddr[2])[0]
cmd[23] = decode_hex(baddr[1])[0]
cmd[24] = decode_hex(baddr[0])[0]

# Send HCI request
bt.hci_send_req(sock, bt.OGF_VENDOR_CMD, 0, bt.EVT_VENDOR, 2000, b"".join(cmd))

sock.close()
print("Dont forget to reset your device")