Exemplo n.º 1
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)
Exemplo n.º 2
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()
Exemplo n.º 3
0
def show_nmea():
    """NMEA"""
    args = add_args()
    gps_connection = gps3.GPSDSocket(args.host, args.port, args.gpsd_protocol, args.devicepath)

    screen = curses.initscr()
    # curses.KEY_RESIZE
    curses.cbreak()
    screen.clear()
    screen.scrollok(True)

    data_window = curses.newwin(23, 79, 1, 1)

    try:
        for new_data in gps_connection:
            if new_data:
                data_window.border(0)
                data_window.addstr(0, 2, 'GPS3 Python {}.{}.{} GPSD Interface Showing NMEA protocol'.format(*sys.version_info), curses.A_BOLD)
                data_window.addstr(2, 2, '{}'.format(gps_connection.response))
                data_window.refresh()
                sleep(.4)

    except KeyboardInterrupt:
        shut_down(gps_connection)
Exemplo n.º 4
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")
Exemplo n.º 5
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)
Exemplo n.º 6
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.daemon = True
     self.gps_socket = gps3.GPSDSocket()
     self.data_stream = gps3.DataStream()
Exemplo n.º 7
0
from gps3 import gps3
import time

gpsdsock = gps3.GPSDSocket()
data = gps3.DataStream()
gpsdsock.connect()
gpsdsock.watch()

for newdata in gpsdsock:
    if newdata:
        data.unpack(newdata)
        print data.TPV['lat'], data.TPV['lon']

Exemplo n.º 8
0
 def setup(self):
     self.gps_socket = gps3.GPSDSocket()
     self.gps_stream = gps3.DataStream()
     self.gps_socket.connect()
     self.gps_socket.watch()
Exemplo n.º 9
0
    def collectData(self):
        self.tf = datetime.time.second
        gps_socket = gps3.GPSDSocket()
        data_stream = gps3.DataStream()
        gps_socket.connect()
        gps_socket.watch()

        sense = SenseHat()
        sense.set_imu_config(True, True, True)

        self.createFile()
        

        while self.ON:
            '''Collect Sense Hat Data'''
            timestamp = datetime.datetime.now() #Date + timestamp
            self.timestr = timestamp.strftime('%H:%M:%S.%f') #pretty format timestamp
            self.gpstimestr = timestamp.strftime('%H:%M:%S') #pretty format for GPS 
            self.tf = time.time()
            self.dt = self.tf - self.ti
            self.ti = self.tf
            orientation = sense.get_orientation_degrees()
            gyroS = ('{pitch},{roll},{yaw}').format(**orientation)

            if (orientation['pitch'] == 'n/a'):
                self.pitch = 'n/a'

            else:
                self.pitch = '{0:.6f}'.format(float(orientation['pitch']))

            if (orientation['roll'] == 'n/a'):
                self.roll = 'n/a'


            else:
                self.roll = '{0:.6f}'.format(float(orientation['roll']))

            if (orientation['yaw'] == 'n/a'):
                self.yaw = 'n/a'

            else:
                self.yaw = '{0:.6f}'.format(float(orientation['yaw']))

            self.rollrate = (float(self.roll) - float(self.oldroll)) / self.dt
            self.yawrate = (float(self.yaw) - float(self.oldyaw)) / self.dt
            self.pitchrate = (float(self.pitch) - float(self.oldpitch)) / self.dt

            self.oldroll = self.roll
            self.oldpitch = self.pitch
            self.oldyaw = self.yaw

            self.temp = '{0:.6f}'.format(sense.temp)
            self.humi = '{0:.6f}'.format(sense.humidity)
            self.pres = '{0:.6f}'.format(sense.pressure)
            
            #collect GPS Data
            for new_data in gps_socket:
                if new_data:
                    #print colored(new_data,"green")
                    data_stream.unpack(new_data)
                    if (data_stream.TPV['alt'] == 'n/a'):
                        self.alt = ''

                    else:
                        self.alt = '{0:.6f}'.format(float(data_stream.TPV['alt']))

                    if (data_stream.TPV['lat'] == 'n/a'):
                        self.lat = ''

                    else:
                        self.lat = '{0:.6f}'.format(float(data_stream.TPV['lat']))

                    if (data_stream.TPV['lon'] == 'n/a'):
                        self.lon = ''

                    else:
                        self.lon = '{0:.6f}'.format(float(data_stream.TPV['lon']))

                else:
                    print colored("No gps data", 'red')
                break
            
            if (self.supressOutput != True):
                 print("Time Stamp: " + str(self.timestr))
                 
                 print(colored(('Roll: ' + str(self.roll)), 'magenta'))
                 print(colored(('Pitch: ' + str(self.pitch)), 'magenta'))
                 print(colored(('Yaw: ' + str(self.yaw)), 'magenta'))
                 
                 print(colored(('Roll Rate: ' + str(self.rollrate)), 'cyan'))
                 print(colored(('Pitch Rate: ' + str(self.pitchrate)), 'cyan'))
                 print(colored(('YawRate: ' + str(self.yawrate)), 'cyan'))
                 
                 print("Temperature: " + self.temp + " C")
                 print("Humidity:    " + self.humi + " rh")
                 print("Pressure:    " + self.pres + " Mb")
                 
                 print(colored(('Altitude: ', self.alt), 'yellow'))
                 print(colored(('Latitude: ', self.lat), 'yellow'))
                 print(colored(('Longitude: ',self.lon), 'yellow'))
                 

            self.write2File()
            print self.timestr
            time.sleep(1/self.RATE) #currently set to 10 Hz
        
        self.f2.close()
        print self.datacsv + " closed."
Exemplo n.º 10
0
        f_s = open(schema_path)
        schema = avro.schema.parse(f_s.read())
        f_s.close()
    except IOError:
        print('cannot open schema file')
        sys.exit()

    try:
        f_id = open(isoblue_id_path)
        isoblue_id = f_id.read().strip('\n')
        f_id.close()
    except IOError:
        print('cannot open isoblue_id file')
        sys.exit()

    s = gps3.GPSDSocket()
    s.connect(host='127.0.0.1', port=2947)
    s.watch()

    timestamp = None
    last_tpv_timestamp = None

    try:
        for data in s:
            if data:
                new_data = json.loads(data)
                object_name = new_data.pop('class', 'ERROR')

                # convert 'n/a' to None for proper
                for key, value in new_data.iteritems():
                    if value == 'n/a':
Exemplo n.º 11
0
#!/usr/bin/python3
# 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 gps3

__author__ = 'Moe'
__copyright__ = 'Copyright 2014-2016 Moe'
__license__ = 'MIT'
__version__ = '0.20'

the_connection = gps3.GPSDSocket(host='192.168.0.4')  # TODO: needs work for commandline host selection
the_fix = gps3.Fix()
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'
             '</kml>').format(the_file)  # inserts 'the file' into a refresh mode default 4 second
f = open(the_link, 'w')
Exemplo n.º 12
0
import rospy 
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)
Exemplo n.º 13
0
def show_human():
    """Curses terminal with standard outputs """
    args = add_args()
    gps_connection = gps3.GPSDSocket(args.host, args.port, args.gpsd_protocol, args.devicepath)
    gps_fix = gps3.Fix()
    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:
                gps_fix.refresh(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:  {time} '.format(**gps_fix.TPV))
                data_window.addstr(2, 2, 'Latitude:  {} '.format(sexagesimal(gps_fix.TPV['lat'], 'lat', form)))
                data_window.addstr(3, 2, 'Longitude: {} '.format(sexagesimal(gps_fix.TPV['lon'], 'lon', form)))
                data_window.addstr(4, 2, 'Altitude:  {} {}'.format(*unit_conversion(gps_fix.TPV['alt'], units, length=True)))
                data_window.addstr(5, 2, 'Speed:     {} {}'.format(*unit_conversion(gps_fix.TPV['speed'], units)))
                data_window.addstr(6, 2, 'Heading:   {track}° True'.format(**gps_fix.TPV))
                data_window.addstr(7, 2, 'Climb:     {} {}/s'.format(*unit_conversion(gps_fix.TPV['climb'], units, length=True)))
                data_window.addstr(8, 2, 'Status:     {mode:<}D  '.format(**gps_fix.TPV))
                data_window.addstr(9, 2, 'Latitude Err:  +/-{} {} '.format(*unit_conversion(gps_fix.TPV['epx'], units, length=True)))
                data_window.addstr(10, 2, 'Longitude Err: +/-{} {}'.format(*unit_conversion(gps_fix.TPV['epy'], units, length=True)))
                data_window.addstr(11, 2, 'Altitude Err:  +/-{} {} '.format(*unit_conversion(gps_fix.TPV['epv'], units, length=True)))
                data_window.addstr(12, 2, 'Course Err:    +/-{epc}  '.format(**gps_fix.TPV), curses.A_DIM)
                data_window.addstr(13, 2, 'Speed Err:     +/-{} {} '.format(*unit_conversion(gps_fix.TPV['eps'], units)), curses.A_DIM)
                data_window.addstr(14, 2, 'Time Offset:   +/-{ept}  '.format(**gps_fix.TPV), curses.A_DIM)
                data_window.addstr(15, 2, 'gdop:{gdop}  pdop:{pdop}  tdop:{tdop}'.format(**gps_fix.SKY))
                data_window.addstr(16, 2, 'ydop:{ydop}  xdop:{xdop} '.format(**gps_fix.SKY))
                data_window.addstr(17, 2, 'vdop:{vdop}  hdop:{hdop} '.format(**gps_fix.SKY))

                sat_window.clear()
                sat_window.box()
                sat_window.addstr(0, 2, 'Using {0[1]}/{0[0]} satellites (truncated)'.format(satellites_used(gps_fix.SKY['satellites'])))
                sat_window.addstr(1, 2, 'PRN     Elev   Azimuth   SNR   Used')
                line = 2
                if isinstance(gps_fix.SKY['satellites'], list):  # Nested lists of dictionaries are strings before data is present
                    for sats in gps_fix.SKY['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(gps_fix.DEVICES['devices'], list):
                    gps_connection.send('?DEVICES;')  # Local machines need a 'device' kick start to have valid data I don't know why.

                if isinstance(gps_fix.DEVICES['devices'], list):  # Nested lists of dictionaries are strings before data is present (REALLY?)

                    for gizmo in gps_fix.DEVICES['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)
Exemplo n.º 14
0
# Author: Matteo Corradini
#
# This Python script logs data from GPSD daemon through gps3 library.

# IMPORT #######################################################################

import time
import sys
import os
from gps3 import gps3
from Utilities import FILE_NAME

# MAIN #########################################################################

gps_socket = gps3.GPSDSocket()  # Initialize socket with default setting
ds = gps3.DataStream()  # Initialize data stream
gps_socket.connect()  # Connect socket
gps_socket.watch()

# Initialize log file
FOLDER = os.environ['TEST_FOLDER']
f = open(FOLDER + FILE_NAME, 'w')
f.writelines('Time,Altitude,Latitude,Longitude,Speed,Climb\n')

# Initilize time settings
zero_time = time.time()
delta_time = zero_time
interval = float(sys.argv[1])

for new_ds in gps_socket:
    if new_ds:
Exemplo n.º 15
0
def poll_gpsd():
    gpsd_socket = gps3.GPSDSocket()
    gpsd_socket.connect()
    gpsd_socket.watch(gpsd_protocol='nmea')
    time_now = None
    json_msg = {'hostname': hostname, 'mode': 0}
    error_count = 0
    while True:
        if error_count > 100:
            logging.warning('too many errors, reconnecting to gpsd...')
            break
        new_data = gpsd_socket.next(timeout=1.0)
        if new_data is None or new_data == '':
            error_count += 1
            sleep(.05)
            continue
        for x in new_data:
            result = my_gps.update(x)
            if result is None or result == '':
                continue
            elif not my_gps.valid:
                continue
            if int(my_gps.fix_time) != time_now:
                if len(json_msg) > 0:
                    if json_msg['mode'] < 3:
                        json_msg['alt'] = None
                        json_msg['vdop'] = None
                        json_msg['pdop'] = None
                    redis_connection.publish('gps', json.dumps(json_msg))
                json_msg = {'hostname': hostname, 'mode': 0}
                time_now = int(my_gps.fix_time)
            if result == 'GPGGA':
                """Parse Global Positioning System Fix Data (GGA) Sentence.
                Updates UTC timestamp, latitude, longitude, fix status,
                satellites in use, Horizontal Dilution of Precision (HDOP),
                altitude, geoid height and fix status"""
                json_msg.update({
                    'alt': my_gps.altitude,
                    'geo_sep': my_gps.geoid_height,
                    'utc': round(my_gps.fix_time, 2),
                    'hdop': my_gps.hdop,
                    'num_sats': my_gps.satellites_in_use,
                    'gps_status': my_gps.fix_stat
                })
                convert_lat_lon(json_msg, my_gps)
                error_count = 0
            elif result == 'GPGSA':
                """Parse GNSS DOP and Active Satellites (GSA) sentence. Updates
                GPS fix type, list of satellites used in fix calculation,
                Position Dilution of Precision (PDOP), Horizontal Dilution of
                Precision (HDOP), Vertical Dilution of Precision, and fix status
                """
                json_msg.update({
                    'hdop': my_gps.hdop,
                    'vdop': my_gps.vdop,
                    'pdop': my_gps.pdop,
                    'mode': my_gps.fix_type,
                    'gps_status': my_gps.fix_stat
                })
                error_count = 0
            elif result == 'GPRMC':
                """Parse Recommended Minimum Specific GPS/Transit data
                (RMC)Sentence. Updates UTC timestamp, latitude, longitude,
                Course, Speed, Date, and fix status """
                json_msg.update({
                    'utc': round(my_gps.fix_time, 2),
                    'track': my_gps.course,
                    'gps_status': my_gps.fix_stat,
                    'speed': round(my_gps.speed[0] * knt_to_mps, 2)
                })
                convert_lat_lon(json_msg, my_gps)
                error_count = 0
Exemplo n.º 16
0
#!/usr/bin/python3.5
from gps3 import gps3
import properties
from db import db
from sensor import sensor
from socket_gps import sio

gps_db = db.MetaDatabase(path=properties.GPS_DB)
gps_table = db.MetaTable(name="gps_table",
                         schema="date text, lat float, lon float")
gps_db.create_table(gps_table)
print(gps_db.list_tables())

gps_sensor = sensor.Sensor(socket=gps3.GPSDSocket(), stream=gps3.DataStream())
gps_sensor.connect()

for new_data in gps_sensor.socket:
    if new_data:
        gps_sensor.stream.unpack(new_data)
        time, lat, lon = gps_sensor.stream.TPV["time"], gps_sensor.stream.TPV[
            "lat"], gps_sensor.stream.TPV["lon"]
        if sensor.check_data(lat, lon):
            print("lat = {lat} - lon = {lon}".format(lat=lat, lon=lon))
            sio.emit("dbs", gps_sensor.stream.TPV)
Exemplo n.º 17
0
 def __init__(self, interface):
     Thread.__init__(self)
     self.isRunning = True
     self.gui = interface
     self.socket = gps3.GPSDSocket()
     self.stream = gps3.DataStream()
Exemplo n.º 18
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)
Exemplo n.º 19
0
    def run(self):

        logging.info("[%s]: Starting collector thread with %s sec interval." %
                     (self.file_name, self.gpslogging_interval))

        while True:

            # Should we exit thread?
            if self.exit_flag:
                logging.info("[%s]: Exiting collector thread." %
                             self.file_name)
                return

            logging.info("[%s]: Connect to gpsd." % self.file_name)
            try:
                gps_socket = gps3.GPSDSocket()
                data_stream = gps3.DataStream()
                gps_socket.connect()
                gps_socket.watch()
            except:
                logging.exception("[%s]: Failed to establish connection " %
                                  self.file_name + "to gpsd.")
                time.sleep(1)
                continue

            failed_ctr = 0
            for new_data in gps_socket:

                # Should we exit thread?
                if self.exit_flag:
                    logging.info("[%s]: Exiting collector thread." %
                                 self.file_name)
                    return

                if failed_ctr > self.max_failed_gps_pos:
                    logging.error(
                        "[%s]: Failed %d times to collect gps data. " %
                        (self.file_name, failed_ctr) +
                        "Resetting connection to gpsd.")
                    gps_socket.close()
                    break

                # Check if we received data.
                if new_data:
                    try:
                        data_stream.unpack(new_data)
                    except:
                        logging.warning("[%s]: Unpacking gps data failed." %
                                        self.file_name)
                        continue

                    # Reset failed counter.
                    failed_ctr = 0

                    # Check if received data is valid.
                    is_valid = True
                    is_valid &= (type(data_stream.TPV["lat"]) == float)
                    is_valid &= (type(data_stream.TPV["lon"]) == float)
                    is_valid &= (type(data_stream.TPV["alt"]) == float)
                    is_valid &= (type(data_stream.TPV["speed"]) == float)
                    is_valid &= (type(data_stream.TPV["time"]) == str)
                    if is_valid:

                        # When time string has following form:
                        # 2018-02-01T20:01:18.500Z
                        # we have to remove the ".500Z"
                        time_str = data_stream.TPV["time"]
                        if time_str.find(".") != -1:
                            time_str = time_str[0:time_str.find(".")]

                        # Convert time string to utc timestamp.
                        dt_obj = datetime.datetime.strptime(
                            time_str, "%Y-%m-%dT%H:%M:%S")
                        utc_time = calendar.timegm(dt_obj.timetuple())

                        # Check if the interval in which we would like
                        # to collect gps data is reached.
                        if ((utc_time - self.last_utc_time) <
                                self.gpslogging_interval):
                            continue

                        # Get difference of current gps data to the last data.
                        diff_lat = self.last_lat - data_stream.TPV["lat"]
                        diff_lon = self.last_lon - data_stream.TPV["lon"]
                        diff_alt = self.last_alt - data_stream.TPV["alt"]

                        # Check if we recognize the gps data as changed
                        # position.
                        no_change = True
                        no_change &= self.lat_change * (-1) <= diff_lat
                        no_change &= diff_lat <= self.lat_change
                        no_change &= self.lon_change * (-1) <= diff_lon
                        no_change &= diff_lon <= self.lon_change
                        no_change &= self.alt_change * (-1) <= diff_alt
                        no_change &= diff_alt <= self.alt_change
                        if no_change:
                            logging.debug("[%s]: Position has not changed." %
                                          self.file_name)
                            continue

                        # Allow only a precision of 14 characters for the
                        # gps data (usual precision is 12 characters).
                        lat = str(data_stream.TPV["lat"])[:14]
                        lon = str(data_stream.TPV["lon"])[:14]
                        alt = str(data_stream.TPV["alt"])[:14]
                        speed = str(data_stream.TPV["speed"])[:14]

                        logging.debug("[%s]: Lat: %s Lon: %s " %
                                      (self.file_name, lat, lon) +
                                      "Alt: %s Speed: %s Time: %s" %
                                      (alt, speed, time_str))

                        element = {
                            "lat": lat,
                            "lon": lon,
                            "alt": alt,
                            "speed": speed,
                            "utctime": utc_time
                        }

                        # Append new gps position to gps data.
                        logging.debug("[%s]: Acquire lock." % self.file_name)
                        self.gps_lock.acquire()
                        self.gps_data.append(element)

                        # Wirte data to storage.
                        try:
                            with open(self.tempfile, 'w') as fp:
                                fp.write(json.dumps(self.gps_data))

                            # Sync filesystem to force writing on storage
                            if self.sync_always:
                                self.libc.sync()
                        except:
                            logging.exception("[%s]: Can not write into " %
                                              self.file_name +
                                              "tempfile (%s)." % self.tempfile)

                        logging.debug("[%s]: Release lock." % self.file_name)
                        self.gps_lock.release()

                        # Set current gps data as last position we
                        # collected.
                        self.last_utc_time = utc_time
                        self.last_lat = data_stream.TPV["lat"]
                        self.last_lon = data_stream.TPV["lon"]
                        self.last_alt = data_stream.TPV["alt"]

                # We got no data from gpsd.
                else:
                    failed_ctr += 1

                # Sleep to give gpsd time to give us the next position.
                time.sleep(self.gps_collect_sleep_time)
Exemplo n.º 20
0
    #print(newHeading_Kart)

    #Optimization of angles for smaller angle
    if newHeading_Kart > 180:
        newHeadingAdjusted_Kart = newHeading_Kart - 360
    elif newHeading_Kart < -180:
        newHeadingAdjusted_Kart = newHeading_Kart + 360
    else:
        newHeadingAdjusted_Kart = newHeading_Kart

    return newHeadingAdjusted_Kart


#- Main code -#
#Interface with the GPS
gps_connection = gps3.GPSDSocket(host='127.0.0.1')
gps_fix = gps3.Fix()
#Interface with the Compass
hmc5883l = i2c_hmc5883l.i2c_hmc5883l(1)
hmc5883l.setContinuousMode()
hmc5883l.setDeclination(7, 52)

#Get the heading updates from the Arduino

#arduino=serial.Serial('/dev/ttyACM0',baudrate=9600, timeout = 3.0)
#arduino.isOpen()
compassHeading = None
while True:
    time.sleep(0.1)
    #compassHeading = arduino.readline().decode('UTF-8')
    #compassHeading = compassHeading.rstrip()
Exemplo n.º 21
0
    def __init__(self, do_upload=False, img_orig_fp="", sentence_count=7, seed_ix=0, ebook_title="", ascii_img_path="", manual=False, looper=False, folderpath=""):
        self.first_pass = True

        # GPS STUFF

        self.gps_socket = gps3.GPSDSocket()
        self.data_stream = gps3.DataStream()
        self.gps_socket.connect()
        self.gps_socket.watch()

        # END OF GPS STUFF

        # FOURSQUARE STUFF

        # Construct the client object
        # TODO: MOVE TO ENV VARIABLES
        self.client = foursquare.Foursquare(
            client_id=fs_api_keys.client_id,
            client_secret=fs_api_keys.client_secret,
            redirect_uri=fs_api_keys.redirect_uri
        )

        # Build the authorization url for your app
        self.auth_uri = self.client.oauth.auth_url()

        # END OF FOURSQUARE


        self.do_upload = do_upload
        self.img_orig_fp = img_orig_fp
        self.manual = manual
        # ebook of results?
        # self.ebook = ebook
        self.ebook_title = ebook_title

        self.folderpath = folderpath

        # ascii img path
        self.ascii_img_path = ascii_img_path

        # Connect to RabbitMQ
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='localhost')
        )
        self.channel = self.connection.channel()

        self.camera_ip = '10.0.0.2'
        self.camera_nums = [5,6,7,8]

        self.cur_cam = -1
        self.cur_hash = ""

        self.cur_exp = None



        possible_pre_seeds = [
            "The dreams of men who would regard the scene,\nThe sorrows of the morn, whose waters wave,\n",
            "~~~The arm of a person or thing and a frequency of a similar process within a postulated printed contest with the weapons of the post office.\n~|~",
            "The door opened and the old man turned in his armchair to see whether he had been to the river bank.\n"
        ]

        self.pre_seed = possible_pre_seeds[seed_ix]

        # Serial to Arduino button
        # self.ser = serial.Serial('/dev/ttyACM0')

        # Queue names
        queue_names = [
            'ImgPaths',
            'Captions',
            'CaptionToExpand',
            'Expansions'
        ]

        # Declare and Purge Queues
        for qn in queue_names:
            self.channel.queue_declare(queue=qn)
            self.channel.queue_purge(queue=qn)

        # HashIds
        self.hashids = Hashids()

        # Unused captions (changes every image)
        self.unused_captions = list()
        self.unused_captions_per_graf = 0

        # Class Variables
        self.sentence_count = sentence_count
        self.sentences = defaultdict(list)
        self.img_dest = '/home/rg/projects/wc3/img'
        self.template_path = '/home/rg/projects/wc3/template.html'
        self.ebook_template_path = '/home/rg/projects/wc3/ebook_template.html'

        self.thr1 = threading.Thread(target=self.consume)
        self.thr1.start()

        self.looper = looper
        self.gogogo = True

        if self.looper:
            if self.img_orig_fp:
                self.process_fp()
            else:
                self.thr2 = threading.Thread(target=self.loop)
                self.thr2.start()

        for i in range(len(self.camera_nums)):
            thr = threading.Thread(target=self.loop_generator(i))
            thr.start()