summaryrefslogtreecommitdiff
path: root/tools/reset.py
blob: 6398c50cb27f37ee7c3239c274d334f1afd2f505 (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
"""A tool to reset a Arduino."""
import os
import sys
from typing import List
import argparse
from time import sleep

import serial.tools.list_ports
from serial.tools.list_ports_common import ListPortInfo


if os.name == "nt":  # NT-based operating systems (Windows)
    from serial.serialwin32 import Serial
elif os.name == "posix":
    from serial.serialposix import Serial
else:
    raise NotImplementedError(
        "Sorry no implementation for your platform ({}) available."
        .format(sys.platform)
    )


def get_ports():
    """Returns a list of serial ports attached."""
    serial_ports = serial.tools.list_ports.comports()

    return [port.device for port in serial_ports]


def compare_ports(
    avail_ports: List[str],
    wanted_ports: List[str]
):
    return [port for port in avail_ports if port in wanted_ports]


class ParsedArguments:
    """Parsed command-line arguments."""
    port: str


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Reset an Arduino')

    parser.add_argument('port', help='Serial device e.g. /dev/ttyACM0 or com3')

    args = parser.parse_args(namespace=ParsedArguments)

    ports: List[str] = []

    while args.port not in ports:
        ports = get_ports()

        sys.stderr.write(
            f"PORTS {{{', '.join(ports)}}} / {{{args.port}}} "
            f"=> {{{', '.join(compare_ports(ports, [args.port]))}}}\n"
        )
        sys.stderr.flush()

        sleep(0.5)

    ser = Serial(args.port, 57600)

    ser.baudrate = 1200

    # ser.setRTS(True)
    # ser.setDTR(False)

    ser.close()

    sleep(2)

    print(get_ports()[0])