Показания GPS не меняются в зависимости от движущегося устройства

Я разрабатываю приложение в Raspberry Pi, чтобы использовать его в качестве трекера местоположения. Я использую neo-6m GPS через интерфейс USB, чтобы получить данные о местоположении в Raspberry Pi. Для этого я настраиваю GPSD, чтобы он указывал на устройство USB-Serial. (См. Инструкции)

Следующий скрипт Python опрашивает демон GPSD и отправляет данные о местоположении в родительский процесс через доменное гнездо Unix:

#!/usr/bin/python
import os
from gps import *
from time import *
import time
import threading
import socket
import math
t1, t2 = socket.socketpair()
gpsd = None #seting the global variable


host = "localhost"
port = 8888
class GpsPoller(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    global gpsd #bring it in scope
    gpsd = gps(mode=WATCH_ENABLE,host=host,port=port) #starting the stream of info
    self.current_value = None
    self.running = True #setting the thread running to true

  def run(self):
    print("%%%%%%%GPS RUN")
    global gpsd
    while self.running:
      gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
      time.sleep(3)


def poll_gps(socket):
  print('GPS POLL')
  gpsp = GpsPoller() # create the thread
  gpsp.start()
  try:
    while True:
      #It may take a second or two to get good data
      #print gpsd.fix.latitude,', ',gpsd.fix.longitude,'  Time: ',gpsd.utc
      #print 'latitude    ' , gpsd.fix.latitude
      #print 'longitude   ' , gpsd.fix.longitude
      if gpsd.fix.latitude is not None and gpsd.fix.longitude is not None and not math.isnan(gpsd.fix.longitude ) and not math.isnan(gpsd.fix.latitude ) and gpsd.fix.latitude != 0.0 and  gpsd.fix.longitude != 0.0 :

            gps_str='{0:.8f},{1:.8f}'.format(gpsd.fix.latitude, gpsd.fix.longitude)
            dict_str="{'type' : 'gps', 'value' : '"+gps_str+"'}"
            dict_str_new="{'type' : 'gps', 'value' : '"+str(gpsd.fix.latitude)+","+str(gpsd.fix.longitude)+"'}"
            print("GPS123_OLD" +dict_str)
            print("GPS123_NEW" +dict_str_new)
            if socket == None:
                print("GOT GPS VALUE")
                sys.exit(0)
            socket.sendall(dict_str+'\n')                        
      else:
            print('%%%%%%%%%%%%%%%%%%GPS reading returnd None!')     

      time.sleep(3) #set to whatever

  except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    print "\nKilling Thread..."
    gpsp.running = False
    gpsp.join() # wait for the thread to finish what it's doing
  print "Done.\nExiting."

if __name__ == '__main__':
    poll_gps(None)    

Когда я запускаю этот код и перемещаю настройку raspberry pi на 1 километр, я вижу новые отчетливые значения в широте, напечатанные в консоли. Но когда я строю эти значения, я вижу, что все эти места находятся в начальной точке. т.е. все значения сгруппированы вокруг одной и той же начальной точки. Я не вижу четкого пути к точке в 1 км.

Чтобы проверить, связана ли проблема с моим кодом, я установил программное обеспечение navit в raspberry pi и указал его демону GPSD. Когда я использовал navit для построения своего пути, он правильно показывал мой прогресс на карте. Итак, я пришел к выводу, что проблема с моим кодом.

Может кто-нибудь взглянуть и сообщить мне, если есть какие-либо проблемы с моим кодом

1 ответ

Решение

Я разобрался в проблеме. В методе "run" класса "GpsPoller" я вызываю спящий вызов. Кажется, что эта задержка заставляет клиента Python отставать от демона GPSD в получении данных о местоположении, поставленных в очередь демоном GPSD. Я просто снял сон и начал вовремя получать правильные места.

  def run(self):
    print("%%%%%%%GPS RUN")
    global gpsd
    while self.running:
      gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
      #time.sleep(3) REMOVE/COMMENT THIS LINE TO GET CORRECT GPS VALUES
Другие вопросы по тегам