Python errno.EALREADY Examples

The following are 30 code examples of errno.EALREADY(). 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 errno , or try the search function .
Example #1
Source File: asyncadapter.py    From plex-for-kodi with GNU General Public License v2.0 6 votes vote down vote up
def _connect(self, sock, sa):
        while not self._canceled and not ABORT_FLAG_FUNCTION():
            time.sleep(0.01)
            self._check_timeout()  # this should be done at the beginning of each loop
            status = sock.connect_ex(sa)
            if not status or status in (errno.EISCONN, WIN_EISCONN):
                break
            elif status in (errno.EINPROGRESS, WIN_EWOULDBLOCK):
                self.deadline = time.time() + self._timeout.getConnectTimeout()
            # elif status in (errno.EWOULDBLOCK, errno.EALREADY) or (os.name == 'nt' and status == errno.WSAEINVAL):
            #     pass
            yield

        if self._canceled or ABORT_FLAG_FUNCTION():
            raise CanceledException('Request canceled')

        error = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if error:
            # TODO: determine when this case can actually happen
            raise socket.error((error,)) 
Example #2
Source File: asyncredis.py    From collection with MIT License 6 votes vote down vote up
def __init__ (self):
		self.sock = None		# socket object
		self.send_buf = []		# send buffer
		self.recv_buf = []		# recv buffer
		self.pend_buf = ''		# send pending
		self.state = NET_STATE_CLOSED
		self.errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ]
		self.conn = ( errno.EISCONN, 10057, 10053 )
		self.errc = 0
		self.ipv6 = False
		self.eintr = ()
		if 'EINTR' in errno.__dict__:
			self.eintr = (errno.__dict__['EINTR'],)
		if 'WSAEWOULDBLOCK' in errno.__dict__:
			self.errd.append(errno.WSAEWOULDBLOCK)
		self.errd = tuple(self.errd)
		self.timeout = 0
		self.timecon = 0 
Example #3
Source File: rwhois.py    From d4rkc0de with GNU General Public License v2.0 6 votes vote down vote up
def _whois(self):
        def alrmhandler(signum,frame):
            raise "TimedOut", "on connect"

        s = None

        ## try until we timeout
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if HAS_ALARM:
            s.setblocking(0)
            signal.signal(signal.SIGALRM,alrmhandler)
            signal.alarm(timeout)
        while 1:	
            try:
                s.connect((self.whoisserver, 43))
            except socket.error, (ecode, reason):
                if ecode==errno.EINPROGRESS: 
                    continue
                elif ecode==errno.EALREADY:
                    continue
                else:
                    raise socket.error, (ecode, reason)
                pass

            break 
Example #4
Source File: protocol_socket.py    From android_universal with MIT License 6 votes vote down vote up
def reset_input_buffer(self):
        """Clear input buffer, discarding all that is in the buffer."""
        if not self.is_open:
            raise portNotOpenError

        # just use recv to remove input, while there is some
        ready = True
        while ready:
            ready, _, _ = select.select([self._socket], [], [], 0)
            try:
                self._socket.recv(4096)
            except OSError as e:
                # this is for Python 3.x where select.error is a subclass of
                # OSError ignore BlockingIOErrors and EINTR. other errors are shown
                # https://www.python.org/dev/peps/pep-0475.
                if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                    raise SerialException('read failed: {}'.format(e))
            except (select.error, socket.error) as e:
                # this is for Python 2.x
                # ignore BlockingIOErrors and EINTR. all errors are shown
                # see also http://www.python.org/dev/peps/pep-3151/#select
                if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                    raise SerialException('read failed: {}'.format(e)) 
Example #5
Source File: rwhois.py    From darkc0de-old-stuff with GNU General Public License v3.0 6 votes vote down vote up
def _whois(self):
        def alrmhandler(signum,frame):
            raise "TimedOut", "on connect"

        s = None

        ## try until we timeout
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if HAS_ALARM:
            s.setblocking(0)
            signal.signal(signal.SIGALRM,alrmhandler)
            signal.alarm(timeout)
        while 1:	
            try:
                s.connect((self.whoisserver, 43))
            except socket.error, (ecode, reason):
                if ecode==errno.EINPROGRESS: 
                    continue
                elif ecode==errno.EALREADY:
                    continue
                else:
                    raise socket.error, (ecode, reason)
                pass

            break 
Example #6
Source File: test_socket_jy.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_connect_ex_workout(self):
        """Verify connect_ex states go through EINPROGRESS?, EALREADY*, EISCONN"""
        # Tests fix for http://bugs.jython.org/issue2428; based in part on the
        # code showing failure that was submitted with that bug
        for result in self.do_workout():
            self.assertIn(result[0], {errno.EINPROGRESS, errno.EISCONN})
            self.assertEqual(result[-1], errno.EISCONN)
            for code in result[1:-1]:
                self.assertEqual(code, errno.EALREADY) 
Example #7
Source File: test_ssl.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_non_blocking_connect_ex(self):
        # Issue #11326: non-blocking connect_ex() should allow handshake
        # to proceed after the socket gets ready.
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT,
                                do_handshake_on_connect=False)
            try:
                s.setblocking(False)
                rc = s.connect_ex((REMOTE_HOST, 443))
                # EWOULDBLOCK under Windows, EINPROGRESS elsewhere
                # Jython added EALREADY, as in Jython connect may have already happened
                self.assertIn(rc, (0, errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK))
                # Wait for connect to finish
                select.select([], [s], [], 5.0)
                # Non-blocking handshake
                while True:
                    try:
                        s.do_handshake()
                        break
                    except ssl.SSLWantReadError:
                        select.select([s], [], [], 5.0)
                    except ssl.SSLWantWriteError:
                        select.select([], [s], [], 5.0)
                # SSL established
                #self.assertTrue(s.getpeercert())
            finally:
                s.close() 
Example #8
Source File: test_socket_jy.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_connect_ex_workout(self):
        """Verify connect_ex states go through EINPROGRESS?, EALREADY*, EISCONN"""
        # Tests fix for http://bugs.jython.org/issue2428; based in part on the
        # code showing failure that was submitted with that bug
        for result in self.do_workout():
            self.assertIn(result[0], {errno.EINPROGRESS, errno.EISCONN})
            self.assertEqual(result[-1], errno.EISCONN)
            for code in result[1:-1]:
                self.assertEqual(code, errno.EALREADY) 
Example #9
Source File: query.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]

        if hasattr(v, 'errno'):
            v_err = v.errno
        else:
            v_err = v[0]
        if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
            raise v 
Example #10
Source File: query.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]

        if hasattr(v, 'errno'):
            v_err = v.errno
        else:
            v_err = v[0]
        if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
            raise v 
Example #11
Source File: query.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]

        if hasattr(v, 'errno'):
            v_err = v.errno
        else:
            v_err = v[0]
        if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
            raise v 
Example #12
Source File: telnet_connection.py    From fuzzowski with GNU General Public License v2.0 5 votes vote down vote up
def open(self):
        """
        Opens connection to the target. Make sure to call close!

        Returns:
            None
        """

        try:
            if self._active_session is False:
                self._client = telnetlib.Telnet(self.host, port=self.port, timeout=self.timeout)
                self._client.read_until(b'User name:')
                self._client.write(self.username + b'\r\n')
                self._client.read_until(b'User password:')
                self._client.write(self.password + b'\r\n')
                m = self._client.read_until(b'>')  # Todo: Implementation dependant
                self._active_session = True

        except socket.error as e:
            self._active_session = False
            if e.errno == errno.ECONNREFUSED:
                # raise exception.FuzzowskiTargetConnectionFailedError(e.message)
                raise exception.FuzzowskiTargetConnectionFailedError('ECONNREFUSED')
            elif e.errno == errno.EALREADY:
                raise exception.FuzzowskiTargetConnectionFailedError('EALREADY')
            elif e.errno == errno.EINPROGRESS:
                raise exception.FuzzowskiTargetConnectionFailedError('EINPROGRESS')
            else:
                raise
        except OSError as e:
            raise exception.FuzzowskiTargetConnectionFailedError(errno.errorcode(e.errno)) 
Example #13
Source File: protocol_socket.py    From android_universal with MIT License 5 votes vote down vote up
def read(self, size=1):
        """\
        Read size bytes from the serial port. If a timeout is set it may
        return less characters as requested. With no timeout it will block
        until the requested number of bytes is read.
        """
        if not self.is_open:
            raise portNotOpenError
        read = bytearray()
        timeout = Timeout(self._timeout)
        while len(read) < size:
            try:
                ready, _, _ = select.select([self._socket], [], [], timeout.time_left())
                # If select was used with a timeout, and the timeout occurs, it
                # returns with empty lists -> thus abort read operation.
                # For timeout == 0 (non-blocking operation) also abort when
                # there is nothing to read.
                if not ready:
                    break   # timeout
                buf = self._socket.recv(size - len(read))
                # read should always return some data as select reported it was
                # ready to read when we get to this point, unless it is EOF
                if not buf:
                    raise SerialException('socket disconnected')
                read.extend(buf)
            except OSError as e:
                # this is for Python 3.x where select.error is a subclass of
                # OSError ignore BlockingIOErrors and EINTR. other errors are shown
                # https://www.python.org/dev/peps/pep-0475.
                if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                    raise SerialException('read failed: {}'.format(e))
            except (select.error, socket.error) as e:
                # this is for Python 2.x
                # ignore BlockingIOErrors and EINTR. all errors are shown
                # see also http://www.python.org/dev/peps/pep-3151/#select
                if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                    raise SerialException('read failed: {}'.format(e))
            if timeout.expired():
                break
        return bytes(read) 
Example #14
Source File: _socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def connect_ex(self, addr):
        was_connecting = self.connected  # actually means self.connecting if
                                         # not blocking
        if not self.connected:
            try:
                self.connect(addr)
            except error as e:
                return e.errno
        if not self.connect_future.isDone():
            if was_connecting:
                try:
                    # Timing is based on CPython and was empirically
                    # guesstimated. Of course this means user code is
                    # polling, so the the best we can do is wait like
                    # this in supposedly nonblocking mode without
                    # completely busy waiting!
                    self.connect_future.get(1500, TimeUnit.MICROSECONDS)
                except ExecutionException:
                    # generally raised if closed; pick up the state
                    # when testing for success
                    pass
                except TimeoutException:
                    # more than 1.5ms, will report EALREADY below
                    pass

        if not self.connect_future.isDone():
            if was_connecting:
                return errno.EALREADY
            else:
                return errno.EINPROGRESS
        elif self.connect_future.isSuccess():
            # from socketmodule.c
            # if (res == EISCONN)
            #   res = 0;
            # but http://bugs.jython.org/issue2428
            return errno.EISCONN
        else:
            return errno.ENOTCONN

    # SERVER METHODS
    # Calling listen means this is a server socket 
Example #15
Source File: _socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def connect_ex(self, addr):
        was_connecting = self.connected  # actually means self.connecting if
                                         # not blocking
        if not self.connected:
            try:
                self.connect(addr)
            except error as e:
                return e.errno
        if not self.connect_future.isDone():
            if was_connecting:
                try:
                    # Timing is based on CPython and was empirically
                    # guesstimated. Of course this means user code is
                    # polling, so the the best we can do is wait like
                    # this in supposedly nonblocking mode without
                    # completely busy waiting!
                    self.connect_future.get(1500, TimeUnit.MICROSECONDS)
                except ExecutionException:
                    # generally raised if closed; pick up the state
                    # when testing for success
                    pass
                except TimeoutException:
                    # more than 1.5ms, will report EALREADY below
                    pass

        if not self.connect_future.isDone():
            if was_connecting:
                return errno.EALREADY
            else:
                return errno.EINPROGRESS
        elif self.connect_future.isSuccess():
            # from socketmodule.c
            # if (res == EISCONN)
            #   res = 0;
            # but http://bugs.jython.org/issue2428
            return errno.EISCONN
        else:
            return errno.ENOTCONN

    # SERVER METHODS
    # Calling listen means this is a server socket 
Example #16
Source File: test_ssl.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_non_blocking_connect_ex(self):
        # Issue #11326: non-blocking connect_ex() should allow handshake
        # to proceed after the socket gets ready.
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT,
                                do_handshake_on_connect=False)
            try:
                s.setblocking(False)
                rc = s.connect_ex((REMOTE_HOST, 443))
                # EWOULDBLOCK under Windows, EINPROGRESS elsewhere
                # Jython added EALREADY, as in Jython connect may have already happened
                self.assertIn(rc, (0, errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK))
                # Wait for connect to finish
                select.select([], [s], [], 5.0)
                # Non-blocking handshake
                while True:
                    try:
                        s.do_handshake()
                        break
                    except ssl.SSLWantReadError:
                        select.select([s], [], [], 5.0)
                    except ssl.SSLWantWriteError:
                        select.select([], [s], [], 5.0)
                # SSL established
                #self.assertTrue(s.getpeercert())
            finally:
                s.close() 
Example #17
Source File: test_socket_jy.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_connect_ex_workout(self):
        """Verify connect_ex states go through EINPROGRESS?, EALREADY*, EISCONN"""
        # Tests fix for http://bugs.jython.org/issue2428; based in part on the
        # code showing failure that was submitted with that bug
        for result in self.do_workout():
            self.assertIn(result[0], {errno.EINPROGRESS, errno.EISCONN})
            self.assertEqual(result[-1], errno.EISCONN)
            for code in result[1:-1]:
                self.assertEqual(code, errno.EALREADY) 
Example #18
Source File: test_socket_jy.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_connect_ex_workout(self):
        """Verify connect_ex states go through EINPROGRESS?, EALREADY*, EISCONN"""
        # Tests fix for http://bugs.jython.org/issue2428; based in part on the
        # code showing failure that was submitted with that bug
        for result in self.do_workout():
            self.assertIn(result[0], {errno.EINPROGRESS, errno.EISCONN})
            self.assertEqual(result[-1], errno.EISCONN)
            for code in result[1:-1]:
                self.assertEqual(code, errno.EALREADY) 
Example #19
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def connect_ex(self, addr):
        was_connecting = self.connected  # actually means self.connecting if
                                         # not blocking
        if not self.connected:
            try:
                self.connect(addr)
            except error as e:
                return e.errno
        if not self.connect_future.isDone():
            if was_connecting:
                try:
                    # Timing is based on CPython and was empirically
                    # guesstimated. Of course this means user code is
                    # polling, so the the best we can do is wait like
                    # this in supposedly nonblocking mode without
                    # completely busy waiting!
                    self.connect_future.get(1500, TimeUnit.MICROSECONDS)
                except ExecutionException:
                    # generally raised if closed; pick up the state
                    # when testing for success
                    pass
                except TimeoutException:
                    # more than 1.5ms, will report EALREADY below
                    pass

        if not self.connect_future.isDone():
            if was_connecting:
                return errno.EALREADY
            else:
                return errno.EINPROGRESS
        elif self.connect_future.isSuccess():
            # from socketmodule.c
            # if (res == EISCONN)
            #   res = 0;
            # but http://bugs.jython.org/issue2428
            return errno.EISCONN
        else:
            return errno.ENOTCONN

    # SERVER METHODS
    # Calling listen means this is a server socket 
Example #20
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def connect_ex(self, addr):
        was_connecting = self.connected  # actually means self.connecting if
                                         # not blocking
        if not self.connected:
            try:
                self.connect(addr)
            except error as e:
                return e.errno
        if not self.connect_future.isDone():
            if was_connecting:
                try:
                    # Timing is based on CPython and was empirically
                    # guesstimated. Of course this means user code is
                    # polling, so the the best we can do is wait like
                    # this in supposedly nonblocking mode without
                    # completely busy waiting!
                    self.connect_future.get(1500, TimeUnit.MICROSECONDS)
                except ExecutionException:
                    # generally raised if closed; pick up the state
                    # when testing for success
                    pass
                except TimeoutException:
                    # more than 1.5ms, will report EALREADY below
                    pass

        if not self.connect_future.isDone():
            if was_connecting:
                return errno.EALREADY
            else:
                return errno.EINPROGRESS
        elif self.connect_future.isSuccess():
            # from socketmodule.c
            # if (res == EISCONN)
            #   res = 0;
            # but http://bugs.jython.org/issue2428
            return errno.EISCONN
        else:
            return errno.ENOTCONN

    # SERVER METHODS
    # Calling listen means this is a server socket 
Example #21
Source File: query.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]

        if hasattr(v, 'errno'):
            v_err = v.errno
        else:
            v_err = v[0]
        if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
            raise v 
Example #22
Source File: query.py    From Cloudmare with GNU General Public License v3.0 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]

        if hasattr(v, 'errno'):
            v_err = v.errno
        else:
            v_err = v[0]
        if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
            raise v 
Example #23
Source File: TimeoutSocket.py    From p2pool-n with GNU General Public License v3.0 5 votes vote down vote up
def connect(self, *addr):
        timeout = self.timeout
        sock = self.sock
        try:
            # Non-blocking mode
            sock.setblocking(0)
            apply(sock.connect, addr)
            sock.setblocking(timeout != 0)
            return 1
        except socket.error,why:
            if not timeout:
                raise
            sock.setblocking(1)
            if len(why.args) == 1:
                code = 0
            else:
                code, why = why
            if code not in (
                errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
                ):
                raise
            r,w,e = select.select([],[sock],[],timeout)
            if w:
                try:
                    apply(sock.connect, addr)
                    return 1
                except socket.error,why:
                    if len(why.args) == 1:
                        code = 0
                    else:
                        code, why = why
                    if code in (errno.EISCONN, WSAEINVAL):
                        return 1
                    raise 
Example #24
Source File: bluetooth_utils.py    From apple_bleee with GNU General Public License v3.0 5 votes vote down vote up
def toggle_device(dev_id, enable):
    """
    Power ON or OFF a bluetooth device.

    :param dev_id: Device id.
    :type dev_id: ``int``
    :param enable: Whether to enable of disable the device.
    :type enable: ``bool``
    """
    hci_sock = socket.socket(socket.AF_BLUETOOTH,
                             socket.SOCK_RAW,
                             socket.BTPROTO_HCI)
    # print("Power %s bluetooth device %d" % ('ON' if enable else 'OFF', dev_id))
    # di = struct.pack("HbBIBBIIIHHHH10I", dev_id, *((0,) * 22))
    # fcntl.ioctl(hci_sock.fileno(), bluez.HCIGETDEVINFO, di)
    req_str = struct.pack("H", dev_id)
    request = array.array("b", req_str)
    try:
        fcntl.ioctl(hci_sock.fileno(),
                    bluez.HCIDEVUP if enable else bluez.HCIDEVDOWN,
                    request[0])
    except IOError as e:
        if e.errno == EALREADY:
            pass
            # print("Bluetooth device %d is already %s" % (
            #       dev_id, 'enabled' if enable else 'disabled'))
        else:
            raise
    finally:
        hci_sock.close()


# Types of bluetooth scan 
Example #25
Source File: bluetooth_utils.py    From HomePWN with GNU General Public License v3.0 5 votes vote down vote up
def toggle_device(dev_id, enable):
    """
    Power ON or OFF a bluetooth device.

    :param dev_id: Device id.
    :type dev_id: ``int``
    :param enable: Whether to enable of disable the device.
    :type enable: ``bool``
    """
    hci_sock = socket.socket(socket.AF_BLUETOOTH,
                             socket.SOCK_RAW,
                             socket.BTPROTO_HCI)
    # print("Power %s bluetooth device %d" % ('ON' if enable else 'OFF', dev_id))
    # di = struct.pack("HbBIBBIIIHHHH10I", dev_id, *((0,) * 22))
    # fcntl.ioctl(hci_sock.fileno(), bluez.HCIGETDEVINFO, di)
    req_str = struct.pack("H", dev_id)
    request = array.array("b", req_str)
    try:
        fcntl.ioctl(hci_sock.fileno(),
                    bluez.HCIDEVUP if enable else bluez.HCIDEVDOWN,
                    request[0])
    except IOError as e:
        if e.errno == EALREADY:
            pass
            # print("Bluetooth device %d is already %s" % (
            #       dev_id, 'enabled' if enable else 'disabled'))
        else:
            raise
    finally:
        hci_sock.close()


# Types of bluetooth scan 
Example #26
Source File: query.py    From script.elementum.burst with Do What The F*ck You Want To Public License 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]

        if hasattr(v, 'errno'):
            v_err = v.errno
        else:
            v_err = v[0]
        if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
            raise v 
Example #27
Source File: bluetooth_utils.py    From py-bluetooth-utils with MIT License 5 votes vote down vote up
def toggle_device(dev_id, enable):
    """
    Power ON or OFF a bluetooth device.

    :param dev_id: Device id.
    :type dev_id: ``int``
    :param enable: Whether to enable of disable the device.
    :type enable: ``bool``
    """
    hci_sock = socket.socket(socket.AF_BLUETOOTH,
                             socket.SOCK_RAW,
                             socket.BTPROTO_HCI)
    print("Power %s bluetooth device %d" % ('ON' if enable else 'OFF', dev_id))
    # di = struct.pack("HbBIBBIIIHHHH10I", dev_id, *((0,) * 22))
    # fcntl.ioctl(hci_sock.fileno(), bluez.HCIGETDEVINFO, di)
    req_str = struct.pack("H", dev_id)
    request = array.array("b", req_str)
    try:
        fcntl.ioctl(hci_sock.fileno(),
                    bluez.HCIDEVUP if enable else bluez.HCIDEVDOWN,
                    request[0])
    except IOError as e:
        if e.errno == EALREADY:
            print("Bluetooth device %d is already %s" % (
                  dev_id, 'enabled' if enable else 'disabled'))
        else:
            raise
    finally:
        hci_sock.close()


# Types of bluetooth scan 
Example #28
Source File: query.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]
        if v[0] != errno.EINPROGRESS and \
               v[0] != errno.EWOULDBLOCK and \
               v[0] != errno.EALREADY:
            raise v 
Example #29
Source File: tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def doConnect(self):
        """
        Initiate the outgoing connection attempt.

        @note: Applications do not need to call this method; it will be invoked
            internally as part of L{IReactorTCP.connectTCP}.
        """
        self.doWrite = self.doConnect
        self.doRead = self.doConnect
        if not hasattr(self, "connector"):
            # this happens when connection failed but doConnect
            # was scheduled via a callLater in self._finishInit
            return

        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err:
            self.failIfNotConnected(error.getConnectError((err, strerror(err))))
            return

        # doConnect gets called twice.  The first time we actually need to
        # start the connection attempt.  The second time we don't really
        # want to (SO_ERROR above will have taken care of any errors, and if
        # it reported none, the mere fact that doConnect was called again is
        # sufficient to indicate that the connection has succeeded), but it
        # is not /particularly/ detrimental to do so.  This should get
        # cleaned up some day, though.
        try:
            connectResult = self.socket.connect_ex(self.realAddress)
        except socket.error as se:
            connectResult = se.args[0]
        if connectResult:
            if connectResult == EISCONN:
                pass
            # on Windows EINVAL means sometimes that we should keep trying:
            # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/connect_2.asp
            elif ((connectResult in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or
                  (connectResult == EINVAL and platformType == "win32")):
                self.startReading()
                self.startWriting()
                return
            else:
                self.failIfNotConnected(error.getConnectError((connectResult, strerror(connectResult))))
                return

        # If I have reached this point without raising or returning, that means
        # that the socket is connected.
        del self.doWrite
        del self.doRead
        # we first stop and then start, to reset any references to the old doRead
        self.stopReading()
        self.stopWriting()
        self._connectDone() 
Example #30
Source File: tco.py    From nfcpy with European Union Public License 1.1 4 votes vote down vote up
def connect(self, dest):
        with self.lock:
            if not self.state.CLOSED:
                self.err("connect() in socket state {0}".format(self.state))
                if self.state.ESTABLISHED:
                    raise err.Error(errno.EISCONN)
                if self.state.CONNECT:
                    raise err.Error(errno.EALREADY)
                raise err.Error(errno.EPIPE)
            if isinstance(dest, (bytes, bytearray)):
                send_pdu = pdu.Connect(1, self.addr, self.recv_miu,
                                       self.recv_win, bytes(dest))
            elif isinstance(dest, str):
                send_pdu = pdu.Connect(1, self.addr, self.recv_miu,
                                       self.recv_win, dest.encode('latin'))
            elif isinstance(dest, int):
                send_pdu = pdu.Connect(dest, self.addr, self.recv_miu,
                                       self.recv_win)
            else:
                raise TypeError("connect destination must be int or bytes")

            self.state.CONNECT = True
            self.send_queue.append(send_pdu)

            try:
                rcvd_pdu = super(DataLinkConnection, self).recv()
            except IndexError:
                raise err.Error(errno.EPIPE)

            if rcvd_pdu.name == "DM":
                logstr = "connect rejected with reason {}"
                self.log(logstr.format(rcvd_pdu.reason))
                self.state.CLOSED = True
                raise err.ConnectRefused(rcvd_pdu.reason)
            elif rcvd_pdu.name == "CC":
                self.peer = rcvd_pdu.ssap
                self.recv_buf = self.recv_win
                self.send_miu = rcvd_pdu.miu
                self.send_win = rcvd_pdu.rw
                self.state.ESTABLISHED = True
                return
            else:  # pragma: no cover
                raise RuntimeError("CC or DM expected, not " + rcvd_pdu.name)