aboutsummaryrefslogtreecommitdiff
path: root/testing/serial/test-serial.py
blob: 8287e9cdd495eb605e2118969f93acd7240a7d76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
#!/usr/bin/env python3
# Test UART controllers, transceivers, adapters and connectors
#
# This is a small autonomous test script to test UART.
# Both ends of the UART communication needs to be connected to the same device.

import argparse
import math
import random
import serial
import serial.rs485
import string
import sys


def randomword(length):
    letters = string.ascii_lowercase
    return "".join(random.choice(letters) for i in range(length))


def set_rs485_mode(port, enable):
    try:
        port._set_rs485_mode(serial.rs485.RS485Settings() if enable else None)
    except ValueError:
        print(f"Port {port.port} does not support ioctl to enable/disable rs485")
        # Continue as the serial port is assumed to be already prepared
        # eg. using an USB to RS485 converter.
        pass


def transfer(tx, rx, size):
    # tx.reset_output_buffer()
    # rx.reset_input_buffer()
    rand = randomword(size)
    tx.write(rand.encode("ascii"))
    # tx.flush()

    recv = rx.read(size).decode("ascii", "ignore")

    if rand == recv:
        return True

    print()
    print(f"ERROR: sent from {tx.name}")
    print(f"{rand}")
    print(f"and received on {rx.name}")
    print(f"{recv}")

    return False


def update_serial_settings(tx, rx, baudrate, size):
    rx.baudrate = tx.baudrate = baudrate
    # Increase timeout based on baudrate and transfer size while giving room for
    # "life" (TM) to happen by adding a second to it.
    timeout = math.ceil(size / baudrate) + 1
    rx.timeout = tx.timeout = timeout


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-b", "--baudrate", type=int, default=115200)
    parser.add_argument(
        "--rs485",
        action="store_true",
        help="Enable rs485 software emulation for half duplex rs485",
    )
    parser.add_argument(
        "-s",
        "--size",
        type=int,
        default=256,
        help="number of characters to send for one test",
    )
    parser.add_argument(
        "-F",
        "--fuzz",
        action="append",
        choices=["size", "baudrate"],
        help="randomly select baudrate and/or size",
    )
    parser.add_argument(
        "--min-baudrate",
        type=int,
        default=serial.Serial.BAUDRATES[0],
        help="if --fuzz is passed, limits the tested baudrates to anything above that baudrate (included)",
    )
    parser.add_argument(
        "--max-baudrate",
        type=int,
        default=serial.Serial.BAUDRATES[-1],
        help="if --fuzz is passed, limits the tested baudrates to anything below that baudrate (included)",
    )
    parser.add_argument(
        "--min-size",
        type=int,
        default=1,
        help="if --fuzz is passed, limits the tested sizes to anything above that size (included) up to --max-size",
    )
    parser.add_argument(
        "--max-size",
        type=int,
        default=1024 * 1024,
        help="if --fuzz is passed, limits the tested sizes to anything below that size (included) down to --min-size",
    )
    parser.add_argument(
        "-n",
        "--loops",
        type=int,
        default=1,
        help="number of tests/loops to run for; -1 for infinite",
    )
    parser.add_argument(
        "-e", "--exit-on-error", action="store_true", help="exit on first error"
    )
    direction = parser.add_mutually_exclusive_group()
    direction.add_argument(
        "-R",
        "--reverse",
        default=False,
        action="store_true",
        help="swap RX and TX roles",
    )
    direction.add_argument(
        "-B",
        "--bidirectional",
        default=False,
        action="store_true",
        help="each test has RX assume RX and TX roles while TX assumes TX and RX roles respectively",
    )
    parser.add_argument("TX", type=str, help="/dev path to TX UART device")
    parser.add_argument("RX", type=str, help="/dev path to RX UART device")

    args = parser.parse_args()

    rx = serial.Serial(args.TX if args.reverse else args.RX)
    tx = serial.Serial(args.RX if args.reverse else args.TX)

    set_rs485_mode(tx, args.rs485)
    set_rs485_mode(rx, args.rs485)

    size = args.size
    baudrate = args.baudrate
    baudrate_choices = list(
        filter(
            lambda baud: args.min_baudrate <= baud <= args.max_baudrate, tx.BAUDRATES
        )
    )
    update_serial_settings(tx, rx, baudrate, size)

    tx_errors = 0
    rx_errors = 0
    loop = 0

    try:
        while loop != args.loops:
            loop += 1
            if args.fuzz:
                if "baudrate" in args.fuzz:
                    baudrate = random.choice(baudrate_choices)
                if "size" in args.fuzz:
                    size = random.randint(args.min_size, args.max_size)
                update_serial_settings(tx, rx, baudrate, size)

            print(
                f"Loop {loop} {tx.name}->{rx.name} {baudrate}bauds size {size}...",
                end="",
            )
            sys.stdout.flush()
            ret = transfer(tx, rx, size)
            print("success" if ret else "fail")
            tx_errors += 0 if ret else 1
            if args.exit_on_error and not ret:
                sys.exit(1)
            if args.bidirectional:
                print(
                    f"Loop {loop} {rx.name}->{tx.name} {baudrate}bauds size {size}...",
                    end="",
                )
                sys.stdout.flush()
                ret = transfer(rx, tx, size)
                print("success" if ret else "fail")
                rx_errors += 0 if ret else 1
                if args.exit_on_error and not ret:
                    sys.exit(1)

            if tx_errors:
                print(f"{tx.name}->{rx.name}: {tx_errors}/{loop} errors")
            if rx_errors:
                print(f"{rx.name}->{tx.name}: {rx_errors}/{loop} errors")
    except KeyboardInterrupt:
        print("")
        print("Normal operation interrupted, stopping...")

    print("Summary:")
    print(f"{tx.name}->{rx.name}: {tx_errors}/{loop} errors")
    if args.bidirectional:
        print(f"{rx.name}->{tx.name}: {rx_errors}/{loop} errors")
    sys.exit(tx_errors or rx_errors)