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"""Wrapers for pyserial classes to log read and write data.""" 15from __future__ import annotations 16 17from typing import TYPE_CHECKING 18 19import serial 20 21from pw_console.plugins.bandwidth_toolbar import SerialBandwidthTracker 22 23if TYPE_CHECKING: 24 from _typeshed import ReadableBuffer 25 26 27class SerialWithLogging(serial.Serial): # pylint: disable=too-many-ancestors 28 """pyserial with read and write wrappers for logging.""" 29 30 def __init__(self, *args, **kwargs): 31 super().__init__(*args, **kwargs) 32 self._bandwidth_tracker = SerialBandwidthTracker() 33 34 def read(self, size: int = 1) -> bytes: 35 data = super().read(size) 36 self._bandwidth_tracker.track_read_data(data) 37 return data 38 39 def write(self, data: ReadableBuffer) -> None: 40 self._bandwidth_tracker.track_write_data(data) 41 super().write(data) 42