Ignore:
Timestamp:
Apr 11, 2020, 4:46:15 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
3db3d13
Parents:
da2be70
Message:
  • Added yapf style config (src/python-style.yapf)
    • Updated all files to the yapf formatted version
Location:
src/common/gnuboat_common/datahandler
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • src/common/gnuboat_common/datahandler/logdataset.py

    rda2be70 r7be94aa  
    1     # -*- coding: utf-8 -*-
     1# -*- coding: utf-8 -*-
    22'''
    33    Copyright (C) 2016 - 2018 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
    … …  
    2121
    2222Location = namedtuple('Location', 'latitude longitude')
    23 
    2423"""@class Dataset of a log entry
    2524"""
     25
     26
    2627class LogDataset:
    27         def __init__(self, datetime = None, gps_status = None, latitude = None, latitude_direction = None,
    28                                         longitude = None, longitude_direction = None, speed_over_ground = None,
    29                                         course_over_ground = None, water_depth = None, water_temperature = None):
    30                 self._datetime = datetime
    31                 self._gps_status = gps_status
    32                 self._latitude = latitude
    33                 self._latitude_direction = latitude_direction
    34                 self._longitude = longitude
    35                 self._longitude_direction = longitude_direction
    36                 self._speed_over_ground = speed_over_ground
    37                 self._course_over_ground = course_over_ground
    38                 self._water_depth = water_depth
    39                 self._water_temperature = water_temperature
    40        
    41         def datetime(self):
    42                 return self._datetime
    43        
    44         def datetime_object(self):
    45                 if self.datetime() is None:
    46                         return None
    47                 return datetime.strptime(self.datetime(), "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
    48        
    49         def datetime_set(self, datetime):
    50                 self._datetime = datetime
    51        
    52         def gps_status(self):
    53                 return self._gps_status
    54        
    55         def gps_status_set(self, status):
    56                 self._gps_status = status
    57        
    58         def latitude(self):
    59                 return self._latitude
    60        
    61         def latitude_set(self, latitude):
    62                 self._latitude = latitude
    63                
    64         def latitude_direction(self):
    65                 return self._latitude_direction
    66        
    67         def latitude_direction_set(self, direction):
    68                 self._latitude_direction = direction
    69                
    70         def longitude(self):
    71                 return self._longitude
    72        
    73         def longitude_set(self, longitude):
    74                 self._longitude = longitude
    75                
    76         def longitude_direction(self):
    77                 return self._longitude_direction
    78        
    79         def longitude_direction_set(self, direction):
    80                 self._longitude_direction = direction
    81                
    82         def location(self):
    83                 if self.latitude_direction() is None:
    84                         return None
    85                 elif self.latitude_direction() == 'N':
    86                         latitude = self.latitude()
    87                 elif self.latitude_direction() == 'S':
    88                         latitude = -1.0 * self.latitude()
    89                 else:
    90                         return None
    91                 if self.longitude_direction() is None:
    92                         return None
    93                 elif self.longitude_direction() == 'E':
    94                         longitude = self.longitude()
    95                 elif self.longitude_direction() == 'W':
    96                         longitude = -1.0 * self.longitude()
    97                 else:
    98                         return None
    99                 return Location(latitude, longitude)
    100        
    101         def speed_over_ground(self):
    102                 return self._speed_over_ground
    103        
    104         def speed_over_ground_set(self, speed):
    105                 self._speed_over_ground = speed
    106                
    107         def course_over_ground(self):
    108                 return self._course_over_ground
    109        
    110         def course_over_ground_set(self, course):
    111                 self._course_over_ground = course
    112                
    113         def water_depth(self):
    114                 return self._water_depth
    115        
    116         def water_depth_set(self, depth):
    117                 self._water_depth = depth
    118                
    119         def water_temperature(self):
    120                 return self._water_temperature
    121        
    122         def water_temperature_set(self, temperature):
    123                 self._water_temperature = temperature
    124                
    125         def to_dict(self):
    126                 return {'datetime': self.datetime(),
    127                                 'gps_status': self.gps_status(),
    128                                 'latitude': self.latitude(),
    129                                 'latitude_direction': self.latitude_direction(),
    130                                 'longitude': self.longitude(),
    131                                 'longitude_direction': self.longitude_direction(),
    132                                 'speed_over_ground': self.speed_over_ground(),
    133                                 'course_over_ground': self.course_over_ground(),
    134                                 'water_depth': self.water_depth(),
    135                                 'water_temperature': self.water_temperature()}
     28    def __init__(
     29        self,
     30        datetime=None,
     31        gps_status=None,
     32        latitude=None,
     33        latitude_direction=None,
     34        longitude=None,
     35        longitude_direction=None,
     36        speed_over_ground=None,
     37        course_over_ground=None,
     38        water_depth=None,
     39        water_temperature=None
     40    ):
     41        self._datetime = datetime
     42        self._gps_status = gps_status
     43        self._latitude = latitude
     44        self._latitude_direction = latitude_direction
     45        self._longitude = longitude
     46        self._longitude_direction = longitude_direction
     47        self._speed_over_ground = speed_over_ground
     48        self._course_over_ground = course_over_ground
     49        self._water_depth = water_depth
     50        self._water_temperature = water_temperature
     51
     52    def datetime(self):
     53        return self._datetime
     54
     55    def datetime_object(self):
     56        if self.datetime() is None:
     57            return None
     58        return datetime.strptime(self.datetime(), "%Y-%m-%d %H:%M:%S").replace(
     59            tzinfo=timezone.utc
     60        )
     61
     62    def datetime_set(self, datetime):
     63        self._datetime = datetime
     64
     65    def gps_status(self):
     66        return self._gps_status
     67
     68    def gps_status_set(self, status):
     69        self._gps_status = status
     70
     71    def latitude(self):
     72        return self._latitude
     73
     74    def latitude_set(self, latitude):
     75        self._latitude = latitude
     76
     77    def latitude_direction(self):
     78        return self._latitude_direction
     79
     80    def latitude_direction_set(self, direction):
     81        self._latitude_direction = direction
     82
     83    def longitude(self):
     84        return self._longitude
     85
     86    def longitude_set(self, longitude):
     87        self._longitude = longitude
     88
     89    def longitude_direction(self):
     90        return self._longitude_direction
     91
     92    def longitude_direction_set(self, direction):
     93        self._longitude_direction = direction
     94
     95    def location(self):
     96        if self.latitude_direction() is None:
     97            return None
     98        elif self.latitude_direction() == 'N':
     99            latitude = self.latitude()
     100        elif self.latitude_direction() == 'S':
     101            latitude = -1.0 * self.latitude()
     102        else:
     103            return None
     104        if self.longitude_direction() is None:
     105            return None
     106        elif self.longitude_direction() == 'E':
     107            longitude = self.longitude()
     108        elif self.longitude_direction() == 'W':
     109            longitude = -1.0 * self.longitude()
     110        else:
     111            return None
     112        return Location(latitude, longitude)
     113
     114    def speed_over_ground(self):
     115        return self._speed_over_ground
     116
     117    def speed_over_ground_set(self, speed):
     118        self._speed_over_ground = speed
     119
     120    def course_over_ground(self):
     121        return self._course_over_ground
     122
     123    def course_over_ground_set(self, course):
     124        self._course_over_ground = course
     125
     126    def water_depth(self):
     127        return self._water_depth
     128
     129    def water_depth_set(self, depth):
     130        self._water_depth = depth
     131
     132    def water_temperature(self):
     133        return self._water_temperature
     134
     135    def water_temperature_set(self, temperature):
     136        self._water_temperature = temperature
     137
     138    def to_dict(self):
     139        return {
     140            'datetime': self.datetime(),
     141            'gps_status': self.gps_status(),
     142            'latitude': self.latitude(),
     143            'latitude_direction': self.latitude_direction(),
     144            'longitude': self.longitude(),
     145            'longitude_direction': self.longitude_direction(),
     146            'speed_over_ground': self.speed_over_ground(),
     147            'course_over_ground': self.course_over_ground(),
     148            'water_depth': self.water_depth(),
     149            'water_temperature': self.water_temperature()
     150        }
  • src/common/gnuboat_common/datahandler/loghandler.py

    rda2be70 r7be94aa  
    1     # -*- coding: utf-8 -*-
     1# -*- coding: utf-8 -*-
    22'''
    33    Copyright (C) 2016 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
    … …  
    2727from gnuboat_common.datahandler import logdataset
    2828
     29
    2930class LogParsingResult:
    30         def __init__(self):
    31                 self._success = False
    32                 self._errors = []
    33        
    34         def error_add(self, error):
    35                 self._errors.append(error)
    36        
    37         def errors(self):
    38                 return self._errors
    39        
    40         def messages(self):
    41                 if len(self._errors) > 0:
    42                         return True
    43                 return False
    44        
    45         def succeeded(self, status):
    46                 self._success = status
    47        
    48         def success(self):
    49                 return self._success
     31    def __init__(self):
     32        self._success = False
     33        self._errors = []
     34
     35    def error_add(self, error):
     36        self._errors.append(error)
     37
     38    def errors(self):
     39        return self._errors
     40
     41    def messages(self):
     42        if len(self._errors) > 0:
     43            return True
     44        return False
     45
     46    def succeeded(self, status):
     47        self._success = status
     48
     49    def success(self):
     50        return self._success
     51
    5052
    5153"""@class LogHandler
    5254"""
     55
     56
    5357class LogHandler:
    54         def __init__(self, log_directory = None):
    55                 self._regex_nmea_sentence = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$")
    56                 self._regex_nmea_sentence_without_checksum = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$")
    57                 self._regex_nmea_position_latitude = re.compile(r"^([0-9]{2})([0-9]{2}\.[0-9]+)$")
    58                 self._regex_nmea_position_longitude = re.compile(r"^([0-9]{3})([0-9]{2}\.[0-9]+)$")
    59                 self._log_directory = log_directory
    60                 self._nmea_file = None
    61                 self._nmea_file_date = None
    62        
    63         def gnuboat_write(self, gps_fix, gps_time, dataset, transducer_valid, log_verbose, log_system_time):
    64                 # Only log, if we have a gps fix
    65                 if gps_fix < 2:
    66                         if not log_verbose:
    67                                 return
    68                         gps_status = 'V'
    69                         mode = 'N'
    70                         if gps_time is None:
    71                                 gps_time = datetime.datetime.utcnow()
    72                
    73                 nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d")
    74                 mode = 'A'
    75                 if self._nmea_file == None or self._nmea_file_date is None or self._nmea_file_date != nmea_file_date_should:
    76                         if self._nmea_file:
    77                                         self._nmea_file.close()
    78                         try:
    79                                 self._nmea_file_date = nmea_file_date_should
    80                                 nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date)
    81                                 self._nmea_file = open(os.path.join(self._log_directory, nmea_log_file), 'a', 0)
    82                         except IOError as error:
    83                                 print('Could not open the logfile: {}'.format(error))
    84                                 return False
    85                 else:
    86                         nmea_log_file = self._nmea_file.name
    87 
    88                 latitude = self._degreesDecimalToNmea(dataset.latitude())
    89                 longitude = self._degreesDecimalToNmea(dataset.longitude())
    90 
    91                 logsystemtime = ""
    92                 if log_system_time:
    93                         logsystemtime = '{}: '.format(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
    94                        
    95                 try:
    96                         self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.RMC('GN', 'RMC',
    97                                                                                                                 (gps_time.strftime("%H%M%S"), dataset.gps_status(),
    98                                                                                                                 '{:02d}{:07.4f}'.format(latitude['degrees'], latitude['minutes']),
    99                                                                                                                 dataset.latitude_direction(),
    100                                                                                                                 '{:03d}{:07.4f}'.format(longitude['degrees'], longitude['minutes']),
    101                                                                                                                 dataset.longitude_direction(),
    102                                                                                                                 '{:04.1f}'.format(dataset.speed_over_ground()), '{:04.1f}'.format(dataset.course_over_ground()),
    103                                                                                                                 gps_time.strftime("%d%m%y"), '', '', mode)))))
    104                         if transducer_valid:
    105                                 self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.DPT('SD', 'DPT', ('{:05.2f}'.format(dataset.water_depth()), '00.00')))))
    106                                 self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.MTW('YX', 'MTW', ('{:04.1f}'.format(dataset.water_temperature()), 'C')))))
    107                         return True
    108                 except:
    109                         print('Failed writing to logfile {}'.format(nmea_log_file))
    110                         print(traceback.format_exc())
    111                         return False
    112                 return False
    113        
    114         def gnuboat_close(self):
    115                 if self._nmea_file:
    116                         self._nmea_file.close()
    117        
    118         def parse_nmea_sentence(self, line, checksum_ingore = False):
    119                 line = line.strip()
    120                 if checksum_ingore:
    121                         matches = self._regex_nmea_sentence_without_checksum.match(line)
    122                 else:
    123                         matches = self._regex_nmea_sentence.match(line)
    124                 if matches is None:
    125                         return None
    126                 return {'log_timestamp': matches.group(1), 'nmea_sentence': pynmea2.parse(matches.group(2), not checksum_ingore)}
    127        
    128         """     Reads the original gnuboat log files and calls a callable function on all complete LogDataset
     58    def __init__(self, log_directory=None):
     59        self._regex_nmea_sentence = re.compile(
     60            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$"
     61        )
     62        self._regex_nmea_sentence_without_checksum = re.compile(
     63            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$"
     64        )
     65        self._regex_nmea_position_latitude = re.compile(
     66            r"^([0-9]{2})([0-9]{2}\.[0-9]+)$"
     67        )
     68        self._regex_nmea_position_longitude = re.compile(
     69            r"^([0-9]{3})([0-9]{2}\.[0-9]+)$"
     70        )
     71        self._log_directory = log_directory
     72        self._nmea_file = None
     73        self._nmea_file_date = None
     74
     75    def gnuboat_write(
     76        self, gps_fix, gps_time, dataset, transducer_valid, log_verbose,
     77        log_system_time
     78    ):
     79        # Only log, if we have a gps fix
     80        if gps_fix < 2:
     81            if not log_verbose:
     82                return
     83            gps_status = 'V'
     84            mode = 'N'
     85            if gps_time is None:
     86                gps_time = datetime.datetime.utcnow()
     87
     88        nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d")
     89        mode = 'A'
     90        if self._nmea_file == None or self._nmea_file_date is None or self._nmea_file_date != nmea_file_date_should:
     91            if self._nmea_file:
     92                self._nmea_file.close()
     93            try:
     94                self._nmea_file_date = nmea_file_date_should
     95                nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date)
     96                self._nmea_file = open(
     97                    os.path.join(self._log_directory, nmea_log_file), 'a', 0
     98                )
     99            except IOError as error:
     100                print('Could not open the logfile: {}'.format(error))
     101                return False
     102        else:
     103            nmea_log_file = self._nmea_file.name
     104
     105        latitude = self._degreesDecimalToNmea(dataset.latitude())
     106        longitude = self._degreesDecimalToNmea(dataset.longitude())
     107
     108        logsystemtime = ""
     109        if log_system_time:
     110            logsystemtime = '{}: '.format(
     111                datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
     112            )
     113
     114        try:
     115            self._nmea_file.write(
     116                '{}{}\r\n'.format(
     117                    logsystemtime,
     118                    str(
     119                        pynmea2.RMC(
     120                            'GN', 'RMC', (
     121                                gps_time.strftime("%H%M%S"),
     122                                dataset.gps_status(), '{:02d}{:07.4f}'.format(
     123                                    latitude['degrees'], latitude['minutes']
     124                                ), dataset.latitude_direction(),
     125                                '{:03d}{:07.4f}'.format(
     126                                    longitude['degrees'], longitude['minutes']
     127                                ), dataset.longitude_direction(),
     128                                '{:04.1f}'.format(dataset.speed_over_ground()),
     129                                '{:04.1f}'.format(
     130                                    dataset.course_over_ground()
     131                                ), gps_time.strftime("%d%m%y"), '', '', mode
     132                            )
     133                        )
     134                    )
     135                )
     136            )
     137            if transducer_valid:
     138                self._nmea_file.write(
     139                    '{}{}\r\n'.format(
     140                        logsystemtime,
     141                        str(
     142                            pynmea2.DPT(
     143                                'SD', 'DPT', (
     144                                    '{:05.2f}'.format(dataset.water_depth()
     145                                                      ), '00.00'
     146                                )
     147                            )
     148                        )
     149                    )
     150                )
     151                self._nmea_file.write(
     152                    '{}{}\r\n'.format(
     153                        logsystemtime,
     154                        str(
     155                            pynmea2.MTW(
     156                                'YX', 'MTW', (
     157                                    '{:04.1f}'.format(
     158                                        dataset.water_temperature()
     159                                    ), 'C'
     160                                )
     161                            )
     162                        )
     163                    )
     164                )
     165            return True
     166        except:
     167            print('Failed writing to logfile {}'.format(nmea_log_file))
     168            print(traceback.format_exc())
     169            return False
     170        return False
     171
     172    def gnuboat_close(self):
     173        if self._nmea_file:
     174            self._nmea_file.close()
     175
     176    def parse_nmea_sentence(self, line, checksum_ingore=False):
     177        line = line.strip()
     178        if checksum_ingore:
     179            matches = self._regex_nmea_sentence_without_checksum.match(line)
     180        else:
     181            matches = self._regex_nmea_sentence.match(line)
     182        if matches is None:
     183            return None
     184        return {
     185            'log_timestamp':
     186                matches.group(1),
     187            'nmea_sentence':
     188                pynmea2.parse(matches.group(2), not checksum_ingore)
     189        }
     190
     191    """ Reads the original gnuboat log files and calls a callable function on all complete LogDataset
    129192                callback must be of a function wich excepts the LogDataset as a parameter.
    130193        """
    131         def gnuboat_read_file(self, input_file_path, callback, checksums_fix = False, errors_ignore = False):
    132                 result = LogParsingResult()
    133                
    134                 # reading input file
    135                 try:
    136                         input_file = open(input_file_path, 'r')
    137                 except IOError as error:
    138                         result.error_add('ERROR: Could not open the input file: {}'.format(error))
    139                         result.succeeded(False)
    140                         return result
    141                 result = self.gnuboat_read(input_file, callback, checksums_fix, errors_ignore = False)
    142                 input_file.close()
    143                 return result
    144 
    145         """     Reads the original gnuboat log from input_list and calls a callable function on all complete LogDataset
     194
     195    def gnuboat_read_file(
     196        self,
     197        input_file_path,
     198        callback,
     199        checksums_fix=False,
     200        errors_ignore=False
     201    ):
     202        result = LogParsingResult()
     203
     204        # reading input file
     205        try:
     206            input_file = open(input_file_path, 'r')
     207        except IOError as error:
     208            result.error_add(
     209                'ERROR: Could not open the input file: {}'.format(error)
     210            )
     211            result.succeeded(False)
     212            return result
     213        result = self.gnuboat_read(
     214            input_file, callback, checksums_fix, errors_ignore=False
     215        )
     216        input_file.close()
     217        return result
     218
     219    """ Reads the original gnuboat log from input_list and calls a callable function on all complete LogDataset
    146220                callback must be of a function wich excepts the LogDataset as a parameter.
    147221        """
    148         def gnuboat_read(self, input_list, callback, checksums_fix = False, errors_ignore = False):
    149                 result = LogParsingResult()
    150                
    151                 current_row = 1
    152                 last_row = None
    153                 for line in input_list:
    154                         nmea_sentence = self.parse_nmea_sentence(line, checksums_fix)
    155                         if nmea_sentence is None:
    156                                 result.error_add('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row))
    157                                 if not errors_ignore:
    158                                         result.succeeded(False)
    159                                         return result
    160                         else:
    161                                 nmea_sentence = nmea_sentence['nmea_sentence']
    162                                 if nmea_sentence.sentence_type == 'RMC':
    163                                         if last_row is not None:
    164                                                 callback(last_row)
    165                                         last_row = logdataset.LogDataset()
    166                                         last_row.datetime_set('{} {}'.format(nmea_sentence.datestamp, nmea_sentence.timestamp))
    167                                         last_row.gps_status_set(nmea_sentence.status)
    168                                         last_row.latitude_set(self._nmeaLatitudeToDecimalDegrees(nmea_sentence.lat, current_row))
    169                                         last_row.latitude_direction_set(nmea_sentence.lat_dir)
    170                                         last_row.longitude_set(self._nmeaLongitudeToDecimalDegrees(nmea_sentence.lon, current_row))
    171                                         last_row.longitude_direction_set(nmea_sentence.lon_dir)
    172                                         last_row.speed_over_ground_set(self._to_float(nmea_sentence.spd_over_grnd, current_row))
    173                                         last_row.course_over_ground_set(self._to_float(nmea_sentence.true_course, current_row))
    174                                         last_row.water_depth_set(None)
    175                                         last_row.water_temperature_set(None)
    176                                 elif nmea_sentence.sentence_type == 'DPT' and last_row is not None:
    177                                         last_row.water_depth_set(self._to_float(nmea_sentence.depth, current_row))
    178                                 elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
    179                                         last_row.water_temperature_set(self._to_float(nmea_sentence.temperature, current_row))
    180                         current_row += 1
    181                 if last_row is not None:
    182                         callback(last_row)
    183                 result.succeeded(True)
    184                 return result
    185 
    186         def _to_float(self, string, current_row):
    187                 try:
    188                         return float(string)
    189                 except ValueError as error:
    190                         try:
    191                                 return int(string)
    192                         except ValueError as error:
    193                                 print('INFO: Failed to convert value from line {} into numeric: {}\n      Message: {}'.format(current_row, string, error))
    194                                 return 0
    195 
    196         def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row):
    197                 if self._to_float(nmea_value, current_row) == 0:
    198                         return 0
    199 
    200                 matches = self._regex_nmea_position_latitude.match(nmea_value)
    201                 if matches is None:
    202                         print('INFO: Failed to convert latitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value))
    203                         return
    204                 decimalDegrees = self._to_float(matches.group(1), current_row)
    205                 decimalMinutes = self._to_float(matches.group(2), current_row)
    206                 return decimalDegrees + (decimalMinutes / 60.0)
    207 
    208         def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row):
    209                 if self._to_float(nmea_value, current_row) == 0:
    210                         return 0
    211 
    212                 matches = self._regex_nmea_position_longitude.match(nmea_value)
    213                 if matches is None:
    214                         print('INFO: Failed to convert longitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value))
    215                         return
    216                 decimalDegrees = self._to_float(matches.group(1), current_row)
    217                 decimalMinutes = self._to_float(matches.group(2), current_row)
    218                 return decimalDegrees + (decimalMinutes / 60.0)
    219 
    220 
    221         def _degreesDecimalToNmea(self, decimalDegrees):
    222                 degrees = int(math.floor(decimalDegrees))
    223                 minutes = 60.0 * (decimalDegrees - degrees)
    224                 return { 'degrees': degrees, 'minutes': minutes}
     222
     223    def gnuboat_read(
     224        self, input_list, callback, checksums_fix=False, errors_ignore=False
     225    ):
     226        result = LogParsingResult()
     227
     228        current_row = 1
     229        last_row = None
     230        for line in input_list:
     231            nmea_sentence = self.parse_nmea_sentence(line, checksums_fix)
     232            if nmea_sentence is None:
     233                result.error_add(
     234                    'INFO: Failed to parse nmea sentence ({}) at line {}'.
     235                    format(line.strip(), current_row)
     236                )
     237                if not errors_ignore:
     238                    result.succeeded(False)
     239                    return result
     240            else:
     241                nmea_sentence = nmea_sentence['nmea_sentence']
     242                if nmea_sentence.sentence_type == 'RMC':
     243                    if last_row is not None:
     244                        callback(last_row)
     245                    last_row = logdataset.LogDataset()
     246                    last_row.datetime_set(
     247                        '{} {}'.format(
     248                            nmea_sentence.datestamp, nmea_sentence.timestamp
     249                        )
     250                    )
     251                    last_row.gps_status_set(nmea_sentence.status)
     252                    last_row.latitude_set(
     253                        self._nmeaLatitudeToDecimalDegrees(
     254                            nmea_sentence.lat, current_row
     255                        )
     256                    )
     257                    last_row.latitude_direction_set(nmea_sentence.lat_dir)
     258                    last_row.longitude_set(
     259                        self._nmeaLongitudeToDecimalDegrees(
     260                            nmea_sentence.lon, current_row
     261                        )
     262                    )
     263                    last_row.longitude_direction_set(nmea_sentence.lon_dir)
     264                    last_row.speed_over_ground_set(
     265                        self._to_float(
     266                            nmea_sentence.spd_over_grnd, current_row
     267                        )
     268                    )
     269                    last_row.course_over_ground_set(
     270                        self._to_float(nmea_sentence.true_course, current_row)
     271                    )
     272                    last_row.water_depth_set(None)
     273                    last_row.water_temperature_set(None)
     274                elif nmea_sentence.sentence_type == 'DPT' and last_row is not None:
     275                    last_row.water_depth_set(
     276                        self._to_float(nmea_sentence.depth, current_row)
     277                    )
     278                elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
     279                    last_row.water_temperature_set(
     280                        self._to_float(nmea_sentence.temperature, current_row)
     281                    )
     282            current_row += 1
     283        if last_row is not None:
     284            callback(last_row)
     285        result.succeeded(True)
     286        return result
     287
     288    def _to_float(self, string, current_row):
     289        try:
     290            return float(string)
     291        except ValueError as error:
     292            try:
     293                return int(string)
     294            except ValueError as error:
     295                print(
     296                    'INFO: Failed to convert value from line {} into numeric: {}\n      Message: {}'
     297                    .format(current_row, string, error)
     298                )
     299                return 0
     300
     301    def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row):
     302        if self._to_float(nmea_value, current_row) == 0:
     303            return 0
     304
     305        matches = self._regex_nmea_position_latitude.match(nmea_value)
     306        if matches is None:
     307            print(
     308                'INFO: Failed to convert latitude position value from line {} into decimal degrees: {}'
     309                .format(current_row, nmea_value)
     310            )
     311            return
     312        decimalDegrees = self._to_float(matches.group(1), current_row)
     313        decimalMinutes = self._to_float(matches.group(2), current_row)
     314        return decimalDegrees + (decimalMinutes / 60.0)
     315
     316    def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row):
     317        if self._to_float(nmea_value, current_row) == 0:
     318            return 0
     319
     320        matches = self._regex_nmea_position_longitude.match(nmea_value)
     321        if matches is None:
     322            print(
     323                'INFO: Failed to convert longitude position value from line {} into decimal degrees: {}'
     324                .format(current_row, nmea_value)
     325            )
     326            return
     327        decimalDegrees = self._to_float(matches.group(1), current_row)
     328        decimalMinutes = self._to_float(matches.group(2), current_row)
     329        return decimalDegrees + (decimalMinutes / 60.0)
     330
     331    def _degreesDecimalToNmea(self, decimalDegrees):
     332        degrees = int(math.floor(decimalDegrees))
     333        minutes = 60.0 * (decimalDegrees - degrees)
     334        return {'degrees': degrees, 'minutes': minutes}
Note: See TracChangeset for help on using the changeset viewer.