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, timeout = None): 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=timeout if timeout else 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.timeout = timeout 47 self.sentinel = object() 48 49 if self.dev: 50 self.read_thread = threading.Thread( 51 target=self.serial_read_thread_loop, daemon=True) 52 else: 53 self.read_thread = threading.Thread( 54 target=self.serial_file_read_thread_loop, daemon=True) 55 self.read_thread.start() 56 57 self.lines_thread = threading.Thread( 58 target=self.serial_lines_thread_loop, daemon=True) 59 self.lines_thread.start() 60 61 # Thread that just reads the bytes from the serial device to try to keep from 62 # buffer overflowing it. If nothing is received in 1 minute, it finalizes. 63 def serial_read_thread_loop(self): 64 greet = "Serial thread reading from %s\n" % self.dev 65 self.byte_queue.put(greet.encode()) 66 67 while True: 68 try: 69 b = self.serial.read() 70 if len(b) > 0: 71 self.byte_queue.put(b) 72 elif self.timeout: 73 self.byte_queue.put(self.sentinel) 74 break 75 except Exception as err: 76 print(self.prefix + str(err)) 77 self.byte_queue.put(self.sentinel) 78 break 79 80 # Thread that just reads the bytes from the file of serial output that some 81 # other process is appending to. 82 def serial_file_read_thread_loop(self): 83 greet = "Serial thread reading from %s\n" % self.filename 84 self.byte_queue.put(greet.encode()) 85 86 while True: 87 line = self.f.readline() 88 if line: 89 self.byte_queue.put(line) 90 else: 91 time.sleep(0.1) 92 93 # Thread that processes the stream of bytes to 1) log to stdout, 2) log to 94 # file, 3) add to the queue of lines to be read by program logic 95 96 def serial_lines_thread_loop(self): 97 line = bytearray() 98 while True: 99 bytes = self.byte_queue.get(block=True) 100 101 if bytes == self.sentinel: 102 self.read_thread.join() 103 self.line_queue.put(self.sentinel) 104 break 105 106 # Write our data to the output file if we're the ones reading from 107 # the serial device 108 if self.dev: 109 self.f.write(bytes) 110 self.f.flush() 111 112 for b in bytes: 113 line.append(b) 114 if b == b'\n'[0]: 115 line = line.decode(errors="replace") 116 117 time = datetime.now().strftime('%y-%m-%d %H:%M:%S') 118 print("{endc}{time} {prefix}{line}".format( 119 time=time, prefix=self.prefix, line=line, endc='\033[0m'), flush=True, end='') 120 121 self.line_queue.put(line) 122 line = bytearray() 123 124 def get_line(self): 125 line = self.line_queue.get() 126 if line == self.sentinel: 127 self.lines_thread.join() 128 return line 129 130 def lines(self): 131 return iter(self.get_line, self.sentinel) 132 133 134def main(): 135 parser = argparse.ArgumentParser() 136 137 parser.add_argument('--dev', type=str, help='Serial device') 138 parser.add_argument('--file', type=str, 139 help='Filename for serial output', required=True) 140 parser.add_argument('--prefix', type=str, 141 help='Prefix for logging serial to stdout', nargs='?') 142 143 args = parser.parse_args() 144 145 ser = SerialBuffer(args.dev, args.file, args.prefix or "") 146 for line in ser.lines(): 147 # We're just using this as a logger, so eat the produced lines and drop 148 # them 149 pass 150 151 152if __name__ == '__main__': 153 main() 154