core_logger.py 6.19 KB
Newer Older
Leon Riesebos's avatar
Leon Riesebos committed
1
2
3
4
#!/usr/bin/env python3

"""
UART logger for ARTIQ core devices.
5
Works for Kasli. The KC705 does not have a UART serial output.
Leon Riesebos's avatar
Leon Riesebos committed
6
7
8
9
10
11
12
13
14
"""

import argparse
import logging
import typing
import datetime
import time
import os
import os.path
Leon Riesebos's avatar
Leon Riesebos committed
15
import serial
Leon Riesebos's avatar
Leon Riesebos committed
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

import dax_comtools.util.args

logger = logging.getLogger(__name__)
"""The module logger."""


class CoreLogger:
    """UART logger for an ARTIQ core device."""

    DEFAULT_BAUD_RATE: typing.ClassVar[int] = 115200
    """Default baud rate."""
    DEFAULT_OUTPUT_DIR: typing.ClassVar[str] = './'
    """Default output directory."""
    DEFAULT_RECONNECT_DELAY: typing.ClassVar[float] = 5.0
    """Default delay before reconnecting."""

    def __init__(self, *,
                 port: str,
                 baud_rate: int = DEFAULT_BAUD_RATE,
                 output_dir: str = DEFAULT_OUTPUT_DIR):
        """Initialize the core logger class.

        :param port: The port to connect to
        :param baud_rate: Baud rate
        :param output_dir: Output directory for the log files
        """
        assert isinstance(port, str)
        assert isinstance(baud_rate, int)
        assert isinstance(output_dir, str)

        # Validate baud rate
        if baud_rate not in serial.SerialBase.BAUDRATES:
            raise ValueError('Invalid baud rate')

        # Expand path and validate existence
        self._output_dir = os.path.expanduser(output_dir)
        if not os.path.isdir(self._output_dir):
            raise NotADirectoryError(f'"{self._output_dir}" is not a valid directory')

        # Create serial port
        logger.info(f'Opening serial connection to "{port}"')
        self._serial = serial.Serial(
            port=port, baudrate=baud_rate,
            bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE
        )
        logger.debug(f'Serial: {self._serial}')

    def start(self) -> None:
        """Start logging."""

        # Generate file name
68
        file_name = os.path.join(self._output_dir, datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S.log'))
Leon Riesebos's avatar
Leon Riesebos committed
69
70
        logger.info(f'Log file: {file_name}')

71
        with open(file_name, mode='w', buffering=1) as file, self._serial:
Leon Riesebos's avatar
Leon Riesebos committed
72
73
74
            while True:
                # Get, print, and write the line
                line = self._serial.readline().decode(encoding='utf8', errors='ignore')
75
76
                line = f'[{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] {line}'
                print(line, end='', flush=True)
Leon Riesebos's avatar
Leon Riesebos committed
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
                file.write(line)

    @classmethod
    def run(cls, *, port: str, baud_rate: int, output_dir: str, reconnect_delay: float) -> None:
        """Run this core logger class in an infinite loop that reconnects if the connection is lost.

        :param port: The port to connect to
        :param baud_rate: Baud rate
        :param output_dir: Output directory for the log files
        :param reconnect_delay: Delay before reconnecting in seconds
        """
        assert isinstance(reconnect_delay, float)
        assert reconnect_delay > 0.0

        try:
            while True:
                try:
                    # Create the core logger
                    core_logger = cls(port=port, baud_rate=baud_rate, output_dir=output_dir)
                except serial.SerialException as e:
                    logger.warning(f'Connection failed: {e}')
                else:
                    try:
                        # Start logging
                        core_logger.start()
                    except serial.SerialException as e:
                        logger.warning(f'Connection lost: {e}')

                # Insert delay
                logger.info(f'Waiting to reconnect ({reconnect_delay} s)...')
                time.sleep(reconnect_delay)

        except ValueError:
            logger.exception('Value error, logger terminated')
        except OSError:
            logger.exception('IO error, logger terminated')
        except KeyboardInterrupt:
            logger.info('Core logger stopped by user')


def _get_args() -> argparse.Namespace:
    # Create an argument parser
119
120
121
122
123
124
    parser = argparse.ArgumentParser(
        description="UART logger for ARTIQ core devices (Kasli)",
        epilog="The USB connection on the Kasli presents itself as a quad-RS232 device.\n"
               "The serial port is on channel 1/2 for v1.0/v1.1 hardware (e.g. /dev/ttyUSB2 for v1.1 hardware).\n"
               "Source: https://www.m-labs.hk/artiq/manual/"
    )
Leon Riesebos's avatar
Leon Riesebos committed
125

Leon Riesebos's avatar
Leon Riesebos committed
126
127
128
129
130
131
132
133
    def baud_rate(arg: typing.Any) -> int:
        try:
            b = int(arg)
        except ValueError:
            raise argparse.ArgumentTypeError(f"invalid int value: '{arg}'")
        if b not in serial.SerialBase.BAUDRATES:
            raise argparse.ArgumentTypeError(f'not a valid baud rate: {b}')
        return b
Leon Riesebos's avatar
Leon Riesebos committed
134
135
136
137
138
139
140
141
142
143

    def positive_float(arg: typing.Any) -> float:
        try:
            f = float(arg)
        except ValueError:
            raise argparse.ArgumentTypeError(f"invalid float value: '{arg}'")
        if not f > 0.0:
            raise argparse.ArgumentTypeError(f'float value must be positive: {f}')
        return f

Leon Riesebos's avatar
Leon Riesebos committed
144
145
146
    group = parser.add_argument_group('Core device')
    group.add_argument('port', type=str, help='Serial port to connect to')
    group.add_argument('--baud-rate', type=baud_rate, default=CoreLogger.DEFAULT_BAUD_RATE,
147
                       help='Baud rate (default: %(default)s)')
Leon Riesebos's avatar
Leon Riesebos committed
148
149
150

    group = parser.add_argument_group('Output')
    group.add_argument('--output-dir', type=str, default=CoreLogger.DEFAULT_OUTPUT_DIR,
151
                       help='Output directory (default: "%(default)s")')
Leon Riesebos's avatar
Leon Riesebos committed
152

Leon Riesebos's avatar
Leon Riesebos committed
153
154
    group = parser.add_argument_group('Connection')
    group.add_argument('--reconnect-delay', type=positive_float, default=CoreLogger.DEFAULT_RECONNECT_DELAY,
155
                       help='Delay before reconnecting in seconds (default: %(default)s)')
Leon Riesebos's avatar
Leon Riesebos committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

    # Add standard arguments
    dax_comtools.util.args.logger_args(parser)

    return parser.parse_args()


def main() -> None:
    # Get the arguments
    args = _get_args()
    # Configure logger
    dax_comtools.util.args.process_logger_args(args)
    # Run the core logger
    CoreLogger.run(port=args.port, baud_rate=args.baud_rate,
                   output_dir=args.output_dir, reconnect_delay=args.reconnect_delay)


if __name__ == '__main__':
    main()