68 lines
2.9 KiB
Python
68 lines
2.9 KiB
Python
"""发命令并按需抓屏:fbshot.py <log> "cmd|等待秒|输出png(或-)" ...
|
||
状态机保证 [FB] 标记不会被日志冲掉。"""
|
||
import serial, sys, time, os
|
||
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
|
||
#: 屏尺寸跟着板子走(320x240 / 240x240 / 172x640):COSMO_FB=172x640 python3 ...
|
||
W,H = [int(v) for v in os.environ.get('COSMO_FB','320x240').lower().split('x')]
|
||
N=W*H*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
|
||
hard=end+90 # 抓屏期间也要有终点:设备中途不发了,脚本不能永远卡在串口上
|
||
while time.time()<end or (f is not None and time.time()<hard):
|
||
d=s.read(4096)
|
||
if not d:
|
||
if f is None and 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 %dx%d -i %s -frames:v 1 -vf "scale=%d:%d:flags=neighbor" %s.png'
|
||
%(W,H,path,W*3,H*3,path))
|
||
print('[fb] rendered %s.png'%(path,),flush=True)
|
||
buf=bytearray(); return True
|
||
if f is not None:
|
||
f.close(); print('[fb] TRUNCATED %d/%d bytes'%(got,N),flush=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()
|