gps.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # http://stackoverflow.com/questions/28867795/reading-i2c-data-from-gps/31010266
  4. import time
  5. import json
  6. import smbus
  7. import logging
  8. import pynmea2
  9. BUS = None
  10. address = 0x42
  11. gpsReadInterval = 1
  12. LOG = logging.getLogger()
  13. def connectBus():
  14. global BUS
  15. BUS = smbus.SMBus(1)
  16. def parseResponse(gpsBytes):
  17. global lastLocation
  18. #gpsLine = "".join(map(chr, gpsBytes))
  19. #gpsLine = "".join([chr(byte) for byte in gpsBytes])
  20. gpsLine = "".join([chr(byte) for byte in gpsBytes])
  21. if "*" not in gpsLine:
  22. return False
  23. print(gpsLine)
  24. gpsObject = pynmea2.parse(gpsLine)
  25. print(gpsObject)
  26. # logs
  27. lt = time.asctime( time.localtime(time.time()) )
  28. with open('/home/alarm/gps.log', 'a') as f:
  29. f.write(lt+' : '+gpsLine+'\n')
  30. def readGPS():
  31. c = None
  32. response = []
  33. try:
  34. while True: # Newline, or bad char.
  35. c = BUS.read_byte(address)
  36. if c == 255:
  37. return False
  38. elif c == 10:
  39. break
  40. else:
  41. #print(c)
  42. response.append(c)
  43. parseResponse(response)
  44. except IOError:
  45. time.sleep(0.5)
  46. connectBus()
  47. except (Exception) as e:
  48. print("Exception")
  49. print(e)
  50. LOG.error(e)
  51. connectBus()
  52. while True:
  53. readGPS()
  54. time.sleep(gpsReadInterval)
  55. #readGPS()