source: src/common/gnuboat_common/datahandler/loghandler.py@ bcaee05

debian/bullseye
Last change on this file since bcaee05 was 9af0638, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago

Created new python gnuboat_common package, with functions used by gnuboat and mapservice

  • Property mode set to 100644
File size: 8.6 KB
RevLine 
[ea6eba1]1 # -*- coding: utf-8 -*-
2'''
[9af0638]3 Copyright (C) 2016 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
[ea6eba1]4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17'''
18
[7b6d348]19import os
[ea6eba1]20import re
21import pynmea2
22import datetime
23from pytz import timezone
24import traceback
25import math
26
[9af0638]27from gnuboat_common.datahandler import logdataset
28
29class 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
[ea6eba1]50
51"""@class LogHandler
52"""
53class 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)
[7b6d348]81 self._nmea_file = open(os.path.join(self._log_directory, nmea_log_file), 'a', 0)
[ea6eba1]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
129 callback must be of a function wich excepts the LogDataset as a parameter.
130 """
[9af0638]131 def gnuboat_read_file(self, input_file_path, callback, checksums_fix = False, errors_ignore = False):
132 result = LogParsingResult()
133
[ea6eba1]134 # reading input file
135 try:
136 input_file = open(input_file_path, 'r')
137 except IOError as error:
[9af0638]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
146 callback must be of a function wich excepts the LogDataset as a parameter.
147 """
148 def gnuboat_read(self, input_list, callback, checksums_fix = False, errors_ignore = False):
149 result = LogParsingResult()
150
[ea6eba1]151 current_row = 1
152 last_row = None
[9af0638]153 for line in input_list:
[ea6eba1]154 nmea_sentence = self.parse_nmea_sentence(line, checksums_fix)
155 if nmea_sentence is None:
[9af0638]156 result.error_add('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row))
[ea6eba1]157 if not errors_ignore:
[9af0638]158 result.succeeded(False)
159 return result
[ea6eba1]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)
[9af0638]183 result.succeeded(True)
184 return result
[ea6eba1]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}
Note: See TracBrowser for help on using the repository browser.