def clear(self, transport):
     with InterProcessTransportLock(transport):
         while True:
             try:
                 transport.read_bytes(25)
             except Timeout:
                 return True
Beispiel #2
0
 def clear(self, transport):
     with InterProcessTransportLock(transport):  # lock and then unlock afterwards
         try:
             while True:
                 transport.read_bytes(10)
         except:
             return
Beispiel #3
0
    def query(self, transport, message):
        with InterProcessTransportLock(transport):
            self.send_message(transport, message)

            length = message.response_length()
            raw_response = transport.read_bytes(length)

            self.logger.debug('Recevied response (%s bytes): "%s"',
                              str(length), " ".join(map(hex, raw_response)))

            response_as_hex = []

            for i in range(0, length):
                response_as_hex.append(raw_response[i])

            response = message.create_response(response_as_hex)

            if not response.is_valid_crc():
                raise CommunicationError(
                    'Received an invalid response packet. CRC dismatch.')

            if response.is_nack():
                self.logger.warning('Received a NAK Response')

            return response
Beispiel #4
0
 def clear(self, transport):
     with InterProcessTransportLock(transport):
         self.logger.debug("Clearing message buffer...")
         try:
             while True:
                 transport.read_bytes(32)
         except slave.transport.Timeout:
             return
Beispiel #5
0
 def read_response(self, transport):
     with InterProcessTransportLock(transport):
         try:
             resp = transport.read_exactly(21)
             self.logger.debug('Received response: "%s"', repr(resp))
             return resp
         except slave.transport.Timeout:
             raise CommunicationError("Could not read response")
Beispiel #6
0
    def write(self, transport, message):
        if not isinstance(message, AbstractMessage):
            raise RuntimeError(
                "Given message is not an instance of AbstractMessage")

        with InterProcessTransportLock(transport):
            msg = self.create_message(message)
            self.logger.debug('Sending: %s', repr(msg))
            with transport:
                transport.write(msg)
                response = self.get_response(transport)
            self.logger.debug('Response: %s', repr(response))
            return self.parse_response(response, message)
    def write(self, transport, message):
        with InterProcessTransportLock(transport):
            if not isinstance(message, Message):
                raise TypeError("message must be of instance Message")

            message.set_waitingbit(0)
            message.set_checksum(message.compute_checksum())

            raw_data = message.get_raw()
            data = "".join(map(chr, raw_data))

            self._send_raw(transport, data)
            response = self._parse_response(self._read_response(transport))

            self.check_checksum(response)
            self._check_ack(response, True)
    def query(self, transport, message):
        with InterProcessTransportLock(transport):
            if not isinstance(message, AbstractMessage):
                raise TypeError(
                    "message must be an instance of AbstractMessage")

            msg = message.get_message()
            msg.set_address(self.receiver)
            msg.set_checksum(msg.compute_checksum())

            self.send_message(transport, msg)
            response = self.read_response(transport)

            resp = message.create_response(response)

            if not resp.is_valid():
                self.logger.error("Received invalid response: %s", resp)
                raise CommunicationError("Invalid response")

            if not resp.is_successful():
                self.logger.warning("Action (%s) was not successful: %s",
                                    message, resp)

            return resp
Beispiel #9
0
 def __init__(self, *args, **kwargs):
     super(Serial, self).__init__(*args, **kwargs)
     self._buffer = bytearray()
     self._max_bytes = 1
     self._lock = InterProcessTransportLock(self)
Beispiel #10
0
class Serial(AbstractSerial, AbstractTransport):
    def __init__(self, *args, **kwargs):
        super(Serial, self).__init__(*args, **kwargs)
        self._buffer = bytearray()
        self._max_bytes = 1
        self._lock = InterProcessTransportLock(self)

    def set_lock(self, lock):
        self._lock = lock

    def get_lock(self):
        return self._lock

    def __enter__(self):
        super(Serial, self).__enter__()
        self._lock.acquire()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # do not call super __exit__, the serial connection should not be closed
        self._lock.release()

    def get_device(self):
        return self._port

    def write(self, data, encoding='ascii'):

        msg = data

        if isinstance(data, str):
            msg = bytearray(data, encoding)
        elif isinstance(data, bytearray):
            pass
        elif isinstance(data, byte):
            pass
        else:
            raise TypeError("Unknown data given")

        ret = super(Serial, self).write(msg)
        self.flush()
        return ret

    def read(self, num_bytes):
        data = super(Serial, self).read(num_bytes)
        if len(data) == 0:
            raise SerialTimeoutException()
        return data

    def read_bytes(self, num_bytes):
        buffer_size = len(self._buffer)
        if buffer_size > num_bytes:
            data, self._buffer = self._buffer[:num_bytes], self._buffer[
                num_bytes:]
        elif 0 < buffer_size <= num_bytes:
            data, self._buffer = self._buffer, bytearray()
        else:
            self._buffer += self.read(num_bytes)
            return self.read_bytes(num_bytes)

        return data

    def read_until(self, delimiter):
        if isinstance(delimiter, int):
            delimiter = chr(delimiter)

        if delimiter in self._buffer:
            data, delimiter, self._buffer = self._buffer.partition(delimiter)
            return data + delimiter
        else:
            self._buffer += self.read(self._max_bytes)
            return self.read_until(delimiter)
Beispiel #11
0
 def write(self, transport, msg: AbstractMessage):
     with InterProcessTransportLock(transport):
         raw_str_msg = self.create_message(msg)
         self._logger.debug('Write: %s', repr(raw_str_msg))
         transport.write(raw_str_msg)
         return self.read_response(transport, msg)
Beispiel #12
0
 def clear(self, transport):
     with InterProcessTransportLock(transport):
         transport.get_serial().reset_input_buffer()