-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathais-fileto-sqlite
76 lines (63 loc) · 2.21 KB
/
ais-fileto-sqlite
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
# Copyright (c) 2019 by Philip Collier, radio AB9IL <[email protected]>
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version. There is NO warranty; not even for
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
import datetime
import json
import sqlite3
import sys
import ais
stime = datetime.datetime.now()
print('AIS file decoder converts logs of NMEA data to an sqlite database file.')
print('Usage: ais-file-decoder < inputfile >')
nmeafile = sys.argv[1]
outfile = str(stime) + '-decoded-ais.db'
outdata = []
# decode and print from raw nmea sentences from a file
q = ais.nmea_queue.NmeaQueue()
with open(nmeafile) as infile:
for msg in infile:
q.put(msg)
if q.qsize():
d = q.get().get('decoded', None)
outdata.append(d)
# create a database file
conn = sqlite3.connect(outfile)
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS VESSELS( \
MMSI INT IGNORE, \
NAME STRING IGNORE, \
LATITUDE REAL IGNORE, \
LONGITUDE REAL IGNORE, \
YEAR INT IGNORE, \
MONTH INT IGNORE, \
DAY INT IGNORE, \
HOUR INT IGNORE, \
MINUTE INT IGNORE, \
SECOND INt IGNORE);")
conn.commit()
# replace missing keys or empty keys with nans
for things in outdata:
keys = ['mmsi', 'name', 'y', 'x', 'year', 'month', 'day', 'hour', \
'minute', 'second']
for key in keys:
try:
if key not in things:
things[key] = 'NaN'
except Exception as E:
print('Missing key', key)
try:
cursor.execute("INSERT INTO VESSELS values (?,?,?,?,?,?,?,?,?,?)", \
(things['mmsi'], things['name'], things['y'], things['x'], \
things['year'], things['month'], things['day'], things['hour'], \
things['minute'], things['second']))
except Exception as E:
print('Error inserting data into db:', E)
pass
# close the database
conn.commit()
runtime = 'Elapsed Runtime: ' + str(datetime.datetime.now() - stime)
print(outfile, 'written.', runtime)