1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-11-07 $'.split()[1]
5 __author__ = 'xmlbinmsg'
6
7 __doc__='''
8
9 Autogenerated python functions to serialize/deserialize binary messages.
10
11 Generated by: ./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 'efid',
57 'day',
58 'hour',
59 'min',
60 'stationid',
61 'longitude',
62 'latitude',
63 'timetoexpire',
64 'radius',
65 )
66
67 fieldListPostgres = (
68 'MessageID',
69 'RepeatIndicator',
70 'UserID',
71 'Spare',
72 'dac',
73 'fid',
74 'efid',
75 'day',
76 'hour',
77 'min',
78 'stationid',
79 'whale',
80 'timetoexpire',
81 'radius',
82 )
83
84 toPgFields = {
85 'longitude':'whale',
86 'latitude':'whale',
87 }
88 '''
89 Go to the Postgis field names from the straight field name
90 '''
91
92 fromPgFields = {
93 'whale':('longitude','latitude',),
94 }
95 '''
96 Go from the Postgis field names to the straight field name
97 '''
98
99 pgTypes = {
100 'whale':'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 whalenotice binary message payload to pack into an AIS Msg whalenotice.
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 for the Whale Notice (field automatically set to "63")
116 - efid(uint): Extended Functional IDentifier. 1 for the Whale Notice (dac+fid+efid defines the exact message type) (field automatically set to "1")
117 - day(uint): Time of most recent whale detection. UTC day of the month 1..31
118 - hour(uint): Time of most recent whale detection. UTC hours 0..23
119 - min(uint): Time of most recent whale detection. UTC minutes
120 - stationid(uint): Identifier of the station that recorded the whale. Usually a number.
121 - longitude(decimal): Center of the detection zone. East West location
122 - latitude(decimal): Center of the detection zone. North South location
123 - timetoexpire(uint): Seconds from the detection time until the notice expires
124 - radius(uint): Distance from center of detection zone (lat/lon above)
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 bvList.append(binary.setBitVectorSize(BitVector(intVal=1),12))
143 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['day']),5))
144 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['hour']),5))
145 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['min']),6))
146 if 'stationid' in params:
147 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['stationid']),8))
148 else:
149 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),8))
150 if 'longitude' in params:
151 bvList.append(binary.bvFromSignedInt(int(Decimal(params['longitude'])*Decimal('600000')),28))
152 else:
153 bvList.append(binary.bvFromSignedInt(108600000,28))
154 if 'latitude' in params:
155 bvList.append(binary.bvFromSignedInt(int(Decimal(params['latitude'])*Decimal('600000')),27))
156 else:
157 bvList.append(binary.bvFromSignedInt(54600000,27))
158 if 'timetoexpire' in params:
159 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['timetoexpire']),16))
160 else:
161 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),16))
162 if 'radius' in params:
163 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['radius']),16))
164 else:
165 bvList.append(binary.setBitVectorSize(BitVector(intVal=65534),16))
166
167 return binary.joinBV(bvList)
168
169 -def decode(bv, validate=False):
170 '''Unpack a whalenotice 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 for the Whale Notice (field automatically set to "63")
179 - efid(uint): Extended Functional IDentifier. 1 for the Whale Notice (dac+fid+efid defines the exact message type) (field automatically set to "1")
180 - day(uint): Time of most recent whale detection. UTC day of the month 1..31
181 - hour(uint): Time of most recent whale detection. UTC hours 0..23
182 - min(uint): Time of most recent whale detection. UTC minutes
183 - stationid(uint): Identifier of the station that recorded the whale. Usually a number.
184 - longitude(decimal): Center of the detection zone. East West location
185 - latitude(decimal): Center of the detection zone. North South location
186 - timetoexpire(uint): Seconds from the detection time until the notice expires
187 - radius(uint): Distance from center of detection zone (lat/lon above)
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['efid']=1
206 r['day']=int(bv[68:73])
207 r['hour']=int(bv[73:78])
208 r['min']=int(bv[78:84])
209 r['stationid']=int(bv[84:92])
210 r['longitude']=Decimal(binary.signedIntFromBV(bv[92:120]))/Decimal('600000')
211 r['latitude']=Decimal(binary.signedIntFromBV(bv[120:147]))/Decimal('600000')
212 r['timetoexpire']=int(bv[147:163])
213 r['radius']=int(bv[163:179])
214 return r
215
218
221
224
227
230
233
236
238 return int(bv[68:73])
239
241 return int(bv[73:78])
242
244 return int(bv[78:84])
245
247 return int(bv[84:92])
248
251
254
256 return int(bv[147:163])
257
259 return int(bv[163:179])
260
261
263 out.write("<h3>whalenotice</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>efid</td>\n")
325 out.write("<td>uint</td>\n")
326 if 'efid' in params:
327 out.write(" <td>"+str(params['efid'])+"</td>\n")
328 out.write(" <td>"+str(params['efid'])+"</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>stationid</td>\n")
357 out.write("<td>uint</td>\n")
358 if 'stationid' in params:
359 out.write(" <td>"+str(params['stationid'])+"</td>\n")
360 out.write(" <td>"+str(params['stationid'])+"</td>\n")
361 out.write("</tr>\n")
362 out.write("\n")
363 out.write("<tr>\n")
364 out.write("<td>longitude</td>\n")
365 out.write("<td>decimal</td>\n")
366 if 'longitude' in params:
367 out.write(" <td>"+str(params['longitude'])+"</td>\n")
368 out.write(" <td>"+str(params['longitude'])+"</td>\n")
369 out.write("<td>degrees</td>\n")
370 out.write("</tr>\n")
371 out.write("\n")
372 out.write("<tr>\n")
373 out.write("<td>latitude</td>\n")
374 out.write("<td>decimal</td>\n")
375 if 'latitude' in params:
376 out.write(" <td>"+str(params['latitude'])+"</td>\n")
377 out.write(" <td>"+str(params['latitude'])+"</td>\n")
378 out.write("<td>degrees</td>\n")
379 out.write("</tr>\n")
380 out.write("\n")
381 out.write("<tr>\n")
382 out.write("<td>timetoexpire</td>\n")
383 out.write("<td>uint</td>\n")
384 if 'timetoexpire' in params:
385 out.write(" <td>"+str(params['timetoexpire'])+"</td>\n")
386 out.write(" <td>"+str(params['timetoexpire'])+"</td>\n")
387 out.write("<td>seconds</td>\n")
388 out.write("</tr>\n")
389 out.write("\n")
390 out.write("<tr>\n")
391 out.write("<td>radius</td>\n")
392 out.write("<td>uint</td>\n")
393 if 'radius' in params:
394 out.write(" <td>"+str(params['radius'])+"</td>\n")
395 out.write(" <td>"+str(params['radius'])+"</td>\n")
396 out.write("<td>m</td>\n")
397 out.write("</tr>\n")
398 out.write("</table>\n")
399
400
402 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer'''
403 out.write("\ <Placemark>\n")
404 out.write("\t <name>"+str(params['stationsid'])+"</name>\n")
405 out.write("\t\t<description>\n")
406 import StringIO
407 buf = StringIO.StringIO()
408 printHtml(params,buf)
409 import cgi
410 out.write(cgi.escape(buf.getvalue()))
411 out.write("\t\t</description>\n")
412 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n")
413 out.write("\t\t<Point>\n")
414 out.write("\t\t\t<coordinates>")
415 out.write(str(params['longitude']))
416 out.write(',')
417 out.write(str(params['latitude']))
418 out.write(",0</coordinates>\n")
419 out.write("\t\t</Point>\n")
420 out.write("\t</Placemark>\n")
421
422 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
423 '''Print a whalenotice message to stdout.
424
425 Fields in params:
426 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
427 - RepeatIndicator(uint): Indicated how many times a message has been repeated
428 - UserID(uint): Unique ship identification number (MMSI)
429 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
430 - dac(uint): Designated Area Code - 366 for the United States (field automatically set to "366")
431 - fid(uint): Functional IDentifier - 63 for the Whale Notice (field automatically set to "63")
432 - efid(uint): Extended Functional IDentifier. 1 for the Whale Notice (dac+fid+efid defines the exact message type) (field automatically set to "1")
433 - day(uint): Time of most recent whale detection. UTC day of the month 1..31
434 - hour(uint): Time of most recent whale detection. UTC hours 0..23
435 - min(uint): Time of most recent whale detection. UTC minutes
436 - stationid(uint): Identifier of the station that recorded the whale. Usually a number.
437 - longitude(decimal): Center of the detection zone. East West location
438 - latitude(decimal): Center of the detection zone. North South location
439 - timetoexpire(uint): Seconds from the detection time until the notice expires
440 - radius(uint): Distance from center of detection zone (lat/lon above)
441 @param params: Dictionary of field names/values.
442 @param out: File like object to write to
443 @rtype: stdout
444 @return: text to out
445 '''
446
447 if 'std'==format:
448 out.write("whalenotice:\n")
449 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n")
450 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n")
451 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n")
452 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n")
453 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n")
454 if 'fid' in params: out.write(" fid: "+str(params['fid'])+"\n")
455 if 'efid' in params: out.write(" efid: "+str(params['efid'])+"\n")
456 if 'day' in params: out.write(" day: "+str(params['day'])+"\n")
457 if 'hour' in params: out.write(" hour: "+str(params['hour'])+"\n")
458 if 'min' in params: out.write(" min: "+str(params['min'])+"\n")
459 if 'stationid' in params: out.write(" stationid: "+str(params['stationid'])+"\n")
460 if 'longitude' in params: out.write(" longitude: "+str(params['longitude'])+"\n")
461 if 'latitude' in params: out.write(" latitude: "+str(params['latitude'])+"\n")
462 if 'timetoexpire' in params: out.write(" timetoexpire: "+str(params['timetoexpire'])+"\n")
463 if 'radius' in params: out.write(" radius: "+str(params['radius'])+"\n")
464 elif 'csv'==format:
465 if None == options.fieldList:
466 options.fieldList = fieldList
467 needComma = False;
468 for field in fieldList:
469 if needComma: out.write(',')
470 needComma = True
471 if field in params:
472 out.write(str(params[field]))
473
474 out.write("\n")
475 elif 'html'==format:
476 printHtml(params,out)
477 elif 'sql'==format:
478 sqlInsertStr(params,out,dbType=dbType)
479 elif 'kml'==format:
480 printKml(params,out)
481 elif 'kml-full'==format:
482 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
483 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n")
484 out.write("<Document>\n")
485 out.write(" <name>whalenotice</name>\n")
486 printKml(params,out)
487 out.write("</Document>\n")
488 out.write("</kml>\n")
489 else:
490 print "ERROR: unknown format:",format
491 assert False
492
493 return
494
495 RepeatIndicatorEncodeLut = {
496 'default':'0',
497 'do not repeat any more':'3',
498 }
499
500 RepeatIndicatorDecodeLut = {
501 '0':'default',
502 '3':'do not repeat any more',
503 }
504
505
506
507
508
509 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
510 ,addCoastGuardFields=True
511 ,dbType='postgres'
512 ):
513 '''
514 Return the SQL CREATE command for this message type
515 @param outfile: file like object to print to.
516 @param fields: which fields to put in the create. Defaults to all.
517 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
518 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
519 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
520 @type addCoastGuardFields: bool
521 @return: sql create string
522 @rtype: str
523
524 @see: sqlCreate
525 '''
526
527 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
528
529 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
530 '''
531 Return the sqlhelp object to create the table.
532
533 @param fields: which fields to put in the create. Defaults to all.
534 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
535 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
536 @type addCoastGuardFields: bool
537 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
538 @return: An object that can be used to generate a return
539 @rtype: sqlhelp.create
540 '''
541 if None == fields: fields = fieldList
542 import sqlhelp
543 c = sqlhelp.create('whalenotice',dbType=dbType)
544 c.addPrimaryKey()
545 if 'MessageID' in fields: c.addInt ('MessageID')
546 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator')
547 if 'UserID' in fields: c.addInt ('UserID')
548 if 'Spare' in fields: c.addInt ('Spare')
549 if 'dac' in fields: c.addInt ('dac')
550 if 'fid' in fields: c.addInt ('fid')
551 if 'efid' in fields: c.addInt ('efid')
552 if 'day' in fields: c.addInt ('day')
553 if 'hour' in fields: c.addInt ('hour')
554 if 'min' in fields: c.addInt ('min')
555 if 'stationid' in fields: c.addInt ('stationid')
556 if dbType != 'postgres':
557 if 'longitude' in fields: c.addDecimal('longitude',8,5)
558 if dbType != 'postgres':
559 if 'latitude' in fields: c.addDecimal('latitude',8,5)
560 if 'timetoexpire' in fields: c.addInt ('timetoexpire')
561 if 'radius' in fields: c.addInt ('radius')
562
563 if addCoastGuardFields:
564
565
566
567
568
569 c.addVarChar('cg_r',15)
570 c.addInt('cg_sec')
571
572 c.addTimestamp('cg_timestamp')
573
574 if dbType == 'postgres':
575
576
577 c.addPostGIS('whale','POINT',2,SRID=4326);
578
579 return c
580
581 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
582 '''
583 Return the SQL INSERT command for this message type
584 @param params: dictionary of values keyed by field name
585 @param outfile: file like object to print to.
586 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
587 @return: sql create string
588 @rtype: str
589
590 @see: sqlCreate
591 '''
592 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
593
594
595 -def sqlInsert(params,extraParams=None,dbType='postgres'):
596 '''
597 Give the SQL INSERT statement
598 @param params: dict keyed by field name of values
599 @param extraParams: any extra fields that you have created beyond the normal ais message fields
600 @rtype: sqlhelp.insert
601 @return: insert class instance
602 @todo: allow optional type checking of params?
603 @warning: this will take invalid keys happily and do what???
604 '''
605 import sqlhelp
606 i = sqlhelp.insert('whalenotice',dbType=dbType)
607
608 if dbType=='postgres':
609 finished = []
610 for key in params:
611 if key in finished:
612 continue
613
614 if key not in toPgFields and key not in fromPgFields:
615 if type(params[key])==Decimal: i.add(key,float(params[key]))
616 else: i.add(key,params[key])
617 else:
618 if key in fromPgFields:
619 val = params[key]
620
621 i.addPostGIS(key,val)
622 finished.append(key)
623 else:
624
625 pgName = toPgFields[key]
626
627 valStr=pgTypes[pgName]+'('
628 vals = []
629 for nonPgKey in fromPgFields[pgName]:
630 vals.append(str(params[nonPgKey]))
631 finished.append(nonPgKey)
632 valStr+=' '.join(vals)+')'
633 i.addPostGIS(pgName,valStr)
634 else:
635 for key in params:
636 if type(params[key])==Decimal: i.add(key,float(params[key]))
637 else: i.add(key,params[key])
638
639 if None != extraParams:
640 for key in extraParams:
641 i.add(key,extraParams[key])
642
643 return i
644
645
646
647
648
651 '''
652 Return the LaTeX definition table for this message type
653 @param outfile: file like object to print to.
654 @type outfile: file obj
655 @return: LaTeX table string via the outfile
656 @rtype: str
657
658 '''
659 o = outfile
660
661 o.write('''
662 \\begin{table}%[htb]
663 \\centering
664 \\begin{tabular}{|l|c|l|}
665 \\hline
666 Parameter & Number of bits & Description
667 \\\\ \\hline\\hline
668 MessageID & 6 & AIS message number. Must be 8 \\\\ \hline
669 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
670 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
671 Spare & 2 & Reserved for definition by a regional authority. \\\\ \hline
672 dac & 10 & Designated Area Code - 366 for the United States \\\\ \hline
673 fid & 6 & Functional IDentifier - 63 for the Whale Notice \\\\ \hline
674 efid & 12 & Extended Functional IDentifier. 1 for the Whale Notice (dac+fid+efid defines the exact message type) \\\\ \hline
675 day & 5 & Time of most recent whale detection. UTC day of the month 1..31 \\\\ \hline
676 hour & 5 & Time of most recent whale detection. UTC hours 0..23 \\\\ \hline
677 min & 6 & Time of most recent whale detection. UTC minutes \\\\ \hline
678 stationid & 8 & Identifier of the station that recorded the whale. Usually a number. \\\\ \hline
679 longitude & 28 & Center of the detection zone. East West location \\\\ \hline
680 latitude & 27 & Center of the detection zone. North South location \\\\ \hline
681 timetoexpire & 16 & Seconds from the detection time until the notice expires \\\\ \hline
682 radius & 16 & Distance from center of detection zone (lat/lon above)\\\\ \\hline \\hline
683 Total bits & 179 & Appears to take 2 slots with 245 pad bits to fill the last slot \\\\ \\hline
684 \\end{tabular}
685 \\caption{AIS message number 8: Endangered whale notification binary message}
686 \\label{tab:whalenotice}
687 \\end{table}
688 ''')
689
690
691
692
693
694 -def textDefinitionTable(outfile=sys.stdout
695 ,delim='\t'
696 ):
697 '''
698 Return the text definition table for this message type
699 @param outfile: file like object to print to.
700 @type outfile: file obj
701 @return: text table string via the outfile
702 @rtype: str
703
704 '''
705 o = outfile
706 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
707 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 8
708 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
709 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
710 Spare'''+delim+'''2'''+delim+'''Reserved for definition by a regional authority.
711 dac'''+delim+'''10'''+delim+'''Designated Area Code - 366 for the United States
712 fid'''+delim+'''6'''+delim+'''Functional IDentifier - 63 for the Whale Notice
713 efid'''+delim+'''12'''+delim+'''Extended Functional IDentifier. 1 for the Whale Notice (dac+fid+efid defines the exact message type)
714 day'''+delim+'''5'''+delim+'''Time of most recent whale detection. UTC day of the month 1..31
715 hour'''+delim+'''5'''+delim+'''Time of most recent whale detection. UTC hours 0..23
716 min'''+delim+'''6'''+delim+'''Time of most recent whale detection. UTC minutes
717 stationid'''+delim+'''8'''+delim+'''Identifier of the station that recorded the whale. Usually a number.
718 longitude'''+delim+'''28'''+delim+'''Center of the detection zone. East West location
719 latitude'''+delim+'''27'''+delim+'''Center of the detection zone. North South location
720 timetoexpire'''+delim+'''16'''+delim+'''Seconds from the detection time until the notice expires
721 radius'''+delim+'''16'''+delim+'''Distance from center of detection zone (lat/lon above)
722 Total bits'''+delim+'''179'''+delim+'''Appears to take 2 slots with 245 pad bits to fill the last slot''')
723
724
725
726
727
728 import unittest
730 '''Return a params file base on the testvalue tags.
731 @rtype: dict
732 @return: params based on testvalue tags
733 '''
734 params = {}
735 params['MessageID'] = 8
736 params['RepeatIndicator'] = 1
737 params['UserID'] = 1193046
738 params['Spare'] = 0
739 params['dac'] = 366
740 params['fid'] = 63
741 params['efid'] = 1
742 params['day'] = 28
743 params['hour'] = 23
744 params['min'] = 45
745 params['stationid'] = 76
746 params['longitude'] = Decimal('-122.16328055555556')
747 params['latitude'] = Decimal('37.424458333333334')
748 params['timetoexpire'] = 1
749 params['radius'] = 5000
750
751 return params
752
754 '''Use testvalue tag text from each type to build test case the whalenotice message'''
756
757 params = testParams()
758 bits = encode(params)
759 r = decode(bits)
760
761
762 self.failUnlessEqual(r['MessageID'],params['MessageID'])
763 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
764 self.failUnlessEqual(r['UserID'],params['UserID'])
765 self.failUnlessEqual(r['Spare'],params['Spare'])
766 self.failUnlessEqual(r['dac'],params['dac'])
767 self.failUnlessEqual(r['fid'],params['fid'])
768 self.failUnlessEqual(r['efid'],params['efid'])
769 self.failUnlessEqual(r['day'],params['day'])
770 self.failUnlessEqual(r['hour'],params['hour'])
771 self.failUnlessEqual(r['min'],params['min'])
772 self.failUnlessEqual(r['stationid'],params['stationid'])
773 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5)
774 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5)
775 self.failUnlessEqual(r['timetoexpire'],params['timetoexpire'])
776 self.failUnlessEqual(r['radius'],params['radius'])
777
779 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
780 help='decode a "whalenotice" AIS message')
781 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
782 help='encode a "whalenotice" AIS message')
783 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
784 ,help='Field parameter value [default: %default]')
785 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
786 ,help='Field parameter value [default: %default]')
787 parser.add_option('--day-field', dest='dayField',metavar='uint',type='int'
788 ,help='Field parameter value [default: %default]')
789 parser.add_option('--hour-field', dest='hourField',metavar='uint',type='int'
790 ,help='Field parameter value [default: %default]')
791 parser.add_option('--min-field', dest='minField',metavar='uint',type='int'
792 ,help='Field parameter value [default: %default]')
793 parser.add_option('--stationid-field', dest='stationidField',default=0,metavar='uint',type='int'
794 ,help='Field parameter value [default: %default]')
795 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string'
796 ,help='Field parameter value [default: %default]')
797 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string'
798 ,help='Field parameter value [default: %default]')
799 parser.add_option('--timetoexpire-field', dest='timetoexpireField',default=0,metavar='uint',type='int'
800 ,help='Field parameter value [default: %default]')
801 parser.add_option('--radius-field', dest='radiusField',default=65534,metavar='uint',type='int'
802 ,help='Field parameter value [default: %default]')
803
804
805 if __name__=='__main__':
806
807 from optparse import OptionParser
808 parser = OptionParser(usage="%prog [options]",
809 version="%prog "+__version__)
810
811 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
812 help='run the documentation tests')
813 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
814 help='run the unit tests')
815 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
816 help='Make the test output verbose')
817
818
819
820 typeChoices = ('binary','nmeapayload','nmea')
821 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
822 ,default='nmeapayload'
823 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
824
825
826 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
827 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
828 ,default='std'
829 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
830
831 parser.add_option('-o','--output',dest='outputFileName',default=None,
832 help='Name of the python file to write [default: stdout]')
833
834 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
835 choices=fieldList,
836 help='Which fields to include in the output. Currently only for csv output [default: all]')
837
838 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
839 help='Print the field name for csv')
840
841 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
842 help='Print out an sql create command for the table.')
843
844 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
845 help='Print a LaTeX table of the type')
846
847 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
848 help='Print delimited table of the type (for Word table importing)')
849 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
850 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
851
852
853 dbChoices = ('sqlite','postgres')
854 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
855 ,choices=dbChoices,type='choice'
856 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
857
858 addMsgOptions(parser)
859
860 (options,args) = parser.parse_args()
861 success=True
862
863 if options.doctest:
864 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
865 sys.argv= [sys.argv[0]]
866 if options.verbose: sys.argv.append('-v')
867 import doctest
868 numfail,numtests=doctest.testmod()
869 if numfail==0: print 'ok'
870 else:
871 print 'FAILED'
872 success=False
873
874 if not success: sys.exit('Something Failed')
875 del success
876
877 if options.unittest:
878 sys.argv = [sys.argv[0]]
879 if options.verbose: sys.argv.append('-v')
880 unittest.main()
881
882 outfile = sys.stdout
883 if None!=options.outputFileName:
884 outfile = file(options.outputFileName,'w')
885
886
887 if options.doEncode:
888
889 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
890 if None==options.UserIDField: parser.error("missing value for UserIDField")
891 if None==options.dayField: parser.error("missing value for dayField")
892 if None==options.hourField: parser.error("missing value for hourField")
893 if None==options.minField: parser.error("missing value for minField")
894 if None==options.stationidField: parser.error("missing value for stationidField")
895 if None==options.longitudeField: parser.error("missing value for longitudeField")
896 if None==options.latitudeField: parser.error("missing value for latitudeField")
897 if None==options.timetoexpireField: parser.error("missing value for timetoexpireField")
898 if None==options.radiusField: parser.error("missing value for radiusField")
899 msgDict={
900 'MessageID': '8',
901 'RepeatIndicator': options.RepeatIndicatorField,
902 'UserID': options.UserIDField,
903 'Spare': '0',
904 'dac': '366',
905 'fid': '63',
906 'efid': '1',
907 'day': options.dayField,
908 'hour': options.hourField,
909 'min': options.minField,
910 'stationid': options.stationidField,
911 'longitude': options.longitudeField,
912 'latitude': options.latitudeField,
913 'timetoexpire': options.timetoexpireField,
914 'radius': options.radiusField,
915 }
916
917 bits = encode(msgDict)
918 if 'binary'==options.ioType: print str(bits)
919 elif 'nmeapayload'==options.ioType:
920
921 print "bitLen",len(bits)
922 bitLen=len(bits)
923 if bitLen%6!=0:
924 bits = bits + BitVector(size=(6 - (bitLen%6)))
925 print "result:",binary.bitvectoais6(bits)[0]
926
927
928
929 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
930 else: sys.exit('ERROR: unknown ioType. Help!')
931
932
933 if options.sqlCreate:
934 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
935
936 if options.latexDefinitionTable:
937 latexDefinitionTable(outfile)
938
939
940 if options.textDefinitionTable:
941 textDefinitionTable(outfile,options.delimTextDefinitionTable)
942
943 if options.printCsvfieldList:
944
945 if None == options.fieldList: options.fieldList = fieldList
946 import StringIO
947 buf = StringIO.StringIO()
948 for field in options.fieldList:
949 buf.write(field+',')
950 result = buf.getvalue()
951 if result[-1] == ',': print result[:-1]
952 else: print result
953
954 if options.doDecode:
955 if len(args)==0: args = sys.stdin
956 for msg in args:
957 bv = None
958
959 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
960
961
962 bv = binary.ais6tobitvec(msg.split(',')[5])
963 else:
964
965 binaryMsg=True
966 for c in msg:
967 if c not in ('0','1'):
968 binaryMsg=False
969 break
970 if binaryMsg:
971 bv = BitVector(bitstring=msg)
972 else:
973 bv = binary.ais6tobitvec(msg)
974
975 printFields(decode(bv)
976 ,out=outfile
977 ,format=options.outputType
978 ,fieldList=options.fieldList
979 ,dbType=options.dbType
980 )
981