Contents

Python gps / gpsd KeyError

Contents

I have been adding GPS logging to my Bicycle Dashcam. All of the example Python code (eg: https://gpsd.gitlab.io/gpsd/gpsd-client-example-code.html) I’ve found online throws this error after about a minute:

1
Exception has occurred: KeyError'el'File "example2.py", line 12, inwhile 0 == session.read():KeyError: 'el'

I’m not sure if this is a problem unique to my GPS receiver, but it regularly sends data that is not “class”:“TPV” (eg: “class”:“SKY”) - TPV is the data with coordinates, and whenever that happens, all the sample code throws a KeyError.

I’ve found the easiest way to fix this is to add a TRY/EXCEPT inside the forever loop, catch the KeyError expection, and PASS. Here is an adaptation of code I found on Stackoverflow that solves the problem - I’ve submitted it as an improvement, hopefully they accept my edits!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import threading
import time
from gps import *
from datetime import datetime

class GpsPoller(threading.Thread):

   def __init__(self):
       threading.Thread.__init__(self)
       self.session = gps(mode=WATCH_ENABLE)
       self.current_value = None

   def get_current_value(self):
       return self.current_value

   def run(self):
        while True: #moved the try INTO the forever loop, so pass from the except resumes collecting data
            try: 
                self.current_value = self.session.next()
                time.sleep(0.2) # tune this, you might not get values that quickly
            except KeyError as e: #catch the KerError, and return to the forever loop
                pass
            except StopIteration:
                pass

#if __name__ == '__main__':

gpsp = GpsPoller()
gpsp.start()
# gpsp now polls every .2 seconds for new data, storing it in self.current_value
while 1:
    # In the main thread, every 5 seconds print the current value
    time.sleep(5)
    value=gpsp.get_current_value()
    print(value) 

Update (May 6, 2023): I found a better solution: the gpsd-py3 library works great.