"""发命令并按需抓屏:fbshot.py "cmd|等待秒|输出png(或-)" ... 状态机保证 [FB] 标记不会被日志冲掉。""" import serial, sys, time, os PORT='/dev/cu.usbserial-210'; BAUD=115200; N=320*240*2 log=open(sys.argv[1],'ab',buffering=0) steps=[a.split('|') for a in sys.argv[2:]] s=serial.Serial(PORT,BAUD,timeout=0.1,write_timeout=10) buf=bytearray() def pump(dur, path=None): """读串口 dur 秒;path 不为空时遇到 [FB] 就抓 N 字节并渲染""" global buf end=time.time()+dur; f=None; got=0 while time.time()end: break continue if f is None: buf.extend(d) i=buf.find(b'[FB]') if i<0: keep=6; n=max(0,len(buf)-keep) if n: log.write(bytes(buf[:n])); del buf[:n] continue log.write(bytes(buf[:i])); del buf[:i+4] if path is None: continue # 不抓屏就丢掉这段二进制 f=open(path,'wb'); print('[fb] capturing...',flush=True) d=bytes(buf); buf=bytearray() # 只写标记之后的数据,否则整幅图右移 2px 且末行丢 2px take=len(d) if f.tell()+len(d)<=N else N-f.tell() f.write(d[:take]); got+=take if f.tell()>=N: f.close(); log.write(d[take:]) print('[fb] %s %d bytes'%(path,got),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'%(path,path)) print('[fb] rendered %s.png'%(path,),flush=True) buf=bytearray(); return True if path: print('[fb] TIMEOUT',flush=True) return False pump(1.5) for st in steps: cmd=st[0]; wait=float(st[1]) if len(st)>1 else 0.2 out=st[2] if len(st)>2 and st[2]!='-' else None if cmd: print('[send] %s'%cmd,flush=True); s.write(cmd.encode()+b'\r\n'); s.flush() pump(wait, out) s.close()