本文整理汇总了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
示例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
示例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:
################################################################################
示例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
示例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()
示例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)
示例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()
示例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)))
示例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?
示例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
示例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')
示例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))
示例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
示例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
示例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"