import asyncio
import websockets
import json
 
async def receive_and_save_raw_data():
    #api_key = "YOUR_API_KEY"
    api_key = "*******"
 
    subscribe_message = {
        "APIKey": api_key,
        "BoundingBoxes": [[[-90, -180], [90, 180]]], # 全球を指定
        "FilterMessageTypes": ["PositionReport"],
    }
 
    async with websockets.connect(
        "wss://stream.aisstream.io/v0/stream"
    ) as websocket:
        await websocket.send(json.dumps(subscribe_message))
 
        # バイナリ追記モードで保存
        with open("ais_raw_data.jsonl", "ab") as f:
            async for message in websocket:
                # メッセージに改行を加えて書き込む
                f.write(message + b"\n")
                f.flush()
 
                # 進捗確認用にMMSIを表示
                data = json.loads(message)
                print(f"Stored raw data from MMSI: {data['MetaData']['MMSI']}")
 
if __name__ == "__main__":
    asyncio.run(receive_and_save_raw_data())
