cosmo/terminal/tools/serial_term.py

62 lines
2.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import serial, sys, threading, time, os, re
import glob
#: 换过 USB 口(CH340 -> 板载 USB-CDC)就别让脚本抓瞎:COSMO_PORT 优先,否则挑一个在的
def _pick_port():
env = os.environ.get('COSMO_PORT')
if env: return env
for pat in ('/dev/cu.usbserial*', '/dev/cu.usbmodem*'):
m = sorted(glob.glob(pat))
if m: return m[0]
return '/dev/cu.usbserial-210'
PORT = _pick_port(); BAUD=115200
OUT=sys.argv[1] if len(sys.argv)>2 else '/tmp/fb.raw'
N=320*240*2
s=serial.Serial(); s.port=PORT; s.baudrate=BAUD; s.timeout=0.1; s.write_timeout=5
s.open()
state=['text']; buf=bytearray(); f=None
def reader():
while True:
try: d=s.read(4096)
except Exception as e:
print('\n[serial error] %s'%e,flush=True); return
if not d: continue
buf.extend(d)
while True:
if state[0]=='text':
i=buf.find(b'[FB]')
if i<0:
keep=6
n=max(0,len(buf)-keep)
out=bytes(buf[:n]); del buf[:n]
if out: sys.stdout.write(out.decode('utf-8','replace')); sys.stdout.flush()
break
head=bytes(buf[:i]); del buf[:i+4]
if head: sys.stdout.write(head.decode('utf-8','replace')); sys.stdout.flush()
f=open(OUT,'wb'); state[0]='raw'; print('\n[fb] capturing %d bytes...'%N,flush=True)
elif state[0]=='raw':
take=min(N-f.tell(),len(buf))
f.write(bytes(buf[:take])); del buf[:take]
if f.tell()>=N:
f.close(); state[0]='tail'; print('\n[fb] got %s (%d bytes)'%(OUT,N),flush=True)
else: break
else:
i=buf.find(b'[FBEND]')
if i<0:
n=max(0,len(buf)-8)
out=bytes(buf[:n]); del buf[:n]
if out: sys.stdout.write(out.decode('utf-8','replace')); sys.stdout.flush()
break
tail=bytes(buf[:i+7]); del buf[:i+7]
print(tail.decode('utf-8','replace'),flush=True)
os.system('/usr/local/bin/ffmpeg -y -loglevel error -f rawvideo -pixel_format rgb565be -video_size 320x240 -i %s -frames:v 1 -vf "scale=960:720:flags=neighbor" %s.png'%(OUT,OUT))
print('[fb] rendered %s.png'%OUT,flush=True)
state[0]='text'
threading.Thread(target=reader,daemon=True).start()
print('[term] attached %s -> %s'%(PORT,OUT),flush=True)
for line in sys.stdin:
try: s.write(line.rstrip('\n').encode()+b'\r\n'); s.flush()
except Exception as e: print('[write failed] %s'%e,flush=True)