Python socket.AF_BLUETOOTH Examples

The following are 9 code examples of socket.AF_BLUETOOTH(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: btk_server.py    From keyboard_mouse_emulate_on_raspberry with MIT License 8 votes vote down vote up
def listen(self):
		print("Waiting for connections")
		self.scontrol = socket.socket(
		    socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP)  # BluetoothSocket(L2CAP)
		self.sinterrupt = socket.socket(
		    socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP)  # BluetoothSocket(L2CAP)
		self.scontrol.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.sinterrupt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		# bind these sockets to a port - port zero to select next available
		self.scontrol.bind((socket.BDADDR_ANY, self.P_CTRL))
		self.sinterrupt.bind((socket.BDADDR_ANY, self.P_INTR))

		# Start listening on the server sockets
		self.scontrol.listen(5)  # Limit of 1 connection
		self.sinterrupt.listen(5)

		self.ccontrol, cinfo = self.scontrol.accept()
		print ("Got a connection on the control channel from " + cinfo[0])

		self.cinterrupt, cinfo = self.sinterrupt.accept()
		print ("Got a connection on the interrupt channel from " + cinfo[0])

	# send a string to the bluetooth host machine 
Example #2
Source File: freebsd.py    From beacontools with MIT License 6 votes vote down vote up
def open_dev(bt_device_id):
    """Open hci device socket."""
    # pylint: disable=no-member
    sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)

    # Unlike Linux, FreeBSD has separate numbering depending on hardware
    # (ubt - USB bluetooth - is the most common, so convert numbers to that)
    if not isinstance(bt_device_id, str):
        bt_device_id = 'ubt{}hci'.format(bt_device_id)

    # Python's BTPROTO_HCI address parsing is busted: https://bugs.python.org/issue41130
    adr = SockaddrHci(ctypes.sizeof(SockaddrHci), socket.AF_BLUETOOTH, bt_device_id.ljust(32, '\0').encode('utf-8'))
    if libc.bind(sock.fileno(), ctypes.pointer(adr), ctypes.sizeof(SockaddrHci)) != 0:
        raise ConnectionError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
    if libc.connect(sock.fileno(), ctypes.pointer(adr), ctypes.sizeof(SockaddrHci)) != 0:
        raise ConnectionError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
    # pylint: enable=no-member

    fltr = HciRawFilter(0, NG_HCI_EVENT_MASK_LE)
    if libc.setsockopt(sock.fileno(),
                       SOL_HCI_RAW, SOL_HCI_RAW_FILTER,
                       ctypes.pointer(fltr), ctypes.sizeof(HciRawFilter)) != 0:
        raise ConnectionError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))

    return sock 
Example #3
Source File: BluetoothHCI.py    From pybleno with MIT License 6 votes vote down vote up
def __init__(self, device_id=0):
        self.device_id = device_id
        self._keep_running = True
        self._socket = None
        self._socket_on_data_user_callback = None
        self._socket_on_started = None
        self._socket_poll_thread = None
        self._l2sockets = {}

        self._socket = BluetoothSocket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)
        
    
        #self._socket = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)
        #self._socket = BluetoothUserSocket()
        #self._socket = bluetooth.bluez._gethcisock(0)

        self._socket.setblocking(0)
        self.__r, self.__w = os.pipe()
        self._r = os.fdopen(self.__r, 'rU')
        self._w = os.fdopen(self.__w, 'w') 
Example #4
Source File: BluetoothSocket.py    From pybleno with MIT License 6 votes vote down vote up
def hci_devinfo(adapter=0):
    # Get Bluetooth device information
    # Takes an adapter number, returns raw data from ioctl
    # FIXME(MR) this function is a complete hack
    # but Python doesn't even dream of offering Bluetooth ioctl's
    dd = BluetoothSocket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)
    dev_info = struct.pack('<H', adapter) + "\x00" * 90
    try:
        r = fcntl.ioctl(dd, 0x800448d3, dev_info) # HCIGETDEVINFO, tested on x64 Linux only
        return r
    except IOError as e:
        # XXX is there a more Pythonic way of doing this?
        if e[0] == 19:
            raise TypeError("No such Bluetooth adapter")
        else:
            raise e 
Example #5
Source File: aioblescan.py    From aioblescan with MIT License 5 votes vote down vote up
def create_bt_socket(interface=0):
    exceptions = []
    sock = None
    try:
        sock = socket.socket(family=socket.AF_BLUETOOTH,
                             type=socket.SOCK_RAW,
                             proto=socket.BTPROTO_HCI)
        sock.setblocking(False)
        sock.setsockopt(socket.SOL_HCI, socket.HCI_FILTER, pack("IIIh2x", 0xffffffff,0xffffffff,0xffffffff,0)) #type mask, event mask, event mask, opcode
        try:
            sock.bind((interface,))
        except OSError as exc:
            exc = OSError(
                    exc.errno, 'error while attempting to bind on '
                    'interface {!r}: {}'.format(
                        interface, exc.strerror))
            exceptions.append(exc)
    except OSError as exc:
        if sock is not None:
            sock.close()
        exceptions.append(exc)
    except:
        if sock is not None:
            sock.close()
        raise
    if len(exceptions) == 1:
        raise exceptions[0]
    elif len(exceptions) > 1:
        model = str(exceptions[0])
        if all(str(exc) == model for exc in exceptions):
            raise exceptions[0]
        raise OSError('Multiple exceptions: {}'.format(
            ', '.join(str(exc) for exc in exceptions)))
    return sock

########### 
Example #6
Source File: BluetoothHCI.py    From pybleno with MIT License 5 votes vote down vote up
def kernel_disconnect_workarounds(self, data):
        #print 'PRE KERNEL WORKAROUND %d' % len(data)
        
        def noop(value):
            return value
            
        if (sys.version_info > (3, 0)):
            ord = noop
        else:
            import __builtin__
            ord = __builtin__.ord
        
        if len(data) == 22 and [ord(elem) for elem in data[0:5]] == [0x04, 0x3e, 0x13, 0x01, 0x00]:
            handle = ord(data[5])
            # get address
            set = data[9:15]
            # get device info
            dev_info = self.get_device_info()
            raw_set = [ord(c) for c in set]
            raw_set.reverse()
            #addz = ''.join([hex(c) for c in set])
            #set.reverse()
            addz = "%02x:%02x:%02x:%02x:%02x:%02x" % struct.unpack("BBBBBB", array.array('B', raw_set))
            socket2 = BluetoothSocket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP)
            
            socket2.bind_l2(0, dev_info['addr'], cid=ATT_CID, addr_type=0)#addr_type=dev_info['type'])
            
            self._l2sockets[handle] = socket2
            try:
                result = socket2.connect_l2(0, addz, cid=ATT_CID, addr_type=ord(data[8]) + 1)
            except:
                pass
        elif len(data) == 7 and [ord(elem) for elem in data[0:4]] == [0x04, 0x05, 0x04, 0x00]:
            handle = ord(data[4])
            
            socket2 = self._l2sockets[handle] if handle in self._l2sockets else None
            if socket2:
                # print 'GOT A SOCKET!'
                socket2.close()
                del self._l2sockets[handle] 
Example #7
Source File: BluetoothSocket.py    From pybleno with MIT License 5 votes vote down vote up
def _sockaddr_l2(self, psm, bdaddr, cid, addr_type):
        if (sys.version_info > (3, 0)):
            ret = struct.pack('<HH', socket.AF_BLUETOOTH, psm) + array.array('B', [ord(x) for x in BDAddr(bdaddr).le_string()]) + struct.pack('<HH', cid, addr_type)
        else:
            ret = ''.join((
                struct.pack('<HH', socket.AF_BLUETOOTH, psm),
                BDAddr(bdaddr).le_string(),
                struct.pack('<HH', cid, addr_type),
            ))
        
        return ret 
Example #8
Source File: BluetoothSocket.py    From pybleno with MIT License 5 votes vote down vote up
def _sockaddr_hci(self, dev, channel):
        if dev is None:
            dev = 0xffff
        return struct.pack('<HHH', socket.AF_BLUETOOTH, dev, channel) 
Example #9
Source File: BluetoothSocket.py    From pybleno with MIT License 5 votes vote down vote up
def _sockaddr_rc(self, bdaddr, channel):

        if (sys.version_info > (3, 0)):
            return struct.pack('<H', socket.AF_BLUETOOTH) + array.array('B', [ord(x) for x in BDAddr(bdaddr).le_string()]) + struct.pack('<H', channel)
        else:
            return ''.join((
                struct.pack('<H', socket.AF_BLUETOOTH),
                BDAddr(bdaddr).le_string(),
                struct.pack('<H', channel),
            ))