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
def _prep_cmd_pkt(self): _request_command = struct.pack(b'6sB17s', bt.str2ba(self._addr), bt.ACL_LINK, b'\0' * 17) _request_as_array = array.array('b', _request_command) _ = fcntl.ioctl(self._hci_fd, bt.HCIGETCONNINFO, _request_as_array, 1) _handle = struct.unpack(b'8xH14x', _request_as_array.tobytes())[0] self._cmd_pkt = struct.pack('H', _handle)
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
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
def create_acl_conn(sock): # save current filter old_filter = save_filter(sock) ## packet structure: 6B -> BT ADDRESS, 2B -> DM1, 1B -> R1, 1B -> reserved 0x00, 2B -> Clock offset 0x0000, 1B -> Allow role switch #cmd_pkt = struct.pack("BBBBBBBBBBBBB", 0x22, 0x22, 0xef, 0xbb, 0x48, 0x6f, 0x00, 0x08, 0x02, 0x00, 0x00, 0x00, 0x01) address = bluez.str2ba(device_address) cmd_pkt = struct.pack("6sBBBBBBB", address, 0x18, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01) bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_CREATE_CONN, cmd_pkt) results = [] done = False while not done: pkt = sock.recv(255) ptype, event, plen = struct.unpack("BBB", pkt[:3]) if event == bluez.EVT_CONN_COMPLETE: done = True status, conn_id = struct.unpack("xBH", pkt[2:6]) print "-" * 10 printpacket(pkt) print conn_id, "status: ", status if status == 4: print "ACL page timed out" raise ConnectionTimedOut("ACL page timed out") elif status == 11: print "ACL connection already established!" raise ConnectionExistsError( "ACL connection already established!") elif status == 0: print "connection successfully completed" elif status == 9: print "connection limit exceeded!" raise ConnectionExistsError( "ACL connection limit exceeded! There must be a connection..." ) elif status == 34: print "link manager timed out..." raise ConnectionTimedOut("Link manager timed out") else: print "something funky happened, let us reset!" raise ConnectionExistsError("Unknown error, resetting") elif event == bluez.EVT_CMD_STATUS: status, ncmd, opcode = struct.unpack("BBH", pkt[3:7]) if status != 0: printpacket(pkt) print "ACL connection failed" done = True raise CommandNotCompletedError( "Connection could not be established") # restore old filter restore_filter(old_filter, sock) return conn_id
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
def prep_cmd_pkt(self): """Prepares the command packet for requesting RSSI""" reqstr = struct.pack(b"6sB17s", bt.str2ba(self.addr), bt.ACL_LINK, b"\0" * 17) request = array.array("b", reqstr) handle = fcntl.ioctl(self.hci_fd, bt.HCIGETCONNINFO, request, 1) handle = struct.unpack(b"8xH14x", request.tostring())[0] self.cmd_pkt = struct.pack('H', handle)
def __get_acl_conn_handle(sock, addr): hci_fd = sock.fileno() reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17) request = array.array("c", reqstr) fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1) handle = struct.unpack("8xH14x", request.tostring())[0] return handle
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
def __get_acl_conn_handle(sock, addr): hci_fd = sock.fileno() reqstr = struct.pack( "6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17) request = array.array( "c", reqstr ) fcntl.ioctl( hci_fd, bt.HCIGETCONNINFO, request, 1 ) handle = struct.unpack("8xH14x", request.tostring())[0] return handle
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
def prepare_command(self): #Creates the command reqstr = struct.pack("6sB17s", bt.str2ba(self.addr), bt.ACL_LINK, bytes("\0", 'utf-8') * 17) request = array.array("b", reqstr) handle = fcntl.ioctl(self.hci_fd, bt.HCIGETCONNINFO, request, 1) handle = struct.unpack("8xH14x", request.tobytes())[0] self.cmd_pkt = struct.pack('H', handle)
def prep_cmd_pkt(self): """Prepares the command packet for requesting RSSI""" str2ba = bt.str2ba(self.addr) third =bytes("\0" * 17, 'utf-8') reqstr = struct.pack("6sB17s", str2ba, bt.ACL_LINK, third) request = array.array("h", reqstr) handle = fcntl.ioctl(self.hci_fd, bt.HCIGETCONNINFO, request, 1) handle = struct.unpack("8xH14x", request.tostring())[0] self.cmd_pkt = struct.pack('H', handle)
def create_acl_conn(sock): # save current filter old_filter = save_filter(sock) ## packet structure: 6B -> BT ADDRESS, 2B -> DM1, 1B -> R1, 1B -> reserved 0x00, 2B -> Clock offset 0x0000, 1B -> Allow role switch #cmd_pkt = struct.pack("BBBBBBBBBBBBB", 0x22, 0x22, 0xef, 0xbb, 0x48, 0x6f, 0x00, 0x08, 0x02, 0x00, 0x00, 0x00, 0x01) address = bluez.str2ba(device_address) cmd_pkt = struct.pack("6sBBBBBBB", address, 0x18, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01) bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_CREATE_CONN, cmd_pkt) results = [] done = False while not done: pkt = sock.recv(255) ptype, event, plen = struct.unpack("BBB", pkt[:3]) if event == bluez.EVT_CONN_COMPLETE: done = True status, conn_id = struct.unpack("xBH", pkt[2:6]) print "-" * 10 printpacket(pkt) print conn_id, "status: ", status if status == 4: print "ACL page timed out" raise ConnectionTimedOut("ACL page timed out") elif status == 11: print "ACL connection already established!" raise ConnectionExistsError("ACL connection already established!") elif status == 0: print "connection successfully completed" elif status == 9: print "connection limit exceeded!" raise ConnectionExistsError("ACL connection limit exceeded! There must be a connection...") elif status == 34: print "link manager timed out..." raise ConnectionTimedOut("Link manager timed out") else: print "something funky happened, let us reset!" raise ConnectionExistsError("Unknown error, resetting") elif event == bluez.EVT_CMD_STATUS: status, ncmd, opcode = struct.unpack("BBH", pkt[3:7]) if status != 0: printpacket(pkt) print "ACL connection failed" done = True raise CommandNotCompletedError("Connection could not be established") # restore old filter restore_filter(old_filter, sock) return conn_id
def prep_cmd_pkt(self): """Prepares the command packet for requesting RSSI""" # print(bt.str2ba("10:2A:B3:84:93:C6")) # print(bytes("10:2A:B3:84:93:C6","utf-8")) reqstr = struct.pack("6sB17s", bt.str2ba("10:2A:B3:84:93:C6"), bt.ACL_LINK, b"\0" * 17) request = array.array("b", reqstr) handle = fcntl.ioctl(self.hci_fd, bt.HCIGETCONNINFO, request, 1) handle = struct.unpack("8xH14x", request.tostring())[0] self.cmd_pkt = struct.pack('H', handle)
def get_acl_conn_handle(hci_sock, addr): hci_fd = hci_sock.fileno() reqstr = struct.pack("6sB17s", _bt.str2ba(addr), _bt.ACL_LINK, b"\0" * 17) request = array.array("b", reqstr) try: fcntl.ioctl(hci_fd, _bt.HCIGETCONNINFO, request, 1) except OSError as e: raise BluetoothError(e.args[0], "There is no ACL connection to %s" % addr) # XXX should this be "<8xH14x"? handle = struct.unpack("8xH14x", request.tostring())[0] return handle
def _send_next_name_req(self): assert len(self.names_to_find) > 0 address = list(self.names_to_find.keys())[0] device_class, rssi, psrm, pspm, clockoff = self.names_to_find[address] bdaddr = _bt.str2ba(address) #TODO not supported in python3 cmd_pkt = "{}{}\0{}".format(bdaddr, psrm, clockoff) try: _bt.hci_send_cmd (self.sock, _bt.OGF_LINK_CTL, \ _bt.OCF_REMOTE_NAME_REQ, cmd_pkt) except _bt.error as e: raise BluetoothError( e.args[0], "error request name of %s - %s:" % (address, e.args[1]))
def prep_cmd_pkt(self): """Prepares the command packet for requesting RSSI""" reqstr = struct.pack(str.encode("6sB17s"), bt.str2ba(self.addr), bt.ACL_LINK, str.encode("\0") * 17) #print(reqstr) request = array.array("b", reqstr) handle = fcntl.ioctl(self.hci_fd, bt.HCIGETCONNINFO, request, 1) if sys.version_info >= (3, 9): handle = struct.unpack( "8xH14x", request.tobytes())[0] # tobytes if using python 3.9 else: handle = struct.unpack( "8xH14x", request.tostring())[0] # tostring if using python 3.8 or older self.cmd_pkt = struct.pack('H', handle)
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)
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
def cancel_acl_conn_old(sock): # save current filter old_filter = save_filter(sock) ## packet structure: 6B -> BT ADDRESS, 2B -> DM1, 1B -> R1, 1B -> reserved 0x00, 2B -> Clock offset 0x0000, 1B -> Allow role switch address = bluez.str2ba(device_address) cmd_pkt = struct.pack("6s", address) bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_RESET) results = [] done = False while not done: pkt = sock.recv(255) ptype, event, plen = struct.unpack("BBB", pkt[:3]) if event == bluez.EVT_CMD_COMPLETE: done = True status = struct.unpack("B", pkt[3])[0] print "-" * 10 printpacket(pkt) print "status: ", status if status == 2: print "No connection requested" elif status == 11: print "ACL connection already established!" elif status == 0: print "connection cancel successfully completed" elif event == bluez.EVT_CMD_STATUS: status, ncmd, opcode = struct.unpack("BBH", pkt[3:7]) if status != 0: print "ACL connection cancel failed" #printpacket(pkt[3:7]) done = True raise CommandNotCompletedError("Connection could not be canceled") # restore old filter restore_filter(old_filter, sock)
def cancel_acl_conn_old(sock): # save current filter old_filter = save_filter(sock) ## packet structure: 6B -> BT ADDRESS, 2B -> DM1, 1B -> R1, 1B -> reserved 0x00, 2B -> Clock offset 0x0000, 1B -> Allow role switch address = bluez.str2ba(device_address) cmd_pkt = struct.pack("6s", address) bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_RESET) results = [] done = False while not done: pkt = sock.recv(255) ptype, event, plen = struct.unpack("BBB", pkt[:3]) if event == bluez.EVT_CMD_COMPLETE: done = True status = struct.unpack("B", pkt[3])[0] print "-" * 10 printpacket(pkt) print "status: ", status if status == 2: print "No connection requested" elif status == 11: print "ACL connection already established!" elif status == 0: print "connection cancel successfully completed" elif event == bluez.EVT_CMD_STATUS: status, ncmd, opcode = struct.unpack("BBH", pkt[3:7]) if status != 0: print "ACL connection cancel failed" #printpacket(pkt[3:7]) done = True raise CommandNotCompletedError( "Connection could not be canceled") # restore old filter restore_filter(old_filter, sock)