本文整理汇总了Python中serial.SerialTimeoutException方法的典型用法代码示例。如果您正苦于以下问题:Python serial.SerialTimeoutException方法的具体用法?Python serial.SerialTimeoutException怎么用?Python serial.SerialTimeoutException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类serial
的用法示例。
在下文中一共展示了serial.SerialTimeoutException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _sendCommand
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [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)
示例2: send_command
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def send_command(self, command):
"""
Send a command to the micro:bit over the serial interface
:param command: command sent to micro:bit
:return: If the command is a poll request, return the poll response
"""
try:
cmd = command + '\n'
self.micro_bit_serial.write(cmd.encode())
except serial.SerialTimeoutException:
return command
# wait for reply
# read and decode a line and strip it of trailing \r\n
if command == 'g':
while not self.micro_bit_serial.inWaiting():
pass
# noinspection PyArgumentList
data = self.micro_bit_serial.readline().decode().strip()
return data
示例3: checkPortStatus
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def checkPortStatus(self, update_button_state):
try:
with serial.Serial(self.port[0], 115200, timeout=0.2, writeTimeout=0.2) as ser:
fpga = TinyFPGAB(ser)
if fpga.is_bootloader_active():
com_port_status_sv.set("Connected to TinyFPGA B2. Ready to program.")
return True
else:
com_port_status_sv.set("Unable to communicate with TinyFPGA. Reconnect and reset TinyFPGA before programming.")
return False
except serial.SerialTimeoutException:
com_port_status_sv.set("Hmm...try pressing the reset button on TinyFPGA again.")
return False
except:
com_port_status_sv.set("Bootloader not active. Press reset button on TinyFPGA before programming.")
return False
示例4: read
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def read(self, count):
"""Reads data from device or interface synchronously.
Corresponds to viRead function of the VISA library.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: bytes, constants.StatusCode
"""
end_in, _ = self.get_attribute(constants.VI_ATTR_ASRL_END_IN)
suppress_end_en, _ = self.get_attribute(constants.VI_ATTR_SUPPRESS_END_EN)
reader = lambda: self.interface.read(1)
if end_in == SerialTermination.none:
checker = lambda current: False
elif end_in == SerialTermination.last_bit:
mask = 2 ** self.interface.bytesize
checker = lambda current: bool(common.last_int(current) & mask)
elif end_in == SerialTermination.termination_char:
end_char, _ = self.get_attribute(constants.VI_ATTR_TERMCHAR)
checker = lambda current: common.last_int(current) == end_char
else:
raise ValueError("Unknown value for VI_ATTR_ASRL_END_IN: %s" % end_in)
return self._read(
reader,
count,
checker,
suppress_end_en,
None,
False,
serial.SerialTimeoutException,
)
示例5: write
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def write(self, frame):
if self.tty is not None:
log.log(logging.DEBUG-1, ">>> %s", hexlify(frame).decode())
self.tty.flushInput()
try:
self.tty.write(frame)
except serial.SerialTimeoutException:
raise IOError(errno.EIO, os.strerror(errno.EIO))
示例6: sendMessage
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def sendMessage(self, data):
message = struct.pack(">BBHB", 0x1B, self.seq, len(data), 0x0E)
for c in data:
message += struct.pack(">B", c)
checksum = 0
for c in message:
checksum ^= c
message += struct.pack(">B", checksum)
try:
self.serial.write(message)
self.serial.flush()
except SerialTimeoutException:
raise ispBase.IspError("Serial send timeout")
self.seq = (self.seq + 1) & 0xFF
return self.recvMessage()
示例7: init
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def init(self):
"""
Метод инициализации устройства перед отправкой команды.
"""
try:
self.serial.write(ENQ)
byte = self.serial.read()
if not byte:
raise excepts.NoConnectionError()
if byte == NAK:
pass
elif byte == ACK:
self.handle_response()
else:
while self.serial.read():
pass
return False
return True
except serial.SerialTimeoutException:
self.serial.flushOutput()
raise excepts.ProtocolError(u'Не удалось записать байт в ККМ')
except serial.SerialException as exc:
self.serial.flushInput()
raise excepts.ProtocolError(unicode(exc))
示例8: read
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def read(self, size):
try:
data = self.com.read(size)
except serial.SerialTimeoutException:
raise LinkTimeoutException
if len(data)<size:
raise LinkTimeoutException
if self.dump:
print "<", hexlify(data).upper()
return data
示例9: write
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def write(self, data, completed= None):
retriesLeft = 5
while True:
try:
if self._link:
self._link.write(data)
if completed:
completed()
else:
self._logger.error("Link has gone away")
break
except serial.SerialTimeoutException:
retriesLeft -= 1
if retriesLeft == 0:
self._serialLoggerEnabled and self._serialLogger.info("No more retries left. Closing the connection")
self._eventListener.onLinkError('unable_to_send', "Line returned nothing")
break
else:
self._serialLoggerEnabled and self._serialLogger.info("Serial Timeout while sending data. Retries left: %d" % retriesLeft)
time.sleep(0.5)
except Exception as e:
self._serialLoggerEnabled and self._serialLogger.info("Unexpected error while writing serial port: %s" % e)
self._eventListener.onLinkError('unable_to_send', str(e))
break
示例10: _doSend
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def _doSend(self, cmd):
#make sure sends are done orderly
with self._sendingLock:
self._serialLoggerEnabled and self._log("Send: %s" % cmd)
retriesLeft = 5
while True:
try:
self._serial.write(cmd + '\n')
if self._callback.broadcastTraffic > 0:
self._callback.doTrafficBroadcast('s', cmd)
break
except serial.SerialTimeoutException:
retriesLeft -= 1
if retriesLeft == 0:
self._serialLoggerEnabled and self._log("No more retries left. Closing the connection")
self._errorValue = "Unable to send data"
self.close(True)
break
else:
self._serialLoggerEnabled and self._log("Serial Timeout while sending data. Retries left: %d" % retriesLeft)
time.sleep(0.5)
except:
self._serialLoggerEnabled and self._log("Unexpected error while writing serial port: %s" % (getExceptionString()))
self._errorValue = getExceptionString()
self.close(True)
break
示例11: serve_forever
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def serve_forever(self, poll_interval=0.5):
""" Wait for incomming requests. """
self.serial_port.timeout = poll_interval
while not self._shutdown_request:
try:
self.serve_once()
except (CRCError, struct.error) as e:
log.error('Can\'t handle request: {0}'.format(e))
except (SerialTimeoutException, ValueError):
pass
示例12: close_can_channel
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def close_can_channel(self):
"""Close CAN channel."""
try:
self.stop_rx_thread()
self.serial_port.write("C\r".encode('ascii'))
except serial.SerialTimeoutException as e:
raise USBtinException(e)
self.firmware_version = 0
self.hardware_version = 0
示例13: send_first_tx_fifo_message
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def send_first_tx_fifo_message(self):
""" Send first message in tx fifo """
if len(self.tx_fifo) == 0:
return
canmsg = self.tx_fifo[0]
try:
self.serial_port.write('{}\r'.format(canmsg.to_string()).encode('ascii'))
except serial.SerialTimeoutException as e:
raise USBtinException(e)
示例14: write_mcp_register
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def write_mcp_register(self, register, value):
"""Write given register of MCP2515
Keyword arguments:
register -- Register address
value -- Value to write
"""
try:
cmd = "W{:02x}{:02x}".format(register, value)
self.transmit(cmd)
except serial.SerialTimeoutException as e:
raise USBtinException(e)
示例15: exitBootloader
# 需要导入模块: import serial [as 别名]
# 或者: from serial import SerialTimeoutException [as 别名]
def exitBootloader(self):
with serial.Serial(self.port[0], 10000000, timeout=0.2, writeTimeout=0.2) as ser:
try:
TinyFPGAB(ser).boot()
except serial.SerialTimeoutException:
com_port_status_sv.set("Hmm...try pressing the reset button on TinyFPGA again.")