Python serial.SerialTimeoutException() Examples

The following are 20 code examples of serial.SerialTimeoutException(). 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: tinyfpga-programmer-gui.py    From TinyFPGA-Programmer-Application with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
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 #3
Source File: s2m.py    From s2m with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: comm.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #5
Source File: modbus.py    From R421A08-rs485-8ch-relay-board with MIT License 5 votes vote down vote up
def send(self, tx_data, append_crc_to_frame=True):
        """
            MODBUS send
        :param tx_data: List data (int)
        :param append_crc_to_frame: Append CRC to TX frame
        :return: None
        """
        assert type(tx_data) == list

        self._tx_data = tx_data

        if append_crc_to_frame:
            # Append CRC to transmit frame
            self._tx_data += self.crc(self._tx_data)

        # Print transmit frame
        if self._verbose:
            print(get_frame_str('TX', self._tx_data))

        try:
            # Clear receive
            while self._ser.read_all():
                time.sleep(0.010)
        except serial.SerialException:
            # Windows: Serial exception
            raise TransferException('RX error: Read failed')
        except AttributeError:
            # Ubuntu: Attribute error (Not documented)
            raise TransferException('RX error: Read failed')

        # Write binary command to relay card over serial port
        try:
            self._ser.write(tx_data)
        except serial.SerialTimeoutException:
            raise TransferException('TX error: Serial write timeout')
        except serial.SerialException:
            raise TransferException('TX error: Serial write failed')

        # Wait between transmitting frames
        time.sleep(FRAME_DELAY) 
Example #6
Source File: gemini_backend.py    From point with MIT License 5 votes vote down vote up
def _str_encoding(self):
        return 'ascii'


# TODO: handle serial.SerialTimeoutException (?) 
Example #7
Source File: tinyfpga-programmer-gui.py    From TinyFPGA-Programmer-Application with GNU General Public License v3.0 5 votes vote down vote up
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.") 
Example #8
Source File: usbtin.py    From pyUSBtin with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #9
Source File: usbtin.py    From pyUSBtin with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #10
Source File: usbtin.py    From pyUSBtin with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #11
Source File: __init__.py    From uModbus with Mozilla Public License 2.0 5 votes vote down vote up
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 
Example #12
Source File: serial_t.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #13
Source File: serial.py    From py9b with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #14
Source File: protocol.py    From pyshtrih with MIT License 5 votes vote down vote up
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)) 
Example #15
Source File: stk500v2.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
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() 
Example #16
Source File: transport.py    From nfcpy with European Union Public License 1.1 5 votes vote down vote up
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)) 
Example #17
Source File: serial.py    From pyvisa-py with MIT License 5 votes vote down vote up
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,
        ) 
Example #18
Source File: _serial.py    From pyuavcan with MIT License 4 votes vote down vote up
def _send_transfer(self, frames: typing.Iterable[SerialFrame], monotonic_deadline: float) \
            -> typing.Optional[pyuavcan.transport.Timestamp]:
        """
        Emits the frames belonging to the same transfer, returns the first frame transmission timestamp.
        The returned timestamp can be used for transfer feedback implementation.
        Aborts if the frames cannot be emitted before the deadline or if a write call fails.
        :returns: The first frame transmission timestamp if all frames are sent successfully.
            None on timeout or on write failure.
        """
        tx_ts: typing.Optional[pyuavcan.transport.Timestamp] = None
        self._ensure_not_closed()
        try:  # Jeez this is getting complex
            for fr in frames:
                async with self._port_lock:       # TODO: the lock acquisition should be prioritized by frame priority!
                    min_buffer_size = len(fr.payload) * 3
                    if len(self._serialization_buffer) < min_buffer_size:
                        _logger.debug('%s: The serialization buffer is being enlarged from %d to %d bytes',
                                      self, len(self._serialization_buffer), min_buffer_size)
                        self._serialization_buffer = bytearray(0 for _ in range(min_buffer_size))
                    compiled = fr.compile_into(self._serialization_buffer)
                    timeout = monotonic_deadline - self._loop.time()
                    if timeout > 0:
                        self._serial_port.write_timeout = timeout
                        try:
                            num_written = await self._loop.run_in_executor(self._background_executor,
                                                                           self._serial_port.write,
                                                                           compiled)
                            tx_ts = tx_ts or pyuavcan.transport.Timestamp.now()
                        except serial.SerialTimeoutException:
                            num_written = 0
                            _logger.info('%s: Port write timed out in %.3fs on frame %r', self, timeout, fr)
                        self._statistics.out_bytes += num_written or 0
                    else:
                        tx_ts = None  # Timed out
                        break

                num_written = len(compiled) if num_written is None else num_written
                if num_written < len(compiled):
                    tx_ts = None  # Write failed
                    break

                self._statistics.out_frames += 1
        except Exception as ex:
            if self._closed:
                raise pyuavcan.transport.ResourceClosedError(f'{self} is closed, transmission aborted.') from ex
            else:
                raise
        else:
            if tx_ts is not None:
                self._statistics.out_transfers += 1
            else:
                self._statistics.out_incomplete += 1
            return tx_ts 
Example #19
Source File: protocol.py    From pyshtrih with MIT License 4 votes vote down vote up
def command_nopass(self, cmd, params=bytearray()):
        """
        Метод отправки команды без пароля оператора.

        :type cmd: int
        :param cmd: номер команды
        :type params: bytearray
        :param params: набор параметров команды

        :rtype: dict
        :return: набор параметров ответа в виде словаря
        """

        if not isinstance(params, bytearray):
            raise TypeError(u'{} expected, got {} instead'.format(bytearray, type(params)))

        cmd_len = len(misc.int_to_bytes(cmd))
        buff = misc.bytearray_concat(
            misc.CAST_SIZE['1'](cmd_len + len(params)),
            misc.CAST_CMD[cmd_len](cmd),
            params
        )
        command = misc.bytearray_concat(STX, buff, misc.CAST_SIZE['1'](misc.lrc(buff)))

        for r in self.check(self.CHECK_NUM):
            if not r:
                continue

            for _ in xrange(self.MAX_ATTEMPTS):
                try:
                    self.serial.write(command)
                    byte = self.serial.read()
                    if byte == ACK:
                        return self.handle_response()

                except serial.SerialTimeoutException:
                    self.serial.flushOutput()
                    raise excepts.ProtocolError(u'Не удалось записать байт в ККМ')
                except serial.SerialException as exc:
                    self.serial.flushInput()
                    raise excepts.ProtocolError(unicode(exc))
            else:
                raise excepts.NoConnectionError()
        else:
            raise excepts.NoConnectionError() 
Example #20
Source File: serial.py    From pyvisa-py with MIT License 4 votes vote down vote up
def write(self, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param data: data to be written.
        :type data: bytes
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """
        logger.debug("Serial.write %r" % data)
        # TODO: How to deal with VI_ATTR_TERMCHAR_EN
        end_out, _ = self.get_attribute(constants.VI_ATTR_ASRL_END_OUT)
        send_end, _ = self.get_attribute(constants.VI_ATTR_SEND_END_EN)

        try:
            # We need to wrap data in common.iter_bytes to Provide Python 2 and 3 compatibility

            if end_out in (SerialTermination.none, SerialTermination.termination_break):
                data = common.iter_bytes(data)

            elif end_out == SerialTermination.last_bit:
                last_bit, _ = self.get_attribute(constants.VI_ATTR_ASRL_DATA_BITS)
                mask = 1 << (last_bit - 1)
                data = common.iter_bytes(data, mask, send_end)

            elif end_out == SerialTermination.termination_char:
                term_char, _ = self.get_attribute(constants.VI_ATTR_TERMCHAR)
                data = common.iter_bytes(data + common.int_to_byte(term_char))

            else:
                raise ValueError("Unknown value for VI_ATTR_ASRL_END_OUT: %s" % end_out)

            count = 0
            for d in data:
                count += self.interface.write(d)

            if end_out == SerialTermination.termination_break:
                logger.debug("Serial.sendBreak")
                self.interface.sendBreak()

            return count, StatusCode.success

        except serial.SerialTimeoutException:
            return 0, StatusCode.error_timeout