summaryrefslogtreecommitdiff
path: root/gpspoller.py
blob: 6f7c19c6fe909aabcaef16c141232c93e7bfda3e (plain)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/python

# Copyright (C) 2007 by Jaroslaw Zachwieja
# Modified (C) 2012 by Tim Redfern
# Published under the terms of GNU General Public License v2 or later.
# License text available at http://www.gnu.org/licenses/licenses.html#GPL

import serial,string,threading,time,sys,random

class GpsPoller(threading.Thread):
	
	latitude = 0
	longitude = 0
	changed = False
	
	def __init__(self,port,test=False):
		self.test=test
		self.port=port
		self.gps = serial.Serial(port, 9600, timeout=1)
		threading.Thread.__init__(self)
		
	def check(self):
		if self.changed:
			self.changed=False
			return (self.latitude,self.longitude)
		else:
			return False

	def run(self):
		if self.test:
			print "GpsPoller: serving random data"
		else:	
			print "GpsPoller: serving data from",self.port
		try:
			while True:
				if self.test:
					self.latitude=random.random()*90
					self.longitude=random.random()*90
					self.changed=True
					time.sleep(0.5)
				else:
					line = self.gps.read(1)
					line = line+self.gps.readline()
					datablock = line.split(',') 

					if line[0:6] == '$GPRMC':
						latitude_in = string.atof(datablock[3])
						longitude_in = string.atof(datablock[5])
						altitude = string.atof(datablock[8])
						speed_in = string.atof(datablock[7])
						heading = string.atof(datablock[8])

						if datablock[4] == 'S':
							 latitude_in = -latitude_in
						if datablock[6] == 'W':
							 longitude_in = -longitude_in

						latitude_degrees = int(latitude_in/100)
						latitude_minutes = latitude_in - latitude_degrees*100

						longitude_degrees = int(longitude_in/100)
						longitude_minutes = longitude_in - longitude_degrees*100

						latitude = latitude_degrees + (latitude_minutes/60)
						longitude = longitude_degrees + (longitude_minutes/60)
						
						if latitude!=self.latitude or longitude!=self.longitude:
							self.latitude=latitude
							self.longitude=longitude
							self.changed=True
			
			
		except StopIteration:
			pass

	def __del__():
		self.gps.close()

if __name__ == '__main__':
	
	gpsp = GpsPoller(sys.argv[1])
	gpsp.start()
	while 1:
		# In the main thread, every 5 seconds print the current value
		time.sleep(0.1)
		check=gpsp.check()
		if check!=False:
			print "changed:",check[0],check[1]