X-Git-Url: http://average.org/gitweb/?a=blobdiff_plain;f=gps303%2Fevstore.py;h=c10ecb17e5d7a191d7bf75a76e768138cc9c2755;hb=96538346bd332d76d2cac5d6a0ef2b4e4a40de30;hp=b1950210555adb532e0cf645941857ca95bc3131;hpb=4c173a5448990cd4da398be1bf3479bef17b1048;p=loctrkd.git diff --git a/gps303/evstore.py b/gps303/evstore.py index b195021..c10ecb1 100644 --- a/gps303/evstore.py +++ b/gps303/evstore.py @@ -1,16 +1,17 @@ +""" sqlite event store """ + from sqlite3 import connect -__all__ = ("initdb", "stow") +__all__ = "fetch", "initdb", "stow" DB = None SCHEMA = """create table if not exists events ( - timestamp real not null, + tstamp real not null, imei text, - clntaddr text not null, - length int, + peeraddr text not null, proto int not null, - payload blob + packet blob )""" @@ -20,20 +21,37 @@ def initdb(dbname): DB.execute(SCHEMA) -def stow(clntaddr, timestamp, imei, length, proto, payload): +def stow(**kwargs): assert DB is not None - parms = dict( - zip( - ("clntaddr", "timestamp", "imei", "length", "proto", "payload"), - (str(clntaddr), timestamp, imei, length, proto, payload), + parms = { + k: kwargs[k] if k in kwargs else v + for k, v in ( + ("peeraddr", None), + ("when", 0.0), + ("imei", None), + ("proto", -1), + ("packet", b""), ) - ) + } + assert len(kwargs) <= len(parms) DB.execute( """insert or ignore into events - (timestamp, imei, clntaddr, length, proto, payload) + (tstamp, imei, peeraddr, proto, packet) values - (:timestamp, :imei, :clntaddr, :length, :proto, :payload) + (:when, :imei, :peeraddr, :proto, :packet) """, parms, ) DB.commit() + +def fetch(imei, protos, backlog): + assert DB is not None + protosel = ", ".join(["?" for _ in range(len(protos))]) + cur = DB.cursor() + cur.execute(f"""select packet from events + where proto in ({protosel}) and imei = ? + order by tstamp desc limit ?""", + protos + (imei, backlog)) + result = [row[0] for row in cur] + cur.close() + return result