• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://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, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Bandwidth Monitor Toolbar"""
15
16from prompt_toolkit.layout import WindowAlign
17
18from pw_console.plugin_mixin import PluginMixin
19from pw_console.widgets import ToolbarButton, WindowPaneToolbar
20from pw_console.pyserial_wrapper import BANDWIDTH_HISTORY_CONTEXTVAR
21
22
23class BandwidthToolbar(WindowPaneToolbar, PluginMixin):
24    """Toolbar for displaying bandwidth history."""
25
26    TOOLBAR_HEIGHT = 1
27
28    def _update_toolbar_text(self):
29        """Format toolbar text.
30
31        This queries pyserial_wrapper's EventCountHistory context var to
32        retrieve the byte count history for read, write and totals."""
33        tokens = []
34        self.plugin_logger.debug('BandwidthToolbar _update_toolbar_text')
35
36        for count_name, events in self.history.items():
37            tokens.extend(
38                [
39                    ('', '  '),
40                    (
41                        'class:theme-bg-active class:theme-fg-active',
42                        ' {}: '.format(count_name.title()),
43                    ),
44                    (
45                        'class:theme-bg-active class:theme-fg-cyan',
46                        '{:.3f} '.format(events.last_count()),
47                    ),
48                    (
49                        'class:theme-bg-active class:theme-fg-orange',
50                        '{} '.format(events.display_unit_title),
51                    ),
52                ]
53            )
54            if count_name == 'total':
55                tokens.append(
56                    ('class:theme-fg-cyan', '{}'.format(events.sparkline()))
57                )
58
59        self.formatted_text = tokens
60
61    def get_left_text_tokens(self):
62        """Formatted text to display on the far left side."""
63        return self.formatted_text
64
65    def get_right_text_tokens(self):
66        """Formatted text to display on the far right side."""
67        return [('class:theme-fg-blue', 'Serial Bandwidth Usage ')]
68
69    def __init__(self, *args, **kwargs):
70        super().__init__(
71            *args, center_section_align=WindowAlign.RIGHT, **kwargs
72        )
73
74        self.history = BANDWIDTH_HISTORY_CONTEXTVAR.get()
75        self.show_toolbar = True
76        self.formatted_text = []
77
78        # Buttons for display in the center
79        self.add_button(
80            ToolbarButton(
81                description='Refresh', mouse_handler=self._update_toolbar_text
82            )
83        )
84
85        # Set plugin options
86        self.background_task_update_count: int = 0
87        self.plugin_init(
88            plugin_callback=self._background_task,
89            plugin_callback_frequency=1.0,
90            plugin_logger_name='pw_console_bandwidth_toolbar',
91        )
92
93    def _background_task(self) -> bool:
94        self.background_task_update_count += 1
95        self._update_toolbar_text()
96        self.plugin_logger.debug(
97            'BandwidthToolbar Scheduled Update: #%s',
98            self.background_task_update_count,
99        )
100        return True
101