1#!/usr/bin/env python3
2# Copyright 2019 The Pigweed Authors
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may not
5# use this file except in compliance with the License. You may obtain a copy of
6# the License at
7#
8#     https://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations under
14# the License.
15"""Detects attached stm32f429i-disc1 boards connected via mini usb."""
16
17import logging
18import typing
19
20import coloredlogs  # type: ignore
21import serial.tools.list_ports
22
23# Vendor/device ID to search for in USB devices.
24_ST_VENDOR_ID = 0x0483
25_DISCOVERY_MODEL_ID = 0x374B
26
27_LOG = logging.getLogger('stm32f429i_detector')
28
29
30class BoardInfo(typing.NamedTuple):
31    """Information about a connected dev board."""
32
33    dev_name: str
34    serial_number: str | None
35
36
37def detect_boards() -> list:
38    """Detect attached boards, returning a list of Board objects."""
39    boards = []
40    all_devs = serial.tools.list_ports.comports()
41    for dev in all_devs:
42        if dev.vid == _ST_VENDOR_ID and dev.pid == _DISCOVERY_MODEL_ID:
43            boards.append(
44                BoardInfo(dev_name=dev.device, serial_number=dev.serial_number)
45            )
46    return boards
47
48
49def main():
50    """This detects and then displays all attached discovery boards."""
51
52    # Try to use pw_cli logs, else default to something reasonable.
53    try:
54        import pw_cli.log  # pylint: disable=import-outside-toplevel
55
56        pw_cli.log.install()
57    except ImportError:
58        coloredlogs.install(
59            level='INFO',
60            level_styles={'debug': {'color': 244}, 'error': {'color': 'red'}},
61            fmt='%(asctime)s %(levelname)s | %(message)s',
62        )
63
64    boards = detect_boards()
65    if not boards:
66        _LOG.info('No attached boards detected')
67    for idx, board in enumerate(boards):
68        _LOG.info('Board %d:', idx)
69        _LOG.info('  - Port: %s', board.dev_name)
70        _LOG.info('  - Serial #: %s', board.serial_number or '<not set>')
71
72
73if __name__ == '__main__':
74    main()
75