import asyncio, json, ssl, sys, time
import numpy as np, soundfile as sf, websockets
URL = sys.argv[1] if len(sys.argv) > 1 else "wss://192.168.31.31:8770/monitor"
DUR = float(sys.argv[2]) if len(sys.argv) > 2 else 12.0
async def main():
    ctx = ssl._create_unverified_context()
    blocks=[]; t0=time.time()
    async with websockets.connect(URL, ssl=ctx, max_size=2**22) as ws:
        while time.time()-t0 < DUR:
            try: m = await asyncio.wait_for(ws.recv(), timeout=DUR)
            except asyncio.TimeoutError: break
            if isinstance(m,str):
                print("[text]", m[:100]); continue
            blocks.append(np.frombuffer(m,dtype="<i2").astype(np.float32)/32768)
    if blocks:
        y=np.concatenate(blocks); sf.write("/tmp/monitor-wss.wav", y, 48000)
        print("blocks=%d audio=%.2fs rms=%.4f"%(len(blocks), len(y)/48000, float(np.sqrt((y**2).mean()))))
    else: print("no audio")
asyncio.run(main())
