Skip to content

Commit

Permalink
Sentence can be converted to a dict, so that it can be encoded in, e.…
Browse files Browse the repository at this point in the history
…g., JSON.
  • Loading branch information
wpietri committed Apr 19, 2017
1 parent 82cbbeb commit ee6aaa4
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from setuptools import setup, find_packages

setup(name='simpleais',
version='0.6.5',
version='0.6.6',
description='a simple ais parser',
url='https://github.com/wpietri/simpleais',
author='William Pietri',
Expand Down
24 changes: 24 additions & 0 deletions simpleais/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,30 @@ def __repr__(self):
def __str__(self):
return "Sentence(type {}, from {}, at {})".format(self.type_num, self['mmsi'], self.time)

def as_dict(self):
result = {}
if self.time:
result['time'] = self.time
result['text'] = self.text
for field in self.fields():
result[field.name()] = field.value()
return result

def __iter__(self):
return iter(self.as_dict())


class SentenceIterator:
def __init__(self, sentence):
self.sentence = sentence
self.fields = sentence.fields().__iter__()

def __iter__(self):
return self

def __next__(self):
field = self.fields.__next__()
return field.name(), field.value()

class FragmentPool:
"""
Expand Down
36 changes: 35 additions & 1 deletion tests/test_field_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ def int_for_bit_range(self, i1, i2):
self.assertEqual("enum-unknown-101", decoded_101.value)
self.assertEqual("enum-unknown-101", str(decoded_101))


def test_type_17_location(self):
# Type 17 locations are weird. I don't have enough data to reliably check,
# and it's not clear that it means the same thing as other lon/lat fields.
Expand Down Expand Up @@ -172,3 +171,38 @@ def test_type_7(self):
self.assertTrue(m.field('mmsiseq3').valid())
self.assertFalse(m.field('mmsi4').valid())
self.assertFalse(m.field('mmsiseq4').valid())


class TestRenderAsDict(TestCase):
def setUp(self):
super().setUp()

def test_type_1(self):
text = '!ABVDM,1,1,,A,15NaEPPP01oR`R6CC?<j@gvr0<1C,0*1F'
time = 12345.0
sentence = parse(str(time) + ' ' + text)
expected_dict = {'accuracy': True,
'course': 57.8,
'heading': 511,
'ignored-145': 0,
'lat': 33.7302,
'lon': -118.2634,
'maneuver': 'enum-0',
'mmsi': '367678850',
'radio': 49235,
'raim': False,
'repeat': 0,
'second': 29,
'speed': 0.1,
'status': 'enum-0',
'text': [text],
'time': time,
'turn': -0.0021,
'type': 1,}
self.assertDictEqual(expected_dict, sentence.as_dict())

def test_type_5(self):
m = parse(['!AIVDM,2,1,8,A,55Mw0BP00001L=WKC?98uT4j1=@580000000000t1@D5540Ht6?UDp4iSp=<,0*74',
'!AIVDM,2,2,8,A,@0000000000,2*5C'])[0]
d = m.as_dict()
print(d)

0 comments on commit ee6aaa4

Please sign in to comment.