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