當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。