0

I am a bit new to python and i'm trying to accomplish a task.

What I am trying to accomplish

I have this code which gathers GPS data from a thread in a while loop and I post that data to my webserver.

Problem

The problem here is, on first run the latitude/longitude is always zero and correct values come after that. The while loop fetches the gps coordinates a random amount of times from 5-10 and they are all written in my database.

This is not correct behavior since I just want ONE instance of results being written to the database at any point in time. I tried putting an IF statement in the while loop to say "If latitude > 0 upload results to database and break else continue looping but I seem to be getting the syntax wrong.

As you can see the code that post to my database is inside the while loop so all

try:  
    gpsp.start() # start it up
    print ' GPS'
    while True:


      print ' GPS reading'
      print 'latitude    ' , gpsd.fix.latitude
      print 'longitude   ' , gpsd.fix.longitude

      if gpsd.fix.latitude > 0:
        payload={'id':"P8",'lat':gpsd.fix.latitude,'lon':gpsd.fix.longitude}
      r= requests.post("http://my-server.com/Pi/Loc.php",data=payload)
      break
      elif gpsd.fix.latutde=0:


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."

Any assistance would be appreciated.

My issue is not "Capturing" the coordinates, however I'm looking for assistance in correcting the syntax to log just one record, I am aware the code I have shown is a bit incorrect, this is just what I have for now.

This is the result from running the code (I Fixed the indent and removed the if). There was actually many more lines but i deleted them for simplicity. I'm just trying to find a way to select the last one to my webserver

 GPS
 GPS reading
latitude     0.0
longitude    0.0
 GPS reading
latitude     **.292548333
longitude    **.379363333
 GPS reading
latitude     **.292548333
longitude    **.379363333
 GPS reading
latitude     **.292546667
longitude    **.379365
 GPS reading
latitude     **.292546667
longitude    **.379365
 GPS reading
latitude     **.292546667
longitude    **.379365
 GPS reading
latitude     **.292546667
longitude    **.379365

 GPS reading
latitude     **.292503333
longitude    **.379376667
 GPS reading
latitude     **.292498333
longitude    **.379376667
Grace
  • 89
  • 8
  • 5
    Your indentation is incorrect. Python relies heavily on indentation. You are also missing a statement under the `elif` entirely. And the `elif` condition is an assignment, not a comparison. – TigerhawkT3 Apr 12 '16 at 06:51
  • 2
    Most GPS systems need a few seconds to a few minutes to capture enough satellites in order to obtain a fix; so you should add a `time.sleep(10)` or something before your while loop in order to give sufficient time for the GPS to warm up. You also have `gpsp.start()`, but you are using `gpsd` everywhere. – Burhan Khalid Apr 12 '16 at 06:54
  • @TigerhawkT3 I'm aware the code is incomplete especially under elif, I was trying to find a way to achieve the task of just taking the last item instead of posting all – Grace Apr 12 '16 at 06:58
  • @BurhanKhalid Thank you for catching gpsp, also i'm aware of setting a sleep time, but right now I am just trying to upload one valid lat/lon into my database instead of 15 of them – Grace Apr 12 '16 at 06:59

2 Answers2

0

If you just want one result written, change your loop's condition:

try:
   gpsp.start()
except SomethingHere:
   print('Oops, GPS failed!')
   sys.exit()

while not gpsp.fix.latitude:
   time.sleep(4) # Pause till the GPS has obtained a fix

lat = gpsp.fix.latitude
lon = gpsp.fix.longitude

payload = {'vehic':"PJ048",'lat':lat,'lon':lon}

r = requests.post("http://my-server.com/Pi/Loc.php",data=payload)
r.raise_for_status()
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Thanks, for the most part it works fine but there are times where it still pushes more than one record in a second. Look at time stamp from database. `2016-04-12 03:12:14 2016-04-12 03:12:14 2016-04-12 03:12:14 2016-04-12 03:12:14` . Would is be because I'm calling the script every minute in a cron job? – Grace Apr 12 '16 at 10:57
  • Why don't you fix it at your server end to reject those records where the timestamp is already recorded, up to a second? – Burhan Khalid Apr 12 '16 at 11:22
  • It could be. Lets say the GPS is "cold". The CRON calls your script every minute for 3 consecutive minutes. All these instances are running, and waiting for the GPS to get "warm". As soon as it is "warm", all these instances will log their data and all three will have the same timestamp. – craigsparks Apr 12 '16 at 11:24
0

For your next issue(multiple scripts running), without having to change the server, you could remove your CRON entry, and run this from a service in /etc/init.d Adding a delay() method and another forever while loop :

try:
   gpsp.start()
except SomethingHere:
   print('Oops, GPS failed!')
   sys.exit()

def delay():
    time.sleep(60) # sleep 60 seconds


while True: 

    while not gpsp.fix.latitude:
       time.sleep(4) # Pause till the GPS has obtained a fix

    lat = gpsp.fix.latitude
    lon = gpsp.fix.longitude

    payload = {'vehic':"PJ048",'lat':lat,'lon':lon}

    r = requests.post("http://my-server.com/Pi/Loc.php",data=payload)
    r.raise_for_status()
    delay()
craigsparks
  • 134
  • 6
  • That's a good method however, The reason I actually loved the CRON method is. If for WHATEVER reason, a call failed and no data was logged for one minute, the cron the next minute would take care of that and probably no one would realize. However, having this in one service, I feel like if for whatever reason the machine restarts and the server doesnt get called (Is that possible?) there is no room for it to correct it's self – Grace Apr 12 '16 at 13:16
  • An init.d service will restart when the machine restarts (if configured to do so). You can still use a cron, but you will make things more complicated if you have more than one script running at a time like you already experienced. Perhaps you could read here how someone else needed cron job to see if a python script was running - [see it here](http://stackoverflow.com/questions/9223381/using-cron-job-to-check-if-python-script-is-running) – craigsparks Apr 12 '16 at 18:08
  • Im actually liking this, except that. if the connection fails. it wont continue, when its reestablished. Do you have a solution for this? – Grace Apr 16 '16 at 19:06