DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Magnus has posted 3 posts at DZone. View Full User Profile

PyS60: Bluetooth GPS Polling Class

11.16.2007
| 7653 views |
  • submit to reddit
        Threaded approach for reading NMEA data from a bluetooth GPS.

import thread, socket

class BTGPSPoller(object):
	def __init__(self, address):
		address, services = socket.bt_discover(address)
		self.target = (address, services.values()[0])
		self.active = True
		self.connected = False
		self.lock = thread.allocate_lock()
		self.sentances = list()
		
	def connect(self):
		if not self.connected:
			thread.start_new_thread(self.run, ())

	def run(self):
		print "BTGPSPoller thread activated"
		try:
			conn = socket.socket(socket.AF_BT, socket.SOCK_STREAM)
			conn.connect(self.target)
			self.connected = True
		except:
			print "Unable to connect"
		
		if self.connected:
			try:
				to_gps = conn.makefile("r", 0)
			except:
				print "Failure calling conn.makefile()"
			while self.active:
				#e32.ao_sleep(1)
				msg = None
				try:
					msg = to_gps.readline()
					if not msg == None and msg.startswith("$GPGGA"):
						gps_data = msg.split(",")
						if not gps_data[2] == "":
							self.lock.acquire()
							self.sentances.append(msg)
							if len(self.sentances) > 10:
								self.sentances.pop(0)
							self.lock.release()
				except:
					self.active = False

			try:
				to_gps.close()
				conn.close()
				self.connected = False
				print "Closed and disconnected"
			except:
				self.connected = False
				print "Unable to close"

	def disconnect(self):
		self.active = False
		print "Disconnecting from GPS"

	def getSentances(self):
		self.lock.acquire()
		l = self.sentances[:]
		self.lock.release()
		return l