import websocket,json,time,sys,struct,wave
url,freq,secs,out=sys.argv[1],float(sys.argv[2]),float(sys.argv[3]),sys.argv[4]
mod=sys.argv[5] if len(sys.argv)>5 else 'nfm'
ws=websocket.create_connection(url.replace('http','ws',1).rstrip('/')+'/ws/',timeout=10,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}}))
center=None;started=False;pcm=bytearray();t0=time.time();info=[];kinds={}
while True:
    try:m=ws.recv()
    except Exception as e: info.append('recv:'+str(e)[:50]);break
    if isinstance(m,str):
        if m.startswith('{'):
            j=json.loads(m)
            if j['type']=='receiver_details': info.append('details:'+json.dumps(j['value'])[:600])
            if j['type']=='config':
                v=j['value']
                if 'center_freq' in v: center=v['center_freq'];sr=v['samp_rate'];info.append(f'center {center} sr {sr} comp {v.get("audio_compression")}')
                if center and not started:
                    started=True
                    ws.send(json.dumps({"type":"dspcontrol","params":{"low_cut":-4000,"high_cut":4000,"offset_freq":int(freq-center),"mod":mod,"dmr_filter":3,"audio_service_id":0,"squelch_level":-150}}))
                    ws.send(json.dumps({"type":"dspcontrol","action":"start"}))
            if j['type'] in('sdr_error','demodulator_error','backoff'): info.append(m[:200])
    else:
        k=m[0];kinds[k]=kinds.get(k,0)+1
        if k==2: pcm+=m[1:]
        if started and time.time()-t0>secs+3 : break
    if time.time()-t0>secs+15:break
print('\n'.join(info));print('frame kinds',kinds,'pcm bytes',len(pcm))
open(out+'.raw','wb').write(pcm)
