gps.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/bin/python
  2. # http://stackoverflow.com/questions/28867795/reading-i2c-data-from-gps/31010266
  3. import time
  4. import json
  5. import smbus
  6. import logging
  7. BUS = None
  8. address = 0x42
  9. gpsReadInterval = 0.1
  10. LOG = logging.getLogger()
  11. # GUIDE
  12. # http://ava.upuaut.net/?p=768
  13. GPSDAT = {
  14. 'strType': None,
  15. 'fixTime': None,
  16. 'lat': None,
  17. 'latDir': None,
  18. 'lon': None,
  19. 'lonDir': None,
  20. 'fixQual': None,
  21. 'numSat': None,
  22. 'horDil': None,
  23. 'alt': None,
  24. 'altUnit': None,
  25. 'galt': None,
  26. 'galtUnit': None,
  27. 'DPGS_updt': None,
  28. 'DPGS_ID': None
  29. }
  30. def connectBus():
  31. global BUS
  32. BUS = smbus.SMBus(1)
  33. def parseResponse(gpsLine):
  34. global lastLocation
  35. gpsChars = ''.join(chr(c) for c in gpsLine)
  36. if "*" not in gpsChars:
  37. return False
  38. gpsStr, chkSum = gpsChars.split('*')
  39. gpsComponents = gpsStr.split(',')
  40. gpsStart = gpsComponents[0]
  41. if (gpsStart == "$GNGGA"):
  42. chkVal = 0
  43. for ch in gpsStr[1:]: # Remove the $
  44. chkVal ^= ord(ch)
  45. if (chkVal == int(chkSum, 16)):
  46. for i, k in enumerate(
  47. ['strType', 'fixTime',
  48. 'lat', 'latDir', 'lon', 'lonDir',
  49. 'fixQual', 'numSat', 'horDil',
  50. 'alt', 'altUnit', 'galt', 'galtUnit',
  51. 'DPGS_updt', 'DPGS_ID']):
  52. GPSDAT[k] = gpsComponents[i]
  53. print(gpsChars)
  54. print(json.dumps(GPSDAT, indent=2))
  55. def readGPS():
  56. c = None
  57. response = []
  58. try:
  59. while True: # Newline, or bad char.
  60. c = BUS.read_byte(address)
  61. if c == 255:
  62. return False
  63. elif c == 10:
  64. break
  65. else:
  66. response.append(c)
  67. parseResponse(response)
  68. except IOError:
  69. time.sleep(0.5)
  70. connectBus()
  71. except (Exception) as e:
  72. print(e)
  73. LOG.error(e)
  74. connectBus()
  75. while True:
  76. readGPS()
  77. time.sleep(gpsReadInterval)