#!/usr/bin/env python
# -*- coding: utf-8 -*-

# http://stackoverflow.com/questions/28867795/reading-i2c-data-from-gps/31010266

import time
import json
import smbus
import logging
import pynmea2

BUS = None
address = 0x42
gpsReadInterval = 1
LOG = logging.getLogger()


def connectBus():
    global BUS
    BUS = smbus.SMBus(1)

def parseResponse(gpsBytes):
    global lastLocation
    #gpsLine = "".join(map(chr, gpsBytes))
    #gpsLine = "".join([chr(byte) for byte in gpsBytes])
    gpsLine = "".join([chr(byte) for byte in gpsBytes])


    if "*" not in gpsLine:
        return False

    print(gpsLine)
    gpsObject = pynmea2.parse(gpsLine)
    print(gpsObject)

    # logs
    lt = time.asctime( time.localtime(time.time()) )
    with open('/home/alarm/gps.log', 'a') as f:
        f.write(lt+' : '+gpsLine+'\n')

def readGPS():
    c = None
    response = []
    try:
        while True: # Newline, or bad char.
            c = BUS.read_byte(address)
            if c == 255:
                return False
            elif c == 10:
                break
            else:
                #print(c)
                response.append(c)

        parseResponse(response)

    except IOError:
        time.sleep(0.5)
        connectBus()

    except (Exception) as e:
        print("Exception")
        print(e)
        LOG.error(e)

connectBus()
while True:
    readGPS()
    time.sleep(gpsReadInterval)
#readGPS()
