1#!/usr/bin/env python3 2# 3# Copyright © 2020 Google LLC 4# 5# Permission is hereby granted, free of charge, to any person obtaining a 6# copy of this software and associated documentation files (the "Software"), 7# to deal in the Software without restriction, including without limitation 8# the rights to use, copy, modify, merge, publish, distribute, sublicense, 9# and/or sell copies of the Software, and to permit persons to whom the 10# Software is furnished to do so, subject to the following conditions: 11# 12# The above copyright notice and this permission notice (including the next 13# paragraph) shall be included in all copies or substantial portions of the 14# Software. 15# 16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 22# IN THE SOFTWARE. 23 24import argparse 25from datetime import datetime, timezone 26import queue 27import serial 28import threading 29import time 30 31 32class SerialBuffer: 33 def __init__(self, dev, filename, prefix): 34 self.filename = filename 35 self.dev = dev 36 37 if dev: 38 self.f = open(filename, "wb+") 39 self.serial = serial.Serial(dev, 115200, timeout=10) 40 else: 41 self.f = open(filename, "rb") 42 43 self.byte_queue = queue.Queue() 44 self.line_queue = queue.Queue() 45 self.prefix = prefix 46 self.sentinel = object() 47 48 if self.dev: 49 self.read_thread = threading.Thread( 50 target=self.serial_read_thread_loop, daemon=True) 51 else: 52 self.read_thread = threading.Thread( 53 target=self.serial_file_read_thread_loop, daemon=True) 54 self.read_thread.start() 55 56 self.lines_thread = threading.Thread( 57 target=self.serial_lines_thread_loop, daemon=True) 58 self.lines_thread.start() 59 60 # Thread that just reads the bytes from the serial device to try to keep from 61 # buffer overflowing it. 62 def serial_read_thread_loop(self): 63 greet = "Serial thread reading from %s\n" % self.dev 64 self.byte_queue.put(greet.encode()) 65 66 while True: 67 try: 68 self.byte_queue.put(self.serial.read()) 69 except Exception as err: 70 print(self.prefix + str(err)) 71 self.byte_queue.put(self.sentinel) 72 break 73 74 # Thread that just reads the bytes from the file of serial output that some 75 # other process is appending to. 76 def serial_file_read_thread_loop(self): 77 greet = "Serial thread reading from %s\n" % self.filename 78 self.byte_queue.put(greet.encode()) 79 80 while True: 81 line = self.f.readline() 82 if line: 83 self.byte_queue.put(line) 84 else: 85 time.sleep(0.1) 86 87 # Thread that processes the stream of bytes to 1) log to stdout, 2) log to 88 # file, 3) add to the queue of lines to be read by program logic 89 90 def serial_lines_thread_loop(self): 91 line = bytearray() 92 while True: 93 bytes = self.byte_queue.get(block=True) 94 95 if bytes == self.sentinel: 96 self.read_thread.join() 97 self.line_queue.put(self.sentinel) 98 break 99 100 # Write our data to the output file if we're the ones reading from 101 # the serial device 102 if self.dev: 103 self.f.write(bytes) 104 self.f.flush() 105 106 for b in bytes: 107 line.append(b) 108 if b == b'\n'[0]: 109 line = line.decode(errors="replace") 110 111 time = datetime.now().strftime('%y-%m-%d %H:%M:%S') 112 print("{endc}{time} {prefix}{line}".format( 113 time=time, prefix=self.prefix, line=line, endc='\033[0m'), flush=True, end='') 114 115 self.line_queue.put(line) 116 line = bytearray() 117 118 def get_line(self): 119 line = self.line_queue.get() 120 if line == self.sentinel: 121 self.lines_thread.join() 122 return line 123 124 def lines(self): 125 return iter(self.get_line, self.sentinel) 126 127 128def main(): 129 parser = argparse.ArgumentParser() 130 131 parser.add_argument('--dev', type=str, help='Serial device') 132 parser.add_argument('--file', type=str, 133 help='Filename for serial output', required=True) 134 parser.add_argument('--prefix', type=str, 135 help='Prefix for logging serial to stdout', nargs='?') 136 137 args = parser.parse_args() 138 139 ser = SerialBuffer(args.dev, args.file, args.prefix or "") 140 for line in ser.lines(): 141 # We're just using this as a logger, so eat the produced lines and drop 142 # them 143 pass 144 145 146if __name__ == '__main__': 147 main() 148