Here's a Python script that accomplishes what you've described:
#!/usr/bin/env python3
import subprocess
import sys
import struct
from typing import Optional, Tuple
def parse_hex_line(line: str) -> Optional[Tuple[int, int, int, int, bytes, bytes, bytes]]:
"""
Parse a hexadecimal string line into its components.
Returns:
Tuple of (msg_type, send_addr, recv_addr, node_rx, last_tx, last_rx)
or None if parsing fails
"""
try:
# Split the line into octets
octets = line.strip().split()
# Convert hex strings to bytes
data = bytes([int(octet, 16) for octet in octets])
# Verify we have exactly 21 bytes
if len(data) != 21:
print(f"Warning: Expected 21 bytes, got {len(data)}")
return None
# Verify first byte is 0x01
if data[0] != 0x01:
print(f"Warning: First byte is {data[0]:02X}, expected 01")
return None
# Parse fields (all little endian)
msg_type = data[1]
# Verify msg_type is in valid range
if msg_type > 3:
print(f"Warning: msg_type {msg_type} is out of range (0-3)")
return None
send_addr = struct.unpack('<H', data[2:4])[0] # 2 bytes, little endian
recv_addr = struct.unpack('<H', data[4:6])[0] # 2 bytes, little endian
node_rx = data[6:11] # 5 bytes
last_tx = data[11:16] # 5 bytes
last_rx = data[16:21] # 5 bytes
return (msg_type, send_addr, recv_addr, node_rx, last_tx, last_rx)
except (ValueError, IndexError, struct.error) as e:
print(f"Error parsing line: {e}")
return None
def process_line(msg_type: int, send_addr: int, recv_addr: int,
node_rx: bytes, last_tx: bytes, last_rx: bytes):
"""
User-defined function to process parsed data.
This is a placeholder - replace with your actual processing logic.
"""
print(f"Processed message:")
print(f" Message Type: {msg_type}")
print(f" Send Address: 0x{send_addr:04X}")
print(f" Recv Address: 0x{recv_addr:04X}")
print(f" Node RX: {node_rx.hex(' ')}")
print(f" Last TX: {last_tx.hex(' ')}")
print(f" Last RX: {last_rx.hex(' ')}")
print()
def main():
"""
Main function to run syslogger and process its output.
"""
# Start the syslogger process
try:
process = subprocess.Popen(
['./syslogger', '-D', '/dev/ttyACM0'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1 # Line buffered
)
except FileNotFoundError:
print("Error: Could not find 'syslogger' executable in current directory")
sys.exit(1)
except Exception as e:
print(f"Error starting syslogger: {e}")
sys.exit(1)
print("Started syslogger process...")
try:
# Process lines from stdout
while True:
line = process.stdout.readline()
# Check if we've reached EOF
if not line:
# Check if process is still alive
if process.poll() is not None:
print(f"Process exited with code: {process.returncode}")
break
continue
# Remove trailing newline
line = line.strip()
# Skip empty lines
if not line:
continue
# Parse the line
parsed = parse_hex_line(line)
if parsed:
msg_type, send_addr, recv_addr, node_rx, last_tx, last_rx = parsed
# Call the user-defined processing function
process_line(msg_type, send_addr, recv_addr, node_rx, last_tx, last_rx)
except KeyboardInterrupt:
print("\nInterrupted by user")
finally:
# Clean up: terminate the process if it's still running
if process.poll() is None:
print("Terminating syslogger process...")
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
print("Process didn't terminate, killing...")
process.kill()
process.wait()
if __name__ == "__main__":
main()
This script:
- Runs the executable: Uses
subprocess.Popen to start ./syslogger with the specified arguments
- Captures stdout: Reads lines from the process's stdout in real-time
- Parses hexadecimal data: The
parse_hex_line function:
- Splits the hex string into octets
- Converts to bytes
- Verifies the first byte is 0x01
- Extracts all fields using little-endian byte order
- Validates msg_type is in range 0-3
- Calls process_line: The parsed data is passed to the
process_line function
The script handles:
- Process lifecycle management (starting, monitoring, cleanup)
- Error handling for malformed input
- Graceful shutdown on Ctrl+C
- Process termination when the script exits
You can modify the process_line function to implement your specific processing logic for the parsed data.