Debian Codegraph @

ais/io.py

raw symbols SCIP
1 """A file-like interface to NMEA parsing.
2
3 >>> import ais
4 >>> import json
5 >>> with ais.open('test/data/typeexamples.nmea') as src:
6 ... msg = next(src)
7 ... print(json.dumps(next(msg), indent=4, sort_keys=True))
8 {
9 "decoded": {
10 "day": 0,
11 "fix_type": 1,
12 "hour": 24,
13 "id": 4,
14 "md5": "7ecb187e7edc1789de436b0c2ccf2963",
15 "minute": 60,
16 "mmsi": 3669713,
17 "month": 0,
18 "position_accuracy": 0,
19 "raim": false,
20 "repeat_indicator": 0,
21 "second": 60,
22 "slot_number": 2105,
23 "slot_timeout": 2,
24 "spare": 0,
25 "sync_state": 1,
26 "transmission_ctl": 0,
27 "x": 181.0,
28 "y": 91.0,
29 "year": 0
30 },
31 "line_nums": [
32 1
33 ],
34 "line_type": "USCG",
35 "lines": [
36 "!AIVDM,1,1,,A,403Ovl@000Htt<tSF0l4Q@100`Pq,0*28,d-109,S2105,t050056.00,T56.13718694,r003669946,1325394060,1325394001"
37 ],
38 "matches": [
39 {
40 "body": "403Ovl@000Htt<tSF0l4Q@100`Pq",
41 "chan": "A",
42 "checksum": "28",
43 "counter": null,
44 "fill_bits": 0,
45 "hour": 5,
46 "minute": 0,
47 "payload": "!AIVDM,1,1,,A,403Ovl@000Htt<tSF0l4Q@100`Pq,0*28",
48 "receiver_time": 50056.0,
49 "rssi": null,
50 "second": 56.0,
51 "sen_num": 1,
52 "sen_tot": 1,
53 "seq_id": null,
54 "signal_strength": -109,
55 "slot": 2105,
56 "station": "r003669946",
57 "station_type": "r",
58 "talker": "AI",
59 "time": 1325394060,
60 "time_of_arrival": 56.13718694,
61 "uscg_metadata": ",d-109,S2105,t050056.00,T56.13718694,r003669946,1325394060",
62 "vdm": "!AIVDM,1,1,,A,403Ovl@000Htt<tSF0l4Q@100`Pq,0*28",
63 "vdm_type": "VDM"
64 }
65 ]
66 }
67
68 """
69
70 import codecs
71 import sys
72
73 import six
74
75 import ais.nmea_queue
76
77
78 def open(name, mode='r', **kwargs):
79 """Open a file containing NMEA and instantiate an instance of `NmeaFile()`.
80 Lke Python's `open()`, set the `mode` parameter to 'r' for normal reading or
81 or 'rU' for opening the file in universal newline mode.
82
83 Args:
84 name: A file path, file-like object, or '-' for stdin.
85 mode: I/O mode for opening the input file. r, rU, or U
86
87 Raises:
88 TypeError: Invalid object for name parameter.
89 ValueError: Invalid value for mode parameter.
90
91 Returns:
92 An instance of NmeaFile that is ready for reading.
93 """
94
95 io_modes = ('r', 'rU', 'U')
96
97 if mode not in io_modes:
98 raise ValueError("Mode '{m}' is unsupported. Must be one of: {ms}".format(
99 m=mode, ms=', '.join(io_modes)))
100
101 if name == '-':
102 fobj = sys.stdin
103 elif isinstance(name, six.string_types):
104 fobj = codecs.open(name, **kwargs)
105 elif hasattr(name, 'close') and \
106 (hasattr(name, 'next') or hasattr(name, '__next__')):
107 fobj = name
108 else:
109 raise TypeError("'name' must be a file path, file-like object, "
110 "or '-' for stdin.")
111
112 return NmeaFile(fobj)
113
114
115 class NmeaFile(object):
116 """Provides a file-like object interface to the `ais.nmea_queue` module."""
117
118 def __init__(self, fobj):
119 """Construct a parsing stream.
120
121 Args:
122 fobj: File-like object.
123 """
124
125 self._fobj = fobj
126 self._queue = ais.nmea_queue.NmeaQueue()
127
128 @property
129 def closed(self):
130 """Is the file-like object from which we are reading open for reading?"""
131 return self._fobj.closed
132
133 @property
134 def name(self):
135 """Name of the file-like object from which we are reading."""
136 return self._fobj.name
137
138 def close(self):
139 """Close the file-like object from which we are reading and dump whats left
140 in the queue."""
141 return self._fobj.close()
142
143 def __iter__(self):
144 return self
145
146 def __enter__(self):
147 return self
148
149 def __exit__(self, exc_type, exc_val, exc_tb):
150 # Destroy the queue, which could be a large in-memory object.
151 self._queue = None
152 return self.close()
153
154 def __next__(self):
155 """Return the next decoded AIS message."""
156 msg = None
157 while not msg:
158 self._queue.put(next(self._fobj))
159 msg = self._queue.GetOrNone()
160 return msg
161
162 next = __next__