您需要做的是定期轮询’session.next()’ – 这里的问题是您正在处理串行接口 – 您按照收到的顺序获得结果.由您来维护具有最新检索值的’current_value’.
如果您不轮询会话对象,最终您的UART FIFO将填满,无论如何您都不会获得任何新值.
考虑使用一个线程,不要等待用户调用gps_poll(),你应该轮询,当用户想要一个新值时,他们使用’get_current_value()’返回current_value.
在我的头顶,它可能是这样简单:
import threading
import time
from gps import *
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):
try:
while True:
self.current_value = self.session.next()
time.sleep(0.2) # tune this, you might not get values that quickly
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)
print gpsp.get_current_value()