sedbgmux/sedbgmux/io/dump_socat.py

106 lines
3.9 KiB
Python

#!/usr/bin/env python3
# This file is a part of sedbgmux, an open source DebugMux client.
# Copyright (c) 2023 Vadim Yanitskiy <fixeria@osmocom.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from datetime import datetime
from . import DumpIO
from . import DumpIOError
from . import DumpIOEndOfFile
# local logger for this module
log = logging.getLogger(__name__)
class DumpIOSocat(DumpIO):
''' Read-only interface for parsing socat hexdumps (-x option) '''
def __init__(self, fname: str, readonly: bool = True) -> None:
self.buf = bytearray()
self.dir = '' # cached
self.timestamp = 0.0 # cached
self.readonly = readonly
# Open a socat hexdump file in read-only mode
log.info('Opening socat hexdump %s', fname)
self._file = open(fname, 'r')
self._find_connect()
def read(self) -> dict:
''' Read a single record from dump '''
frame: bytes = self._read(4) # Magic + Length
if frame[:2] != b'\x42\x42':
raise DumpIOError('Unexpected DebugMux frame magic')
# A single DebugMux frame may be split across several
# chunks, so obtain cached metadata as early as possible
(dir, timestamp) = (self.dir, self.timestamp)
# Read the remaining part of the frame
length: int = int.from_bytes(frame[2:], byteorder='little')
frame += self._read(length)
return dict(timestamp=timestamp, dir=dir, data=frame)
def write(self, record: dict) -> None:
''' Store a single record to dump (no-op method, read-only) '''
if self.readonly:
raise DumpIOError('Read-only mode')
raise NotImplementedError
def _find_connect(self) -> None:
''' Skip DebugMux carrier establishment (AT commands) '''
while True:
data: bytes = self._parse_chunk()
if self.dir != 'Rx':
continue
if data.strip() == b'CONNECT':
break
log.debug('Found the CONNECT line')
def _read(self, length: int) -> bytes:
''' Read the given number of bytes from the buffer '''
while len(self.buf) < length:
data: bytes = self._parse_chunk()
self.buf.extend(data)
data = bytes(self.buf[:length])
self.buf = self.buf[length:]
return data
def _parse_chunk(self) -> bytes:
''' Parse a chunk of data from dump '''
stats: str = self._file.readline()
if stats == '':
raise DumpIOEndOfFile('EOF while reading a stats line')
if stats[0] not in ('>', '<'):
raise DumpIOError('Unexpected stats line format')
log.debug('STATS: %s', stats.rstrip())
data: str = self._file.readline()
if data == '':
raise DumpIOEndOfFile('EOF while reading data line')
log.debug('DATA: %s', data.strip())
self.dir = 'Tx' if stats[0] == '<' else 'Rx'
self.timestamp = self._parse_datetime(stats)
return bytes.fromhex(data)
def _parse_datetime(self, stats: str) -> float:
''' Convert datetime (e.g. '2023/01/10 06:59:16.000629627') into a timestamp '''
dt = datetime.strptime(stats[2:][:29], '%Y/%m/%d %H:%M:%S.000%f')
return datetime.timestamp(dt)