import asyncio, json, sys, time
import numpy as np, soundfile as sf
import websockets

URL = sys.argv[1] if len(sys.argv) > 1 else "ws://192.168.31.31:8771/monitor"
DUR = float(sys.argv[2]) if len(sys.argv) > 2 else 15.0

async def main():
    blocks = []
    t0 = time.time()
    async with websockets.connect(URL, max_size=2**22) as ws:
        while time.time() - t0 < DUR:
            try:
                msg = await asyncio.wait_for(ws.recv(), timeout=DUR)
            except asyncio.TimeoutError:
                break
            if isinstance(msg, str):
                print("[text]", msg[:120])
                continue
            blocks.append(np.frombuffer(msg, dtype="<i2").astype(np.float32) / 32768.0)
    if blocks:
        y = np.concatenate(blocks)
        sf.write("/tmp/monitor-out.wav", y, 48000)
        print("monitor blocks=%d  audio=%.2fs  rms=%.4f" % (len(blocks), len(y)/48000, float(np.sqrt((y**2).mean()))))
    else:
        print("no audio received")

asyncio.run(main())
