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  # type: ignore
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    dev_name: str
33    serial_number: str
34
35
36def detect_boards() -> list:
37    """Detect attached boards, returning a list of Board objects."""
38    boards = []
39    all_devs = serial.tools.list_ports.comports()
40    for dev in all_devs:
41        if dev.vid == _ST_VENDOR_ID and dev.pid == _DISCOVERY_MODEL_ID:
42            boards.append(
43                BoardInfo(dev_name=dev.device,
44                          serial_number=dev.serial_number))
45    return boards
46
47
48def main():
49    """This detects and then displays all attached discovery boards."""
50
51    # Try to use pw_cli logs, else default to something reasonable.
52    try:
53        import pw_cli.log  # pylint: disable=import-outside-toplevel
54        pw_cli.log.install()
55    except ImportError:
56        coloredlogs.install(level='INFO',
57                            level_styles={
58                                'debug': {
59                                    'color': 244
60                                },
61                                'error': {
62                                    'color': 'red'
63                                }
64                            },
65                            fmt='%(asctime)s %(levelname)s | %(message)s')
66
67    boards = detect_boards()
68    if not boards:
69        _LOG.info('No attached boards detected')
70    for idx, board in enumerate(boards):
71        _LOG.info('Board %d:', idx)
72        _LOG.info('  - Port: %s', board.dev_name)
73        _LOG.info('  - Serial #: %s', board.serial_number)
74
75
76if __name__ == '__main__':
77    main()
78