Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reading GPS Data with Python #50

Open
cmurray3 opened this issue Apr 19, 2024 · 0 comments
Open

Reading GPS Data with Python #50

cmurray3 opened this issue Apr 19, 2024 · 0 comments
Labels
documentation Improvements or additions to documentation

Comments

@cmurray3
Copy link
Contributor

These are my notes for capturing GPS data in Ubuntu using Python. You'll need a GPS receiver for this to work.

  • This is not an assignment...just information that may be useful for some student projects.

Installation

  1. Install a GPS Daemon (gpsd)

    sudo apt-get install gpsd gpsd-clients 
    
  2. You'll need to disable a systemd service that gpsd installs. This service has systemd listen on a local socket and run gpsd when clients connect to it, however it will also interfere with other gpsd instances that are manually run (like in this guide). You will need to disable the gpsd systemd service by running the following commands:

    sudo systemctl stop gpsd.socket
    sudo systemctl disable gpsd.socket
    

    NOTE: disable means gpsd.socket will not be re-started on reboot.

    To re-enable gpsd.socket:

    ```
    sudo systemctl enable gpsd.socket
    sudo systemctl start gpsd.socket
    ```
    
  3. Manually start gpsd and point it at the GPS breakout on the USB serial adapter port:

    sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock
    

    Change /dev/ttyUSB0 to another port if necessary.

    FIXME -- How can we make this run automatically on startup?

  4. Test:

    cgps -s
    

Python Code

I have two scripts in my notes, and I'm not sure which one works best (if at all). So, I'm posting both here...if you experiment with these please let me know which script is preferred (or if you have a new script, please post that).

Version 1: adafruit_gps_test.py:

import gps

# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)

while True:
	try:
		report = session.next()
		# Wait for a 'TPV' report and display the current time.
		# To see all report data, uncomment the line below:
		# print report
		'''
		<dictwrapper: {
			'epx': 8.537, 
			'epy': 11.432, 
			'epv': 34.73, 
			'ept': 0.005, 
			'lon': -78.758323243, 
			'eps': 0.65, 
			'epc': 0.76, 
			'lat': 42.99768934, 
			'track': 158.1103, 			<-- heading?  Course over ground.
			'mode': 3, 
			'time': '2018-01-20T21:27:21.000Z', 
			'device': '/dev/ttyUSB0', 
			'climb': 0.032, 	[m/s]
			'alt': 183.44, 		[m]
			'speed': 0.032, 	[m/s]
			'class': 'TPV'
			}

			2018-01-20T21:27:21.000Z
		
		'''
		# See http://www.catb.org/gpsd/gpsd_json.html for report explanation.
		
		
		[lat, lon, alt, hdg] = ['', '', '', '']
		
		if report['class'] == 'TPV':
			#if hasattr(report, 'time'):
			#	print report.time
			if hasattr(report, 'lon'):	
				lon = report.lon
			if hasattr(report, 'lat'):
				lat = report.lat
			if hasattr(report, 'alt'):
				alt = report.alt
			if hasattr(report, 'track'):
				hdg = report.track
			print lat, lon, alt, hdg
			
	except KeyError:
		pass
	except KeyboardInterrupt:
		quit()
	except StopIteration:
		session = None
		print "GPSD has terminated"

Version 2: gps_test.py:

from gps import *
# import gps
from time import *
import time
import threading
 
import random  
  
class GpsPoller(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)

		# Listen on port 2947 (gpsd) of localhost
		# session = gps.gps("localhost", "2947")
		# session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
	
		self.session = gps(mode=WATCH_ENABLE)
		self.current_value = None
		self.report = {'lat': None, 'lon': None, 'alt': None, 'track': None}
		
		self.running = True # Setting the thread running to true
	
	'''
	def get_gps_report(self):
		return self.report
		# return (self.lat, self.lon, self.alt, self.track)
	'''
		
	def run(self):
		while gpsp.running:
			self.current_value = self.session.next()
			
			# Wait for a 'TPV' report and display the current time.
			# To see all report data, uncomment the line below:
			# print self.report
			'''
			<dictwrapper: {
				'epx': 8.537, 
				'epy': 11.432, 
				'epv': 34.73, 
				'ept': 0.005, 
				'lon': -78.758323243, 
				'eps': 0.65, 
				'epc': 0.76, 
				'lat': 42.99768934, 
				'track': 158.1103, 			<-- heading?  Course over ground.
				'mode': 3, 
				'time': '2018-01-20T21:27:21.000Z', 
				'device': '/dev/ttyUSB0', 
				'climb': 0.032, 	[m/s]
				'alt': 183.44, 		[m]
				'speed': 0.032, 	[m/s]
				'class': 'TPV'
				}
	
				2018-01-20T21:27:21.000Z
			
			'''
			# See http://www.catb.org/gpsd/gpsd_json.html for report explanation.
						
			if self.current_value['class'] == 'TPV':
				[lat, lon, alt, track] = [None, None, None, None]
		
				#if hasattr(self.report, 'time'):
				#	print self.report.time
				if hasattr(self.current_value, 'lon'):	
					lon = self.current_value.lon
				if hasattr(self.current_value, 'lat'):
					lat = self.current_value.lat
				if hasattr(self.current_value, 'alt'):
					alt = self.current_value.alt
				if hasattr(self.current_value, 'track'):
					hdg = self.current_value.track
				
				lat = random.random()
				
				# print lat, lon, alt, hdg
				# [self.lat, self.lon, self.alt, self.track] = [lat, lon, alt, track]
				self.report = {'lat': lat, 'lon': lon, 'alt': alt, 'track': track}
			
			

class roverControl():
	def __init__(self):
		
		# gpsp.get_current_value() 
		
		try:
			while 1:
				# In the main thread, every 5 seconds print the current value
				# print gpsp.get_gps_report() 
				# print gpsp.lat
				print gpsp.report
				# print len(gpsp.report)
				#if hasattr(gpsp.report, 'lat'):
				#	print gpsp.report.lat
				if ('lat' in gpsp.report):
					print gpsp.report['lat']
				time.sleep(5)
				
	
		except (KeyboardInterrupt, SystemExit): # when you press ctrl+c
			self.shutdown()
				
		print "Done.\nExiting."

	def shutdown(self):
		print "\nKilling Thread..."
		gpsp.running = False
		gpsp.join() # wait for the thread to finish what it's doing
		
	
if __name__ == '__main__':
	try:
		gpsp = GpsPoller() # create the thread
		gpsp.start() # start it up

		roverControl()
	except:
		print "failure"
	
	'''
	print "\nKilling Thread..."
	gpsp.running = False
	gpsp.join() # wait for the thread to finish what it's doing
	'''


	
	'''
	try:
	while True:
	#It may take a second or two to get good data
	#print gpsd.fix.latitude,', ',gpsd.fix.longitude,'  Time: ',gpsd.utc
	
	os.system('clear')
	
	print
	print ' GPS reading'
	print '----------------------------------------'
	print 'latitude    ' , gpsd.fix.latitude
	print 'longitude   ' , gpsd.fix.longitude
	print 'time utc    ' , gpsd.utc,' + ', gpsd.fix.time
	print 'altitude (m)' , gpsd.fix.altitude
	print 'eps         ' , gpsd.fix.eps
	print 'epx         ' , gpsd.fix.epx
	print 'epv         ' , gpsd.fix.epv
	print 'ept         ' , gpsd.fix.ept
	print 'speed (m/s) ' , gpsd.fix.speed
	print 'climb       ' , gpsd.fix.climb
	print 'track       ' , gpsd.fix.track
	print 'mode        ' , gpsd.fix.mode
	print
	print 'sats        ' , gpsd.satellites
	
	time.sleep(5) #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."
	'''
@cmurray3 cmurray3 added the documentation Improvements or additions to documentation label Apr 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant