Python serial.SerialException() Examples

The following are 30 code examples of serial.SerialException(). 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: serial_list.py    From wio-cli with MIT License 15 votes vote down vote up
def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/ttyUSB*') # ubuntu is /dev/ttyUSB0
    elif sys.platform.startswith('darwin'):
        # ports = glob.glob('/dev/tty.*')
        ports = glob.glob('/dev/tty.SLAB_USBtoUART*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except serial.SerialException as e:
            if e.errno == 13:
                raise e
            pass
        except OSError:
            pass
    return result


# if __name__ == '__main__':
#     print(serial_ports()) 
Example #2
Source File: io_serial.py    From foos with GNU General Public License v3.0 6 votes vote down vote up
def reader_thread(self):
        while True:
            if not self.ser:
                self.open_serial()
            try:
                line = self.ser.readline()
                try:
                    line = line.decode('ascii').strip()
                    ev = getEventForButton(line)
                    if ev:
                        self.bus.notify(*ev)
                except Exception as e:
                    logger.exception("Error reading data")

            except serial.SerialException as e:
                logger.error("Error reading data: %s", e)
                self.open_serial() 
Example #3
Source File: lynx_motion.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def _test_serial_connection(self):
        return

        # try:
            # If we fail to ping the port, this is a wrong port

            #self._serial.write("L\n")
#             r = self._serial.readline()
#             if not r:
#                 raise WrongSleepDepPortError
#             self.deprive(0)
#
#         except (OSError, serial.SerialException):
#             raise WrongSleepDepPortError
# #
#
# 
Example #4
Source File: lynx_basics.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def _find_port(self):
        all_port_tuples = list_ports.comports()
        logging.info("listing serial ports")

        all_ports = set()
        for ap, _, _  in all_port_tuples:
            all_ports |= {ap}
            logging.info("\t%s", str(ap))

        for ap in list(all_ports):
            logging.info("trying port %s", str(ap))

            try:
                #here we use a recursive strategy to find the good port (ap).
                SimpleLynxMotionConnection(ap)
                return ap
            except (WrongSleepDepPortError, serial.SerialException):
                warn_str = "Tried to use port %s. Failed." % ap
                logging.warning(warn_str)
                pass

        logging.error("No valid port detected!. Possibly, device not plugged/detected.")
        raise NoValidPortError() 
Example #5
Source File: lynx_basics.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def _test_serial_connection(self):
        return

        # try:
            # If we fail to ping the port, this is a wrong port

            #self._serial.write("L\n")
#             r = self._serial.readline()
#             if not r:
#                 raise WrongSleepDepPortError
#             self.deprive(0)
#
#         except (OSError, serial.SerialException):
#             raise WrongSleepDepPortError
# #
#
# 
Example #6
Source File: VNA.py    From nanovna-saver with GNU General Public License v3.0 6 votes vote down vote up
def readValues(self, value) -> List[str]:
        logger.debug("VNA reading %s", value)
        try:
            with self.app.serialLock:
                drain_serial(self.serial)
                self.serial.write(f"{value}\r".encode('ascii'))
                result = ""
                data = ""
                sleep(0.05)
                while data != "ch> ":
                    data = self.serial.readline().decode('ascii')
                    result += data
            values = result.split("\r\n")
            logger.debug(
                "VNA done reading %s (%d values)",
                value, len(values)-2)
            return values[1:-1]
        except serial.SerialException as exc:
            logger.exception(
                "Exception while reading %s: %s", value, exc)
        return [] 
Example #7
Source File: stk500v2.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def connect(self, port = 'COM22', speed = 115200):
		if self.serial != None:
			self.close()
		try:
			self.serial = Serial(str(port), speed, timeout=1, writeTimeout=10000)
		except SerialException as e:
			raise ispBase.IspError("Failed to open serial port")
		except:
			raise ispBase.IspError("Unexpected error while connecting to serial port:" + port + ":" + str(sys.exc_info()[0]))
		self.seq = 1
		
		#Reset the controller
		self.serial.setDTR(1)
		time.sleep(0.1)
		self.serial.setDTR(0)
		time.sleep(0.2)
		
		self.sendMessage([1])
		if self.sendMessage([0x10, 0xc8, 0x64, 0x19, 0x20, 0x00, 0x53, 0x03, 0xac, 0x53, 0x00, 0x00]) != [0x10, 0x00]:
			self.close()
			raise ispBase.IspError("Failed to enter programming mode") 
Example #8
Source File: serial_asyncio.py    From kivy-smoothie-host with GNU General Public License v3.0 6 votes vote down vote up
def _call_connection_lost(self, exc):
        """Close the connection.

        Informs the protocol through connection_lost() and clears
        pending buffers and closes the serial connection.
        """
        assert self._closing
        assert not self._has_writer
        assert not self._has_reader
        try:
            self._serial.flush()
        except (serial.SerialException if os.name == "nt" else termios.error):
            # ignore serial errors which may happen if the serial device was
            # hot-unplugged.
            pass
        try:
            self._protocol.connection_lost(exc)
        finally:
            self._write_buffer.clear()
            self._serial.close()
            self._serial = None
            self._protocol = None
            self._loop = None 
Example #9
Source File: RPiSensors.py    From BerePi with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def read(self):

        # for temperature and humidity
        sht_instance = SHT25()

        temp = sht_instance.read_temperature() 
        humidity = sht_instance.read_humidity()
        
        self.add('/temp', temp)
        self.add('/humidity', humidity)
        time.sleep(1.5)
        
        # for CO2
        ppm = 0
        try:
            in_byte = serial_in_device.read(SERIAL_READ_BYTE) 
            pos = 0
        except serial.SerialException, e:
            print e
        # sometimes, 12 byte alignment is incorrect
        # especially run on /etc/rc.local 
Example #10
Source File: quality_control.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def _find_port(self):
        all_port_tuples = list_ports.comports()
        logging.info("listing serial ports")

        all_ports = set()
        for ap, _, _  in all_port_tuples:
            all_ports |= {ap}
            logging.info("\t%s", str(ap))

        for ap in list(all_ports):
            logging.info("trying port %s", str(ap))

            try:
                #here we use a recursive strategy to find the good port (ap).
                SimpleLynxMotionConnection(ap)
                return ap
            except (WrongSleepDepPortError, serial.SerialException):
                warn_str = "Tried to use port %s. Failed." % ap
                logging.warning(warn_str)
                pass

        logging.error("No valid port detected!. Possibly, device not plugged/detected.")
        raise NoValidPortError() 
Example #11
Source File: layer_2_protocol.py    From Faraday-Software with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        while self.enabled:
            #Delay to allow threaded CPU utilization relaxing
            time.sleep(0.01)
            if(self.enabled):
                #Check for bytes to transmit over serial
                if(not self.serial_tx_queue.empty()):
                    while(not self.serial_tx_queue.empty()):
                        self.ser.write(self.serial_tx_queue.get())
                #Check for bytes to receive from serial
                try:
                    if self.ser.inWaiting() > 0:
                        rx_buffer_inwaiting = self.ser.inWaiting()
                        self.serial_rx_queue.put(self.ser.read(rx_buffer_inwaiting))
                except serial.SerialException:
                    logger.error("Port '{0}' disconnected!".format(self._port))
                    self.abort()


################################################################################
# Faraday_Datalink_Device_Transmit_Class() CLASS
# Description:
################################################################################ 
Example #12
Source File: serial_terminal.py    From pros-cli2 with Mozilla Public License 2.0 6 votes vote down vote up
def reader(self):
        start_time = time.clock
        try:
            while self.alive and self._reader_alive:
                data = self.serial.read(self.serial.in_waiting or 1)
                if data:
                    if self.output_raw:
                        self.console.write_bytes(data)
                    else:
                        text = data.decode('utf-8', 'ignore')
                        for transformation in self.transformations:
                            text = transformation(text)
                        self.console.write(text)
        except serial.SerialException as e:
            debug(e)
            self.alive = False 
Example #13
Source File: VNA.py    From nanovna-saver with GNU General Public License v3.0 6 votes vote down vote up
def readFirmware(self) -> str:
        try:
            with self.app.serialLock:
                drain_serial(self.serial)
                self.serial.write("info\r".encode('ascii'))
                result = ""
                data = ""
                sleep(0.01)
                while data != "ch> ":
                    data = self.serial.readline().decode('ascii')
                    result += data
            return result
        except serial.SerialException as exc:
            logger.exception(
                "Exception while reading firmware data: %s", exc)
        return "" 
Example #14
Source File: AVNA.py    From nanovna-saver with GNU General Public License v3.0 6 votes vote down vote up
def getCalibration(self) -> str:
        logger.debug("Reading calibration info.")
        if not self.serial.is_open:
            return "Not connected."
        with self.app.serialLock:
            try:
                data = "a"
                while data != "":
                    data = self.serial.readline().decode('ascii')
                self.serial.write("cal\r".encode('ascii'))
                result = ""
                data = ""
                sleep(0.1)
                while "ch>" not in data:
                    data = self.serial.readline().decode('ascii')
                    result += data
                values = result.splitlines()
                return values[1]
            except serial.SerialException as exc:
                logger.exception("Exception while reading calibration info: %s", exc)
        return "Unknown" 
Example #15
Source File: NanoVNA.py    From nanovna-saver with GNU General Public License v3.0 6 votes vote down vote up
def readVersion(self):
        logger.debug("Reading version info.")
        if not self.serial.is_open:
            return ""
        try:
            with self.app.serialLock:
                drain_serial(self.serial)
                self.serial.write("version\r".encode('ascii'))
                result = ""
                data = ""
                sleep(0.1)
                while "ch>" not in data:
                    data = self.serial.readline().decode('ascii')
                    result += data
            values = result.splitlines()
            logger.debug("Found version info: %s", values[1])
            return values[1]
        except serial.SerialException as exc:
            logger.exception("Exception while reading firmware version: %s", exc)
        return "" 
Example #16
Source File: NanoVNA.py    From nanovna-saver with GNU General Public License v3.0 6 votes vote down vote up
def getCalibration(self) -> str:
        logger.debug("Reading calibration info.")
        if not self.serial.is_open:
            return "Not connected."
        with self.app.serialLock:
            try:
                drain_serial(self.serial)
                self.serial.write("cal\r".encode('ascii'))
                result = ""
                data = ""
                sleep(0.1)
                while "ch>" not in data:
                    data = self.serial.readline().decode('ascii')
                    result += data
                values = result.splitlines()
                return values[1]
            except serial.SerialException as exc:
                logger.exception("Exception while reading calibration info: %s", exc)
        return "Unknown" 
Example #17
Source File: USBPrinterOutputDevice.py    From Cura with GNU Lesser General Public License v3.0 6 votes vote down vote up
def connect(self):
        self._firmware_name = None  # after each connection ensure that the firmware name is removed

        if self._baud_rate is None:
            if self._use_auto_detect:
                auto_detect_job = AutoDetectBaudJob(self._serial_port)
                auto_detect_job.start()
                auto_detect_job.finished.connect(self._autoDetectFinished)
            return
        if self._serial is None:
            try:
                self._serial = Serial(str(self._serial_port), self._baud_rate, timeout=self._timeout, writeTimeout=self._timeout)
            except SerialException:
                Logger.warning("An exception occurred while trying to create serial connection.")
                return
            except OSError as e:
                Logger.warning("The serial device is suddenly unavailable while trying to create a serial connection: {err}".format(err = str(e)))
                return
        CuraApplication.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerStackChanged)
        self._onGlobalContainerStackChanged()
        self.setConnectionState(ConnectionState.Connected)
        self._update_thread.start() 
Example #18
Source File: USBPrinterOutputDevice.py    From Cura with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _sendCommand(self, command: Union[str, bytes]):
        if self._serial is None or self._connection_state != ConnectionState.Connected:
            return

        new_command = cast(bytes, command) if type(command) is bytes else cast(str, command).encode() # type: bytes
        if not new_command.endswith(b"\n"):
            new_command += b"\n"
        try:
            self._command_received.clear()
            self._serial.write(new_command)
        except SerialTimeoutException:
            Logger.log("w", "Timeout when sending command to printer via USB.")
            self._command_received.set()
        except SerialException:
            Logger.logException("w", "An unexpected exception occurred while writing to the serial.")
            self.setConnectionState(ConnectionState.Error) 
Example #19
Source File: protocol.py    From pyshtrih with MIT License 6 votes vote down vote up
def connect(self):
        """
        Метод подключения к устройству.
        """

        if not self.connected:
            self.serial.port = self.port
            if not self.serial.isOpen():
                try:
                    self.serial.open()
                except serial.SerialException as exc:
                    raise excepts.NoConnectionError(
                        u'Не удалось открыть порт {} ({})'.format(
                            self.port, exc
                        )
                    )

            for r in self.check(self.CHECK_NUM, True):
                if r:
                    self.connected = True
                    return
            else:
                self.serial.close()
                raise excepts.NoConnectionError() 
Example #20
Source File: termWidget.py    From uPyIDE with GNU General Public License v3.0 6 votes vote down vote up
def serial_ports():
    """ Lists serial port names
        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')
    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result 
Example #21
Source File: cyton.py    From OpenBCI_Python with MIT License 6 votes vote down vote up
def find_port(self):
        # Finds the serial port names
        if sys.platform.startswith('win'):
            ports = ['COM%s' % (i + 1) for i in range(256)]
        elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
            ports = glob.glob('/dev/ttyUSB*')
        elif sys.platform.startswith('darwin'):
            ports = glob.glob('/dev/tty.usbserial*')
        else:
            raise EnvironmentError('Error finding ports on your operating system')
        openbci_port = ''
        for port in ports:
            try:
                s = serial.Serial(port=port, baudrate=self.baudrate, timeout=self.timeout)
                s.write(b'v')
                openbci_serial = self.openbci_id(s)
                s.close()
                if openbci_serial:
                    openbci_port = port
            except (OSError, serial.SerialException):
                pass
        if openbci_port == '':
            raise OSError('Cannot find OpenBCI port')
        else:
            return openbci_port 
Example #22
Source File: log.py    From cloudbase-init with Apache License 2.0 6 votes vote down vote up
def setup(product_name):
    log.setup(CONF, product_name)

    if CONF.logging_serial_port_settings:
        try:
            serialportlog = SerialPortHandler()
            log_root = log.getLogger(product_name).logger
            log_root.addHandler(serialportlog)

            datefmt = CONF.log_date_format
            serialportlog.setFormatter(
                formatters.ContextFormatter(project=product_name,
                                            datefmt=datefmt))
        except serial.SerialException:
            LOG.warn("Serial port: {0} could not be opened".format(
                     CONF.logging_serial_port_settings)) 
Example #23
Source File: serialcommunicator.py    From enocean with MIT License 6 votes vote down vote up
def run(self):
        self.logger.info('SerialCommunicator started')
        while not self._stop_flag.is_set():
            # If there's messages in transmit queue
            # send them
            while True:
                packet = self._get_from_send_queue()
                if not packet:
                    break
                try:
                    self.__ser.write(bytearray(packet.build()))
                except serial.SerialException:
                    self.stop()

            # Read chars from serial port as hex numbers
            try:
                self._buffer.extend(bytearray(self.__ser.read(16)))
            except serial.SerialException:
                self.logger.error('Serial port exception! (device disconnected or multiple access on port?)')
                self.stop()
            self.parse()
            time.sleep(0)

        self.__ser.close()
        self.logger.info('SerialCommunicator stopped') 
Example #24
Source File: miniterm.py    From ddt4all with GNU General Public License v3.0 6 votes vote down vote up
def dump_port_settings(self):
        """Write current settings to sys.stderr"""
        sys.stderr.write("\n--- Settings: {p.name}  {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
            p=self.serial))
        sys.stderr.write('--- RTS: {:8}  DTR: {:8}  BREAK: {:8}\n'.format(
            ('active' if self.serial.rts else 'inactive'),
            ('active' if self.serial.dtr else 'inactive'),
            ('active' if self.serial.break_condition else 'inactive')))
        try:
            sys.stderr.write('--- CTS: {:8}  DSR: {:8}  RI: {:8}  CD: {:8}\n'.format(
                ('active' if self.serial.cts else 'inactive'),
                ('active' if self.serial.dsr else 'inactive'),
                ('active' if self.serial.ri else 'inactive'),
                ('active' if self.serial.cd else 'inactive')))
        except serial.SerialException:
            # on RFC 2217 ports, it can happen if no modem state notification was
            # yet received. ignore this error.
            pass
        sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
        sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
        sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
        sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
        sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
        sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters))) 
Example #25
Source File: miniterm.py    From ddt4all with GNU General Public License v3.0 6 votes vote down vote up
def reader(self):
        """loop and copy serial->console"""
        try:
            while self.alive and self._reader_alive:
                # read all that is there or wait for one byte
                data = self.serial.read(self.serial.in_waiting or 1)
                if data:
                    if self.raw:
                        self.console.write_bytes(data)
                    else:
                        text = self.rx_decoder.decode(data)
                        for transformation in self.rx_transformations:
                            text = transformation.rx(text)
                        self.console.write(text)
        except serial.SerialException:
            self.alive = False
            self.console.cancel()
            raise       # XXX handle instead of re-raise? 
Example #26
Source File: __init__.py    From android3dblendermouse with Apache License 2.0 5 votes vote down vote up
def run(self):
        """Reader loop"""
        self.serial.timeout = 1
        self.protocol = self.protocol_factory()
        try:
            self.protocol.connection_made(self)
        except Exception as e:
            self.alive = False
            self.protocol.connection_lost(e)
            self._connection_made.set()
            return
        error = None
        self._connection_made.set()
        while self.alive and self.serial.is_open:
            try:
                # read all that is there or wait for one byte (blocking)
                data = self.serial.read(self.serial.in_waiting or 1)
            except serial.SerialException as e:
                # probably some I/O problem such as disconnected USB serial
                # adapters -> exit
                error = e
                break
            else:
                if data:
                    # make a separated try-except for called used code
                    try:
                        self.protocol.data_received(data)
                    except Exception as e:
                        error = e
                        break
        self.alive = False
        self.protocol.connection_lost(error)
        self.protocol = None 
Example #27
Source File: serial_asyncio.py    From kivy-smoothie-host with GNU General Public License v3.0 5 votes vote down vote up
def _read_ready(self):
        try:
            data = self._serial.read(self._max_read_size)
        except serial.SerialException as e:
            self._close(exc=e)
        else:
            if data:
                self._protocol.data_received(data) 
Example #28
Source File: protocol_hwgrep.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fromURL(self, url):
        """extract host and port from an URL string"""
        if url.lower().startswith("hwgrep://"): url = url[9:]
        # use a for loop to get the 1st element from the generator
        for port, desc, hwid in serial.tools.list_ports.grep(url):
            return port
        else:
            raise serial.SerialException('no ports found matching regexp %r' % (url,))

    # override property 
Example #29
Source File: miniterm.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dump_port_settings(self):
        sys.stderr.write("\n--- Settings: %s  %s,%s,%s,%s\n" % (
                self.serial.portstr,
                self.serial.baudrate,
                self.serial.bytesize,
                self.serial.parity,
                self.serial.stopbits))
        sys.stderr.write('--- RTS: %-8s  DTR: %-8s  BREAK: %-8s\n' % (
                (self.rts_state and 'active' or 'inactive'),
                (self.dtr_state and 'active' or 'inactive'),
                (self.break_state and 'active' or 'inactive')))
        try:
            sys.stderr.write('--- CTS: %-8s  DSR: %-8s  RI: %-8s  CD: %-8s\n' % (
                    (self.serial.getCTS() and 'active' or 'inactive'),
                    (self.serial.getDSR() and 'active' or 'inactive'),
                    (self.serial.getRI() and 'active' or 'inactive'),
                    (self.serial.getCD() and 'active' or 'inactive')))
        except serial.SerialException:
            # on RFC 2217 ports it can happen to no modem state notification was
            # yet received. ignore this error.
            pass
        sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
        sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
        sys.stderr.write('--- data escaping: %s  linefeed: %s\n' % (
                REPR_MODES[self.repr_mode],
                LF_MODES[self.convert_outgoing])) 
Example #30
Source File: miniterm.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dump_port_settings(self):
        sys.stderr.write("\n--- Settings: %s  %s,%s,%s,%s\n" % (
                self.serial.portstr,
                self.serial.baudrate,
                self.serial.bytesize,
                self.serial.parity,
                self.serial.stopbits))
        sys.stderr.write('--- RTS: %-8s  DTR: %-8s  BREAK: %-8s\n' % (
                (self.rts_state and 'active' or 'inactive'),
                (self.dtr_state and 'active' or 'inactive'),
                (self.break_state and 'active' or 'inactive')))
        try:
            sys.stderr.write('--- CTS: %-8s  DSR: %-8s  RI: %-8s  CD: %-8s\n' % (
                    (self.serial.getCTS() and 'active' or 'inactive'),
                    (self.serial.getDSR() and 'active' or 'inactive'),
                    (self.serial.getRI() and 'active' or 'inactive'),
                    (self.serial.getCD() and 'active' or 'inactive')))
        except serial.SerialException:
            # on RFC 2217 ports it can happen to no modem state notification was
            # yet received. ignore this error.
            pass
        sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
        sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
        sys.stderr.write('--- data escaping: %s  linefeed: %s\n' % (
                REPR_MODES[self.repr_mode],
                LF_MODES[self.convert_outgoing]))