import asyncio
from bleak import BleakClient
import time

AUDIO_CHAR_UUID = "19b10001-e8f2-537e-4f6c-d104768a1214"
packets = []

def audio_callback(sender, data):
    packets.append(data)
    print(f"Packet received: {len(data)} bytes")

async def capture(address):
    print(f"Connecting to {address}...")
    try:
        async with BleakClient(address) as client:
            print(f"✓ Connected")
            print("Starting audio notification listener...")
            await client.start_notify(AUDIO_CHAR_UUID, audio_callback)
            print("Capturing audio for 5 seconds...")
            await asyncio.sleep(5)
            await client.stop_notify(AUDIO_CHAR_UUID)
            
        print(f"\n✓ Total packets received: {len(packets)}")
        if packets:
            total_bytes = sum(len(p) for p in packets)
            print(f"  Total bytes: {total_bytes}")
            print(f"  Average packet size: {total_bytes / len(packets):.1f} bytes")
            print(f"  Min packet: {min(len(p) for p in packets)} bytes")
            print(f"  Max packet: {max(len(p) for p in packets)} bytes")
            
            # Save raw audio
            with open("audio_sample.bin", "wb") as f:
                for p in packets:
                    f.write(p)
            print(f"\n✓ Saved raw audio to audio_sample.bin")
        else:
            print("✗ No packets received")
    except Exception as e:
        print(f"✗ Error: {e}")

asyncio.run(capture("BD3FF870-B161-ACF9-84B5-2A6B0963C2BF"))
