AIS Save to database using Python: Difference between revisions

From wikiluntti
(Created page with "== Introduction == Use ais_rtl and python to save data to db == Python == <syntaxhighlight lang="python"> import sys import sqlite3 from pyais.stream import IterMessages from datetime import datetime, timezone DB = "ais.db" conn = sqlite3.connect(DB) cur = conn.cursor() print("AIS logger started", flush=True) def clean_stream(): for line in sys.stdin.buffer: if not line: continue line = line.strip() if not line: c...")
 
 
Line 2: Line 2:


Use ais_rtl and python to save data to db
Use ais_rtl and python to save data to db
The following code will do the trick
<code>rtl_ais -n 2>&1 | python -u ais_logger.py</code>


== Python ==
== Python ==

Latest revision as of 17:15, 29 May 2026

Introduction

Use ais_rtl and python to save data to db

The following code will do the trick

rtl_ais -n 2>&1 | python -u ais_logger.py

Python

import sys
import sqlite3
from pyais.stream import IterMessages
from datetime import datetime, timezone

DB = "ais.db"
conn = sqlite3.connect(DB)
cur = conn.cursor()
print("AIS logger started", flush=True)

def clean_stream():
    for line in sys.stdin.buffer:
        if not line:
            continue

        line = line.strip()
        if not line:
            continue

        # AIS sentences always start with !
        if not line.startswith(b"!"):
            continue

        yield line

stream = IterMessages(clean_stream())

for msg in stream:
    try:
        data = msg.decode().asdict()
        print( data )
        ts = datetime.now(timezone.utc).isoformat()

        cur.execute("""
            INSERT INTO ais_data (ts, mmsi, msg_type, lat, lon, sog, cog, heading, shipname, raw)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (ts,data.get("mmsi"),data.get("msg_type"),data.get("lat"),data.get("lon"),data.get("speed"),data.get("course"),data.get("heading"),data.get("shipname"),str(msg)  ))

        conn.commit()

        print("INSERTED:", data.get("mmsi"), flush=True)

    except Exception as e:
        print("ERROR:", e, flush=True)