Пример #1
0
def loop(gpsd_socket):
    global position, lock, RUNNING
    print("gpsd receive loop started")
    data_stream = gps3.DataStream()
    gpsd_socket.watch()
    for new_data in gpsd_socket:
        if new_data:
            if RUNNING == False:
                return
            data_stream.unpack(new_data)
            print("GPSD data....")

            lock.acquire()
            position['lat'] = data_stream.TPV['lat']
            position['lon'] = data_stream.TPV['lon']
            position['alt'] = data_stream.TPV['alt']
            position['speed'] = data_stream.TPV['speed']
            if "hdop" in data_stream.SKY:
                position['hdop'] = data_stream.SKY['hdop']

            #check if position valid
            if 'n/a' in position.values():
                position['valid'] = False
            else:
                position['valid'] = True
            lock.release()
Пример #2
0
def worker():
    setup()
    while True:
        running = Systemd.running('gpsd')
        if running == True:
            service_change(running)
            gpsd_socket = gps3.GPSDSocket()
            try:
                gpsd_socket.connect(host='127.0.0.1', port=2947)
                gpsd_socket.watch()
                data_stream = gps3.DataStream()
                for new_data in gpsd_socket:
                    if new_data:
                        data_stream.unpack(new_data)
                        handle_data(data_stream)
                    else:
                        eventlet.sleep(.1)
                    eventlet.sleep(.8)
                    if not Systemd.running('gpsd'):
                        service_change(False)
                        break
            except Exception as e:
                # only display error if service is running
                app.logger.error(traceback.format_exc())
            finally:
                try:
                    gpsd_socket.close()
                except:
                    pass
        else:
            service_change(running)
        eventlet.sleep(1)
Пример #3
0
def getgps():
    global gpsData
    gps_socket = gps3.GPSDSocket()
    data_stream = gps3.DataStream()
    gps_socket.connect()
    gps_socket.watch()

    for new_data in gps_socket:
        if new_data:

            data_stream.unpack(new_data)
            data_temp_gps = {}  # 一時格納用

            lat = data_stream.TPV['lat']
            lon = data_stream.TPV['lon']
            if (lat != 'n/a' and lon != 'n/a'):
                data_temp_gps["gps_lat"] = float(lat)
                data_temp_gps["gps_lon"] = float(lon)
            else:
                data_temp_gps["gps_lat"] = 0.0
                data_temp_gps["gps_lon"] = 0.0

            alt = data_stream.TPV['alt']
            if (alt == 'n/a'):
                data_temp_gps["gps_alt"] = 0.0
            else:
                data_temp_gps["gps_alt"] = float(alt)
            speed = data_stream.TPV['speed']
            if (speed == 'n/a'):
                data_temp_gps["gps_speed"] = 0.0
            else:
                data_temp_gps["gps_speed"] = float(speed)

        gpsData = data_temp_gps
Пример #4
0
def getGPS():
    global lat, lon
    gps_socket = gps3.GPSDSocket()
    data_stream = gps3.DataStream()
    gps_socket.connect()
    gps_socket.watch()
    temp_lat = 0
    temp_lon = 0
    last_lat = 0
    last_lon = 0
    last_time = 0

    print("getGPS起動")
    for new_data in gps_socket:
        if new_data:
            current_time = round(time.time())
            if current_time - last_time >= 0.5:
                last_time = current_time

                data_stream.unpack(new_data)
                temp_lat = data_stream.TPV['lat']
                temp_lon = data_stream.TPV['lon']
                if (temp_lat != 'n/a' and temp_lon != 'n/a'):
                    lat = float(temp_lat)
                    lon = float(temp_lon)
                    # lat = round(float(temp_lat)*10000000)
                    # lon = round(float(temp_lon)*10000000)
                    last_lat = lat
                    last_lon = lon

                else:
                    lat = last_lat
                    lon = last_lon
Пример #5
0
    def __record_from_gps(self):
        # TODO auto retry and reinit on hotplug

        if not self.pipe_out:
            raise ValueError("Illegal argument, no queue specified")

        os.system("taskset -p 0xfe %d" % os.getpid())
        os.nice(19)

        print("Starting GPS reader")
        gps_socket = gps3.GPSDSocket()
        data_stream = gps3.DataStream()
        gps_socket.connect()
        gps_socket.watch()
        while not self.doneEvent.is_set():
            newdata = gps_socket.next(timeout=GPS_READ_TIMEOUT)
            now = time.time()
            if newdata:
                data_stream.unpack(newdata)
                sample = data_stream.TPV
                t = sample.get('time')
                if t is not None and set(GPS_REQUIRED_FIELDS).issubset(
                        set(sample.keys())):
                    self.pipe_out.send((now, sample))

        print("GPS reader shutdown")
Пример #6
0
    def __init__(self, writerobj):
        self.finished_init = False
        # ----------------- init GPS ---------------------
        # set GPS to 10 Hz.
        #
        #os.system('sudo python3 /home/pi/git/raspberry/Programs/gpsconfig.py')

        # U-Blox USB GPS
        #os.system('sudo gpsd /dev/ttyACM0 -F /var/run/gpsd.sock')

        # Ultimate UART GPS
        #os.system('sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock')

        # Ultimate USB TTY GPS
        #os.system('sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock')

        self.gps3_conn = gps3.GPSDSocket()
        self.gps3_stream = gps3.DataStream()
        # needed in new versions!!! because of exception handling
        self.gps3_conn.connect()
        self.gps3_conn.watch()

        writerobj.add_headrow([
            'gps_timestamp', 'lat', 'lon', 'speed', 'alt', 'climb',
            'error_longitude', 'error_latitude', 'gdop'
        ])
        logging.info("finished init of gps.")
        self.finished_init = True
        # Wait till gps fix is there
        for new_data in self.gps3_conn:
            if new_data:
                return
            time.sleep(1 / 2)
Пример #7
0
    def loop(self, gpsd_socket):
        print("gpsd receive loop started")
        data_stream = gps3.DataStream()
        gpsd_socket.watch()
        for new_data in gpsd_socket:
            if new_data:
                if self.running == False:
                    return
                data_stream.unpack(new_data)
                print("GPSD data....")

                self.lock.acquire()
                self.position['lat'] = data_stream.TPV['lat']
                self.position['lon'] = data_stream.TPV['lon']
                self.position['alt'] = data_stream.TPV['alt']
                self.position['speed'] = data_stream.TPV['speed']
                if "hdop" in data_stream.SKY:
                    self.position['hdop'] = data_stream.SKY['hdop']

                #check if self.position valid
                if 'n/a' in self.position.values():
                    self.position['valid'] = False
                else:
                    self.position['valid'] = True
                self.lock.release()
Пример #8
0
def get_gps():
    gps_data = []
    timeout = datetime.timedelta(seconds=10)
    loop_time = 1
    gps_start_time = datetime.datetime.utcnow()
    status = 'Trying GPS'

    gpsd_socket = gps3.GPSDSocket()
    gpsd_socket.connect()
    gpsd_socket.watch()
    data_stream = gps3.DataStream()

    for new_data in gpsd_socket:
        waiting_time = datetime.datetime.utcnow() - gps_start_time
        if waiting_time > timeout:
            raise gpsTimeout("GPS timeout")
        if new_data:
            data_stream.unpack(new_data)
            if data_stream.TPV['lat'] != 'n/a' and int(
                    data_stream.TPV['mode']) == 3:
                gps_data.append(data_stream.TPV['lat'])
                gps_data.append(data_stream.TPV['lon'])
                gps_data.append(data_stream.TPV['alt'])
                gps_data.append(data_stream.TPV['time'])
                break
        else:
            time.sleep(loop_time)
        if DEBUG:
            status = status + '.'
            print("%s" % status, end='\r')

    gpsd_socket.close()
    return gps_data
Пример #9
0
def get_gps_data():
    gps_socket = gps3.GPSDSocket()
    data_stream = gps3.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.TPV['lgn'])
            print('Latitude = ', data_stream.TPV['lat'])
Пример #10
0
    def __init__(self, delay=60):
        """Initialize the GPS listener.

        Args:
            delay (int, optional): Delay between polls of gpsd.
        """
        self.delay = delay
        self.gps_socket = gps3.GPSDSocket()
        self.data_stream = gps3.DataStream()
        self.gps_socket.connect()
        self.gps_socket.watch()
Пример #11
0
def gps_default():
    from gps3 import gps3

    gps_socket = gps3.GPSDSocket()
    data_stream = gps3.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.TPV['alt'])
            print('Latitude = ', data_stream.TPV['lat'])
Пример #12
0
    def __init__(self):
        self.socket = gps3.GPSDSocket()
        self.data_stream = gps3.DataStream()
        self.socket.connect()
        self.socket.watch()

        self.valid = False
        self.latitude = 0.0
        self.longitude = 0.0
        self.altitude = 0.0
        self.separation = 0.0
        
        self.lock = threading.Lock()
Пример #13
0
def run():
    try:
        args = setup_args()
        logger.setLevel(getattr(logging, args.loglevel.upper()))
        logger.debug("Args: %s", args)

        gpsd_socket = gps3.GPSDSocket()
        logger.info("Connecting to GPSd service")
        gpsd_socket.connect(args.gpsd_host, args.gpsd_port)
        try:
            gpsd_socket.watch(gpsd_protocol=args.gpsd_protocol)
        except (OSError, IOError) as e:
            logger.critical(
                "Can't connect to GPSd service. Is it running and listening on %s:%s",
                args.gpsd_host, args.gpsd_port)
            sys.exit(1)
        else:
            logger.info("Connected to GPSd service")
            data_stream = gps3.DataStream()
            pollution_sensor = PollutionSensor(args.sdevice)
            for new_data in gpsd_socket:
                if new_data:
                    data_stream.unpack(new_data)
                    gps_data = cleanup_gps_dict(data_stream.TPV)
                    logger.debug("GPS reports %s", gps_data)
                    if (gps_data.get('lat')
                            and gps_data.get('lon')) or args.skip_gps:
                        ps_data = pollution_sensor.read()
                        if not ps_data:
                            continue
                        gps_data.update(ps_data)
                        logger.debug("Data Ready to be sent: %s", gps_data)
                        if args.url:
                            r = requests.post(args.url, json=gps_data)
                            logger.info("Server responded %s" % r.status_code)
                            if not r.ok:
                                logger.error("Server response:")
                                logger.error(r.content)
                        else:
                            logger.info(
                                "Reporting PM10:%(pm10)s PM2.5:%(pm25)s at LAT: %(lat)s LNG: %(lon)s, ALT: %(alt)sm",
                                gps_data)
                    else:
                        logger.info(
                            "GPS reports incomplete data %s. Sleeping.",
                            gps_data)
                    sleep(args.t)
    except (KeyboardInterrupt, SystemExit) as err:
        logger.info("Bye!")
Пример #14
0
def gpsPoll(lat, lon):
    conexion = gps3.GPSDSocket()
    stream = gps3.DataStream()
    conexion.connect()
    conexion.watch()
    for datos in conexion:
        if datos:
            stream.unpack(datos)
            print(stream.TPV['time'])
            lat = stream.TPV['lat']
            lon = stream.TPV['lon']
            print(lat, "\n", lon, "\n")
            takePicture()
            save_entry(lat, lon, app_id, numCamion, access_token)
            upload_file()
Пример #15
0
 def sensor_init(self):
     if _SENSOR_GPS_GPSD:
         self.gps_socket = gps3.GPSDSocket()
         self.gps_datastream = gps3.DataStream()
         self.gps_socket.connect()
         self.gps_socket.watch()
         self.config.G_GPS_NULLVALUE = "n/a"
     elif _SENSOR_GPS_ADAFRUIT_I2C or _SENSOR_GPS_ADAFRUIT_UART:
         self.adafruit_gps = _sensor_adafruit_gps
         self.config.G_GPS_NULLVALUE = None
         #(GPGLL), GPRMC, (GPVTG), GPGGA, GPGSA, GPGSV, (GPGSR), (GPGST)
         self.adafruit_gps.send_command(
             b'PMTK314,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0')
         self.adafruit_gps.send_command(b"PMTK220,1000")
     self.reset()
     for element in self.elements:
         self.values[element] = np.nan
Пример #16
0
 def start_continous_scan(self):
     gps_socket = gps3.GPSDSocket()
     data_stream = gps3.DataStream()
     gps_socket.connect()
     gps_socket.watch()
     for new_data in gps_socket:
         if (not getattr(self.worker, "do_run", True)):
             break
         if new_data:
             data_stream.unpack(new_data)
             lat = data_stream.TPV['lat']
             lon = data_stream.TPV['lon']
             if (src.utils.utils.is_number(lat)
                     and src.utils.utils.is_number(lon)):
                 self.recent_lat = lat
                 self.recent_lon = lon
                 self.recent_scan_time_utc_sec = time.time()
Пример #17
0
    def gps_read(self):
        gps_socket = gps3.GPSDSocket()
        data_stream = gps3.DataStream()
        gps_socket.connect()
        gps_socket.watch()

        for new_data in gps_socket:
            if new_data:
                data_stream.unpack(new_data)

                # Reading data from GPS stream
                lat = data_stream.TPV['lat']
                lon = data_stream.TPV['lon']
                alt = data_stream.TPV['alt']
                track = data_stream.TPV['track']
                speed = data_stream.TPV['speed']
                climb = data_stream.TPV['climb']
                time = data_stream.TPV['time']

                # Sanitizing location
                if lat == 'n/a' and lon == 'n/a' and alt == 'n/a':
                    self.gps_latitude = None
                    self.gps_longitude = None
                    self.gps_altitude = None
                else:
                    self.gps_latitude = lat
                    self.gps_longitude = lon
                    self.gps_altitude = alt

                # Sanitizing velocity
                if track == 'n/a' and speed == 'n/a' and climb == 'n/a':
                    self.gps_track = None
                    self.gps_speed = None
                    self.gps_climb = None
                else:
                    self.gps_track = track
                    self.gps_speed = speed
                    self.gps_climb = climb

                if time == 'n/a':
                    gps_time = None
                else:
                    gps_time = time
Пример #18
0
    def __init__(self, compass_file=None, gps_timeout=5):

        self.compass_file = compass_file
        self.gps_timeout = gps_timeout

        #assumes gpsd daemon has already been started
        self.gps_socket = gps3.GPSDSocket()
        self.data_stream = gps3.DataStream()
        self.gps_socket.connect()
        self.gps_socket.watch()
        self.gps_data = dict(datetime=np.nan,
                         lat=np.nan,
                         lon=np.nan,
                         COG=np.nan,
                         speed=np.nan)

        self._init_pressure_gauge()
        self._init_compass()
        self.last_gps_read_time = time.time()
Пример #19
0
    def __init__(self, out_queue):
        # Call the threading super-class constructor (inheritance)
        threading.Thread.__init__(self)

        self.gps_socket = None
        self.data_stream = None
        self.running = False
        self.out_q = out_queue

        # Try to connect to GPSD socket (if gpsd is not installed, this will error)
        try:
            # TODO something happens here on OSX i guess?
            self.gps_socket = gps3.GPSDSocket()
            self.data_stream = gps3.DataStream()
        except:
            raise Exception(
                "[GPS] Could not create gpsd-socket or data stream object.")

        # Start our thread
        self.start()
Пример #20
0
    def run(self):
        self.enabled = True
        gps_socket = gps3.GPSDSocket()
        data_stream = gps3.DataStream()
        gps_socket.connect()
        gps_socket.watch()

        for new_data in gps_socket:
            if self.enabled is False:
                break

            if new_data is None:
                continue

            data_stream.unpack(new_data)
            if data_stream.TPV['lat'] == 'n/a':
                continue

            position = (data_stream.TPV['lat'], data_stream.TPV['lon'])
            self.on_changed_gps.emit(position)
Пример #21
0
async def run(loop):
    # Prometheus variables to export
    global lat_gauge
    lat_gauge = Gauge('avena_position_lat', 'Last know fix latitude')
    global lng_gauge
    lng_gauge = Gauge('avena_position_lng', 'Last know fix longitude')
    global time_gauge
    time_gauge = Gauge('avena_position_time', 'Last know fix time')
    #start_http_server(10001)

    gps_socket = gps3.GPSDSocket()
    data_stream = gps3.DataStream()
    #gps_socket.connect(host='127.0.0.1', port=2948)
    gps_socket.connect(host='127.0.0.1', port=2947)
    gps_socket.watch()

    # Create nats object and connect to local nats server
    print('Setting up NATS')
    sys.stdout.flush()
    nc = NATS()
    await nc.connect("nats://localhost:4222")
    #await nc.connect("nats://nats:4222")

    for new_data in gps_socket:
        if new_data:
            fix = json.loads(new_data)
            subject = "gps." + str(fix["class"])
            print("Publishing new data point to subject", subject, ": ",
                  new_data[:-1])
            await nc.publish(subject, bytes(new_data, 'utf-8'))
            await nc.flush(1)

            if "activated" in fix and fix["activated"] == 0:
                await nc.flush(10)
                print("NC flushed")
            sys.stdout.flush()
        # Loop runs out of control without this
        sleep(0.1)

    print("This should never be reached")
Пример #22
0
def continuousRead():
    try:
        # calls constructor of gpsd daemon's interface
        gpsSocket = gps3.GPSDSocket()
        # calls constructor of json data stream adapter
        jsonBuffer = gps3.DataStream()
        # connects to port
        gpsSocket.connect()
        # sets the ?WATCH= json tag to enabled
        gpsSocket.watch()
        # deal with all data coming in from socket
        for incomingData in gpsSocket:
            # valid data
            if incomingData:
                # now jsonBuffer has the json as dict
                jsonBuffer.unpack(incomingData)
                printData(jsonBuffer)
                time.sleep(0.5)
    except KeyboardInterrupt as e_intentional:
        raise e_intentional
    except Exception as e:
        raise e
Пример #23
0
 def __init__(self, freq=1000):
     import socket
     from gps3 import gps3
     threading.Thread.__init__(self)
     self._stop_event = threading.Event()
     self.displayMessage = True
     self.old = 0
     self.freq = freq
     self.altitude = 0
     self.latitude = 0
     self.longitude = 0
     self.value = {'altitude': 0, 'latitude': 0, 'longitude': 0}
     try:
         self.gps_socket = gps3.GPSDSocket()
         self.data_stream = gps3.DataStream()
         self.gps_socket.connect()
         self.gps_socket.watch()
         print("[GPS ] GPS setup finished.")
     except BaseException as e:
         print("[GPS ] Capture Exception while setup! ")
         print(type(e), str(e))
         exit(1)
Пример #24
0
def fetch_gps_fix():
    altitude = None
    latitude = None
    longitude = None
    unix_time = None
    clock_offset = None

    gps_socket = gps3.GPSDSocket()
    data_stream = gps3.DataStream()
    gps_socket.connect(host="localhost", port=2947)
    gps_socket.watch(devicepath="/dev/ttyUSB0")
    while True:
        new_data = gps_socket.next(timeout=1)
        if new_data:
            data_stream.unpack(new_data)
            if isinstance(data_stream.TPV['alt'], float):
                altitude = data_stream.TPV['alt']
            if isinstance(data_stream.TPV['lat'], float):
                latitude = data_stream.TPV['lat']
            if isinstance(data_stream.TPV['lon'], float):
                longitude = data_stream.TPV['lon']
            if isinstance(data_stream.TPV['time'], str):
                try:
                    dt = dateutil.parser.parse(data_stream.TPV['time'])
                    unix_time = time.mktime(dt.timetuple())
                    clock_offset = time.time() - unix_time
                except ValueError:
                    pass

        # If we have a complete fix, we can quit
        if altitude is not None and latitude is not None and longitude is not None and unix_time is not None:
            return {
                "time": unix_time,
                "clock_offset": clock_offset,
                "latitude": latitude,
                "longitude": longitude,
                "altitude": altitude
            }
Пример #25
0
    async def monitor_positions(self, sender):
        """Starts the GPS position monitor loop"""

        # Initialize GPSD objects
        if(self._use_alternate_gpslib):
            from gps_alternate import AltGPSDSocket
            gps_socket = AltGPSDSocket()
        else:
            gps_socket = gps3.GPSDSocket()

        data = gps3.DataStream()

        # Start fetching data
        gps_socket.connect()
        gps_socket.watch()

        # Position monitor loop
        # for gps_data in gps_socket:
        while True:
            gps_data = gps_socket.next()
            if gps_data:  # We have data
                # Load the JSON into the mapping class dictionary
                data.unpack(gps_data)

                if self._gps_data_logging:
                    self._logger.debug("GPS Data: " + gps_data)

                #pylint: disable=E1101
                # (no, data.TPV doesn't exist in the code. yes, we can still call it)
                if self._ok(data.TPV['lat']):  # We have position data
                    gpos = data.TPV
                    pos = self.parsePosition(gpos)
                    if pos.time != self._last_position_time:
                        sender.send_position(pos)
                        self._last_position_time = pos.time

            await asyncio.sleep(0.1)
Пример #26
0
    def __init__(self):
        self.sock = gps3.GPSDSocket()
        self.stream = gps3.DataStream()

        # GPS3 throws no exceptions and returns no status,
        # so we have to capture stdout and do string matching, sigh
        f = io.StringIO()
        with redirect_stderr(f):
            self.sock.connect()
        if "Connection refused" in f.getvalue():
            log.warn(
                "Could not connect to GPSD socket, continuing with GPS_BOX")
            self.sock = None
        else:
            log.info("Connected to GPSD socket")
            self.sock.watch()

        # we will use the GPS_BOX setting to determine if
        # queries will return locations within a specified range
        if len(GPS_BOX) == 4:
            self.gps_box = box(GPS_BOX[0], GPS_BOX[1], GPS_BOX[2], GPS_BOX[3])
            log.info("Created GPS box")
        else:
            log.warn("Invalid GPS_BOX size, using GPS_DEFAULT")
Пример #27
0
    def __init__(self):
        # Call the threading super-class constructor (inheritance)
        threading.Thread.__init__(self)

        self.gps_socket = None
        self.data_stream = None
        self.running = False
        self.speed = 0
        self.latitude = 0
        self.longitude = 0
        self.altitude = 0

        # Try to connect to GPSD socket (if gpsd is not installed, this will error)
        try:
            # TODO something happens here on OSX i guess?
            self.gps_socket = gps3.GPSDSocket()
            self.data_stream = gps3.DataStream()
        except:
            raise Exception(
                "Could not create gpsd-socket or data stream object.")

        # TODO testing
        if (self.gps_socket is not None):
            self.gps_socket.connect()
Пример #28
0
from std_msgs.msg import String 
import serial
import time
from gps3 import gps3
from math import radians, cos, sin, asin, sqrt
from geopy import distance
import pyproj
import socket
import sys
import threading,os
latitude=longitude=heading=0
gps_obtained=imu_obtained=False
###############################Initialization#####################################################
g = pyproj.Geod(ellps='WGS84')
gps_socket = gps3.GPSDSocket()
data_stream = gps3.DataStream()
gps_socket.connect()
gps_socket.watch()
ser = serial.Serial(port='/dev/ttyTHS2',baudrate = 38400)
def pos_update():
    while True:
        for new_data in gps_socket:
            if new_data:
                data_stream.unpack(new_data)
                global latitude,longitude
                latitude =  data_stream.TPV['lat']
                longitude =  data_stream.TPV['lon']
                if type(longitude) is type('sdas') or type(latitude) is type('sdas'):
                    continue                 
                #print(latitude,longitude)
                return latitude,longitude
Пример #29
0
def get_gps_location():
    """ Attempt to get a location from gpsd. Return all as None on fail.

        :returns: accuracy, latlong, timestamp, altitude, velocity, course, satelittes
        :rtype: float, list, float, float, float, float, float
    """
    from socket import error as socketerror
    from datetime import datetime

    gpsd_tries = 1
    gpsd_tries_max = 10
    latlong = (None, None)
    acc = None
    tst = None
    alt = None
    cog = None
    vel = None
    sat = 0

    from gps3 import gps3
    gpsd_socket = gps3.GPSDSocket()
    data_stream = gps3.DataStream()

    try:
        gpsd_socket.connect()
        gpsd_socket.watch()

        for new_data in gpsd_socket:
            if new_data:
                data_stream.unpack(new_data)
                print('Reading gps data (%s/%s), epx %s' %
                      (gpsd_tries, gpsd_tries_max, data_stream.TPV['epx']))

                if 'n/a' == data_stream.TPV['lat']:  # No data
                    gpsd_tries += 1
                    if gpsd_tries_max <= gpsd_tries:
                        if cfg.verbose:
                            print('No valid gps data!')
                        return acc, latlong, tst, alt, vel, cog, sat
                else:
                    # TODO: optimize?
                    gpstime = time.mktime(
                        time.strptime(data_stream.TPV['time'],
                                      '%Y-%m-%dT%H:%M:%S.000Z'))
                    offset = datetime.fromtimestamp(
                        gpstime) - datetime.utcfromtimestamp(gpstime)
                    tst = gpstime + offset.seconds

                    if 'n/a' != data_stream.TPV['epx']:
                        acc = (int(data_stream.TPV['epx'] +
                                   data_stream.TPV['epy'])) / 2

                    try:
                        latlong = (data_stream.TPV['lat'],
                                   data_stream.TPV['lon'])
                        alt = round(data_stream.TPV['alt'], 0)
                        cog = round(data_stream.TPV['track'], 0)
                        vel = round(data_stream.TPV['speed'], 0)

                        if data_stream.SKY['satellites'] not in ['n/a', 'n']:
                            #  [{u'ss': 27, u'el': 0, u'PRN': 4, u'az': 0, u'used': False},
                            for satelitte in data_stream.SKY['satellites']:
                                if satelitte['used']:
                                    sat += 1
                    except TypeError, err:
                        print("Error: %s" % err)
                        pass

                    if cfg.verbose:
                        print(acc, latlong[0],
                              latlong[1])  # ie. 25, (50.1234567,-1.234567)
                    break

            time.sleep(0.1)  # Don't grind CPU when gpsd doesn't work
    except socketerror, err:
        print(
            "Error: Unable to connect to gpsd. Is it installed and enabled? (%s)"
            % err)
Пример #30
0
    def _gps_thread(self):
        """ """
        first_gps_time_received = False
        first_gps_pos_received = False
        #
        try:
            gps_socket = gps3.GPSDSocket()
            data_stream = gps3.DataStream()
            gps_socket.connect()
            gps_socket.watch(True)
            #
            while self._active:

                new_data = gps_socket.next(
                    timeout=5)  # Timeout for thread termination.
                if new_data:
                    data_stream.unpack(new_data)
                    #
                    gps_time = data_stream.TPV['time']
                    gps_latitude = data_stream.TPV['lat']
                    gps_longitude = data_stream.TPV['lon']
                    #
                    if gps_time and (gps_time != 'n/a'):
                        if first_gps_time_received:
                            self.gps_time = data_stream.TPV['time']
                        else:
                            if self.is_time_valid(gps_time):
                                self.gps_time = data_stream.TPV['time']
                                first_gps_time_received = True
                                self._logger.info(
                                    'GPS reader: First GPS time received: ' +
                                    self.get_time_local_string())
                                # Set Raspberry Pi time.
                                if self._set_rpi_time_from_gps:
                                    datetime_gps = dateutil.parser.parse(
                                        gps_time).astimezone(self._timezone)
                                    datetime_now = datetime.datetime.now(
                                        datetime_gps.tzinfo)
                                    if datetime_gps > datetime_now:
                                        self._logger.info(
                                            'GPS reader: Raspberry Pi date/time is set.'
                                        )
                                        os.system('sudo date --set "' +
                                                  str(self.gps_time) + '"')
                                    else:
                                        self._logger.info(
                                            'GPS reader: Raspberry Pi date/time is NOT set.'
                                        )
                    else:
                        # Don't use the old fetched time.
                        self.gps_time = None

                    if gps_latitude and (gps_latitude != 'n/a'):
                        if gps_longitude and (gps_longitude != 'n/a'):
                            # Always use last known position.
                            self.gps_latitude = gps_latitude
                            self.gps_longitude = gps_longitude
                            #
                            if not first_gps_pos_received:
                                first_gps_pos_received = True
                                self._logger.info(
                                    'GPS reader: First GPS position received: '
                                    + self.get_latlong_string())
                    #
                    if self._debug:
                        if self.gps_time: print(str(self.gps_time))
                        if self.gps_latitude: print(str(self.gps_latitude))
                        if self.gps_longitude: print(str(self.gps_longitude))
                else:
                    # Don't use the old fetched time.
                    self.gps_time = None
        #
        finally:
            gps_socket.watch(False)