tmtcc_serial_com_if.py 9.81 KB
Newer Older
Robin Mueller's avatar
Robin Mueller committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
@file   tmtcc_serial_com_if.py
@brief  Serial Communication Interface
@author R. Mueller
@date   01.11.2019
"""
import threading
import time
import logging
from enum import Enum
from collections import deque

import serial
import serial.tools.list_ports

Robin Mueller's avatar
Robin Mueller committed
16
17
18
19
20
21
from tmtccmd.com_if.tmtcc_com_interface_base import CommunicationInterface
from tmtccmd.utility.tmtcc_tmtc_printer import TmTcPrinter
from tmtccmd.pus_tm.tmtcc_pus_tm_factory import PusTelemetryFactory, PusTmListT
from tmtccmd.pus_tc.tmtcc_pus_tc_base import PusTcInfoT
from tmtccmd.utility.tmtcc_logger import get_logger
from tmtccmd.utility.dle_encoder import encode_dle, decode_dle, STX_CHAR, ETX_CHAR, DleErrorCodes
Robin Mueller's avatar
Robin Mueller committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249


LOGGER = get_logger()
SERIAL_FRAME_LENGTH = 256
DLE_FRAME_LENGTH = 1500
HEADER_BYTES_BEFORE_SIZE = 5


class SerialCommunicationType(Enum):
    TIMEOUT_BASED = 0
    FIXED_FRAME_BASED = 1
    DLE_ENCODING = 2


# pylint: disable=arguments-differ
class SerialComIF(CommunicationInterface):
    """
    Communication Interface to use serial communication. This requires the PySerial library.
    """
    def __init__(self, tmtc_printer: TmTcPrinter, com_port: str, baud_rate: int,
                 serial_timeout: float,
                 ser_com_type: SerialCommunicationType = SerialCommunicationType.FIXED_FRAME_BASED):
        """
        Initiaze a serial communication handler.
        :param tmtc_printer: TMTC printer object. Can be used for diagnostic purposes, but main
        packet handling should be done by a separate thread.
        :param com_port: Specify COM port.
        :param baud_rate: Specify baud rate
        :param serial_timeout: Specify serial timeout
        :param ser_com_type: Specify how to handle serial reception
        """
        super().__init__(tmtc_printer)

        self.com_port = com_port
        self.baud_rate = baud_rate
        self.serial_timeout = serial_timeout
        self.serial = None

        self.ser_com_type = ser_com_type
        if self.ser_com_type == SerialCommunicationType.FIXED_FRAME_BASED:
            # Set to default value.
            self.serial_frame_size = 256
        elif self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
            self.reception_thread = None
            self.reception_buffer = None
            self.dle_polling_active_event = None
            # Set to default value.
            self.dle_queue_len = 10
            self.dle_max_frame = 256
            self.dle_timeout = 0.01

    def __del__(self):
        if self.serial is not None:
            self.close()

    def set_fixed_frame_settings(self, serial_frame_size: int):
        self.serial_frame_size = serial_frame_size

    def set_dle_settings(self, dle_queue_len: int, dle_max_frame: int, dle_timeout: float):
        self.dle_queue_len = dle_queue_len
        self.dle_max_frame = dle_max_frame
        self.dle_timeout = dle_timeout

    def initialize(self):
        if self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
            self.reception_buffer = deque(maxlen=self.dle_queue_len)
            self.dle_polling_active_event = threading.Event()

    def open(self) -> None:
        try:
            if self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
                self.dle_polling_active_event.set()
                self.reception_thread = threading.Thread(target=self.poll_dle_packets, daemon=True)
            self.serial = serial.Serial(
                port=self.com_port, baudrate=self.baud_rate, timeout=self.serial_timeout)
        except serial.SerialException:
            LOGGER.error("Serial Port opening failure!")
            raise IOError
        """
        Needs to be called by application code once for DLE mode!
        """
        if self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
            self.reception_thread.start()

    def close(self):
        try:
            if self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
                self.dle_polling_active_event.clear()
                self.reception_thread.join(0.4)
            self.serial.close()
        except serial.SerialException:
            logging.warning("Serial Port could not be closed!")

    def send_data(self, data: bytearray):
        self.serial.write(data)

    def send_telecommand(self, tc_packet: bytearray, tc_packet_info: PusTcInfoT = None) -> None:
        if self.ser_com_type == SerialCommunicationType.FIXED_FRAME_BASED:
            data = tc_packet
        elif self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
            data = encode_dle(tc_packet)
        else:
            LOGGER.warning("This communication type was not implemented yet!")
            return

        self.send_data(data)

    def receive_telemetry(self, parameters: any = 0) -> PusTmListT:
        return self.poll_interface()

    def poll_interface(self, parameters: any = 0) -> PusTmListT:
        packet_list = []
        if self.ser_com_type == SerialCommunicationType.FIXED_FRAME_BASED:
            if self.data_available():
                data = self.serial.read(self.serial_frame_size)
                pus_data_list = self.poll_pus_packets_fixed_frames(bytearray(data))
                for pus_packet in pus_data_list:
                    packet = PusTelemetryFactory.create(pus_packet)
                    if packet is None:
                        continue
                    packet_list.append(packet)
        elif self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
            while self.reception_buffer:
                data = self.reception_buffer.pop()
                dle_retval, decoded_packet, read_len = decode_dle(data)
                if dle_retval == DleErrorCodes.OK:
                    packet = PusTelemetryFactory.create(decoded_packet)
                    if packet is None:
                        continue
                    packet_list.append(packet)
                else:
                    LOGGER.warning("DLE decoder error!")
        else:
            LOGGER.warning("This communication type was not implemented yet!")
        return packet_list

    def data_available(self, timeout: float = 0) -> int:
        elapsed_time = 0
        start_time = time.time()
        sleep_time = timeout / 3.0
        if self.ser_com_type == SerialCommunicationType.FIXED_FRAME_BASED:
            if timeout > 0:
                start_time = time.time()
                elapsed_time = 0
                while elapsed_time < timeout:
                    if self.serial.inWaiting() > 0:
                        return self.serial.inWaiting()
                    elapsed_time = time.time() - start_time
                    time.sleep(sleep_time)
            if self.serial.inWaiting() > 0:
                return self.serial.inWaiting()
        elif self.ser_com_type == SerialCommunicationType.DLE_ENCODING:
            if timeout > 0:
                while elapsed_time < timeout:
                    if self.reception_buffer:
                        return self.reception_buffer.__len__()
                    elapsed_time = time.time() - start_time
                    time.sleep(sleep_time)
            if self.reception_buffer:
                return self.reception_buffer.__len__()
        return 0

    def poll_dle_packets(self):
        while True and self.dle_polling_active_event.is_set():
            # Poll permanently, but it is possible to join this thread every 200 ms
            self.serial.timeout = 0.2
            data = bytearray()
            byte = self.serial.read()
            if len(byte) == 1 and byte[0] == STX_CHAR:
                data.append(byte[0])
                self.serial.timeout = 0.1
                bytes_rcvd = self.serial.read_until(serial.to_bytes([ETX_CHAR]), DLE_FRAME_LENGTH)
                if bytes_rcvd[len(bytes_rcvd) - 1] == ETX_CHAR:
                    data.extend(bytes_rcvd)
                    self.reception_buffer.appendleft(data)
            elif len(byte) >= 1:
                data.append(byte[0])
                data.extend(self.serial.read(self.serial.inWaiting()))
                # It is assumed that all packets are DLE encoded, so throw it away for now.
                LOGGER.info("Non DLE-Encoded data with length " + str(len(data) + 1) + " found..")

    @staticmethod
    def poll_pus_packets_fixed_frames(data: bytearray) -> list:
        pus_data_list = []
        if len(data) == 0:
            return pus_data_list

        payload_length = data[4] << 8 | data[5]
        packet_size = payload_length + 7
        if payload_length == 0:
            return []
        read_size = len(data)
        pus_data = data[0:packet_size]
        pus_data_list.append(pus_data)

        SerialComIF.read_multiple_packets(data, packet_size, read_size, pus_data_list)
        return pus_data_list

    @staticmethod
    def read_multiple_packets(data: bytearray, start_index: int, frame_size: int,
                              pus_data_list: list):
        while start_index < frame_size:
            start_index = SerialComIF.parse_next_packets(data, start_index, frame_size,
                                                         pus_data_list)

    @staticmethod
    def parse_next_packets(data: bytearray, start_index: int, frame_size: int,
                           pus_data_list: list) -> int:
        next_payload_len = data[start_index + 4] << 8 | data[start_index + 5]
        if next_payload_len == 0:
            end_index = frame_size
            return end_index
        next_packet_size = next_payload_len + 7
        # remaining_size = frame_size - start_index

        if next_packet_size > SERIAL_FRAME_LENGTH:
            LOGGER.error("PUS Polling: Very large packet detected, "
                         "packet splitting not implemented yet!")
            LOGGER.error("Detected Size: " + str(next_packet_size))
            end_index = frame_size
            return end_index

        end_index = start_index + next_packet_size
        pus_data = data[start_index:end_index]
        pus_data_list.append(pus_data)
        return end_index