def __init__(self, sessionID, userID): time.sleep(1) #LET SLEEP FOR SECURE STARTUP, CAN BE LOWERED self.port = "/dev/ttyUSB0" self.obd = OBD_IO.OBDPort(self.port, 1, 5) print("Restarting GPS...") os.system("sudo killall gpsd") print("OBD connected to: " + self.obd.getPortName()) if(self.obd.getPortName() == "/dev/ttyUSB0"): ## Connect next ttyUSB to GPS os.system("sudo gpsd /dev/ttyUSB1 -F /var/run/gpsd.sock") else: os.system("sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock") time.sleep(5) # LET GPS ESTABLISH FIX try: ## IF GPS FAILS TO LOAD, RESTART self.session = gps.gps("localhost", "2947") except: os.system("sudo killall gpsd") if(self.obd.getPortName() == "/dev/ttyUSB0"): os.system("sudo gpsd /dev/ttyUSB1 -F /var/run/gpsd.sock") else: os.system("sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock") self.session = gps.gps("localhost", "2947") self.session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) self.UID = userID self.sessionID = sessionID + 1 self.nrOfResponses = 0 self.timeGone = 0 self.seq = "" self.startLogging()
def __init__(self, **kwargs): GPSlistenerBase.__init__(self, **kwargs) self.gpsd = None interface = kwargs['interface'].split(',') if len(interface) != 1 and len(self.interface) != 2: raise BadConfigParams self.watch_in = None try: import gps except ImportError: raise BadConfigImport params = { 'mode': gps.WATCH_ENABLE|gps.WATCH_JSON|gps.WATCH_SCALED, 'verbose': 0 } if len(interface) == 2: params['host'], params['port'] = interface[1].split(':') print " gps.gps(", params, ")" try: self.debug(1, "Connecting to GPSd...") self.gpsd = gps.gps(**params) except Exception as e: raise BadConfigOther("%s: %s" % (type(e).__name__, str(e))) self.watch_in = gobject.io_add_watch(self.gpsd.sock, gobject.IO_IN, self.packet)
def __init__(self, gps_infos): """Creates GPS_SESSION.""" _LOG.debug('Create GPSReceiver.') self.result = gps_infos file_ = None try: file_ = open(os.path.join(constants.CONFIG_PATH, 'gpsdevice')) devices_ = [dev.strip() for dev in file_.readlines() if not dev.startswith('#')] _LOG.debug('available GPS interfaces: %s', devices_) if len(devices_) != 1: _LOG.warn('Check your gpsdevices config file.') _LOG.debug("init GPS session with '%s'", 'gpsd ' + devices_[0]) cmd = 'whereis gpsd' p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out = p.communicate()[0].split(' ') _LOG.debug("out: %s", out) cmd = out[1] + " " + devices_[0] _LOG.debug(cmd) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) self.GPS_SESSION = gps.gps() time.sleep(0.5) except Exception, e: self.GPS_SESSION = None _LOG.warning('Could not initialize GPS session in postion.py: %s', e) if p is not None: _LOG.error(p.communicate())
def run(self): session = gps.gps(mode=gps.WATCH_ENABLE) while self.iterate(): gpsinfo = None satellites = None maxtries = 10 try: while not gpsinfo and maxtries: report = session.next() if report['class'] == 'TPV': gpsinfo = dict(report) gpsinfo['satellites'] = satellites break elif report['class'] == 'SKY': sats_used = len([ s for s in report.get('satellites', {}) if s['used'] == True]) sats_avail = len([ s for s in report.get('satellites', {})]) satellites = (sats_used, sats_avail) maxtries -= 1 except StopIteration: pass if gpsinfo: self.set_data(gpsinfo) if self.sleep(1): break session.close()
def __init__(self,startstop): self.daemon = gps.gps(host="localhost",port=2947,mode=gps.WATCH_ENABLE|gps.WATCH_RAW|gps.WATCH_NMEA, verbose=0) gobject.io_add_watch(self.daemon.sock, gobject.IO_IN, self.handle_response) gobject.timeout_add(2000,self.check_counter) self.prev = 0 self.counter = 0 self.start = True if startstop == "start" else False
def gps_mode(): # Listen on port 2947 (gpsd) of localhost try: session = gps.gps("localhost", "2947") except: return 0 session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) i = 0 while i < 100: try: report = session.next() # Wait for a 'TPV' report and get mode if report['class'] == 'TPV': if report.mode == 1: return 1 elif report.mode == 2: return 2 elif report.mode == 3: return 3 except StopIteration: return 0 # Timeout return -1
def run(self): print "run" #return True try: self.__gpsd_daemon_handler = gps.gps( host = GPSD_HOST, port = GPSD_PORT, mode = gps.WATCH_ENABLE|gps.WATCH_JSON|gps.WATCH_SCALED, verbose = None ) self.watch(self.__gpsd_daemon_handler, GPS_DEV) return True except SocketError: self.gps_disable() #self.__gps_on = False #self.toggle_gps(self.gpsState) w = gtk.MessageDialog( type=gtk.MESSAGE_ERROR, flags=gtk.DIALOG_DESTROY_WITH_PARENT, buttons=gtk.BUTTONS_OK ) w.set_title('socket error') w.set_markup( "could not connect to gpsd socket. make sure gpsd is running." ) w.run() w.destroy() return False except KeyboardInterrupt: self.gps_disable() #self.gpsState.set_active(False) #self.toggle_gps(self.gpsState) return False
def init(): # socket setting global receiver global sender receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) receiver.bind(("", RECEIVE_PORT)) sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sender.bind(("", SEND_PORT)) # arduino setting global arduino try: arduino = serial.Serial(SERIAL_PORT, 9600) except: arduino = serial.Serial(SERIAL_PORT2, 9600) arduino.flushInput() # thread setting global receiver_thread global sender_thread global gps_thread receiver_thread = threading.Thread(target=receive_thread) sender_thread = threading.Thread(target=send_thread) gps_thread = gps_drive_class() # GPS setting global gpsd gpsd = gps.gps("127.0.0.1", "2947") gpsd.stream(gps.WATCH_ENABLE|gps.WATCH_NEWSTYLE)
def __init__(self): threading.Thread.__init__(self) print threading.current_thread() # Listen on port 2947 (gpsd) of localhost self.session = gps.gps("localhost", "2947") self.session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) self.current_value = {'error': 'GPS error...'}
def __init__(self): logging.debug("[%s]: Initializing GPSDataUpdater" % (__file__)) threading.Thread.__init__(self) # initialize python gps modul try: self.session = gps.gps() self.session.next() self.session.stream() except: logging.warning("[%s]: Failed to initialize GPSDataUpdater" \ % (__file__)) return # set exit flag as false self.exitflag = False self.latitude = None self.longitude = None self.utctime = None self.altitude = None self.speed = None # initialize lock for data acess self.accessdatalock = threading.Semaphore(1) # set thread to daemon threading.daemon = True
def get_gps_data(self): """ Return GPS fix mode, latitude and longitude """ # Listen on port 2947 (gpsd) of localhost try: session = gps.gps("localhost", "2947") except: return 0 # setup session session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) # read stream until receiving a 'TPV' packet i = 0 while i < 100: try: report = session.next() # Wait for a 'TPV' report and get mode if report['class'] == 'TPV': if report.mode == 1: return (1, None, None) elif report.mode == 2: return (2, report.lat,report.lon) elif report.mode == 3: return (3, report.lat,report.lon) except StopIteration: return (0, None, None) # Timeout - GPS respond NOT received return (-1,None,None)
def get_gps(): console = logging.getLogger('console') console.debug('Getting location from gps') session = None try: session = gps.gps() session.stream(gps.WATCH_ENABLE|gps.WATCH_NEWSTYLE) #if len(session.satellites) == 0: # log.debug('Gps has no satellites') # return for i in range(0,5): console.debug('Try %s' % i) report = session.next() if 'lat' in report: console.debug('Got location from gps\n%s' % report) session.close() return {'latitude' : report['lat'], 'longitude' : report['lon'], 'accurancy' : report['alt'], 'provider' : 'gps'} except StopIteration: pass except: pass console.debug('Gps not available') if session: session.close() return
def __init__(self): if gps is None or not useGPS: self.g = None else: self.g = gps.gps() self.g.poll() self.g.stream()
def gpsdPoller(currentGPS): ''' @type currentGPS multiprocessing.Manager dict manager @arg currentGPS store relavent pieces of up-to-date GPS info ''' import gps gpsd = gps.gps() gpsd.poll() gpsd.stream() try: while True: gpsd.poll() if gpsd.fix.mode > 1: #1=NO_FIX, 2=FIX, 3=DGPS_FIX lat = gpsd.fix.latitude lng = gpsd.fix.longitude alt = gpsd.fix.altitude #print 'latitude ' , lat #print 'longitude ' , lng #TODO do we want to use the GPS time in any way? #print 'time utc ' , gpsd.utc,' + ', gpsd.fix.time #print 'altitude (m)' , alt currentGPS['lat'] = lat currentGPS['lng'] = lng currentGPS['alt'] = alt else: print "Waiting for a GPS fix." #TODO timeout lat/lng/alt values if too old...? sleep(GPS_FREQUENCY) except KeyboardInterrupt: print "Got KeyboardInterrupt in gpsdPoller, returning." return
def __init__(self): global session # Bring it in scope 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.running = True # Setting the thread running to true
def check_gps(): #listen on port 2947 (gpsd) of localhost session = gps.gps("localhost","2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) for i in range(5): 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 if report['class']=='TPV': if hasattr(report,'time'): gps_time = report.time if report['class']=='TPV': if hasattr(report,'lon'): gps_longitude = report.lon if report['class']=='TPV': if hasattr(report,'lat'): gps_latitude = report.lat except KeyError: pass except KeyboardInterrupt: quit() except StopIteration: session=None print "GPSD has terminated" gps_complete = " Date and Time in UTC: " + str(gps_time) + " Longitude: " + str(gps_longitude) + " Latitude: " + str(gps_latitude) return gps_complete
def gpsdConnect(self): try: flags= gps.WATCH_ENABLE | gps.WATCH_PPS self.session = gps.gps(mode=flags) print "GPSD contacted" except: print "GPSD not running. Retrying.."
def gps_logger( gps_data, results ): session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) time.sleep(1) while True: try: report = session.next() # Wait for a 'TPV' report and get the information if report['class'] == 'TPV': if hasattr(report, 'time'): timestamp = report.time if hasattr(report, 'lat'): latitude = report.lat if hasattr(report, 'lon'): longitude = report.lon # hack timestamp, # from '2015-03-30T16:09:29.000Z' to '2015-03-30T16:09:29' gps_data.put( [ device_id, timestamp[0:19], latitude, longitude ] ) except: print 'unable to get GPS data'
def getGpsPosition(): session = gps.gps() session.stream(0x80) try: # enable extended output # session.verbose = 1 i = 0 while i < MAX_GPS_TRIES: r = session.next() logging.debug("GPS query result: %s", r) if session.fix.mode > 1: logging.info("Fetched GPS data after %s cycles.", i) return session.fix time.sleep(GPS_TRY_SLEEP) i = i + 1 logging.warn("Can't fetch GPS data after %s cycles.", i) return None finally: session.close()
def run(waypoint_filename=None, variation=None, threshold=None): r''' variation > 0 for W, < 0 for E. ''' output_filename = Config.get('gps_nav', 'output') if waypoint_filename is None: waypoint_filename = Config.get('gps_nav', 'waypoints') if variation is None: variation = Config.getfloat('gps_nav', 'variation') if threshold is None: threshold = Config.getfloat('gps_nav', 'threshold') Logger.info("started waypoints: %r, outputting to: %r", waypoint_filename, output_filename) Logger.info("variation=%r, threshold=%r", variation, threshold) try: with open(waypoint_filename) as waypoints: with contextlib.closing(gps.gps()) as session: with open(output_filename, 'wt', 1) as outfile: for waypoint in waypoints: latitude, longitude = \ (float(x) for x in waypoint.split()) Logger.info("new waypoint: %s, %s", latitude, longitude) navigate_to(latitude, longitude, session, outfile, variation, threshold) Logger.info("done!") outfile.write("1000.0\n") # signal to stop except Exception, e: Logger.exception("%s: %s", e.__class__.__name__, e) raise
def main(): # Listen on port 2947 (gpsd) of localhost session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) while True: try: report = unwrap( session.next() ) if args.full: # Send whole report debug_print(report) stomp_send(json.dumps(report)) elif not rate_limited(): # Filter 'TPV' reports for interesting values if report['class'] == 'TPV': to_send = { a:report[a] for a in [u'time',u'lat',u'lon',u'alt',u'track',u'speed',u'climb'] } debug_print(to_send) stomp_send(json.dumps(to_send)) except KeyError: pass except KeyboardInterrupt: exit() except StopIteration: session = None print("GPSD terminated")
def __init__(self): threading.Thread.__init__(self) self.gpsd = gps.gps(mode=gps.WATCH_ENABLE) #starting the stream of info self.current_value = None self.running = True #setting the thread running to true self.daemon = True self.last = None
def __init__(self): threading.Thread.__init__(self) #self.session = gps(mode=WATCH_ENABLE) # Listen on port 2947 (gpsd) of localhost self.session = gps.gps("localhost", "2947") self.session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) self.current_value = None self.running = True
def init(self): from BBBgps import RoboGPS os.system("echo BB-UART4 > /sys/devices/bone_capemgr.9/slots") os.system("gpsd /dev/ttyO4 -F /var/run/gpsd.sock") session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) gps1 = RoboGPS() gps1.read(session)
def __init__(self): import gps threading.Thread.__init__(self) self.gpsd = gps.gps() # self.gpsd.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) self.gpsd.stream(gps.WATCH_ENABLE) self.running = False
def _setup(self): """ attempt to connect to device if fixed is off """ if self._conf['fixed']: return # static, do nothing try: self._gpsd = gps.gps('127.0.0.1',self._conf['port']) self._gpsd.stream(gps.WATCH_ENABLE) except socket.error as e: raise RuntimeError(e)
def __init__(self): # os.system("sudo killall gpsd") # os.system("sudo gpsd /dev/tty/AMA0 -F /var/run/gpsd.sock") self.gpssession = gps.gps("localhost", "2947") self.gpssession.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) self.lat = 0 self.alt = 0 self.lon = 0
def __init__(self): threading.Thread.__init__(self) global session #bring it in scope session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) self.running = True #setting the thread running to true
def toggle(self): #xprint "vivo 3" global session session = gps.gps() if self.running: self.running = 0 else : self.running = 1
import datetime import time import serial import pynmea2 import gps from gpsd_poller import GpsPoller t1_0 = time.clock() t2_0 = datetime.datetime.now() #sudo gpsd /dev/ttyUSB1 -F /var/run/gpsd.sock gpsd_ses = gps.gps("localhost", "2947") gpsd_ses.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) while True: try: report = gpsd_ses.next() if report['class'] == 'TPV': if hasattr(report, 'lat'): print report.lat, ' ', report.lon if hasattr(report, 'time'): print report.time except KeyError: pass except KeyboardInterrupt: quit() except StopIteration: gpsd_ses = None print "GPSD has terminated"
#! /usr/local/bin/python #-*- coding: utf-8 -*- import gps, os, time g = gps.gps(mode=gps.WATCH_NEWSTYLE) while 1: os.system('clear') g.poll() if gps.PACKET_SET: g.stream() print print ' GPS reading' print '----------------------------------------' print 'latitude ' , g.fix.latitude print 'longitude ' , g.fix.longitude print 'time utc ' , g.utc,' + ', g.fix.time print 'altitude ' , g.fix.altitude print 'epc ' , g.fix.epc print 'epd ' , g.fix.epd print 'eps ' , g.fix.eps print 'epx ' , g.fix.epx print 'epv ' , g.fix.epv print 'ept ' , g.fix.ept print 'speed ' , g.fix.speed print 'climb ' , g.fix.climb print 'track ' , g.fix.track print 'mode ' , g.fix.mode print print 'sats ' , g.satellites time.sleep(1)
from gps import gps gps = gps() localZone = gps.getTimeZone() print("Time zone here is: " + str(localZone))
def __init__(self): threading.Thread.__init__(self) global gpsd #bring it in scope gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.current_value = None self.running = True #setting the thread running to true
def test_start(): curMode = Startup.Drone.State.connect testFail = 0 xapikey = {"Content-Type":"application/json; charset=utf-8","X-API-Key":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVkZW50aWFsX2lkIjoiY3JlZGVudGlhbHxHTk5nbUxuaTlYM1p3UlRYTU9sMnFmS0o1Z0xLIiwiYXBwbGljYXRpb25faWQiOiJhcHBsaWNhdGlvbnxuOW41QmtZc0JhNkFvM3NBUkpHeXlVYWxZUUVZIiwib3JnYW5pemF0aW9uX2lkIjoiZGV2ZWxvcGVyfDJ6b2JiN3loeGVZNHFrQzNQUngwWkhLTXoyMzgiLCJpYXQiOjE0NzExMjY1NDJ9.v4STUtbJa3uJZFsJLpWZRgUYoyz1X6BxKW8kokerjCg"} try: #Start GPS p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gpsfake' in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) if 'run-fake-gps' in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) if 'gpsd' in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) subprocess.Popen('./run-fake-gps.sh', shell=True, stderr=subprocess.STDOUT) time.sleep(5) #Access GPS gpsReady = False gpsd = gps.gps(mode=gps.WATCH_ENABLE) while not gpsReady: print "Waiting for GPS..." # Read the GPS state gpsd.next() # Wait for GPS lock if (gpsd.valid & gps.LATLON_SET) != 0: lat = str(gpsd.fix.latitude) lon = str(gpsd.fix.longitude) alt = str(gpsd.fix.altitude) ground_speed = str(gpsd.fix.speed) heading = str(gpsd.fix.track) gpstime = str(gpsd.fix.time) curMode = str(gpsd.fix.mode) gpsReady = True #breakout except socket.error: print "Error: gpsd service does not seem to be running, plug in USB GPS, run fake-gps-data.sh or run set 'test' flag" sys.exit(1) barometer = '28.4' log_perct = '31.2' bogeyid = '37849329' drone_mode = "follow-me" battery_chrg= '11.2' cur_status= "warning" print lat print lon print alt print ground_speed print heading print time airconnect = Connect() airflight = Flight() airtelemetry = Telemetry() airconnect.set_Timeout(16) airconnect.set_XAPIKey(xapikey) Ret = airconnect.connect() if Ret: airconnect.get_SecureToken() if Globals.myToken == "": testFail = 1 try: flightID = airflight.create_FlightPoint (5,lat,lon,Public.on,Notify.on) if len(flightID) != 35: testFail = 1 myPilotID = airflight.get_PilotID() if len(myPilotID) != 30: testFail = 1 except: print flightID print myPilotID testFail = 1 print "Telemetry..." testCount = 0 response = airtelemetry.post_Telemetry(flightID,lat,lon,alt,ground_speed,heading,barometer,cur_status,battery_chrg,drone_mode,bogeyid,log_perct) if len(response) < 24: testFail = 1 testCount = 18 print "No Telemetry..." else: print response while testCount < 18: gpsReady = False while not gpsReady: print "Waiting for GPS..." # Read the GPS state gpsd.next() # Wait for GPS lock if (gpsd.valid & gps.LATLON_SET) != 0: lat = str(gpsd.fix.latitude) lon = str(gpsd.fix.longitude) alt = str(gpsd.fix.altitude) ground_speed = str(gpsd.fix.speed) heading = str(gpsd.fix.track) gpstime = str(gpsd.fix.time) curMode = str(gpsd.fix.mode) gpsReady = True #breakout response = airtelemetry.post_Telemetry(flightID,lat,lon,alt,ground_speed,heading,barometer,cur_status,battery_chrg,drone_mode,bogeyid,log_perct) testCount += 1 if len(response) < 14: testFail = 1 testCount = 18 print "No Telemetry..." else: print response Ret = airflight.end_Flight(flightID) if Ret == False: testFail = 1 Ret = airflight.delete_Flight(flightID) if Ret == False: testFail = 1 try: flightID = airflight.create_FlightPoint (2,lat,lon,Public.on,Notify.on) except: print "flight creation execption..." flights = airflight.get_FlightList(myPilotID) if flights == "": testFail = 1 try: airflight.cmd_KillFlights(myPilotID) except: testFail = 1 #clean up p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gpsfake' in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) if 'run-fake-gps' in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) if 'gpsd' in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) return testFail
import math import gps import time session = gps.gps("127.0.0.1", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) def gpsdis(): while True: try: time.sleep(0.5) raw_data = session.next() return (raw_data.lat, raw_data.lon) except KeyError: pass except KeyboardInterrupt: quit() except StopIteration: session = None print("No incoming data from the GPS module") def distance(x1, y1, x2, y2): return (math.sqrt(((y1 - y2)**2) + ((x1 - x2)**2))) def run(): for i in range(2):
import gps gs = gps.gps("localhost", "2947") gs.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) for i in range(0, 10): report = gs.next() print(report)
''' Read gps cordinates from gpsd @organization: Steelsquid @author: Andreas Nilsson @contact: [email protected] @license: GNU Lesser General Public License v2.1 @change: 2013-10-25 Created ''' import steelsquid_utils import thread import gps import math gpsd = gps.gps(mode=gps.WATCH_ENABLE) def _thread(): ''' Thread read from gps ''' while True: try: gpsd.next() except: steelsquid_utils.shout() def connected(): '''
def gps_logger(output_directory): """ GPS Data Logger """ global SKY, TPV global HOLD global GPS_NUM_SAT, GPS_NUM_USED hold_lat = [] hold_lon = [] hold_alt = [] config = util.read_config() # Create the output directory if not os.path.isdir(output_directory): os.mkdir(output_directory) # Listen on port 2947 (gpsd) of localhost session = gps.gps(mode=gps.WATCH_ENABLE) # Open the output file timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M") with open(os.path.join(output_directory,timestamp+"_gps.csv"), "w") as gps_output: gps_output.write("%s %s %s *\n" % (config['time'], "VERSION", json.dumps({"class": "VERSION", "version": util.DATA_API}))) gps_output.write("%s %s %s *\n" % (config['time'], config['class'], json.dumps(config))) while not util.DONE: # GPS report = session.next() # To see all report data, uncomment the line below #print(report) if report['class'] == 'TPV': obj = nmea.tpv_to_json(report) # Add Sat Metrics obj['num_sat'] = GPS_NUM_SAT obj['num_used'] = GPS_NUM_USED obj['hold'] = HOLD TPV = obj elif report['class'] == 'SKY': obj = nmea.sky_to_json(report) # Add Time obj['time'] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ") (GPS_NUM_USED, GPS_NUM_SAT) = nmea.calc_used(obj) SKY = obj else: continue # Log the Data if 'time' in obj: gps_output.write("%s %s %s *\n" % (obj['time'], obj['class'], json.dumps(obj))) # Short Circuit the rest of the checks if HOLD == -1: continue if obj['class'] == 'TPV' and 'lat' in obj and 'lon' in obj and 'time' in obj: if HOLD > 0: hold_lat.append(report.lat) hold_lon.append(report.lon) if 'alt' in report: hold_alt.append(report.alt) HOLD -= 1 elif HOLD == 0: with open(os.path.join(output_directory,timestamp+"_marks.csv"), "a") as mark: mark_obj = { "class": "MARK", "lat": statistics.mean(hold_lat), "lon": statistics.mean(hold_lon), "num_sat": GPS_NUM_SAT, "num_used": GPS_NUM_USED, "time": obj['time'], "memo": MEMO, } if len(hold_alt) > 0: mark_obj['alt'] = statistics.mean(hold_alt) mark.write("%s %s %s *\n" % (mark_obj['time'], mark_obj['class'], json.dumps(mark_obj))) hold_lat = [] hold_lon = [] hold_alt = [] HOLD = -1
def main(): """ The Main function of this script. """ args = _parse_arguments() util.log_init("gcs_%s.txt" % util.get_latest_log("latest_gcs.txt"), util.log_level[args.level]) shared.AGENT_ID = 'GCS' shared.CURRENT_ALGORITHM = args.algorithm util.log_info("AGENT_ID = %s" % shared.AGENT_ID) util.log_info("Algorithm: %s" % shared.CURRENT_ALGORITHM) util.log_info("Agent type: Ground station.") fparam = args.param ser = serial.Serial(args.xbee, 230400) xbee = comm.xbee_init(ser) util.log_info("Xbee initialized.") gpsd = gps.gps() # in some cases, the gpsd need to be flushed and reset gps_thread = GNSS(gpsd) gps_thread.start() util.log_info('GNSS running.') # This dictionary should keep the <offset> consistant with <cmd_list>. # It is useful for multi-to-one mapping. All the keys are lower-cased, # the first key is the native one, others are considered alias, and are # only for conveinience usage. key_dict = { # <key> <offset> 'p': -4, # set parameters 's': -3, # set HOME ORIGIN 'o': -2, # send origin 't': -1, # send rendezvous 'r': 0, # RTL command 'l': 1, # land command 'b': 2, # lift command 'e': 3, # exit command 'c': 4, # clear rendezvous } cmd_list = [ # <command string> <key> <description> # -----------------Positive Index----------------- ['CTR,RTL ', 'r', 'Exit algorithms at run and RTL'], # 0 ['CTR,LAND', 'l', 'Exit algorithms at run and LAND'], # 1 ['CTR,LIFT', 'b', 'Initiate takeoff.'], # 2 ['CTR,EXIT', 'e', 'Exit takeoff when on the ground.'], # 3 ['CLR_RDV ', 'c', 'Clear rendezvous coordinates'], # 4 # -----------------Negative Index----------------- ['"None" ', 'p', 'Update parameters'], # -4 ['"None" ', 's', 'Set HOME ORIGIN coordinates'], # -3 ['ORG,<pack>', 'o', 'Send HOME ORIGIN coordinates'], # -2 ['TAR,<pack>', 't', 'Send rendezvous coordinates'], # -1 ] # get keyboard file descrpter from stdin and save current terminal attribute # then turn into cbreak style, without terminal echo # See: https://docs.python.org/2/faq/library.html?highlight=read keyboard = sys.stdin old_attr = termios.tcgetattr(keyboard) new_attr = termios.tcgetattr(keyboard) new_attr[3] = new_attr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(keyboard, termios.TCSANOW, new_attr) old_flags = fcntl.fcntl(keyboard, fcntl.F_GETFL) fcntl.fcntl(keyboard, fcntl.F_SETFL, old_flags) # | os.O_NONBLOCK) key = None while True: # main loop try: time.sleep(.05) key = keyboard.read(1) # read only one key if key in key_dict: # valid key if key_dict[key] >= 0: # positive value: send command util.log_info("Sending command: '%s'" % cmd_list[key_dict[key]][0].strip(' ')) comm.xbee_broadcast(xbee, cmd_list[key_dict[key]][0].strip(' ')) else: # negative value: send coordinates or parameters # TODO(Q.Yuan): try to get automated broadcasting if key_dict[key] == -1: _broadcast_rendezvous(gpsd, xbee) elif key_dict[key] == -2: _broadcast_origin(xbee) elif key_dict[key] == -3: _set_home_origin(gpsd) elif key_dict[key] == -4: _update_parameter(xbee, fparam) else: # not a valid key, print help print "\n---- Command List ----\nCommand:\tKey:\tDescription" for idx in range(0, len(cmd_list)): print '%s\t%s\t%s' % (cmd_list[idx][0], cmd_list[idx][1], cmd_list[idx][2]) except IOError: pass except KeyboardInterrupt: break # clean up gps_thread.stop() while gps_thread.is_alive(): util.log_info('Waiting for GNSS to shutdown') gps_thread.join(3) util.log_info('GNSS shutdown.') xbee.halt() ser.close() util.log_info("Xbee and serial closed.") # restore previous terminal attribute termios.tcsetattr(keyboard, termios.TCSAFLUSH, old_attr) fcntl.fcntl(keyboard, fcntl.F_SETFL, old_flags)
#Import of the GPS Lib import gps shipjourney_gps = gps.gps("I do not have a Server, it could be 127.0.0.1", "Using the Standartport 2974") shipjourney_gps.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) while True: try: tellmewhere = shipjourney_gps.next() print tellmewhere except KeyError: quit() except StopIteration: shipjourney_gps = None print("GPS are not here anymore, please try again")
# MAIN START INLOCSYNC = False DONE = False RESTART = True VERSION = "#v9" CURRENT = {} TEMP = 0 MARK = False MEMO = "" GPS_STATUS = 0 ACC_STATUS = False LIDAR_STATUS = False # Listen on port 2947 (gpsd) of localhost SESSION = gps.gps("localhost", "2947") SESSION.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) # Web Server httpd = HTTPServer((HOST_NAME, PORT_NUMBER), MyHandler) T3 = threading.Thread(name="W", target=web_server, args=(httpd, )) T3.start() # Make sure we have a time sync TIMESTAMP = wait_for_timesync(SESSION) print(TIMESTAMP) try: T1 = threading.Thread(name="G",
"call fake pastor", "preconds": ["fake pastor responds to post asking you to call him"], "add": ["talking to fake pastor"], "delete": ["fake pastor responds to post asking you to call him"] }, { "action": "post on facebook asking for help", "preconds": ["you conform to societal pressures"], "add": ["fake pastor responds to post asking you to call him"], "delete": [] }, { "action": "give fake pastor money", "preconds": ["you have money"], "add": ["fake pastor has your money"], "delete": ["you have money"] }] } if __name__ == '__main__': # Use GPS to solve the problem formulated above. actionSequence = [ gps(problem['initial'], problem['goal'], problem['actions']), gps(problem['initial'], [problem['goal'][1], problem['goal'][0]], problem['actions']), ] # Print the solution, if there is one. if actionSequence is not None: for action in actionSequence: print(action) else: print('plan failure...')
def __init__(self): CarPiThread.__init__(self, None) self._gps = gps(mode=WATCH_ENABLE)
#!env python import pdb import gps file = '/tmp/nmea.kml' session = gps.gps(host="localhost", port="2947") session.stream(flags=gps.WATCH_JSON) for report in session: if report['class'] == 'TPV' and 'lat' in report: latitude = report['lat'] longitude = report['lon'] altitude = report['alt'] speed_in = report['speed'] heading = report['track'] speed = int(speed_in * 1.852) range = ((speed / 100) * 350) + 650 tilt = ((speed / 120) * 43) + 30 if speed < 10: range = 200 tilt = 30 heading = 0 output = """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.0"> <Placemark> <name>%s km/h</name>
'delete': ['c on table', 'space on table2'] }, { 'action': 'move c from b to table2', 'preconds': ['space on c', 'space on table2', 'c on b'], 'add': ['c on table2', 'space on b'], 'delete': ['c on b', 'space on table2'] }, { 'action': 'move c from a to table2', 'preconds': ['space on c', 'space on table2', 'c on a'], 'add': ['c on table2', 'space on a'], 'delete': ['c on a', 'space on table2'] } ##### END ] } if __name__ == '__main__': # Use GPS to solve the problem formulated above. actionSequence = gps(problem['initial'], problem['goal'], problem['actions']) # Print the solution, if there is one. if actionSequence is not None: for action in actionSequence: print(action) else: print('plan failure...')
def __init__(self, resolution=(1280, 720), title="Test dashcam"): """ This is where we go bob ross on the frames Happy little mistakes """ # We also need to initialize the class we inherited for some reason. super(DashCamData, self).__init__(name='py.prutt', outputs=2) self._lock = Lock() self.inputs[0].supported_formats = {mmal.MMAL_ENCODING_I420} self.width, self.height = (resolution) self.resolution = resolution self.dashcam_title = title # We use this to hold the text backgrounds self.dashcam_overlay_bg_image = None self.dashcam_title_img = None # And this for the actual text data self.dashcam_overlay_text_image = None # Threads and stuff self.dashcam_overlay_text_thread = None # Set bar height pixels self.bar_height = 25 self.bottom_bar_bg = None # Calculate the position of the bottom bar where we keep important text # such as the date and time, and the ridiculous speeds in which we are # traveling with. These are very advanced arithmetics - data is (x, y) self.bottom_bar_position = (0, self.height - self.bar_height) # We set the font upfront. self.__font = ImageFont.truetype("/usr/share/fonts/game_over.ttf", 50) # In order to determine how big our background box for the # dashcam title will be we need to cheat to get it. dashcam_title_bg_size = self.__font.getsize(self.dashcam_title) # Now we add a bit on both axis to have margins so that # the title doesn't look cramped. dashcam_title_bg_width = dashcam_title_bg_size[0] + 10 dashcam_title_bg_height = dashcam_title_bg_size[1] + 5 self.dashcam_title_image = Image.new( 'RGBA', (dashcam_title_bg_width, dashcam_title_bg_height), (255, 255, 255, 0)) title_box_draw = ImageDraw.Draw(self.dashcam_title_image) title_box_draw.rectangle( ((0, 0), (dashcam_title_bg_width, dashcam_title_bg_height)), (0, 0, 0, 128)) # Draw our cool dashcam title here. title_box_draw.text((5, -5), self.dashcam_title, font=self.__font) self.bottom_bar_bg = Image.new('RGBA', (self.width, self.bar_height), (255, 255, 255, 0)) # Start painting the bottom bar draw = ImageDraw.Draw(self.bottom_bar_bg) # Draw a rectangle as wide as the resolution permits # And 25 pixels high and make it black and an opacity of 128 draw.rectangle(((0, 0), (self.width, self.bar_height)), (0, 0, 0, 128)) # Initialize GPS self.__gps = gps(mode=WATCH_ENABLE | WATCH_NEWSTYLE) self.__gps.next() self.__gps_thread = None self.__mc_client = Client(('127.0.0.1', 11211)) # Set first speed so we don't print # nan as first value self.__current_speed = 0 # This might be implemented later self.__bearing = None
# Copyright (C) 2017 Sean D'Epagnier # # This Program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either # version 3 of the License, or (at your option) any later version. # automatically set system clock to gps time if available import os, sys, time while True: while True: try: import gps gpsd = gps.gps(mode=gps.WATCH_ENABLE) #starting the stream of info break except: time.sleep(3) while True: try: gpsd.next() except KeyboardInterrupt: exit(1) except: break if len(gpsd.utc): date, t = gpsd.utc[:-5].split('T') print('Setting date to gps time', date, t)
def __init__(self, hardware_id, latitude=0, longitude=0, altitude=0): GPS.__init__(self, hardware_id) self.latitude = latitude self.longitude = longitude self.altitude = altitude self.gpsd = gps.gps(mode=gps.WATCH_ENABLE) # start the stream of info
target_azimuth=target_azimuth, tolerance=5, min_successes=10) show_image(sense, image=SH_CHECKMARK) sense.show_message("Altitude: %d" % target_altitude, text_colour=SH_COLORS["red"]) find_altitude(sense, target_altitude=target_altitude, tolerance=5, min_successes=10) show_image(sense, image=SH_CHECKMARK) # If we got here, we're ON TARGET! show_image(sense, image=SH_ONTARGET, flash=20, pause=3, clear=True) # By this point, we've found the object and the display is off. # If we click the joystick button, though, wake up and start over # again. Or maybe we want to shake the device and shutdown the system. wait_for_command(sense) except (KeyboardInterrupt, Exception) as e: # On any kind of error, be sure to turn off the LEDs and the GPS. sense.clear() gps.gps(mode=gps.WATCH_DISABLE) # Print a traceback so we can figure out what went wrong, unless it was # keyboard interrupt (CTRL-C, presumably from the user) if not type(e) == KeyboardInterrupt: print traceback.format_exc()
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 if report['class'] == 'TPV': if hasattr(report, 'time'): print(report.time) except KeyError: pass except KeyboardInterrupt: quit() except StopIteration: session = None print("GPSD has terminated")
#import smbus import time from datetime import datetime import RPi.GPIO as GPIO import requests import json import serial import os import struct import gps, os, time time.sleep(3) #This section deals with GPS session = gps.gps() #os.system('clear') print ' GPS reading' print '----------------------------------------' print 'latitude ' , session.fix.latitude print 'longitude ' , session.fix.longitude print 'time utc ' , session.utc, session.fix.time print 'altitude ' , session.fix.altitude #print 'eph ' , session.fix.eph print 'epv ' , session.fix.epv print 'ept ' , session.fix.ept print 'speed ' , session.fix.speed print 'climb ' , session.fix.climb print ' Satellites (total of', len(session.satellites) , ' in view)' for i in session.satellites: print '\t', i
def record(): # Listen on port 2947 (gpsd) of localhost session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) timestr = time.strftime("%Y%m%d-%H%M%S") outputfile = '/home/pi/pyobd-pi/outputDRIVE-'+timestr+'.txt' o = OBD_Recorder('/home/pi/pyobd-pi/log/', logitems) o.sensorlist o.connect() if not o.is_connected(): print("Not connected to OBDII") if o.is_connected(): logOBD,displayOBD=o.report_OBDdata() #obdName,obdValue,obdUnit=o.report_OBDdata() print(logOBD) #print(obdName+obdValue+obdUnit) #print("hello world, record") #o.record_data() try: fp = open(outputfile, 'r') except IOError: fp = open(outputfile, 'w') filepath = outputfile with open(outputfile, "a") as myfile: myfile.write("System Time,RPM,MPH,Throttle,Load,Fuel Status,"); myfile.write("Sat time,lat,long,alt,sat speed, X,Y,Z\n") 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) flushcounter=0 # flushing RAM to file write periodically if o.is_connected(): logOBD,displayOBD=o.report_OBDdata() #print("OBD Data \n "+displayOBD) print(displayOBD) myfile.write(logOBD)###jwg if report['class'] == 'TPV': flushcounter +=1 if hasattr(report, 'time'): print("SAT TIME (GMT)= " + str(report.time)) myfile.write(str(report.time)+",") if hasattr(report, 'lat'): print(" LAT = " + str(report.lat)) myfile.write(str(report.lat)+",") if hasattr(report, 'lon'): print(" LON = " + str(report.lon)) myfile.write(str(report.lon)+",") if hasattr(report, 'alt'): print(" ALT = " + str(report.alt)) myfile.write(str(report.alt)+" ft,") if hasattr(report, 'speed'): print(" SPEED = " + str("{:.1f}".format(report.speed))) myfile.write(str("{:.1f}".format(report.speed)+" mph,")) #print(report.speed * gps.MPS_TO_KPH) #print("\n") myfile.write(' G (calibrated) ' + str("{:.2f}".format(accel_value(chan0.value,0))) + ',' + str("{:.2f}".format(accel_value(chan1.value,1)))+ ',' + str("{:.2f}".format(accel_value(chan2.value,2))) ) myfile.write("\n") print(' Raw ADC Value: ', chan0.value, ',',chan1.value,',',chan2.value) print(' ADC Voltage: ' + str(chan0.voltage) + ','+ str(chan1.voltage)+','+str(chan2.voltage)) print(' G (calibrated) ' + str("{:.2f}".format(accel_value(chan0.value,0))) + ',' + str("{:.2f}".format(accel_value(chan1.value,1)))+ ',' + str("{:.2f}".format(accel_value(chan2.value,2))) ) print('---Event Complete') print("\n") if flushcounter ==60: #flushing RAM to file periodically fp.flush() #time.sleep(3) #os.fsync(fp) #time.sleep(3) print("flush to file") flushcounter=0 else: print("no Time-Position-Velocity(TPV) report\n\n\n\n\n\n\n\n") print('---Event Complete\n') myfile.write("\n") except KeyError: pass except KeyboardInterrupt: # all this is leaving last buffer uncommitted...why? #decider = input("Do you want to quit?") #if decider == "y": # fp.flush() #time.sleep(15) #wait for file write complete so we don't miss data #fp.close() # os.fsync(fp) # time.sleep(15) # connectandship() ###ships file on quit, should move out of main() # quit() #else: return except StopIteration: session = None print("GPSD has terminated")
def __init__(self): Thread.__init__(self) self.gps_listener = gps.gps(mode=gps.WATCH_ENABLE) self.active = True
def __init__(self): self.session = gps.gps("localhost", "2947") self.session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) thread.start_new_thread(self.update, ())
def initHardware(self): self.get_logger().info('initHardware...') self.gpsd = gps.gps(host='127.0.0.1', port=4000, verbose=1, mode=gps.WATCH_ENABLE|gps.WATCH_NEWSTYLE) self.get_logger().info('initHardware.')
def __init__(self): self.session = gps.gps('localhost', '2947') self.session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
}, { 'action': 'move c from b to table', 'preconds': ['space on c', 'space on table', 'c on b'], 'add': ['c on table', 'space on b'], 'delete': ['c on b'] }] } if __name__ == '__main__': # This turns on detailed logging for the GPS "thought" process. # logging.basicConfig(level=logging.DEBUG) print('1.2 a...') # Use GPS to solve the problem formulated above. actionSequenceA = gps(problem['initialA'], problem['goalA'], problem['actions']) # Print the solution, if there is one. if actionSequenceA is not None: for action in actionSequenceA: print(action) else: print('plan failure...') actionSequenceB = gps(problem['initialB'], problem['goalB'], problem['actions']) # Print the solution, if there is one. print('1.2 b...') if actionSequenceB is not None: for action in actionSequenceB:
def __init__(self): self.session = gps.gps("localhost", "2947") self.session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
def process(self): gpss = [] #get list of all attached gps units all_gps_list = gps_list() print "Total # GPS Units Found:", len(all_gps_list) #start all gps units start_all_gps() #connect via python for n in range(len(all_gps_list)): port = str(2947 + n) print "port", port gpss.append(gps.gps(host="localhost", port=port)) print "starting_gps:", gpss[n] #returncode = call(start_gps, shell=True) time.sleep(1) gpss[n].next() gpss[n].stream() #print 'Satellites (total of', len(gpss[n].satellites) , ' in view)' #time.sleep(1) while True: avg_latitude = 0.0 avg_longitude = 0.0 avg_altitude = 0.0 avg_satellites = 0 avg_active_satellites = 0 avg_track = 0.0 avg_speed = 0.0 try: for n in range(len(all_gps_list)): for x in xrange(1, self.samples): #os.system("clear") #while ActiveSatelliteCount(gpss[n].satellites) < 4: # print "Acquiring at least 6 GPS Satellites..." # print 'Satellites (total of', len(gpss[n].satellites) , ' in view)' # print "Number of acquired satellites: ", ActiveSatelliteCount(gpss[n].satellites) # time.sleep(1) # os.system("clear") # gpss[n].next() # gpss[n].stream() gpss[n].next() gpss[n].stream() #test data #gpss[n].fix.latitude = 53.32055555555556 + (random.random() * 0.00005) #gpss[n].fix.longitude =-1.7297222222222221 + (random.random() * 0.00005) #print "READING GPS:", n, " ", x #print "-------------" #print 'latitude ' , gpss[n].fix.latitude #print 'longitude ' , gpss[n].fix.longitude #print 'mode:', gpss[n].fix.mode #print 'track: ', gpss[n].fix.track #print 'time utc ' , gpss[n].utc, gpss[n].fix.time #print 'altitude ' , gpss[n].fix.altitude #print 'epx ', gpss[n].fix.epx #print 'epv ', gpss[n].fix.epv #print 'ept ', gpss[n].fix.ept #print 'epc ', gpss[n].fix.epc #print 'epd ', gpss[n].fix.epd #print 'eps ', gpss[n].fix.eps #print "speed ", gpss[n].fix.speed #print "climb " , gpss[n].fix.climb #print #print 'Satellites (total of', len(gpss[n].satellites) , ' in view)' #for i in gpss[n].satellites: # print '\t', i #print "Active satellites used: ", ActiveSatelliteCount(gpss[n].satellites) avg_latitude = (avg_latitude + gpss[n].fix.latitude) avg_longitude = (avg_longitude + gpss[n].fix.longitude) avg_altitude = (avg_altitude + gpss[n].fix.altitude) avg_track = (avg_track + gpss[n].fix.track) avg_speed = (avg_speed + gpss[n].fix.speed) avg_active_satellites = ( avg_active_satellites + ActiveSatelliteCount(gpss[n].satellites)) avg_satellites = (avg_satellites + len(gpss[n].satellites)) time.sleep(.2) #print "Averaging....", (x*len(all_gps_list)) self.latitude = (avg_latitude / (x * len(all_gps_list))) self.longitude = (avg_longitude / (x * len(all_gps_list))) #print "total sats:", self.active_satellites self.active_satellites = (avg_active_satellites / (x * len(all_gps_list))) self.track = (avg_track / (x * len(all_gps_list))) self.speed = (avg_speed / (x * len(all_gps_list))) self.altitude = (avg_altitude / (x * len(all_gps_list))) self.satellites = (avg_satellites / (x * len(all_gps_list))) #time.sleep(1) #print 'Avg latitude : ' , self.latitude, " ", abs(self.latitude - gpss[n].fix.latitude) #print 'Avg longitude: ' , self.longitude, " ", abs(self.longitude - gpss[n].fix.longitude) #print 'Avg Active Satellites: ' , self.active_satellites #print "Distance: ", round((lldistance((self.latitude, self.longitude), (gpss[n].fix.latitude, gpss[n].fix.longitude)) * 3.28084), 4), " feet" #time.sleep(5) except: #time.sleep(1) pass
def setup(): # Listen on port 2947 (gpsd) of localhost session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) wait=0 tryAttempt=0 ## first get initial location ... wait until you get a report try: report = session.next() if report['class'] == 'TPV': if hasattr(report, 'time'): time = report.time if hasattr(report, 'latitude'): latitude = report.latitude if hasattr(report, 'longitude'): longitude = report.longitude if hasattr(report,'altitude'): altitude=report.altitude if hasattr(report,'speed'): speed=report.speed oldNorthing, oldEasting, oldZone = latLongToUTM(latitude,longitude) currentNorthing = oldNorthing currentEasting = oldNorthing currentZone=oldZone currentAltitude=altitude currentTime = datetime.datetime.now() oldTime=currentTime wait = 1 ## break if we get values... except KeyError: pass except KeyboardInterrupt: quit() except StopIteration: session = None print "GPSD has terminated"