1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2008-01-31 $'.split()[1]
5 __author__ = 'xmlbinmsg'
6
7 __doc__='''
8
9 Autogenerated python functions to serialize/deserialize binary messages.
10
11 Generated by: ../scripts/aisxmlbinmsg2py.py
12
13 Need to then wrap these functions with the outer AIS packet and then
14 convert the whole binary blob to a NMEA string. Those functions are
15 not currently provided in this file.
16
17 serialize: python to ais binary
18 deserialize: ais binary to python
19
20 The generated code uses translators.py, binary.py, and aisstring.py
21 which should be packaged with the resulting files.
22
23
24 @requires: U{epydoc<http://epydoc.sourceforge.net/>} > 3.0alpha3
25 @requires: U{BitVector<http://cheeseshop.python.org/pypi/BitVector>}
26
27 @author: '''+__author__+'''
28 @version: ''' + __version__ +'''
29 @var __date__: Date of last svn commit
30 @undocumented: __version__ __author__ __doc__ parser
31 @status: under development
32 @license: Generated code has no license
33 @todo: FIX: put in a description of the message here with fields and types.
34 '''
35
36 import sys
37 from decimal import Decimal
38 from BitVector import BitVector
39
40 import binary, aisstring
41
42
43 TrueBV = BitVector(bitstring="1")
44 "Why always rebuild the True bit? This should speed things up a bunch"
45 FalseBV = BitVector(bitstring="0")
46 "Why always rebuild the False bit? This should speed things up a bunch"
47
48
49 fieldList = (
50 'MessageID',
51 'RepeatIndicator',
52 'UserID',
53 'Spare',
54 'dac',
55 'fid',
56 'month',
57 'day',
58 'hour',
59 'min',
60 'longitude',
61 'latitude',
62 'timetoexpire',
63 'radius',
64 'areatype',
65 )
66
67 fieldListPostgres = (
68 'MessageID',
69 'RepeatIndicator',
70 'UserID',
71 'Spare',
72 'dac',
73 'fid',
74 'month',
75 'day',
76 'hour',
77 'min',
78 'center',
79 'timetoexpire',
80 'radius',
81 'areatype',
82 )
83
84 toPgFields = {
85 'longitude':'center',
86 'latitude':'center',
87 }
88 '''
89 Go to the Postgis field names from the straight field name
90 '''
91
92 fromPgFields = {
93 'center':('longitude','latitude',),
94 }
95 '''
96 Go from the Postgis field names to the straight field name
97 '''
98
99 pgTypes = {
100 'center':'POINT',
101 }
102 '''
103 Lookup table for each postgis field name to get its type.
104 '''
105
106 -def encode(params, validate=False):
107 '''Create a timed_circular_notice binary message payload to pack into an AIS Msg timed_circular_notice.
108
109 Fields in params:
110 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
111 - RepeatIndicator(uint): Indicated how many times a message has been repeated
112 - UserID(uint): Unique ship identification number (MMSI)
113 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
114 - dac(uint): Designated Area Code - 366 for the United States (field automatically set to "366")
115 - fid(uint): Functional IDentifier - 63 (field automatically set to "63")
116 - month(uint): Start time of most recent notice UTC month
117 - day(uint): Start time of most recent notice UTC day of the month 1..31
118 - hour(uint): Start time of most recent notice UTC hours 0..23
119 - min(uint): Start time of most recent notice UTC minutes
120 - longitude(decimal): Center of the area/zone East West location
121 - latitude(decimal): Center of the area/zone North South location
122 - timetoexpire(uint): Minutes from the start time until the notice expires. Max is aprox 23 days
123 - radius(uint): Distance from center of detection zone (lat/lon above)
124 - areatype(uint): What does this circular area represent
125 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
126 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
127 @rtype: BitVector
128 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
129 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
130 '''
131
132 bvList = []
133 bvList.append(binary.setBitVectorSize(BitVector(intVal=8),6))
134 if 'RepeatIndicator' in params:
135 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2))
136 else:
137 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
138 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30))
139 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
140 bvList.append(binary.setBitVectorSize(BitVector(intVal=366),10))
141 bvList.append(binary.setBitVectorSize(BitVector(intVal=63),6))
142 if 'month' in params:
143 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['month']),4))
144 else:
145 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),4))
146 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['day']),5))
147 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['hour']),5))
148 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['min']),6))
149 if 'longitude' in params:
150 bvList.append(binary.bvFromSignedInt(int(Decimal(params['longitude'])*Decimal('600000')),28))
151 else:
152 bvList.append(binary.bvFromSignedInt(108600000,28))
153 if 'latitude' in params:
154 bvList.append(binary.bvFromSignedInt(int(Decimal(params['latitude'])*Decimal('600000')),27))
155 else:
156 bvList.append(binary.bvFromSignedInt(54600000,27))
157 if 'timetoexpire' in params:
158 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['timetoexpire']),15))
159 else:
160 bvList.append(binary.setBitVectorSize(BitVector(intVal=32767),15))
161 if 'radius' in params:
162 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['radius']),15))
163 else:
164 bvList.append(binary.setBitVectorSize(BitVector(intVal=32767),15))
165 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['areatype']),7))
166
167 return binary.joinBV(bvList)
168
169 -def decode(bv, validate=False):
170 '''Unpack a timed_circular_notice message
171
172 Fields in params:
173 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
174 - RepeatIndicator(uint): Indicated how many times a message has been repeated
175 - UserID(uint): Unique ship identification number (MMSI)
176 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
177 - dac(uint): Designated Area Code - 366 for the United States (field automatically set to "366")
178 - fid(uint): Functional IDentifier - 63 (field automatically set to "63")
179 - month(uint): Start time of most recent notice UTC month
180 - day(uint): Start time of most recent notice UTC day of the month 1..31
181 - hour(uint): Start time of most recent notice UTC hours 0..23
182 - min(uint): Start time of most recent notice UTC minutes
183 - longitude(decimal): Center of the area/zone East West location
184 - latitude(decimal): Center of the area/zone North South location
185 - timetoexpire(uint): Minutes from the start time until the notice expires. Max is aprox 23 days
186 - radius(uint): Distance from center of detection zone (lat/lon above)
187 - areatype(uint): What does this circular area represent
188 @type bv: BitVector
189 @param bv: Bits defining a message
190 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
191 @rtype: dict
192 @return: params
193 '''
194
195
196
197
198 r = {}
199 r['MessageID']=8
200 r['RepeatIndicator']=int(bv[6:8])
201 r['UserID']=int(bv[8:38])
202 r['Spare']=0
203 r['dac']=366
204 r['fid']=63
205 r['month']=int(bv[56:60])
206 r['day']=int(bv[60:65])
207 r['hour']=int(bv[65:70])
208 r['min']=int(bv[70:76])
209 r['longitude']=Decimal(binary.signedIntFromBV(bv[76:104]))/Decimal('600000')
210 r['latitude']=Decimal(binary.signedIntFromBV(bv[104:131]))/Decimal('600000')
211 r['timetoexpire']=int(bv[131:146])
212 r['radius']=int(bv[146:161])
213 r['areatype']=int(bv[161:168])
214 return r
215
218
221
224
227
230
233
235 return int(bv[56:60])
236
238 return int(bv[60:65])
239
241 return int(bv[65:70])
242
244 return int(bv[70:76])
245
248
251
253 return int(bv[131:146])
254
256 return int(bv[146:161])
257
259 return int(bv[161:168])
260
261
263 out.write("<h3>timed_circular_notice</h3>\n")
264 out.write("<table border=\"1\">\n")
265 out.write("<tr bgcolor=\"orange\">\n")
266 out.write("<th align=\"left\">Field Name</th>\n")
267 out.write("<th align=\"left\">Type</th>\n")
268 out.write("<th align=\"left\">Value</th>\n")
269 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
270 out.write("<th align=\"left\">Units</th>\n")
271 out.write("\n")
272 out.write("<tr>\n")
273 out.write("<td>MessageID</td>\n")
274 out.write("<td>uint</td>\n")
275 if 'MessageID' in params:
276 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
277 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
278 out.write("</tr>\n")
279 out.write("\n")
280 out.write("<tr>\n")
281 out.write("<td>RepeatIndicator</td>\n")
282 out.write("<td>uint</td>\n")
283 if 'RepeatIndicator' in params:
284 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n")
285 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut:
286 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>")
287 else:
288 out.write("<td><i>Missing LUT entry</i></td>")
289 out.write("</tr>\n")
290 out.write("\n")
291 out.write("<tr>\n")
292 out.write("<td>UserID</td>\n")
293 out.write("<td>uint</td>\n")
294 if 'UserID' in params:
295 out.write(" <td>"+str(params['UserID'])+"</td>\n")
296 out.write(" <td>"+str(params['UserID'])+"</td>\n")
297 out.write("</tr>\n")
298 out.write("\n")
299 out.write("<tr>\n")
300 out.write("<td>Spare</td>\n")
301 out.write("<td>uint</td>\n")
302 if 'Spare' in params:
303 out.write(" <td>"+str(params['Spare'])+"</td>\n")
304 out.write(" <td>"+str(params['Spare'])+"</td>\n")
305 out.write("</tr>\n")
306 out.write("\n")
307 out.write("<tr>\n")
308 out.write("<td>dac</td>\n")
309 out.write("<td>uint</td>\n")
310 if 'dac' in params:
311 out.write(" <td>"+str(params['dac'])+"</td>\n")
312 out.write(" <td>"+str(params['dac'])+"</td>\n")
313 out.write("</tr>\n")
314 out.write("\n")
315 out.write("<tr>\n")
316 out.write("<td>fid</td>\n")
317 out.write("<td>uint</td>\n")
318 if 'fid' in params:
319 out.write(" <td>"+str(params['fid'])+"</td>\n")
320 out.write(" <td>"+str(params['fid'])+"</td>\n")
321 out.write("</tr>\n")
322 out.write("\n")
323 out.write("<tr>\n")
324 out.write("<td>month</td>\n")
325 out.write("<td>uint</td>\n")
326 if 'month' in params:
327 out.write(" <td>"+str(params['month'])+"</td>\n")
328 out.write(" <td>"+str(params['month'])+"</td>\n")
329 out.write("</tr>\n")
330 out.write("\n")
331 out.write("<tr>\n")
332 out.write("<td>day</td>\n")
333 out.write("<td>uint</td>\n")
334 if 'day' in params:
335 out.write(" <td>"+str(params['day'])+"</td>\n")
336 out.write(" <td>"+str(params['day'])+"</td>\n")
337 out.write("</tr>\n")
338 out.write("\n")
339 out.write("<tr>\n")
340 out.write("<td>hour</td>\n")
341 out.write("<td>uint</td>\n")
342 if 'hour' in params:
343 out.write(" <td>"+str(params['hour'])+"</td>\n")
344 out.write(" <td>"+str(params['hour'])+"</td>\n")
345 out.write("</tr>\n")
346 out.write("\n")
347 out.write("<tr>\n")
348 out.write("<td>min</td>\n")
349 out.write("<td>uint</td>\n")
350 if 'min' in params:
351 out.write(" <td>"+str(params['min'])+"</td>\n")
352 out.write(" <td>"+str(params['min'])+"</td>\n")
353 out.write("</tr>\n")
354 out.write("\n")
355 out.write("<tr>\n")
356 out.write("<td>longitude</td>\n")
357 out.write("<td>decimal</td>\n")
358 if 'longitude' in params:
359 out.write(" <td>"+str(params['longitude'])+"</td>\n")
360 out.write(" <td>"+str(params['longitude'])+"</td>\n")
361 out.write("<td>degrees</td>\n")
362 out.write("</tr>\n")
363 out.write("\n")
364 out.write("<tr>\n")
365 out.write("<td>latitude</td>\n")
366 out.write("<td>decimal</td>\n")
367 if 'latitude' in params:
368 out.write(" <td>"+str(params['latitude'])+"</td>\n")
369 out.write(" <td>"+str(params['latitude'])+"</td>\n")
370 out.write("<td>degrees</td>\n")
371 out.write("</tr>\n")
372 out.write("\n")
373 out.write("<tr>\n")
374 out.write("<td>timetoexpire</td>\n")
375 out.write("<td>uint</td>\n")
376 if 'timetoexpire' in params:
377 out.write(" <td>"+str(params['timetoexpire'])+"</td>\n")
378 if str(params['timetoexpire']) in timetoexpireDecodeLut:
379 out.write("<td>"+timetoexpireDecodeLut[str(params['timetoexpire'])]+"</td>")
380 else:
381 out.write("<td><i>Missing LUT entry</i></td>")
382 out.write("<td>Minutes</td>\n")
383 out.write("</tr>\n")
384 out.write("\n")
385 out.write("<tr>\n")
386 out.write("<td>radius</td>\n")
387 out.write("<td>uint</td>\n")
388 if 'radius' in params:
389 out.write(" <td>"+str(params['radius'])+"</td>\n")
390 out.write(" <td>"+str(params['radius'])+"</td>\n")
391 out.write("<td>m</td>\n")
392 out.write("</tr>\n")
393 out.write("\n")
394 out.write("<tr>\n")
395 out.write("<td>areatype</td>\n")
396 out.write("<td>uint</td>\n")
397 if 'areatype' in params:
398 out.write(" <td>"+str(params['areatype'])+"</td>\n")
399 if str(params['areatype']) in areatypeDecodeLut:
400 out.write("<td>"+areatypeDecodeLut[str(params['areatype'])]+"</td>")
401 else:
402 out.write("<td><i>Missing LUT entry</i></td>")
403 out.write("</tr>\n")
404 out.write("</table>\n")
405
406
408 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer'''
409 out.write("\ <Placemark>\n")
410 out.write("\t <name>"+str(params['stationsid'])+"</name>\n")
411 out.write("\t\t<description>\n")
412 import StringIO
413 buf = StringIO.StringIO()
414 printHtml(params,buf)
415 import cgi
416 out.write(cgi.escape(buf.getvalue()))
417 out.write("\t\t</description>\n")
418 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n")
419 out.write("\t\t<Point>\n")
420 out.write("\t\t\t<coordinates>")
421 out.write(str(params['longitude']))
422 out.write(',')
423 out.write(str(params['latitude']))
424 out.write(",0</coordinates>\n")
425 out.write("\t\t</Point>\n")
426 out.write("\t</Placemark>\n")
427
428 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
429 '''Print a timed_circular_notice message to stdout.
430
431 Fields in params:
432 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
433 - RepeatIndicator(uint): Indicated how many times a message has been repeated
434 - UserID(uint): Unique ship identification number (MMSI)
435 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
436 - dac(uint): Designated Area Code - 366 for the United States (field automatically set to "366")
437 - fid(uint): Functional IDentifier - 63 (field automatically set to "63")
438 - month(uint): Start time of most recent notice UTC month
439 - day(uint): Start time of most recent notice UTC day of the month 1..31
440 - hour(uint): Start time of most recent notice UTC hours 0..23
441 - min(uint): Start time of most recent notice UTC minutes
442 - longitude(decimal): Center of the area/zone East West location
443 - latitude(decimal): Center of the area/zone North South location
444 - timetoexpire(uint): Minutes from the start time until the notice expires. Max is aprox 23 days
445 - radius(uint): Distance from center of detection zone (lat/lon above)
446 - areatype(uint): What does this circular area represent
447 @param params: Dictionary of field names/values.
448 @param out: File like object to write to
449 @rtype: stdout
450 @return: text to out
451 '''
452
453 if 'std'==format:
454 out.write("timed_circular_notice:\n")
455 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n")
456 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n")
457 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n")
458 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n")
459 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n")
460 if 'fid' in params: out.write(" fid: "+str(params['fid'])+"\n")
461 if 'month' in params: out.write(" month: "+str(params['month'])+"\n")
462 if 'day' in params: out.write(" day: "+str(params['day'])+"\n")
463 if 'hour' in params: out.write(" hour: "+str(params['hour'])+"\n")
464 if 'min' in params: out.write(" min: "+str(params['min'])+"\n")
465 if 'longitude' in params: out.write(" longitude: "+str(params['longitude'])+"\n")
466 if 'latitude' in params: out.write(" latitude: "+str(params['latitude'])+"\n")
467 if 'timetoexpire' in params: out.write(" timetoexpire: "+str(params['timetoexpire'])+"\n")
468 if 'radius' in params: out.write(" radius: "+str(params['radius'])+"\n")
469 if 'areatype' in params: out.write(" areatype: "+str(params['areatype'])+"\n")
470 elif 'csv'==format:
471 if None == options.fieldList:
472 options.fieldList = fieldList
473 needComma = False;
474 for field in fieldList:
475 if needComma: out.write(',')
476 needComma = True
477 if field in params:
478 out.write(str(params[field]))
479
480 out.write("\n")
481 elif 'html'==format:
482 printHtml(params,out)
483 elif 'sql'==format:
484 sqlInsertStr(params,out,dbType=dbType)
485 elif 'kml'==format:
486 printKml(params,out)
487 elif 'kml-full'==format:
488 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
489 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n")
490 out.write("<Document>\n")
491 out.write(" <name>timed_circular_notice</name>\n")
492 printKml(params,out)
493 out.write("</Document>\n")
494 out.write("</kml>\n")
495 else:
496 print "ERROR: unknown format:",format
497 assert False
498
499 return
500
501 RepeatIndicatorEncodeLut = {
502 'default':'0',
503 'do not repeat any more':'3',
504 }
505
506 RepeatIndicatorDecodeLut = {
507 '0':'default',
508 '3':'do not repeat any more',
509 }
510
511 timetoexpireEncodeLut = {
512 'No detection or notice not active in region':'0',
513 'Will not expire until another message has been received to replace the message for that location':'32767',
514 }
515
516 timetoexpireDecodeLut = {
517 '0':'No detection or notice not active in region',
518 '32767':'Will not expire until another message has been received to replace the message for that location',
519 }
520
521 areatypeEncodeLut = {
522 'Right whale acoustic detection':'0',
523 'Restricted Area':'1',
524 'Prohibited Area (no unauthorized entry)':'2',
525 'Diving operations':'4',
526 'Underwater obstruction':'5',
527 'Fishing nets':'6',
528 'Oil in water':'7',
529 'Towing prohibited':'9',
530 'Anchorage area (large vessels)':'10',
531 'Anchorage area (small vessels)':'11',
532 'Anchorage area (general)':'12',
533 'Anchorage area (deep water)':'13',
534 'Anchorage area (tanker)':'14',
535 'Anchorage area (24h max)':'15',
536 'Anchorage area (explosives)':'16',
537 'Sea-plane landing area':'17',
538 'Anchorage area (sea planes)':'18',
539 'Anchoring prohibited':'20',
540 'Fishing prohibited':'21',
541 'Actively dumping explosives':'23',
542 'Actively dumping':'24',
543 'Firing danger area':'30',
544 'Military area, entry prohibited':'31',
545 'Mine-laying practice area':'32',
546 'Submarine transit and exercise area':'33',
547 'Mine field':'34',
548 'Fast ice':'61',
549 'Sea ice':'62',
550 'Logs':'63',
551 'Dredging area':'65',
552 'Cargo transhipment area':'66',
553 'Incineration area':'67',
554 'SAR - Region of search (what SAR keys should there be?)':'70',
555 'SAR - Man Overboard':'71',
556 'Debris, Generic':'80',
557 'LNG security zone':'111',
558 }
559
560 areatypeDecodeLut = {
561 '0':'Right whale acoustic detection',
562 '1':'Restricted Area',
563 '2':'Prohibited Area (no unauthorized entry)',
564 '4':'Diving operations',
565 '5':'Underwater obstruction',
566 '6':'Fishing nets',
567 '7':'Oil in water',
568 '9':'Towing prohibited',
569 '10':'Anchorage area (large vessels)',
570 '11':'Anchorage area (small vessels)',
571 '12':'Anchorage area (general)',
572 '13':'Anchorage area (deep water)',
573 '14':'Anchorage area (tanker)',
574 '15':'Anchorage area (24h max)',
575 '16':'Anchorage area (explosives)',
576 '17':'Sea-plane landing area',
577 '18':'Anchorage area (sea planes)',
578 '20':'Anchoring prohibited',
579 '21':'Fishing prohibited',
580 '23':'Actively dumping explosives',
581 '24':'Actively dumping',
582 '30':'Firing danger area',
583 '31':'Military area, entry prohibited',
584 '32':'Mine-laying practice area',
585 '33':'Submarine transit and exercise area',
586 '34':'Mine field',
587 '61':'Fast ice',
588 '62':'Sea ice',
589 '63':'Logs',
590 '65':'Dredging area',
591 '66':'Cargo transhipment area',
592 '67':'Incineration area',
593 '70':'SAR - Region of search (what SAR keys should there be?)',
594 '71':'SAR - Man Overboard',
595 '80':'Debris, Generic',
596 '111':'LNG security zone',
597 }
598
599
600
601
602
603 dbTableName='timed_circular_notice'
604 'Database table name'
605
606 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
607 ,addCoastGuardFields=True
608 ,dbType='postgres'
609 ):
610 '''
611 Return the SQL CREATE command for this message type
612 @param outfile: file like object to print to.
613 @param fields: which fields to put in the create. Defaults to all.
614 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
615 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
616 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
617 @type addCoastGuardFields: bool
618 @return: sql create string
619 @rtype: str
620
621 @see: sqlCreate
622 '''
623
624 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
625
626 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
627 '''
628 Return the sqlhelp object to create the table.
629
630 @param fields: which fields to put in the create. Defaults to all.
631 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
632 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
633 @type addCoastGuardFields: bool
634 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
635 @return: An object that can be used to generate a return
636 @rtype: sqlhelp.create
637 '''
638 if None == fields: fields = fieldList
639 import sqlhelp
640 c = sqlhelp.create('timed_circular_notice',dbType=dbType)
641 c.addPrimaryKey()
642 if 'MessageID' in fields: c.addInt ('MessageID')
643 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator')
644 if 'UserID' in fields: c.addInt ('UserID')
645 if 'Spare' in fields: c.addInt ('Spare')
646 if 'dac' in fields: c.addInt ('dac')
647 if 'fid' in fields: c.addInt ('fid')
648 if 'month' in fields: c.addInt ('month')
649 if 'day' in fields: c.addInt ('day')
650 if 'hour' in fields: c.addInt ('hour')
651 if 'min' in fields: c.addInt ('min')
652 if dbType != 'postgres':
653 if 'longitude' in fields: c.addDecimal('longitude',8,5)
654 if dbType != 'postgres':
655 if 'latitude' in fields: c.addDecimal('latitude',8,5)
656 if 'timetoexpire' in fields: c.addInt ('timetoexpire')
657 if 'radius' in fields: c.addInt ('radius')
658 if 'areatype' in fields: c.addInt ('areatype')
659
660 if addCoastGuardFields:
661
662
663
664
665
666 c.addVarChar('cg_r',15)
667 c.addInt('cg_sec')
668
669 c.addTimestamp('cg_timestamp')
670
671 if dbType == 'postgres':
672
673
674 c.addPostGIS('center','POINT',2,SRID=4326);
675
676 return c
677
678 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
679 '''
680 Return the SQL INSERT command for this message type
681 @param params: dictionary of values keyed by field name
682 @param outfile: file like object to print to.
683 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
684 @return: sql create string
685 @rtype: str
686
687 @see: sqlCreate
688 '''
689 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
690
691
692 -def sqlInsert(params,extraParams=None,dbType='postgres'):
693 '''
694 Give the SQL INSERT statement
695 @param params: dict keyed by field name of values
696 @param extraParams: any extra fields that you have created beyond the normal ais message fields
697 @rtype: sqlhelp.insert
698 @return: insert class instance
699 @todo: allow optional type checking of params?
700 @warning: this will take invalid keys happily and do what???
701 '''
702 import sqlhelp
703 i = sqlhelp.insert('timed_circular_notice',dbType=dbType)
704
705 if dbType=='postgres':
706 finished = []
707 for key in params:
708 if key in finished:
709 continue
710
711 if key not in toPgFields and key not in fromPgFields:
712 if type(params[key])==Decimal: i.add(key,float(params[key]))
713 else: i.add(key,params[key])
714 else:
715 if key in fromPgFields:
716 val = params[key]
717
718 i.addPostGIS(key,val)
719 finished.append(key)
720 else:
721
722 pgName = toPgFields[key]
723
724 valStr=pgTypes[pgName]+'('
725 vals = []
726 for nonPgKey in fromPgFields[pgName]:
727 vals.append(str(params[nonPgKey]))
728 finished.append(nonPgKey)
729 valStr+=' '.join(vals)+')'
730 i.addPostGIS(pgName,valStr)
731 else:
732 for key in params:
733 if type(params[key])==Decimal: i.add(key,float(params[key]))
734 else: i.add(key,params[key])
735
736 if None != extraParams:
737 for key in extraParams:
738 i.add(key,extraParams[key])
739
740 return i
741
742
743
744
745
748 '''
749 Return the LaTeX definition table for this message type
750 @param outfile: file like object to print to.
751 @type outfile: file obj
752 @return: LaTeX table string via the outfile
753 @rtype: str
754
755 '''
756 o = outfile
757
758 o.write('''
759 \\begin{table}%[htb]
760 \\centering
761 \\begin{tabular}{|l|c|l|}
762 \\hline
763 Parameter & Number of bits & Description
764 \\\\ \\hline\\hline
765 MessageID & 6 & AIS message number. Must be 8 \\\\ \hline
766 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
767 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
768 Spare & 2 & Reserved for definition by a regional authority. \\\\ \hline
769 dac & 10 & Designated Area Code - 366 for the United States \\\\ \hline
770 fid & 6 & Functional IDentifier - 63 \\\\ \hline
771 month & 4 & Start time of most recent notice UTC month \\\\ \hline
772 day & 5 & Start time of most recent notice UTC day of the month 1..31 \\\\ \hline
773 hour & 5 & Start time of most recent notice UTC hours 0..23 \\\\ \hline
774 min & 6 & Start time of most recent notice UTC minutes \\\\ \hline
775 longitude & 28 & Center of the area/zone East West location \\\\ \hline
776 latitude & 27 & Center of the area/zone North South location \\\\ \hline
777 timetoexpire & 15 & Minutes from the start time until the notice expires. Max is aprox 23 days \\\\ \hline
778 radius & 15 & Distance from center of detection zone (lat/lon above) \\\\ \hline
779 areatype & 7 & What does this circular area represent\\\\ \\hline \\hline
780 Total bits & 168 & Appears to take 1 slot \\\\ \\hline
781 \\end{tabular}
782 \\caption{AIS message number 8: Timed circular notice}
783 \\label{tab:timed_circular_notice}
784 \\end{table}
785 ''')
786
787
788
789
790
791 -def textDefinitionTable(outfile=sys.stdout
792 ,delim='\t'
793 ):
794 '''
795 Return the text definition table for this message type
796 @param outfile: file like object to print to.
797 @type outfile: file obj
798 @return: text table string via the outfile
799 @rtype: str
800
801 '''
802 o = outfile
803 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
804 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 8
805 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
806 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
807 Spare'''+delim+'''2'''+delim+'''Reserved for definition by a regional authority.
808 dac'''+delim+'''10'''+delim+'''Designated Area Code - 366 for the United States
809 fid'''+delim+'''6'''+delim+'''Functional IDentifier - 63
810 month'''+delim+'''4'''+delim+'''Start time of most recent notice UTC month
811 day'''+delim+'''5'''+delim+'''Start time of most recent notice UTC day of the month 1..31
812 hour'''+delim+'''5'''+delim+'''Start time of most recent notice UTC hours 0..23
813 min'''+delim+'''6'''+delim+'''Start time of most recent notice UTC minutes
814 longitude'''+delim+'''28'''+delim+'''Center of the area/zone East West location
815 latitude'''+delim+'''27'''+delim+'''Center of the area/zone North South location
816 timetoexpire'''+delim+'''15'''+delim+'''Minutes from the start time until the notice expires. Max is aprox 23 days
817 radius'''+delim+'''15'''+delim+'''Distance from center of detection zone (lat/lon above)
818 areatype'''+delim+'''7'''+delim+'''What does this circular area represent
819 Total bits'''+delim+'''168'''+delim+'''Appears to take 1 slot''')
820
821
822
823
824
825 import unittest
827 '''Return a params file base on the testvalue tags.
828 @rtype: dict
829 @return: params based on testvalue tags
830 '''
831 params = {}
832 params['MessageID'] = 8
833 params['RepeatIndicator'] = 1
834 params['UserID'] = 1193046
835 params['Spare'] = 0
836 params['dac'] = 366
837 params['fid'] = 63
838 params['month'] = 2
839 params['day'] = 28
840 params['hour'] = 23
841 params['min'] = 45
842 params['longitude'] = Decimal('-122.16328055555556')
843 params['latitude'] = Decimal('37.424458333333334')
844 params['timetoexpire'] = 1
845 params['radius'] = 5000
846 params['areatype'] = 1
847
848 return params
849
851 '''Use testvalue tag text from each type to build test case the timed_circular_notice message'''
853
854 params = testParams()
855 bits = encode(params)
856 r = decode(bits)
857
858
859 self.failUnlessEqual(r['MessageID'],params['MessageID'])
860 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
861 self.failUnlessEqual(r['UserID'],params['UserID'])
862 self.failUnlessEqual(r['Spare'],params['Spare'])
863 self.failUnlessEqual(r['dac'],params['dac'])
864 self.failUnlessEqual(r['fid'],params['fid'])
865 self.failUnlessEqual(r['month'],params['month'])
866 self.failUnlessEqual(r['day'],params['day'])
867 self.failUnlessEqual(r['hour'],params['hour'])
868 self.failUnlessEqual(r['min'],params['min'])
869 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5)
870 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5)
871 self.failUnlessEqual(r['timetoexpire'],params['timetoexpire'])
872 self.failUnlessEqual(r['radius'],params['radius'])
873 self.failUnlessEqual(r['areatype'],params['areatype'])
874
876 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
877 help='decode a "timed_circular_notice" AIS message')
878 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
879 help='encode a "timed_circular_notice" AIS message')
880 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
881 ,help='Field parameter value [default: %default]')
882 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
883 ,help='Field parameter value [default: %default]')
884 parser.add_option('--month-field', dest='monthField',default=0,metavar='uint',type='int'
885 ,help='Field parameter value [default: %default]')
886 parser.add_option('--day-field', dest='dayField',metavar='uint',type='int'
887 ,help='Field parameter value [default: %default]')
888 parser.add_option('--hour-field', dest='hourField',metavar='uint',type='int'
889 ,help='Field parameter value [default: %default]')
890 parser.add_option('--min-field', dest='minField',metavar='uint',type='int'
891 ,help='Field parameter value [default: %default]')
892 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string'
893 ,help='Field parameter value [default: %default]')
894 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string'
895 ,help='Field parameter value [default: %default]')
896 parser.add_option('--timetoexpire-field', dest='timetoexpireField',default=32767,metavar='uint',type='int'
897 ,help='Field parameter value [default: %default]')
898 parser.add_option('--radius-field', dest='radiusField',default=32767,metavar='uint',type='int'
899 ,help='Field parameter value [default: %default]')
900 parser.add_option('--areatype-field', dest='areatypeField',metavar='uint',type='int'
901 ,help='Field parameter value [default: %default]')
902
903
904 if __name__=='__main__':
905
906 from optparse import OptionParser
907 parser = OptionParser(usage="%prog [options]",
908 version="%prog "+__version__)
909
910 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
911 help='run the documentation tests')
912 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
913 help='run the unit tests')
914 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
915 help='Make the test output verbose')
916
917
918
919 typeChoices = ('binary','nmeapayload','nmea')
920 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
921 ,default='nmeapayload'
922 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
923
924
925 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
926 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
927 ,default='std'
928 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
929
930 parser.add_option('-o','--output',dest='outputFileName',default=None,
931 help='Name of the python file to write [default: stdout]')
932
933 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
934 choices=fieldList,
935 help='Which fields to include in the output. Currently only for csv output [default: all]')
936
937 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
938 help='Print the field name for csv')
939
940 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
941 help='Print out an sql create command for the table.')
942
943 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
944 help='Print a LaTeX table of the type')
945
946 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
947 help='Print delimited table of the type (for Word table importing)')
948 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
949 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
950
951
952 dbChoices = ('sqlite','postgres')
953 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
954 ,choices=dbChoices,type='choice'
955 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
956
957 addMsgOptions(parser)
958
959 (options,args) = parser.parse_args()
960 success=True
961
962 if options.doctest:
963 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
964 sys.argv= [sys.argv[0]]
965 if options.verbose: sys.argv.append('-v')
966 import doctest
967 numfail,numtests=doctest.testmod()
968 if numfail==0: print 'ok'
969 else:
970 print 'FAILED'
971 success=False
972
973 if not success: sys.exit('Something Failed')
974 del success
975
976 if options.unittest:
977 sys.argv = [sys.argv[0]]
978 if options.verbose: sys.argv.append('-v')
979 unittest.main()
980
981 outfile = sys.stdout
982 if None!=options.outputFileName:
983 outfile = file(options.outputFileName,'w')
984
985
986 if options.doEncode:
987
988 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
989 if None==options.UserIDField: parser.error("missing value for UserIDField")
990 if None==options.monthField: parser.error("missing value for monthField")
991 if None==options.dayField: parser.error("missing value for dayField")
992 if None==options.hourField: parser.error("missing value for hourField")
993 if None==options.minField: parser.error("missing value for minField")
994 if None==options.longitudeField: parser.error("missing value for longitudeField")
995 if None==options.latitudeField: parser.error("missing value for latitudeField")
996 if None==options.timetoexpireField: parser.error("missing value for timetoexpireField")
997 if None==options.radiusField: parser.error("missing value for radiusField")
998 if None==options.areatypeField: parser.error("missing value for areatypeField")
999 msgDict={
1000 'MessageID': '8',
1001 'RepeatIndicator': options.RepeatIndicatorField,
1002 'UserID': options.UserIDField,
1003 'Spare': '0',
1004 'dac': '366',
1005 'fid': '63',
1006 'month': options.monthField,
1007 'day': options.dayField,
1008 'hour': options.hourField,
1009 'min': options.minField,
1010 'longitude': options.longitudeField,
1011 'latitude': options.latitudeField,
1012 'timetoexpire': options.timetoexpireField,
1013 'radius': options.radiusField,
1014 'areatype': options.areatypeField,
1015 }
1016
1017 bits = encode(msgDict)
1018 if 'binary'==options.ioType: print str(bits)
1019 elif 'nmeapayload'==options.ioType:
1020
1021 print "bitLen",len(bits)
1022 bitLen=len(bits)
1023 if bitLen%6!=0:
1024 bits = bits + BitVector(size=(6 - (bitLen%6)))
1025 print "result:",binary.bitvectoais6(bits)[0]
1026
1027
1028
1029 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1030 else: sys.exit('ERROR: unknown ioType. Help!')
1031
1032
1033 if options.sqlCreate:
1034 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1035
1036 if options.latexDefinitionTable:
1037 latexDefinitionTable(outfile)
1038
1039
1040 if options.textDefinitionTable:
1041 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1042
1043 if options.printCsvfieldList:
1044
1045 if None == options.fieldList: options.fieldList = fieldList
1046 import StringIO
1047 buf = StringIO.StringIO()
1048 for field in options.fieldList:
1049 buf.write(field+',')
1050 result = buf.getvalue()
1051 if result[-1] == ',': print result[:-1]
1052 else: print result
1053
1054 if options.doDecode:
1055 if len(args)==0: args = sys.stdin
1056 for msg in args:
1057 bv = None
1058
1059 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1060
1061
1062 bv = binary.ais6tobitvec(msg.split(',')[5])
1063 else:
1064
1065 binaryMsg=True
1066 for c in msg:
1067 if c not in ('0','1'):
1068 binaryMsg=False
1069 break
1070 if binaryMsg:
1071 bv = BitVector(bitstring=msg)
1072 else:
1073 bv = binary.ais6tobitvec(msg)
1074
1075 printFields(decode(bv)
1076 ,out=outfile
1077 ,format=options.outputType
1078 ,fieldList=options.fieldList
1079 ,dbType=options.dbType
1080 )
1081