当前位置: 首页>>代码示例>>Python>>正文


Python serial.SerialException方法代码示例

本文整理汇总了Python中serial.SerialException方法的典型用法代码示例。如果您正苦于以下问题:Python serial.SerialException方法的具体用法?Python serial.SerialException怎么用?Python serial.SerialException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在serial的用法示例。


在下文中一共展示了serial.SerialException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _call_connection_lost

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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 
开发者ID:wolfmanjm,项目名称:kivy-smoothie-host,代码行数:25,代码来源:serial_asyncio.py

示例2: __init__

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
def __init__(self, port, baud, timeout):
        self._port = port
        self._baud = baud
        self._timeout = timeout
        self.serial_rx_queue = Queue.Queue()  # Infinite
        self.serial_tx_queue = Queue.Queue()  # Infinite
        self.enabled = True
        try:
            self.ser = serial.Serial(port, baud, timeout=timeout)
        except serial.SerialException as e:
            logger.error(e)
            sys.exit(1)  # Sys.exit(1) is an error

        #Start
        threading.Thread.__init__(self)
        self.start()  #Starts the run() function and thread 
开发者ID:FaradayRF,项目名称:Faraday-Software,代码行数:18,代码来源:layer_2_protocol.py

示例3: run

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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:
################################################################################ 
开发者ID:FaradayRF,项目名称:Faraday-Software,代码行数:25,代码来源:layer_2_protocol.py

示例4: read

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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 
开发者ID:jeonghoonkang,项目名称:BerePi,代码行数:23,代码来源:RPiSensors.py

示例5: connect

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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() 
开发者ID:Ultimaker,项目名称:Cura,代码行数:24,代码来源:USBPrinterOutputDevice.py

示例6: _sendCommand

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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) 
开发者ID:Ultimaker,项目名称:Cura,代码行数:18,代码来源:USBPrinterOutputDevice.py

示例7: connect

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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() 
开发者ID:oleg-golovanov,项目名称:pyshtrih,代码行数:26,代码来源:protocol.py

示例8: dump_port_settings

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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))) 
开发者ID:cedricp,项目名称:ddt4all,代码行数:26,代码来源:miniterm.py

示例9: reader

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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? 
开发者ID:cedricp,项目名称:ddt4all,代码行数:20,代码来源:miniterm.py

示例10: reader

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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 
开发者ID:purduesigbots,项目名称:pros-cli2,代码行数:18,代码来源:serial_terminal.py

示例11: run

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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') 
开发者ID:kipe,项目名称:enocean,代码行数:27,代码来源:serialcommunicator.py

示例12: setup

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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)) 
开发者ID:cloudbase,项目名称:cloudbase-init,代码行数:18,代码来源:log.py

示例13: find_port

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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 
开发者ID:openbci-archive,项目名称:OpenBCI_Python,代码行数:27,代码来源:cyton.py

示例14: serial_ports

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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 
开发者ID:martinribelotta,项目名称:uPyIDE,代码行数:27,代码来源:termWidget.py

示例15: getCalibration

# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialException [as 别名]
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" 
开发者ID:NanoVNA-Saver,项目名称:nanovna-saver,代码行数:21,代码来源:NanoVNA.py


注:本文中的serial.SerialException方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。