Python serial.serial_for_url() Examples

The following are 24 code examples of serial.serial_for_url(). 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 serial , or try the search function .
Example #1
Source File: miniterm.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
        try:
            self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
        except AttributeError:
            # happens when the installed pyserial is older than 2.5. use the
            # Serial class directly then.
            self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
        self.echo = echo
        self.repr_mode = repr_mode
        self.convert_outgoing = convert_outgoing
        self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
        self.dtr_state = True
        self.rts_state = True
        self.break_state = False 
Example #2
Source File: miniterm.py    From android_universal with MIT License 5 votes vote down vote up
def change_port(self):
        """Have a conversation with the user to change the serial port"""
        with self.console:
            try:
                port = ask_for_port()
            except KeyboardInterrupt:
                port = None
        if port and port != self.serial.port:
            # reader thread needs to be shut down
            self._stop_reader()
            # save settings
            settings = self.serial.getSettingsDict()
            try:
                new_serial = serial.serial_for_url(port, do_not_open=True)
                # restore settings and open
                new_serial.applySettingsDict(settings)
                new_serial.rts = self.serial.rts
                new_serial.dtr = self.serial.dtr
                new_serial.open()
                new_serial.break_condition = self.serial.break_condition
            except Exception as e:
                sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
                new_serial.close()
            else:
                self.serial.close()
                self.serial = new_serial
                sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
            # and restart the reader thread
            self._start_reader() 
Example #3
Source File: gateway_serial.py    From pymysensors with MIT License 5 votes vote down vote up
def sync_connect(transport):
    """Connect to the serial port.

    This should be run in a new thread.
    """
    while transport.protocol:
        _LOGGER.info("Trying to connect to %s", transport.gateway.port)
        try:
            ser = serial.serial_for_url(
                transport.gateway.port,
                transport.gateway.baud,
                timeout=transport.timeout,
            )
        except serial.SerialException:
            _LOGGER.error("Unable to connect to %s", transport.gateway.port)
            _LOGGER.info(
                "Waiting %s secs before trying to connect again",
                transport.reconnect_timeout,
            )
            time.sleep(transport.reconnect_timeout)
        else:
            serial_transport = serial.threaded.ReaderThread(
                ser, lambda: transport.protocol
            )
            serial_transport.daemon = False
            serial_transport.start()
            serial_transport.connect()
            return 
Example #4
Source File: test_rtu.py    From uModbus with Mozilla Public License 2.0 5 votes vote down vote up
def test_rtu_server_send_empty_message(rtu_server):
    rtu_server.serial_port = serial_for_url('loop://')
    rtu_server.serial_port.write(b'')

    with pytest.raises(ValueError):
        rtu_server.serve_once() 
Example #5
Source File: test_rtu.py    From uModbus with Mozilla Public License 2.0 5 votes vote down vote up
def test_send_message_with_timeout():
    """ Test if TimoutError is raised when serial port doesn't receive enough
    data.
    """
    s = serial_for_url('loop://', timeout=0)
    # As we are using a loop, the sent request will be read back as response.
    # To test timeout use a request that needs more bytes for the response.
    message = read_coils(slave_id=0, starting_address=1, quantity=40)

    with pytest.raises(ValueError):
        send_message(message, s) 
Example #6
Source File: Serial.py    From insteon-mqtt with GNU General Public License v3.0 5 votes vote down vote up
def _open_client(self):
        """Create the serial client.

        The connection is not actually opened yet - that happens in
        connect().
        """
        client = serial.serial_for_url(self._port, do_not_open=True, timeout=0,
                                       write_timeout=0)
        client.baudrate = self._baudrate
        client.parity = self._parity
        return client

    #----------------------------------------------------------------------- 
Example #7
Source File: Serial.py    From insteon-mqtt with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, port=None, baudrate=19200, parity=serial.PARITY_NONE,
                 reconnect_dt=10):
        """Constructor.

        The client will not be connected until connect() is called.
        Either manually or by the network manager.

        Args:
          port (str):  The serial device or URL to connect to.  See
                       the serial.serial_for_url() documentation for details.
          baudrate (int):  Baud rate to use in the connection.
          parity:  serial.PARITY value to use.
          reconnect_dt (int): Time in seconds to try and reconnect if the
                       connection drops.

        """
        # Public signals to connect to for read/write notification.
        self.signal_read = Signal()   # (Serial, bytes)
        self.signal_wrote = Signal()  # (Serial, bytes)

        super().__init__()

        self._port = port
        self._baudrate = baudrate
        self._parity = parity
        self._reconnect_dt = reconnect_dt
        self._fd = None

        # List of packets to write.  Each is a tuple of (bytes, time) where
        # the time is the time after which to do the write.
        self._write_buf = []

        # Create the serial client but don't open it yet.  We'll wait for a
        # connection call to do that.
        self.client = None
        if port:
            self._open_client()

        self.signal_connected.connect(self._connected)

    #----------------------------------------------------------------------- 
Example #8
Source File: esptool.py    From EspBuddy with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
        """Base constructor for ESPLoader bootloader interaction

        Don't call this constructor, either instantiate ESP8266ROM
        or ESP32ROM, or use ESPLoader.detect_chip().

        This base class has all of the instance methods for bootloader
        functionality supported across various chips & stub
        loaders. Subclasses replace the functions they don't support
        with ones which throw NotImplementedInROMError().

        """
        if isinstance(port, basestring):
            self._port = serial.serial_for_url(port)
        else:
            self._port = port
        self._slip_reader = slip_reader(self._port, self.trace)
        # setting baud rate in a separate step is a workaround for
        # CH341 driver on some Linux versions (this opens at 9600 then
        # sets), shouldn't matter for other platforms/drivers. See
        # https://github.com/espressif/esptool/issues/44#issuecomment-107094446
        self._set_port_baudrate(baud)
        self._trace_enabled = trace_enabled
        # set write timeout, to prevent esptool blocked at write forever.
        try:
            self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT
        except NotImplementedError:
            # no write timeout for RFC2217 ports
            # need to set the property back to None or it will continue to fail
            self._port.write_timeout = None 
Example #9
Source File: test_source_handler.py    From python-can-monitor with MIT License 5 votes vote down vote up
def setUp(self):
        self.serial_handler = SerialHandler("LOOP FOR TESTS")  # device_name will not be used
        self.serial_handler.serial_device = serial.serial_for_url('loop://') 
Example #10
Source File: serial_asyncio.py    From kivy-smoothie-host with GNU General Public License v3.0 5 votes vote down vote up
def create_serial_connection(loop, protocol_factory, *args, **kwargs):
    ser = serial.serial_for_url(*args, **kwargs)
    protocol = protocol_factory()
    transport = SerialTransport(loop, protocol, ser)
    return (transport, protocol) 
Example #11
Source File: miniterm.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
        try:
            self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
        except AttributeError:
            # happens when the installed pyserial is older than 2.5. use the
            # Serial class directly then.
            self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
        self.echo = echo
        self.repr_mode = repr_mode
        self.convert_outgoing = convert_outgoing
        self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
        self.dtr_state = True
        self.rts_state = True
        self.break_state = False 
Example #12
Source File: miniterm.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
        try:
            self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
        except AttributeError:
            # happens when the installed pyserial is older than 2.5. use the
            # Serial class directly then.
            self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
        self.echo = echo
        self.repr_mode = repr_mode
        self.convert_outgoing = convert_outgoing
        self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
        self.dtr_state = True
        self.rts_state = True
        self.break_state = False 
Example #13
Source File: test_serial.py    From pyrealtime with MIT License 5 votes vote down vote up
def setUp(self):
        self.s = serial.serial_for_url(PORT, timeout=10) 
Example #14
Source File: test_esptool.py    From esptool with GNU General Public License v2.0 5 votes vote down vote up
def test_load_ram(self):
        """ Verify load_ram command

        The "hello world" binary programs for each chip print
        "Hello world!\n" to the serial port.
        """
        self.run_esptool("load_ram images/helloworld-%s.bin" % chip)
        p = serial.serial_for_url(serialport, default_baudrate)
        p.timeout = 0.2
        output = p.read(100)
        print("Output: %r" % output)
        self.assertIn(b"Hello world!", output)
        p.close() 
Example #15
Source File: esptool.py    From esptool with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
        """Base constructor for ESPLoader bootloader interaction

        Don't call this constructor, either instantiate ESP8266ROM
        or ESP32ROM, or use ESPLoader.detect_chip().

        This base class has all of the instance methods for bootloader
        functionality supported across various chips & stub
        loaders. Subclasses replace the functions they don't support
        with ones which throw NotImplementedInROMError().

        """
        self.secure_download_mode = False  # flag is set to True if esptool detects the ROM is in Secure Download Mode

        if isinstance(port, basestring):
            self._port = serial.serial_for_url(port)
        else:
            self._port = port
        self._slip_reader = slip_reader(self._port, self.trace)
        # setting baud rate in a separate step is a workaround for
        # CH341 driver on some Linux versions (this opens at 9600 then
        # sets), shouldn't matter for other platforms/drivers. See
        # https://github.com/espressif/esptool/issues/44#issuecomment-107094446
        self._set_port_baudrate(baud)
        self._trace_enabled = trace_enabled
        # set write timeout, to prevent esptool blocked at write forever.
        try:
            self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT
        except NotImplementedError:
            # no write timeout for RFC2217 ports
            # need to set the property back to None or it will continue to fail
            self._port.write_timeout = None 
Example #16
Source File: mppinverter.py    From mpp-solar with MIT License 5 votes vote down vote up
def _doSerialCommand(self, command):
        """
        Opens serial connection, sends command (multiple times if needed)
        and returns the byte_response
        """
        command.clearByteResponse()
        response_line = None
        log.debug('port %s, baudrate %s', self._serial_device, self._baud_rate)
        try:
            with serial.serial_for_url(self._serial_device, self._baud_rate) as s:
                # Execute command multiple times, increase timeouts each time
                for x in range(1, 5):
                    log.debug('Command execution attempt %d...', x)
                    s.timeout = 1 + x
                    s.write_timeout = 1 + x
                    s.flushInput()
                    s.flushOutput()
                    s.write(command.byte_command)
                    time.sleep(0.5 * x)  # give serial port time to receive the data
                    response_line = s.readline()
                    log.debug('serial byte_response was: %s', response_line)
                    command.setByteResponse(response_line)
                    return command
        except Exception as e:
            log.warning("Serial read error: {}".format(e))
        log.info('Command execution failed')
        return command 
Example #17
Source File: test_ayab_communication.py    From knitlib with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
    self.dummy_serial = serial.serial_for_url("loop://logging=debug")
    self.comm_dummy = AyabCommunication(self.dummy_serial) 
Example #18
Source File: esptool.py    From phatsniffer with MIT License 5 votes vote down vote up
def __init__(self, port=0, baud=ESP_ROM_BAUD):
        self._port = serial.serial_for_url(port)
        self._slip_reader = slip_reader(self._port)
        # setting baud rate in a separate step is a workaround for
        # CH341 driver on some Linux versions (this opens at 9600 then
        # sets), shouldn't matter for other platforms/drivers. See
        # https://github.com/espressif/esptool/issues/44#issuecomment-107094446
        self._port.baudrate = baud 
Example #19
Source File: esptool.py    From nodemcu-pyflasher with MIT License 5 votes vote down vote up
def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
        """Base constructor for ESPLoader bootloader interaction

        Don't call this constructor, either instantiate ESP8266ROM
        or ESP32ROM, or use ESPLoader.detect_chip().

        This base class has all of the instance methods for bootloader
        functionality supported across various chips & stub
        loaders. Subclasses replace the functions they don't support
        with ones which throw NotImplementedInROMError().

        """
        if isinstance(port, basestring):
            self._port = serial.serial_for_url(port)
        else:
            self._port = port
        self._slip_reader = slip_reader(self._port, self.trace)
        # setting baud rate in a separate step is a workaround for
        # CH341 driver on some Linux versions (this opens at 9600 then
        # sets), shouldn't matter for other platforms/drivers. See
        # https://github.com/espressif/esptool/issues/44#issuecomment-107094446
        self._set_port_baudrate(baud)
        self._trace_enabled = trace_enabled
        # set write timeout, to prevent esptool blocked at write forever.
        try:
            self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT
        except NotImplementedError:
            # no write timeout for RFC2217 ports
            # need to set the property back to None or it will continue to fail
            self._port.write_timeout = None 
Example #20
Source File: test_communication.py    From ayab-desktop with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
    self.dummy_serial = serial.serial_for_url("loop://logging=debug")
    self.comm_dummy = AyabCommunication(self.dummy_serial) 
Example #21
Source File: uploader.py    From nodemcu-uploader with MIT License 4 votes vote down vote up
def __init__(self, port=PORT, baud=BAUD, start_baud=START_BAUD, timeout=TIMEOUT, autobaud_time=AUTOBAUD_TIME):
        self._timeout = Uploader.TIMEOUT
        self.set_timeout(timeout)
        log.info('opening port %s with %s baud', port, start_baud)
        if port == 'loop://':
            self._port = serial.serial_for_url(port, start_baud, timeout=timeout)
        else:
            self._port = serial.Serial(port, start_baud, timeout=timeout)

        # black magic aka proxifying
        # self._port = wrap(self._port)

        self.start_baud = start_baud
        self.baud = baud
        self.autobaud_time = autobaud_time
        # Keeps things working, if following connections are made:
        # RTS = CH_PD (i.e reset)
        # DTR = GPIO0
        self._port.setRTS(False)
        self._port.setDTR(False)

        def __sync():
            """Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)"""
            log.debug('getting in sync with LUA')
            self.__clear_buffers()
            try:
                self.__writeln('UUUUUUUUUUUU')  # Send enough characters for auto-baud
                self.__clear_buffers()
                time.sleep(self.autobaud_time)  # Wait for autobaud timer to expire
                self.__exchange(';')  # Get a defined state
                self.__writeln('print("%sync%");')
                self.__expect('%sync%\r\n> ')
            except CommunicationTimeout:
                raise DeviceNotFoundException('Device not found or wrong port')

        __sync()

        if baud != start_baud:
            self.__set_baudrate(baud)

            # Get in sync again
            __sync()

        self.line_number = 0 
Example #22
Source File: wmr928nx.py    From wfrog with GNU General Public License v3.0 4 votes vote down vote up
def run(self, generate_event, send_event):     
        import serial
        # Initialize injected functions used by BaseStation
        self.generate_event = generate_event
        self.send_event = send_event        
        
        self.logger.info("Thread started")
        while True:
            try:
                self.logger.info("Opening serial port")
                ## Open Serial port
                try:
                    ser = serial.serial_for_url(self.port, 9600, 
                                                parity=serial.PARITY_NONE, 
                                                bytesize=serial.EIGHTBITS,
                                                stopbits=serial.STOPBITS_ONE,
                                                timeout=60)
                except AttributeError:
                    # happens when the installed pyserial is older than 2.5. use the
                    # Serial class directly then.
                    ser = serial.Serial(self.port, 9600, 
                                        parity=serial.PARITY_NONE, 
                                        bytesize=serial.EIGHTBITS,
                                        stopbits=serial.STOPBITS_ONE,
                                        timeout=60)
                #ser = serial.Serial()
                #ser.setBaudrate(9600)
                #ser.setParity(serial.PARITY_NONE)
                #ser.setByteSize(serial.EIGHTBITS)
                #ser.setStopbits(serial.STOPBITS_ONE)
                #ser.setPort(self.port)
                #ser.setTimeout(60)  # 60s timeout
                #ser.open()
                
                ser.setRTS(True)
                ## Do the actual work
                self.logger.info("Serial port open")
                self._run(ser)
            except:
                self.logger.exception("WMR928NX reader exception")

            ## Close serial port connection
            self.logger.critical("Serial port WMR928NX connection failure")
            try:
                ser.close()
                ser = None
            except:
                pass
            ## Wait 10 seconds
            time.sleep(10) 
Example #23
Source File: cyton.py    From OpenBCI_Python with MIT License 4 votes vote down vote up
def __init__(self, port=None, baud=115200, filter_data=True, scaled_output=True,
                 daisy=False, aux=False, impedance=False, log=True, timeout=None):
        self.log = log  # print_incoming_text needs log
        self.streaming = False
        self.baudrate = baud
        self.timeout = timeout
        if not port:
            port = self.find_port()
        self.port = port
        # might be handy to know API
        self.board_type = "cyton"
        print("Connecting to V3 at port %s" % (port))
        if port == "loop://":
            # For testing purposes
            self.ser = serial.serial_for_url(port, baudrate=baud, timeout=timeout)
        else:
            self.ser = serial.Serial(port=port, baudrate=baud, timeout=timeout)

        print("Serial established...")

        time.sleep(2)
        # Initialize 32-bit board, doesn't affect 8bit board
        self.ser.write(b'v')

        # wait for device to be ready
        time.sleep(1)
        if port != "loop://":
            self.print_incoming_text()

        self.streaming = False
        self.filtering_data = filter_data
        self.scaling_output = scaled_output
        # number of EEG channels per sample *from the board*
        self.eeg_channels_per_sample = 8
        # number of AUX channels per sample *from the board*
        self.aux_channels_per_sample = 3
        self.imp_channels_per_sample = 0  # impedance check not supported at the moment
        self.read_state = 0
        self.daisy = daisy
        self.last_odd_sample = OpenBCISample(-1, [], [])  # used for daisy
        self.log_packet_count = 0
        self.attempt_reconnect = False
        self.last_reconnect = 0
        self.reconnect_freq = 5
        self.packets_dropped = 0

        # Disconnects from board when terminated
        atexit.register(self.disconnect) 
Example #24
Source File: serial.py    From mqttwarn with Eclipse Public License 2.0 4 votes vote down vote up
def plugin(srv, item):
    global _serialport
    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    # item.config is brought in from the configuration file
    config   = item.config

    # addrs is a list[] associated with a particular target.
    # While it may contain more than one item (e.g. pushover)
    # the `serial' service carries one two, i.e. a com name and baudrate
    try:
        comName = item.addrs[0].format(**item.data)
        comBaudRate = int(item.addrs[1])
    except:
        srv.logging.error("Incorrect target configuration for {0}/{1}".format(item.service, item.target))
        return False

    # If the incoming payload has been transformed, use that,
    # else the original payload
    text = item.message

    # If message specifies the hex keyword try to transform bytes from hex
    # else send string as it is
    test = text[:5]
    if test == ":HEX:":
        text = bytes(bytearray.fromhex(text[5:]))

    # Append newline if config option is set
    if type(config) == dict and 'append_newline' in config and config['append_newline']:
        text = text + "\n"

    try:
        try:
            if callable(getattr(_serialport, "is_open", None)):
                _serialport.is_open
            else:
                _serialport.isOpen
            srv.logging.debug("%s already open", comName)
        except:
            #Open port for first use
            srv.logging.debug("Open %s with %d baud", comName, comBaudRate)
            _serialport = serial.serial_for_url(comName)
            _serialport.baudrate = comBaudRate

        _serialport.write(text.encode('utf-8'))

    except serial.SerialException as e:
        srv.logging.warning("Cannot write to com port `%s': %s" % (comName, e))
        return False

    return True