You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

251 lines
11 KiB

  1. # The MIT License (MIT)
  2. #
  3. # Copyright (c) 2017 Tony DiCola for Adafruit Industries
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. # THE SOFTWARE.
  22. """
  23. `adafruit_gps`
  24. ====================================================
  25. GPS parsing module. Can parse simple NMEA data sentences from serial GPS
  26. modules to read latitude, longitude, and more.
  27. * Author(s): Tony DiCola
  28. Implementation Notes
  29. --------------------
  30. **Hardware:**
  31. * Adafruit `Ultimate GPS Breakout <https://www.adafruit.com/product/746>`_
  32. * Adafruit `Ultimate GPS FeatherWing <https://www.adafruit.com/product/3133>`_
  33. **Software and Dependencies:**
  34. * Adafruit CircuitPython firmware for the ESP8622 and M0-based boards:
  35. https://github.com/adafruit/circuitpython/releases
  36. """
  37. import time
  38. __version__ = "3.0.2"
  39. __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_GPS.git"
  40. # Internal helper parsing functions.
  41. # These handle input that might be none or null and return none instead of
  42. # throwing errors.
  43. def _parse_degrees(nmea_data):
  44. # Parse a NMEA lat/long data pair 'dddmm.mmmm' into a pure degrees value.
  45. # Where ddd is the degrees, mm.mmmm is the minutes.
  46. if nmea_data is None or len(nmea_data) < 3:
  47. return None
  48. raw = float(nmea_data)
  49. deg = raw // 100
  50. minutes = raw % 100
  51. return deg + minutes/60
  52. def _parse_int(nmea_data):
  53. if nmea_data is None or nmea_data == '':
  54. return None
  55. return int(nmea_data)
  56. def _parse_float(nmea_data):
  57. if nmea_data is None or nmea_data == '':
  58. return None
  59. return float(nmea_data)
  60. # lint warning about too many attributes disabled
  61. #pylint: disable-msg=R0902
  62. class GPS:
  63. """GPS parsing module. Can parse simple NMEA data sentences from serial GPS
  64. modules to read latitude, longitude, and more.
  65. """
  66. def __init__(self, uart):
  67. self._uart = uart
  68. # Initialize null starting values for GPS attributes.
  69. self.timestamp_utc = None
  70. self.latitude = None
  71. self.longitude = None
  72. self.fix_quality = None
  73. self.satellites = None
  74. self.horizontal_dilution = None
  75. self.altitude_m = None
  76. self.height_geoid = None
  77. self.velocity_knots = None
  78. self.speed_knots = None
  79. self.track_angle_deg = None
  80. def update(self):
  81. """Check for updated data from the GPS module and process it
  82. accordingly. Returns True if new data was processed, and False if
  83. nothing new was received.
  84. """
  85. # Grab a sentence and check its data type to call the appropriate
  86. # parsing function.
  87. sentence = self._parse_sentence()
  88. if sentence is None:
  89. return False
  90. data_type, args = sentence
  91. data_type = data_type.upper()
  92. if data_type == 'GPGGA': # GGA, 3d location fix
  93. self._parse_gpgga(args)
  94. elif data_type == 'GPRMC': # RMC, minimum location info
  95. self._parse_gprmc(args)
  96. return True
  97. def send_command(self, command, add_checksum=True):
  98. """Send a command string to the GPS. If add_checksum is True (the
  99. default) a NMEA checksum will automatically be computed and added.
  100. Note you should NOT add the leading $ and trailing * to the command
  101. as they will automatically be added!
  102. """
  103. self._uart.write('$')
  104. self._uart.write(command)
  105. if add_checksum:
  106. checksum = 0
  107. for char in command:
  108. checksum ^= ord(char)
  109. self._uart.write('*')
  110. self._uart.write('{:02x}'.format(checksum).upper())
  111. self._uart.write('\r\n')
  112. @property
  113. def has_fix(self):
  114. """True if a current fix for location information is available."""
  115. return self.fix_quality is not None and self.fix_quality >= 1
  116. def _parse_sentence(self):
  117. # Parse any NMEA sentence that is available.
  118. sentence = self._uart.readline()
  119. if sentence is None or sentence == b'' or len(sentence) < 1:
  120. return None
  121. sentence = str(sentence, 'ascii').strip()
  122. # Look for a checksum and validate it if present.
  123. if len(sentence) > 7 and sentence[-3] == '*':
  124. # Get included checksum, then calculate it and compare.
  125. expected = int(sentence[-2:], 16)
  126. actual = 0
  127. for i in range(1, len(sentence)-3):
  128. actual ^= ord(sentence[i])
  129. if actual != expected:
  130. return None # Failed to validate checksum.
  131. # Remove checksum once validated.
  132. sentence = sentence[:-3]
  133. # Parse out the type of sentence (first string after $ up to comma)
  134. # and then grab the rest as data within the sentence.
  135. delineator = sentence.find(',')
  136. if delineator == -1:
  137. return None # Invalid sentence, no comma after data type.
  138. data_type = sentence[1:delineator]
  139. return (data_type, sentence[delineator+1:])
  140. def _parse_gpgga(self, args):
  141. # Parse the arguments (everything after data type) for NMEA GPGGA
  142. # 3D location fix sentence.
  143. data = args.split(',')
  144. if data is None or len(data) != 14:
  145. return # Unexpected number of params.
  146. # Parse fix time.
  147. time_utc = int(_parse_float(data[0]))
  148. if time_utc is not None:
  149. hours = time_utc // 10000
  150. mins = (time_utc // 100) % 100
  151. secs = time_utc % 100
  152. # Set or update time to a friendly python time struct.
  153. if self.timestamp_utc is not None:
  154. self.timestamp_utc = time.struct_time((
  155. self.timestamp_utc.tm_year, self.timestamp_utc.tm_mon,
  156. self.timestamp_utc.tm_mday, hours, mins, secs, 0, 0, -1))
  157. else:
  158. self.timestamp_utc = time.struct_time((0, 0, 0, hours, mins,
  159. secs, 0, 0, -1))
  160. # Parse latitude and longitude.
  161. self.latitude = _parse_degrees(data[1])
  162. if self.latitude is not None and \
  163. data[2] is not None and data[2].lower() == 's':
  164. self.latitude *= -1.0
  165. self.longitude = _parse_degrees(data[3])
  166. if self.longitude is not None and \
  167. data[4] is not None and data[4].lower() == 'w':
  168. self.longitude *= -1.0
  169. # Parse out fix quality and other simple numeric values.
  170. self.fix_quality = _parse_int(data[5])
  171. self.satellites = _parse_int(data[6])
  172. self.horizontal_dilution = _parse_float(data[7])
  173. self.altitude_m = _parse_float(data[8])
  174. self.height_geoid = _parse_float(data[10])
  175. def _parse_gprmc(self, args):
  176. # Parse the arguments (everything after data type) for NMEA GPRMC
  177. # minimum location fix sentence.
  178. data = args.split(',')
  179. if data is None or len(data) < 11:
  180. return # Unexpected number of params.
  181. # Parse fix time.
  182. time_utc = int(_parse_float(data[0]))
  183. if time_utc is not None:
  184. hours = time_utc // 10000
  185. mins = (time_utc // 100) % 100
  186. secs = time_utc % 100
  187. # Set or update time to a friendly python time struct.
  188. if self.timestamp_utc is not None:
  189. self.timestamp_utc = time.struct_time((
  190. self.timestamp_utc.tm_year, self.timestamp_utc.tm_mon,
  191. self.timestamp_utc.tm_mday, hours, mins, secs, 0, 0, -1))
  192. else:
  193. self.timestamp_utc = time.struct_time((0, 0, 0, hours, mins,
  194. secs, 0, 0, -1))
  195. # Parse status (active/fixed or void).
  196. status = data[1]
  197. self.fix_quality = 0
  198. if status is not None and status.lower() == 'a':
  199. self.fix_quality = 1
  200. # Parse latitude and longitude.
  201. self.latitude = _parse_degrees(data[2])
  202. if self.latitude is not None and \
  203. data[3] is not None and data[3].lower() == 's':
  204. self.latitude *= -1.0
  205. self.longitude = _parse_degrees(data[4])
  206. if self.longitude is not None and \
  207. data[5] is not None and data[5].lower() == 'w':
  208. self.longitude *= -1.0
  209. # Parse out speed and other simple numeric values.
  210. self.speed_knots = _parse_float(data[6])
  211. self.track_angle_deg = _parse_float(data[7])
  212. # Parse date.
  213. if data[8] is not None and len(data[8]) == 6:
  214. day = int(data[8][0:2])
  215. month = int(data[8][2:4])
  216. year = 2000 + int(data[8][4:6]) # Y2k bug, 2 digit date assumption.
  217. # This is a problem with the NMEA
  218. # spec and not this code.
  219. if self.timestamp_utc is not None:
  220. # Replace the timestamp with an updated one.
  221. # (struct_time is immutable and can't be changed in place)
  222. self.timestamp_utc = time.struct_time((year, month, day,
  223. self.timestamp_utc.tm_hour,
  224. self.timestamp_utc.tm_min,
  225. self.timestamp_utc.tm_sec,
  226. 0,
  227. 0,
  228. -1))
  229. else:
  230. # Time hasn't been set so create it.
  231. self.timestamp_utc = time.struct_time((year, month, day, 0, 0,
  232. 0, 0, 0, -1))