import websocket,json,time,sys,math
from datetime import datetime,timedelta,timezone
sys.path.insert(0,'/tmp')
import passes as P
label,url,lat,lon,f0,start_iso,end_iso=sys.argv[1],sys.argv[2],float(sys.argv[3]),float(sys.argv[4]),float(sys.argv[5]),sys.argv[6],sys.argv[7]
start=datetime.fromisoformat(start_iso);end=datetime.fromisoformat(end_iso)
sat,ep=P.sat_of('ISS (ZARYA)')
def rng(t):
    p=P.ecef(sat,t);la,lo=math.radians(lat),math.radians(lon);a=6378.137;f=1/298.257;e2=f*(2-f)
    N=a/math.sqrt(1-e2*math.sin(la)**2);o=((N)*math.cos(la)*math.cos(lo),N*math.cos(la)*math.sin(lo),N*(1-e2)*math.sin(la))
    return math.sqrt(sum((p[k]-o[k])**2 for k in range(3)))
def dop(t):
    rr=(rng(t+timedelta(seconds=0.5))-rng(t-timedelta(seconds=0.5)))*1000
    return f0*(1-rr/299792458.0)
while datetime.now(timezone.utc)<start: time.sleep(1)
log=open(f'/tmp/cap_{label}.log','w')
ws=websocket.create_connection(url.replace('http','ws',1).rstrip('/')+'/ws/',timeout=20,header=['User-Agent: anan2090-research'])
ws.send('SERVER DE CLIENT client=openwebrx.js type=receiver')
ws.send(json.dumps({"type":"connectionproperties","params":{"output_rate":12000,"hd_output_rate":44100}}))
out=open(f'/tmp/cap_{label}.adpcm','wb');center=None;started=False;last=0;t_first=None;nb=0
def retune():
    t=datetime.now(timezone.utc);fr=dop(t)
    ws.send(json.dumps({"type":"dspcontrol","params":{"offset_freq":int(fr-center)}}))
    log.write(f'{t.isoformat()} tune {fr:.0f} el {P.el(P.ecef(sat,t),lat,lon):.1f}\n');log.flush()
while datetime.now(timezone.utc)<end:
    try:m=ws.recv()
    except Exception as e: log.write('recv err '+str(e)+'\n');break
    if isinstance(m,str):
        if m.startswith('{'):
            j=json.loads(m)
            if j['type']=='config' and 'center_freq' in j['value'] and not started:
                center=j['value']['center_freq'];started=True;t=datetime.now(timezone.utc)
                ws.send(json.dumps({"type":"dspcontrol","params":{"low_cut":-4000,"high_cut":4000,"offset_freq":int(dop(t)-center),"mod":"nfm","squelch_level":-150}}))
                ws.send(json.dumps({"type":"dspcontrol","action":"start"}));log.write(f'{t.isoformat()} start center {center}\n')
            elif j['type'] in('sdr_error','backoff','demodulator_error'): log.write(m[:200]+'\n')
    elif m[0]==2:
        if t_first is None:t_first=datetime.now(timezone.utc);log.write(f'first audio {t_first.isoformat()}\n')
        out.write(m[1:]);nb+=len(m)-1
    if started and time.time()-last>5: last=time.time();retune();out.flush()
out.close();log.write(f'done bytes {nb}\n');log.close()
