1# Copyright 2015-2021 Espressif Systems (Shanghai) CO LTD
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import datetime
16import os
17import re
18from typing import BinaryIO, Callable, Optional, Union  # noqa: F401
19
20from serial.tools import miniterm  # noqa: F401
21
22from .constants import MATCH_PCADDR
23from .output_helpers import lookup_pc_address, red_print, yellow_print
24
25
26class Logger:
27    def __init__(self, elf_file, console, timestamps, timestamp_format, pc_address_buffer, enable_address_decoding,
28                 toolchain_prefix):
29        # type: (str, miniterm.Console, bool, str, bytes, bool, str) -> None
30        self.log_file = None  # type: Optional[BinaryIO]
31        self._output_enabled = True  # type: bool
32        self.elf_file = elf_file
33        self.console = console
34        self.timestamps = timestamps
35        self.timestamp_format = timestamp_format
36        self._pc_address_buffer = pc_address_buffer
37        self.enable_address_decoding = enable_address_decoding
38        self.toolchain_prefix = toolchain_prefix
39
40    @property
41    def pc_address_buffer(self):  # type: () -> bytes
42        return self._pc_address_buffer
43
44    @pc_address_buffer.setter
45    def pc_address_buffer(self, value):  # type: (bytes) -> None
46        self._pc_address_buffer = value
47
48    @property
49    def output_enabled(self):  # type: () -> bool
50        return self._output_enabled
51
52    @output_enabled.setter
53    def output_enabled(self, value):  # type: (bool) -> None
54        self._output_enabled = value
55
56    @property
57    def log_file(self):  # type: () -> Optional[BinaryIO]
58        return self._log_file
59
60    @log_file.setter
61    def log_file(self, value):  # type: (Optional[BinaryIO]) -> None
62        self._log_file = value
63
64    def toggle_logging(self):  # type: () -> None
65        if self._log_file:
66            self.stop_logging()
67        else:
68            self.start_logging()
69
70    def toggle_timestamps(self):  # type: () -> None
71        self.timestamps = not self.timestamps
72
73    def start_logging(self):  # type: () -> None
74        if not self._log_file:
75            name = 'log.{}.{}.txt'.format(os.path.splitext(os.path.basename(self.elf_file))[0],
76                                          datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
77            try:
78                self.log_file = open(name, 'wb+')
79                yellow_print('\nLogging is enabled into file {}'.format(name))
80            except Exception as e:  # noqa
81                red_print('\nLog file {} cannot be created: {}'.format(name, e))
82
83    def stop_logging(self):  # type: () -> None
84        if self._log_file:
85            try:
86                name = self._log_file.name
87                self._log_file.close()
88                yellow_print('\nLogging is disabled and file {} has been closed'.format(name))
89            except Exception as e:  # noqa
90                red_print('\nLog file cannot be closed: {}'.format(e))
91            finally:
92                self._log_file = None
93
94    def print(self, string, console_printer=None):  # noqa: E999
95        # type: (Union[str, bytes], Optional[Callable]) -> None
96        if console_printer is None:
97            console_printer = self.console.write_bytes
98
99        if self.timestamps and (self._output_enabled or self._log_file):
100            t = datetime.datetime.now().strftime(self.timestamp_format)
101            # "string" is not guaranteed to be a full line. Timestamps should be only at the beginning of lines.
102            if isinstance(string, type(u'')):
103                search_patt = '\n'
104                replacement = '\n' + t + ' '
105            else:
106                search_patt = b'\n'  # type: ignore
107                replacement = b'\n' + t.encode('ascii') + b' '  # type: ignore
108            string = string.replace(search_patt, replacement)  # type: ignore
109        if self._output_enabled:
110            console_printer(string)
111        if self._log_file:
112            try:
113                if isinstance(string, type(u'')):
114                    string = string.encode()  # type: ignore
115                self._log_file.write(string)  # type: ignore
116            except Exception as e:
117                red_print('\nCannot write to file: {}'.format(e))
118                # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
119                self.stop_logging()
120
121    def output_toggle(self):  # type: () -> None
122        self.output_enabled = not self.output_enabled
123        yellow_print('\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.'.format(
124            self.output_enabled))
125
126    def handle_possible_pc_address_in_line(self, line):  # type: (bytes) -> None
127        line = self._pc_address_buffer + line
128        self._pc_address_buffer = b''
129        if not self.enable_address_decoding:
130            return
131        for m in re.finditer(MATCH_PCADDR, line.decode(errors='ignore')):
132            translation = lookup_pc_address(m.group(), self.toolchain_prefix, self.elf_file)
133            if translation:
134                self.print(translation, console_printer=yellow_print)
135