aboutsummaryrefslogtreecommitdiff
path: root/pw_arduino_build/py/pw_arduino_build/teensy_detector.py
blob: e5b4b7b0d8962f048da63f164ad4b476d877d7f1 (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
#!/usr/bin/env python3
# Copyright 2020 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Detects attached Teensy boards connected via usb."""

import logging
import re
import subprocess
import typing

from pathlib import Path
from typing import List

import pw_arduino_build.log

_LOG = logging.getLogger('teensy_detector')


class UnknownArduinoCore(Exception):
    """Exception raised when a given core can not be found."""


def log_subprocess_output(level, output):
    """Logs subprocess output line-by-line."""

    lines = output.decode('utf-8', errors='replace').splitlines()
    for line in lines:
        _LOG.log(level, line)


class BoardInfo(typing.NamedTuple):
    """Information about a connected dev board."""

    dev_name: str
    usb_device_path: str
    protocol: str
    label: str
    arduino_upload_tool_name: str

    def test_runner_args(self) -> List[str]:
        return [
            "--set-variable",
            f"serial.port.protocol={self.protocol}",
            "--set-variable",
            f"serial.port={self.usb_device_path}",
            "--set-variable",
            f"serial.port.label={self.dev_name}",
        ]


def detect_boards(arduino_package_path=False) -> list:
    """Detect attached boards, returning a list of Board objects."""

    teensy_core = Path()
    if arduino_package_path:
        teensy_core = Path(arduino_package_path)
    else:
        teensy_core = Path("third_party/arduino/cores/teensy")
        if not teensy_core.exists():
            teensy_core = Path(
                "third_party/pigweed/third_party/arduino/cores/teensy"
            )

    if not teensy_core.exists():
        raise UnknownArduinoCore

    teensy_device_line_regex = re.compile(
        r"^(?P<address>[^ ]+) (?P<dev_name>[^ ]+) "
        r"\((?P<label>[^)]+)\) ?(?P<rest>.*)$"
    )

    boards = []
    detect_command = [
        (teensy_core / "tools" / "teensy-tools" / "1.58.0" / "teensy_ports")
        .absolute()
        .as_posix(),
        "-L",
    ]

    # TODO(tonymd): teensy_ports -L on windows does not return the right port
    # string Example:
    #
    #   $ teensy_ports -L
    #   Port_#0001.Hub_#0003 COM3 (Teensy 3.6) Serial
    #
    # So we get "-port=Port_#0001.Hub_#0003"
    # But it should be "-port=usb:0/140000/0/1"

    process = subprocess.run(
        detect_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
    )
    if process.returncode != 0:
        _LOG.error("Command failed with exit code %d.", process.returncode)
        _LOG.error("Full command:")
        _LOG.error("")
        _LOG.error("  %s", " ".join(detect_command))
        _LOG.error("")
        _LOG.error("Process output:")
        log_subprocess_output(logging.ERROR, process.stdout)
        _LOG.error('')
    for line in process.stdout.decode("utf-8", errors="replace").splitlines():
        device_match_result = teensy_device_line_regex.match(line)
        if device_match_result:
            teensy_device = device_match_result.groupdict()
            boards.append(
                BoardInfo(
                    dev_name=teensy_device["dev_name"],
                    usb_device_path=teensy_device["address"],
                    protocol="Teensy",
                    label=teensy_device["label"],
                    arduino_upload_tool_name="teensyloader",
                )
            )
    return boards


def main():
    """This detects and then displays all attached discovery boards."""

    pw_arduino_build.log.install(logging.INFO)

    boards = detect_boards()
    if not boards:
        _LOG.info("No attached boards detected")
    for idx, board in enumerate(boards):
        _LOG.info("Board %d:", idx)
        _LOG.info("  - Name: %s", board.label)
        _LOG.info("  - Port: %s", board.dev_name)
        _LOG.info("  - Address: %s", board.usb_device_path)
        _LOG.info(
            "  - Test runner args: %s", " ".join(board.test_runner_args())
        )


if __name__ == "__main__":
    main()