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 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 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 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 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 __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 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 lon = data_stream.lon
def __init__(self): self.gps_socket = agps3.GPSDSocket() self.data_stream = agps3.DataStream() self.gps_socket.connect() self.gps_socket.watch()
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