usb_pcap_logger.py
1 import sys 2 import os 3 import time 4 import serial 5 from datetime import datetime 6 from serial.tools import list_ports 7 8 def connect_to_bristlemouth(): 9 for port in list_ports.comports(): 10 if 'Bristlemouth' in port.description: 11 try: 12 ser = serial.Serial(port.device) 13 print(f'Connected to {port.device}') 14 return ser 15 except serial.SerialException as e: 16 print(f'Could not open port {port.device}: {e}') 17 return None 18 19 # Check if a COM port and file path were provided 20 if len(sys.argv) < 2: 21 print("Please provide a COM port and a file path.") 22 sys.exit(1) 23 24 # Get the file path from the command-line arguments 25 file_path = sys.argv[1] 26 27 # Create the file if it doesn't exist 28 if not os.path.exists(file_path): 29 open(file_path, 'w').close() 30 31 failed_to_connect_count = 0 32 33 while True: 34 try: 35 # Open the serial port 36 ser = connect_to_bristlemouth() 37 if ser is None: 38 raise serial.SerialException 39 failed_to_connect_count = 0 40 print("Logging serial data from {} to {}".format(ser.port, file_path)) 41 42 # Open the log file in append mode 43 with open(file_path, 'a') as file: 44 # Write a message to the file indicating that the serial device was connected 45 timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') 46 file.write(f'{timestamp}: Connected to {ser.port}\n') 47 print(f'{timestamp}: Connected to {ser.port}') 48 file.flush() 49 50 # Continuously read from the serial port and write to the log file 51 while True: 52 try: 53 line = ser.readline().decode(errors='replace') 54 if line: 55 if "rtc: 0," in line or "rtc: ," in line: 56 print("RTC 0 detected!!!") 57 timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') 58 file.write(f'{timestamp}: {line}') 59 file.flush() 60 except serial.SerialException: 61 # Write a message to the file indicating that the serial device was disconnected 62 timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') 63 file.write(f'{timestamp}: Disconnected from {ser.port}\n') 64 print(f'{timestamp}: Disconnected from {ser.port}') 65 file.flush() 66 break 67 68 except serial.SerialException as e: 69 if failed_to_connect_count % 30 == 0: 70 timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') 71 sys.stderr.write('{}: lost/could not find a bristlmouth port\n'.format(timestamp)) 72 failed_to_connect_count += 1 73 74 # Wait for a second before the next attempt 75 time.sleep(0.5)