Repository navigation
Expand file tree
/
Copy pathais_msg_3_handcoded.py
More file actions
executable file
·408 lines (357 loc) · 12.3 KB
/
Copy pathais_msg_3_handcoded.py
File metadata and controls
executable file
·408 lines (357 loc) · 12.3 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#!/usr/bin/env python
"""Adds ITDMA commstate to message 3."""
import io
import sys
from decimal import Decimal
from optparse import OptionParser
from BitVector import BitVector
from aisutils import binary, sqlhelp
from . import commstate
# from ais_msg_1 import *
fieldList = (
"MessageID",
"RepeatIndicator",
"UserID",
"NavigationStatus",
"ROT",
"SOG",
"PositionAccuracy",
"longitude",
"latitude",
"COG",
"TrueHeading",
"TimeStamp",
"RegionalReserved",
"Spare",
"RAIM",
*commstate.itdma_fields,
)
def decode_aivdm(msg):
bv = binary.ais6tobitvec(msg.split(",")[5])
print(decode(bv))
def decode(bv, validate=False):
r = {}
r["MessageID"] = int(bv[:6])
r["RepeatIndicator"] = int(bv[6:8])
r["UserID"] = int(bv[8:38])
r["NavigationStatus"] = int(bv[38:42])
r["ROT"] = binary.signedIntFromBV(bv[42:50])
r["SOG"] = Decimal(int(bv[50:60])) / Decimal("10")
r["PositionAccuracy"] = int(bv[60:61])
r["longitude"] = Decimal(binary.signedIntFromBV(bv[61:89])) / Decimal("600000")
r["latitude"] = Decimal(binary.signedIntFromBV(bv[89:116])) / Decimal("600000")
r["COG"] = Decimal(int(bv[116:128])) / Decimal("10")
r["TrueHeading"] = int(bv[128:137])
r["TimeStamp"] = int(bv[137:143])
r["RegionalReserved"] = 0
r["Spare"] = 0
r["RAIM"] = bool(int(bv[148:149]))
r.update(commstate.itdma_parse_bits(bv[-19:]))
return r
def sqlCreateStr(
outfile=sys.stdout,
fields=None,
extraFields=None,
addCoastGuardFields=True,
dbType="postgres",
):
outfile.write(
str(sqlCreate(fields, extraFields, addCoastGuardFields, dbType=dbType))
)
def sqlCreate(
fields=None, extraFields=None, addCoastGuardFields=True, dbType="postgres"
):
"""Return the sqlhelp object to create the table.
Args:
fields: which fields to put in the create. Defaults to all.
extraFields: A sequence of tuples containing (name,sql type) for additional fields
addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
@type addCoastGuardFields: bool
dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
Returns:
An object that can be used to generate a return
sqlhelp.create
"""
if not fields:
fields = fieldList
c = sqlhelp.create("position", dbType=dbType)
c.addPrimaryKey()
if "MessageID" in fields:
c.addInt("MessageID")
if "RepeatIndicator" in fields:
c.addInt("RepeatIndicator")
if "UserID" in fields:
c.addInt("UserID")
if "NavigationStatus" in fields:
c.addInt("NavigationStatus")
if "ROT" in fields:
c.addInt("ROT")
if "SOG" in fields:
c.addDecimal("SOG", 4, 1)
if "PositionAccuracy" in fields:
c.addInt("PositionAccuracy")
if dbType != "postgres" and "longitude" in fields:
c.addDecimal("longitude", 8, 5)
if dbType != "postgres" and "latitude" in fields:
c.addDecimal("latitude", 8, 5)
if "COG" in fields:
c.addDecimal("COG", 4, 1)
if "TrueHeading" in fields:
c.addInt("TrueHeading")
if "TimeStamp" in fields:
c.addInt("TimeStamp")
if "RegionalReserved" in fields:
c.addInt("RegionalReserved")
if "Spare" in fields:
c.addInt("Spare")
if "RAIM" in fields:
c.addBool("RAIM")
# Include both ITDMA and SOTDMA so we have one position table.
commstate.sql_fields(c)
if addCoastGuardFields:
# c.addInt('cg_s_rssi') # Relative signal strength indicator
# c.addInt('cg_d_strength') # dBm receive strength
# c.addVarChar('cg_x',10) # Idonno
c.addInt("cg_t_arrival") # Receive timestamp from the AIS equipment 'T'
c.addInt("cg_s_slotnum") # Slot received in.
c.addVarChar("cg_r", 15) # Receiver station ID.
c.addInt("cg_sec") # UTC seconds since the epoch.
c.addTimestamp(
"cg_timestamp"
) # UTC decoded cg_sec - not actually in the data stream
if dbType == "postgres":
c.addPostGIS("Position", "POINT", 2, SRID=4326)
return c
def printFields(
params, out=sys.stdout, format="std", fieldList=None, dbType="postgres"
):
if format == "std":
out.write("position:\n")
if "MessageID" in params:
out.write(" MessageID: " + str(params["MessageID"]) + "\n")
if "RepeatIndicator" in params:
out.write(
" RepeatIndicator: " + str(params["RepeatIndicator"]) + "\n"
)
if "UserID" in params:
out.write(" UserID: " + str(params["UserID"]) + "\n")
if "NavigationStatus" in params:
out.write(
" NavigationStatus: " + str(params["NavigationStatus"]) + "\n"
)
if "ROT" in params:
out.write(" ROT: " + str(params["ROT"]) + "\n")
if "SOG" in params:
out.write(" SOG: " + str(params["SOG"]) + "\n")
if "PositionAccuracy" in params:
out.write(
" PositionAccuracy: " + str(params["PositionAccuracy"]) + "\n"
)
if "longitude" in params:
out.write(" longitude: " + str(params["longitude"]) + "\n")
if "latitude" in params:
out.write(" latitude: " + str(params["latitude"]) + "\n")
if "COG" in params:
out.write(" COG: " + str(params["COG"]) + "\n")
if "TrueHeading" in params:
out.write(" TrueHeading: " + str(params["TrueHeading"]) + "\n")
if "TimeStamp" in params:
out.write(" TimeStamp: " + str(params["TimeStamp"]) + "\n")
if "RegionalReserved" in params:
out.write(
" RegionalReserved: " + str(params["RegionalReserved"]) + "\n"
)
if "Spare" in params:
out.write(" Spare: " + str(params["Spare"]) + "\n")
if "RAIM" in params:
out.write(" RAIM: " + str(params["RAIM"]) + "\n")
for field in commstate.itdma_fields:
fieldname = "\t" + (field + ":").ljust(30)
if field in params:
out.write(fieldname + str(params[field]) + "\n")
else:
out.write(fieldname + "n/a\n")
elif format == "csv":
if options.fieldList is None:
options.fieldList = fieldList
needComma = False
for field in fieldList:
if needComma:
out.write(",")
needComma = True
if field in params:
out.write(str(params[field]))
# else: leave it empty
out.write("\n")
elif format == "html":
printHtml(params, out)
elif format == "sql":
sqlInsertStr(params, out, dbType=dbType)
elif format == "kml":
printKml(params, out)
elif format == "kml-full":
out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
out.write('<kml xmlns="http://earth.google.com/kml/2.1">\n')
out.write("<Document>\n")
out.write(" <name>position</name>\n")
printKml(params, out)
out.write("</Document>\n")
out.write("</kml>\n")
else:
print("ERROR: unknown format:", format)
raise AssertionError()
def main():
parser = OptionParser(usage="%prog [options]")
parser.add_option(
"-v",
"--verbose",
dest="verbose",
default=False,
action="store_true",
help="Make the test output verbose",
)
# FIX: remove nmea from binary messages. No way to build the whole packet?
# FIX: or build the surrounding msg 8 for a broadcast?
typeChoices = (
"binary",
"nmeapayload",
"nmea",
) # FIX: what about a USCG type message?
parser.add_option(
"-t",
"--type",
choices=typeChoices,
type="choice",
dest="ioType",
default="nmeapayload",
help="What kind of string to write for encoding ("
+ ", ".join(typeChoices)
+ ") [default: %default]",
)
outputChoices = ("std", "html", "csv", "sql", "kml", "kml-full")
parser.add_option(
"-T",
"--output-type",
choices=outputChoices,
type="choice",
dest="outputType",
default="std",
help="What kind of string to output ("
+ ", ".join(outputChoices)
+ ") [default: %default]",
)
parser.add_option(
"-o",
"--output",
dest="outputFileName",
default=None,
help="Name of the python file to write [default: stdout]",
)
parser.add_option(
"-f",
"--fields",
dest="fieldList",
default=None,
action="append",
choices=fieldList,
help="Which fields to include in the output. Currently only for csv output [default: all]",
)
parser.add_option(
"-p",
"--print-csv-field-list",
dest="printCsvfieldList",
default=False,
action="store_true",
help="Print the field name for csv",
)
parser.add_option(
"-c",
"--sql-create",
dest="sqlCreate",
default=False,
action="store_true",
help="Print out an sql create command for the table.",
)
parser.add_option(
"--latex-table",
dest="latexDefinitionTable",
default=False,
action="store_true",
help="Print a LaTeX table of the type",
)
parser.add_option(
"--text-table",
dest="textDefinitionTable",
default=False,
action="store_true",
help="Print delimited table of the type (for Word table importing)",
)
parser.add_option(
"--delimt-text-table",
dest="delimTextDefinitionTable",
default="\t",
help="Delimiter for text table [default: '%default'](for Word table importing)",
)
dbChoices = ("sqlite", "postgres")
parser.add_option(
"-D",
"--db-type",
dest="dbType",
default="postgres",
choices=dbChoices,
type="choice",
help="What kind of database (" + ", ".join(dbChoices) + ") [default: %default]",
)
addMsgOptions(parser)
(options, args) = parser.parse_args()
outfile = sys.stdout
if options.outputFileName is not None:
outfile = file(options.outputFileName, "w")
if options.sqlCreate:
sqlCreateStr(outfile, options.fieldList, dbType=options.dbType)
if options.latexDefinitionTable:
latexDefinitionTable(outfile)
# For conversion to word tables
if options.textDefinitionTable:
textDefinitionTable(outfile, options.delimTextDefinitionTable)
if options.printCsvfieldList:
# Make a csv separated list of fields that will be displayed for csv
if options.fieldList is None:
options.fieldList = fieldList
buf = io.StringIO()
for field in options.fieldList:
buf.write(field + ",")
result = buf.getvalue()
if result[-1] == ",":
print(result[:-1])
else:
print(result)
if options.doDecode:
if len(args) == 0:
args = sys.stdin
for msg in args:
bv = None
if msg[0] in ("$", "!") and msg[3:6] in ("VDM", "VDO"):
# Found nmea
# FIX: do checksum
bv = binary.ais6tobitvec(msg.split(",")[5])
else: # either binary or nmeapayload... expect mostly nmeapayloads
# assumes that an all 0 and 1 string can not be a nmeapayload
binaryMsg = True
for c in msg:
if c not in ("0", "1"):
binaryMsg = False
break
if binaryMsg:
bv = BitVector.from_bitstring(msg)
else: # nmeapayload
bv = binary.ais6tobitvec(msg)
printFields(
decode(bv),
out=outfile,
format=options.outputType,
fieldList=options.fieldList,
dbType=options.dbType,
)
if __name__ == "__main__":
main()