# Konsole: Schritte als JSON in argv[1]: [{"send":..,"expect":..,"timeout":..,"interrupt":bool}]
import os,sys,termios,time,select,json,re
fd=os.open('/dev/ttyACM0',os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)
a=termios.tcgetattr(fd); a[0]=0;a[1]=0;a[2]=termios.CS8|termios.CREAD|termios.CLOCAL;a[3]=0;a[4]=a[5]=termios.B115200
termios.tcsetattr(fd,termios.TCSANOW,a)
def out(b): sys.stdout.buffer.write(b); sys.stdout.flush()
buf=b''
def read(t=0.05):
    global buf
    r,_,_=select.select([fd],[],[],t)
    if r:
        try: d=os.read(fd,4096)
        except BlockingIOError: return
        buf+=d; out(d)
for st in json.loads(sys.argv[1]):
    buf=b''
    if st.get('send') is not None:
        for ch in st['send'].encode(): os.write(fd,bytes([ch])); time.sleep(0.015)
    end=time.time()+st.get('timeout',10); pat=st.get('expect'); hit=False
    while time.time()<end:
        read()
        if st.get('interrupt') and b'U-Boot 20' in buf:
            if b'>> ' in buf or b'Starting kernel' in buf: st['interrupt']=False
            else: os.write(fd,b'1')
        if pat and re.search(pat.encode(),buf): hit=True; break
    if pat and not hit: out(('\n### TIMEOUT bei: %r\n'%pat).encode()); sys.exit(2)
