def start(self): #---------------------------------------- ''' start() Starts the connection with the GPS board, opens a data file, and prints a message to standard out. ''' #---------------------------------------- #begin by starting the GPS daemon. system('gpsd /dev/ttyUSB0') #instantiate a socket object, which is an interface with the GPS daemon. self.gps_socket = agps3.GPSDSocket() #instantiate a dot object--basically, one data point--which unpacks the GPS data into attribute values. self.dot = agps3.Dot() #now start the stream of data self.gps_socket.connect() self.gps_socket.watch() #open a file for the data self.file_name = self._name_file() self.data_file = open(self.file_name, 'a') self.data_file.write('\nNew data.\n\n') self.data_file.close() #print a confirmation. print(self.name, 'has started.')
def update_location(url): info = {} ''' The 2 following variables are abstractiosn to connect to the current gps daemon running in the background. This is a service that creates a socket and binds to port 2947 commonly. ''' try: gps_socket = agps3.GPSDSocket() data_stream = agps3.DataStream() gps_socket.connect() gps_socket.watch() except e: print("The error", e) print("gps could not connect") #using the watch function allows us to only send new gps updates for new_data in gps_socket: try: if new_data: data_stream.unpack(new_data) info["longitude"] = data_stream.lon info["latitude"] = data_stream.lat info["timestamp"] = datetime.now().isoformat() res = requests.post(url, json=info) except: print("could not send info")
def __init__(self, lock): super(GpsProcess, self).__init__() self.file_lock = lock self.gpsd_socket = agps3.GPSDSocket() self.gpsd_socket.connect() self.gpsd_socket.watch() self.data_stream = agps3.DataStream()
def startup(self): self._log = log = logger(self.name) log.info("Starting up %s ...", self.name) retries = 5 bus = self._build_bus_writer() while True: sock = agps3.GPSDSocket() strm = agps3.DataStream() log.info("Connecting to GPSD...") sock.connect(self._get_config('GPSD', 'Host', agps3.HOST), self._get_config_int('GPSD', 'Port', agps3.GPSD_PORT)) sock.watch() log.info("Watching for new GPSD packages...") try: for d in sock: if d: strm.unpack(d) di = self._build_messages(strm, d) self._send_dict(bus, di) except OSError: if retries > 0: log.error( "Failed to fetch data from GPSD! Retrying %s more times", retries) retries -= 1 else: raise GpsdConnectionError() sleep(5)
def setup_gpsd_socket(): gpsd_socket = agps3.GPSDSocket() gpsd_socket.connect(host="localhost", port=2947) gpsd_socket.watch() #logging.info(str(datetime.datetime.now()) + ": GPSDSocket created") data_stream = agps3.DataStream() #logging.info(str(datetime.datetime.now()) + ": DataStream acquired") return gpsd_socket, data_stream
class GPS(object): # - These four open a connection to the GPS receiver, create a stream to this class, and monitor the connection gps_socket = agps3.GPSDSocket() data_stream = agps3.DataStream() gps_socket.connect() gps_socket.watch() # - Constructor with relevant values. It also defines the GPS data socket and data stream def __GPS__(self): #- Latitude self.lat = 0.0 #- Longitude self.long = 0.0 #- Speed self.speed = 0.0 #- Altitude self.alt = 0.0 #- Accurate time self.time = 0 #- Setter. Collects data from the receiver, formats it, and updates the GPS object fields def setValues(self): for new_data in self.gps_socket: if new_data: self.data_stream.unpack(new_data) self.lat = (self.data_stream.lat) self.long = (self.data_stream.lon) self.speed = (self.data_stream.speed) self.alt = (self.data_stream.alt) self.time = (self.data_stream.time) return True else: return False # - Getters @property def getLat(self): return self.lat @property def getLong(self): return self.long @property def getSpeed(self): return self.speed @property def getTime(self): return self.time @property def getAlt(self): return self.alt
def check_GPS_show_users(self): """GPS FIX""" #Sets flat 'show user list button' so that the user knows the #software is still working."" self.ui.pushButtonUserList.setFlat(True) self.ui.pushButtonUserList.setText(u"Espere al FIX del GPS...") #R-pi GPSD needs to be disabled as well: """Raspbian default install already features a gpsd daemon of its own. We will be calling it on demand so it needs to be disabled due to compatibility issues, as both instances cannot be running at once.""" os.system('sudo systemctl stop gpsd.socket') os.system('sudo systemctl disable gpsd.socket') """ Communication with the GPS device takes place using the agps3 library, available through pip. This library acts as an interface to parse the raw data provided by the gpsd daemon. In order to get the data a GPS fix (i.e. a working satellite link) is required. """ try: gpsd_socket = agps3.GPSDSocket() #Opens a 'socket' form which #can be polled data_stream = agps3.DataStream() #Opens a new data stream #inside the socket gpsd_socket.connect() #Links to the socket. gpsd_socket.watch() #Watches the socket for changes. #Tries to grab an object from the data stream. #If no new objects are found inside the data stream, an #exception is issued warning the user to check the gps link. #If there's a working link but no fix, then the gps device #will be repeatedly polled until success. #Meanwhile, the user is instructed to wait patiently. for new_data in gpsd_socket: if new_data: data_stream.unpack(new_data) if data_stream.lat != 'n/a': break except (OSError, IOError): mb = QtGui.QMessageBox(u'Advertencia', u'Compruebe la conexión del GPS', QtGui.QMessageBox.Warning, QtGui.QMessageBox.Ok, 0, 0) mb.setWindowFlags(QtCore.Qt.FramelessWindowHint) mb.setAttribute(QtCore.Qt.WA_DeleteOnClose, True) # delete dialog on close mb.exec_() #prevent focus loss raise SystemExit #No gps device found -- QUIT #Now a login dialog object is created with all the #collected user data as an argument from LoginDialog import LoginDialog login = LoginDialog(self.obd_path, self.data) self.close() #closes login dialog login.exec_() #keeps focus on loginion dialog
def gps_attributes(): from gps3 import agps3 gps_socket = agps3.GPSDSocket() data_stream = agps3.DataStream() gps_socket.connect() gps_socket.watch() for new_data in gps_socket: if new_data: data_stream.unpack(new_data) print('Altitude = ', data_stream.alt) print('Latitude = ', data_stream.lat)
def main(): # register the process identifier utility for multiprocess logging argparser = argparse.ArgumentParser() argparser.add_argument('--settings', help='Path to settings INI file for AIS Receiver', required=True) argparser.add_argument('--init-db', help='Initialize the database, creating tables', action="store_true", required=False) options = argparser.parse_args() settings_file = options.settings config = ConfigParser() config.read(settings_file) settings = dict(config.items('app:main')) # TODO later, config logging from ini file #logging.config.fileConfig(settings_file) #log = logging.getLogger(__name__) log = setup_logging(logging.DEBUG) log.debug("instantiating model") model = Model(settings, logger=log) if options.init_db: log.info("Initializing database") model.init_db() log.info(" db initialized, exiting") return log.info("ais_receiver main()") # wait for five seconds to let gpsd settle down time.sleep(5) # connect to the gpsd server # TODO: do the right thing if gpsd not on or can't connect gps_socket = agps3.GPSDSocket() ds = agps3.DataStream() gps_socket.connect() gps_socket.watch() for json_msg in gps_socket: if json_msg: #log.debug("received msg: %s" % json_msg) try: model.handle_json_message(json_msg) except Exception as e: log.debug(" error handling message: %s" % e) pass else: time.sleep(.001)
def __init__(self, itype=None, **other): super().__init__("GPS", itype=None, **other) # Setup gps connection and data stream: self.sock = agps3.GPSDSocket() self.stream = agps3.DataStream() self.sock.connect() self.sock.watch() self.thread = threading.Thread(target=self.run) self.thread.daemon = False self.running = True self.thread.start()
def __init__(self): self.stoprequest = threading.Event() threading.Thread.__init__(self) host = os.environ.get('GPSD_HOST', '127.0.0.1') port = int(os.environ.get('GPSD_PORT', '2947')) self.gps_socket = agps3.GPSDSocket() self.data_stream = agps3.DataStream() self.gps_socket.connect(host=host, port=port) self.gps_socket.watch() self.current = {} self.previous = None self.last_time = None
def getLatLng(): gps_socket = agps3.GPSDSocket() # Init GPS socket data_stream = agps3.DataStream() # Init GPS data stream gps_socket.connect() # Connect GPS socket gps_socket.watch() # Watch for data over socket for new_data in gps_socket: # On new data: if new_data: data_stream.unpack( new_data) # Unpack data into python-readable format print('Altitude = ', data_stream.alt) if DEBUG else 0 print('Latitude = ', data_stream.lat) if DEBUG else 0 if data_stream.lat != "n/a": # If GPS lock present return { 'lat': round(float(data_stream.lat), 4), 'lng': round(float(data_stream.lon), 4) }
def get_loc_time(): gps_socket = agps3.GPSDSocket() data_stream = agps3.DataStream() gps_socket.connect() gps_socket.watch() for new_data in gps_socket: if new_data: data_stream.unpack(new_data) if data_stream.alt != 'n/a': logging.debug(f"Altitude = {data_stream.alt}") logging.debug(f"Latitude = {data_stream.lat}") logging.debug(f"Longitude = {data_stream.lon}") logging.debug(f"Time (UTC) = {data_stream.time}") return ({ 'Alt': data_stream.alt, 'Lat': data_stream.lat, 'Lon': data_stream.lon, 'Time': data_stream.time }) else: sleep(1)
def __init__( self, resultQue, # Queue to put the results controlPipe): # Worker <-> Application super(GPS, self).__init__() #self.daemon=False self.name = 'GPS' self.__gpsd = agps3.GPSDSocket() self.__gpsd.connect(host=HOST, port=PORT) self.__gpsd.watch() #gpsd_protocol=PROTOCOL) self.__stream = agps3.DataStream() self.__frequency = 1 self.__running = False self.__paused = True self.__pollCount = 0 self.__resultQue = resultQue self.__pipes = {} self.__pipes['GPS'] = PipeWatcher(self, controlPipe, 'APP->GPS') logger.debug('GPS process initalised')
import csv import math #Setup AWS IoT certificate myMQTT = AWSIoTMQTTClient("") myMQTT.configureEndpoint("af6uejkaq6p6d-ats.iot.us-east-1.amazonaws.com", 8883) myMQTT.configureCredentials("root.ca.pem", "e30c90799f.private.key", "e30c90799f.cert.pem") myMQTT.configureOfflinePublishQueueing(-1) myMQTT.configureDrainingFrequency(2) myMQTT.configureConnectDisconnectTimeout(10) myMQTT.configureMQTTOperationTimeout(5) myMQTT.connect() #GPS-Set-up gps_socket = agps3.GPSDSocket() data_stream = agps3.DataStream() gps_socket.connect() gps_socket.watch() while True: humidity, temperature = Adafruit_DHT.read_retry(11, 4) temperature = (temperature * 9 / 5) + 32 print(humidity) print(temperature) print() for new_data in gps_socket: if new_data: data_stream.unpack(new_data) alt = data_stream.alt lat = data_stream.lat
def show_human(): """Curses terminal with standard outputs """ args = add_args() gps_connection = agps3.GPSDSocket(args.host, args.port, args.gpsd_protocol, args.devicepath) dot = agps3.Dot() form = 'RAW' units = 'raw' # units = 'metric' screen = curses.initscr() screen.clear() screen.scrollok(True) curses.noecho() curses.curs_set(0) curses.cbreak() data_window = curses.newwin(19, 39, 1, 1) sat_window = curses.newwin(19, 39, 1, 40) device_window = curses.newwin(6, 39, 14, 40) packet_window = curses.newwin(20, 78, 20, 1) try: for new_data in gps_connection: if new_data: dot.unpack(new_data) screen.nodelay(1) event = screen.getch() if event == ord('q'): shut_down(gps_connection) elif event == ord('0'): # raw form = 'RAW' units = 'raw' data_window.clear() elif event == ord("1"): # DDD form = 'DDD' data_window.clear() elif event == ord('2'): # DMM form = 'DMM' data_window.clear() elif event == ord("3"): # DMS form = 'DMS' data_window.clear() elif event == ord("m"): # Metric units = 'metric' data_window.clear() elif event == ord("i"): # Imperial units = 'imperial' data_window.clear() elif event == ord("n"): # Nautical units = 'nautical' data_window.clear() data_window.box() data_window.addstr( 0, 2, 'GPS3 Python {}.{}.{} GPSD Interface'.format( *sys.version_info), curses.A_BOLD) data_window.addstr(1, 2, 'Time: {} '.format(dot.time)) data_window.addstr( 2, 2, 'Latitude: {} '.format(sexagesimal(dot.lat, 'lat', form))) data_window.addstr( 3, 2, 'Longitude: {} '.format(sexagesimal(dot.lon, 'lon', form))) data_window.addstr( 4, 2, 'Altitude: {} {}'.format( *unit_conversion(dot.alt, units, length=True))) data_window.addstr( 5, 2, 'Speed: {} {}'.format( *unit_conversion(dot.speed, units))) data_window.addstr(6, 2, 'Heading: {}° True'.format(dot.track)) data_window.addstr( 7, 2, 'Climb: {} {}'.format( *unit_conversion(dot.climb, units, length=True))) data_window.addstr(8, 2, 'Status: {:<}D '.format(dot.mode)) data_window.addstr( 9, 2, 'Latitude Err: +/-{} {}'.format( *unit_conversion(dot.epx, units, length=True))) data_window.addstr( 10, 2, 'Longitude Err: +/-{} {}'.format( *unit_conversion(dot.epy, units, length=True))) data_window.addstr( 11, 2, 'Altitude Err: +/-{} {}'.format( *unit_conversion(dot.epv, units, length=True))) data_window.addstr(12, 2, 'Course Err: +/-{} '.format(dot.epc), curses.A_DIM) data_window.addstr( 13, 2, 'Speed Err: +/-{} {}'.format( *unit_conversion(dot.eps, units)), curses.A_DIM) data_window.addstr(14, 2, 'Time Offset: +/-{} '.format(dot.ept), curses.A_DIM) data_window.addstr( 15, 2, 'gdop:{} pdop:{} tdop:{}'.format(dot.gdop, dot.pdop, dot.tdop)) data_window.addstr( 16, 2, 'ydop:{} xdop:{} '.format(dot.ydop, dot.xdop)) data_window.addstr( 17, 2, 'vdop:{} hdop:{} '.format(dot.vdop, dot.hdop)) sat_window.clear() sat_window.box() sat_window.addstr( 0, 2, 'Using {0[1]}/{0[0]} satellites (truncated)'.format( satellites_used(dot.satellites))) sat_window.addstr(1, 2, 'PRN Elev Azimuth SNR Used') line = 2 if isinstance( dot.satellites, list ): # Nested lists of dictionaries are strings before data is present for sats in dot.satellites[0:10]: sat_window.addstr( line, 2, '{PRN:>2} {el:>6} {az:>5} {ss:>5} {used:}'. format(**sats)) line += 1 # device_window.clear() device_window.box() if not isinstance(dot.devices, list): gps_connection.send( '?DEVICES;' ) # Local machines need a 'device' kick start to have valid data I don't know why. if isinstance(dot.devices, list): for gizmo in dot.devices: start_time, _uicroseconds = gizmo['activated'].split( '.') # Remove '.000Z' elapsed = elapsed_time_from(start_time) device_window.addstr( 1, 2, 'Activated: {}'.format(gizmo['activated'])) device_window.addstr( 2, 2, 'Host:{0.host}:{0.port} {1}'.format( args, gizmo['path'])) device_window.addstr( 3, 2, 'Driver:{driver} BPS:{bps}'.format(**gizmo)) device_window.addstr( 4, 2, 'Cycle:{0} Hz {1!s:>14} Elapsed'.format( gizmo['cycle'], elapsed)) packet_window.clear() packet_window.border(0) packet_window.scrollok(True) packet_window.addstr(0, 0, '{}'.format(new_data)) sleep(.4) data_window.refresh() sat_window.refresh() device_window.refresh() packet_window.refresh() except KeyboardInterrupt: shut_down(gps_connection)
class GpsProvider(DataProvider, TimeProvider, PositionProvider, SpeedProvider): __gpsd_socket = agps3.GPSDSocket() __data_stream = agps3.DataStream() __is_started = False __position = (None, None) __time = None __speed = None __fixtype = None __has_error_occurred = False __last_error = None def __init__(self, host="localhost", port=2947): self.__host = host self.__port = port def start(self): if not self.__is_started: self.__gpsd_socket.connect(self.__host, self.__port) self.__gpsd_socket.watch() self.__is_started = True def stop(self): if self.__is_started: self.__gpsd_socket.close() self.__is_started = False def update(self): self.__has_error_occurred = False try: new_data = self.__gpsd_socket.next() if new_data: self.__data_stream.unpack(new_data) if self.__data_stream.mode != 'n/a': fixtype = int(self.__data_stream.mode) if fixtype > 0: self.__fixtype = fixtype else: self.__fixtype = None if self.__data_stream.lat != 'n/a' and self.__data_stream.lon != 'n/a': self.__position = (float(self.__data_stream.lat), float(self.__data_stream.lon)) else: self.__position = (None, None) if self.__data_stream.time != 'n/a': time = parse(self.__data_stream.time) self.__time = time.timestamp() else: self.__time = None if self.__data_stream.speed != 'n/a': self.__speed = float(self.__data_stream.speed) else: self.__speed = None except Exception as e: print("Could not retrieve gps data ", e) self.__has_error_occurred = True self.__last_error = e def get_speed(self): self.update() return self.__speed def get_position(self): self.update() if self.__fixtype is not None and self.__position is not (None, None): return self.__fixtype, self.__position return None def get_time(self): self.update() return self.__time def has_error_occured(self): return self.__has_error_occurred def get_last_error(self): return self.__last_error
#!/usr/bin/python # coding=utf-8 # Concept from Jaroslaw Zachwieja <grok!warwick.ac.uk> & TJ <linux!tjworld.net> # from their work in gegpsd.py included in gpsd project (http://catb.org/gpsd) """creates Google Earth kml file (/tmp/gps3_live.kml) for realtime (4 second GE default) updates of gps coordinates""" import time from gps3 import agps3 __author__ = 'Moe' __copyright__ = 'Copyright 2016 Moe' __license__ = 'MIT' __version__ = '0.20' the_connection = agps3.GPSDSocket( host='192.168.0.4') # TODO: needs work for commandline host selection dot = agps3.Dot() the_link = '/tmp/gps3_live.kml' # AFAIK, 'Links' call href on time events or entry/exit Multiple href may be possible. the_file = '/tmp/gps3_static.kml' the_history = [] live_link = ( '<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n' '<kml xmlns=\'http://www.opengis.net/kml/2.2\' xmlns:gx=\'http://www.google.com/kml/ext/2.2\' xmlns:kml=\'http://www.opengis.net/kml/2.2\' xmlns:atom=\'http://www.w3.org/2005/Atom\'>\n' '<NetworkLink>\n' ' <name>GPS3 Live</name>\n' ' <Link>\n' ' <href>{0}</href>\n' ' <refreshMode>onInterval</refreshMode>\n' ' </Link>\n' '</NetworkLink>\n'
def __init__(self): self.gps_socket = agps3.GPSDSocket() self.data_stream = agps3.DataStream() self.gps_socket.connect() self.gps_socket.watch()
sats_used = i sats = j f['sats'] = sats f['sats_used'] = sats_used led = led.Led(5, 25, led.BRIGHT_HIGHEST) led.Clear() influxdb = InfluxDBClient('localhost', 8086, 'root', 'root', 'gps') influxdb.create_database('gps') shiftpi.startup_mode(shiftpi.LOW, True) gps = agps3.GPSDSocket() dot = agps3.Dot() gps.connect() gps.watch() for n in gps: if n: dot.unpack(n) if dot.mode == 'n/a': print "Fixing location" sleep(.5) continue data = GpsData() data.populate_gps_data(dot)