Knio / pynmea2

Python library for parsing the NMEA 0183 protocol (GPS)
MIT License
632 stars 223 forks source link

Add default constructors for NMEA types #19

Open Roel84 opened 10 years ago

Roel84 commented 10 years ago

It would be convenient to have default constructors for the NMEA types. When using pynmea2 for encoding NMEA messages we now have to provide constructor parameters which are already known to the NMEA types itself.

An example of how the default constructor would look like for the HDG type;

class HDG(TalkerSentence):
    """ NOTE! This is a GUESS as I cannot find an actual spec
        telling me the fields. Updates are welcome!
    """
    fields = (
        ("Heading", "heading", Decimal),
        ("Deviation", "deviation", Decimal),
        ("Deviation Direction", "dev_dir"),
        ("Variation", "variation", Decimal),
        ("Variation Direction", "var_dir")
    )

    def __init__(self, talker=None, sentence_type=None, data=None):
        if talker == None: 
            talker = 'HC'
        if sentence_type == None:
            sentence_type = 'HDG'
        if data == None:
            data = [''] * len(self.fields)

        super(HDG, self).__init__(talker, sentence_type, data)

The usage would be as followed;

class NmeaTests(unittest.TestCase):
    def testCreateHDG(self):
        hdg = HDG()
        hdg.heading = 180.0
        hdg.deviation = 1.0
        hdg.dev_dir = 'E'
        hdg.variation = 90.0
        hdg.var_dir = 'W'

        msg = str(hdg)
        self.assertEqual('$HCHDG,180.0,1.0,E,90.0,W*61', msg)
jmwooten commented 10 years ago

A constructor that defaults the sentence_type and blanks the fields would be possible; however, the "talker" is an application specific default.

Knio commented 10 years ago

having defaults for sentence_type (and manufacturer for proprietary sentences) so that they don't have to be given in the constructor is a good idea. Those fields should possibly be class attributes and not instance attributes anyway.

I will look into this.