Exemple #1
0
def add_run(gpx, name,act_type,filename,polyline):
    conn = sqlite3.connect('%s/activities.db' % filebase)
    cursor = conn.cursor()
    cursor.execute("""CREATE TABLE if not exists activities
                  (id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text,
                   speed text, act_type text,filename text,polyline text)""")
    sql = "INSERT INTO activities VALUES (?,?,?,?,?,?,?,?)"
    start_time, end_time = gpx.get_time_bounds()
    l2d='{:.3f}'.format(gpx.length_2d() / 1000.)
    moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
    print(max_speed)
    #print('%sStopped distance: %sm' % stopped_distance)
    maxspeed = 'Max speed: {:.2f}km/h'.format(max_speed * 60. ** 2 / 1000. if max_speed else 0)
    duration = '{:.2f}'.format(gpx.get_duration() / 60)

    print("-------------------------")
    print(name)
    print(start_time)
    print(l2d)
    print(maxspeed)
    print("-------------------------")
    try:
        cursor.execute(sql, [None, name,start_time,l2d,duration,act_type,filename,polyline])
        conn.commit()
    except sqlite3.Error as er:
        print("-------------______---_____---___----____--____---___-----")
        print(er)
    conn.close()
Exemple #2
0
def leave(gpx):
    global info_display
    filename = str(round(time.time() * 1000))
    os.system('clear')
    print('\nGPX file Created : ' + filename + ".gpx")
    file = open("/home/phablet/Downloads/" + filename + ".gpx", "w+")
    file.write(gpx.to_xml())
    file.close()
    gpx_file = "/home/phablet/Downloads/" + filename + ".gpx"
    shutil.chown(gpx_file, user="******", group="phablet")
    gpx = gpxpy.parse(open(gpx_file))
    indentation = '   '
    info_display = ""
    length_2d = gpx.length_2d()
    length_3d = gpx.length_3d()
    info_display += "\n%sLength 2D: %s" % (indentation, format_long_length(length_2d))
    info_display += "\n%sLength 3D: %s" % (indentation, format_long_length(length_3d))
    moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
    info_display += "\n%sMoving time: %s" %(indentation, format_time(moving_time))
    info_display += "\n%sStopped time: %s" %(indentation, format_time(stopped_time))
    info_display += "\n%sMax speed: %s" % (indentation, format_speed(max_speed))
    info_display += "\n%sAvg speed: %s" % (indentation, format_speed(moving_distance / moving_time) if moving_time > 0 else "?")
    uphill, downhill = gpx.get_uphill_downhill()
    info_display += "\n%sTotal uphill: %s" % (indentation, format_short_length(uphill))
    info_display += "\n%sTotal downhill: %s" % (indentation, format_short_length(downhill))
    info_display += "\n\n\n"
    print(info_display)
    if args.activity:
        newlocation="/home/phablet/.local/share/activitytracker.cwayne18/{}".format(filename + ".gpx")
        copyfile(gpx_file, newlocation)
        shutil.chown(newlocation, user="******", group="phablet")
        add_run(gpx,filename,"", newlocation)
    p.kill()
    sys.exit()
def add_run(gpx, name, act_type, filename, polyline):
    conn = sqlite3.connect("%s/activities.db" % filebase)
    cursor = conn.cursor()
    cursor.execute(
        """CREATE TABLE if not exists activities
                  (id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text, 
                   speed text, act_type text,filename text,polyline text)"""
    )
    sql = "INSERT INTO activities VALUES (?,?,?,?,?,?,?,?)"
    start_time, end_time = gpx.get_time_bounds()
    l2d = "{:.3f}".format(gpx.length_2d() / 1000.0)
    moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
    print(max_speed)
    # print('%sStopped distance: %sm' % stopped_distance)
    maxspeed = "Max speed: {:.2f}km/h".format(max_speed * 60.0 ** 2 / 1000.0 if max_speed else 0)
    duration = "Duration: {:.2f}min".format(gpx.get_duration() / 60)

    print("-------------------------")
    print(name)
    print(start_time)
    print(l2d)
    print(maxspeed)
    print("-------------------------")
    try:
        cursor.execute(sql, [None, name, start_time, l2d, duration, act_type, filename, polyline])
        conn.commit()
    except sqlite3.Error as er:
        print(er)
    conn.close()
Exemple #4
0
def analyse_gpx(file, index=-1):
    gpx = gpxpy.parse(file)
    data = {}
    data["length2D"] = gpx.length_2d()
    data["length3D"] = gpx.length_3d()
    c = gpx.get_uphill_downhill()
    data["pos_climb"] = c.uphill
    data["pos_climb"] = c.downhill
    gpx.smooth()
    d = gpx.get_uphill_downhill()
    data["pos_climb_smooth"] = d.uphill
    data["neg_climb_smooth"] = d.downhill
    data["duration"] = gpx.get_duration()
    data["average_speed"] = 3.6 * data["length3D"] / data["duration"]
    data["elevation_extreme"] = gpx.get_elevation_extremes()
    #print(data["elevation_extreme"])

    raw_data_lat = []
    raw_data_lon = []
    raw_data_alt = []
    for track_idx, track in enumerate(gpx.tracks):
        for seg_idx, segment in enumerate(track.segments):
            for point_idx, point in enumerate(segment.points):
                raw_data_lat.append(point.latitude)
                raw_data_lon.append(point.longitude)
                raw_data_alt.append(point.elevation)

    #gmap = gmplot.GoogleMapPlotter(raw_data_lat[0], raw_data_lon[0], 14)
    #gmap.scatter(raw_data_lat, raw_data_lon, 'k', marker=True)

    #gmap.draw(os.path.join(settings.MEDIA_ROOT, str(index) + ".html"))

    return data
    """
Exemple #5
0
def upload(request):
    if request.method == 'POST' and request.FILES['upload']:
        file = request.FILES['upload']

        if file.name.split(".")[-1] != 'gpx':
            return JsonResponse({"status": "error"})

        with open('/tmp/' + file.name, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        with open('/tmp/' + file.name, 'r') as destination:
            gpx = gpxpy.parse(destination)

            json_points = []
            i = 0
            for track in gpx.tracks:
                for segment in track.segments:
                    for p in segment.points:
                        if waffle.switch_is_active('ele-switch'):
                            json_points.append({
                                'id': i + 1,
                                'lat': p.latitude,
                                'lon': p.longitude,
                                'ele': p.elevation
                            })
                        else:
                            json_points.append({
                                'id': i + 1,
                                'lat': p.latitude,
                                'lon': p.longitude,
                            })

                        i += 1

            with reversion.create_revision():
                route = Route(title=file.name.split(".")[0],
                              date=datetime.now().date(),
                              length=gpx.length_2d(),
                              points=json_points)

                route.save()

                op = OperationStack(op='add_gpx',
                                    pk_route=route.id,
                                    num_version=0)
                op.save()
            return JsonResponse({
                "status": "server",
                'id': route.id,
                'name': route.title,
                'len': round(route.length),
                'date': route.date
            })

        os.remove('/tmp/' + file.name)

    return JsonResponse({"status": "server"})
def getInfos(gpx): 
    # creates json with infos about gpx track e.g. uphill, downhill, distance etc.
    indentation = '   '
    infos = {}
    infos['uphill'], infos['downhill'] = gpx.get_uphill_downhill()
    infos['uphill'] = int(round(infos['uphill']))
    infos['downhill'] = int(round(infos['downhill']))
    #print('%sTotal uphill: %sm' % (indentation, infos['uphill']))
    #print('%sTotal downhill: %sm' % (indentation, infos['downhill']))
    infos['length_2d'] = round(gpx.length_2d()/1000., 2)
    infos['length_3d'] = round(gpx.length_3d()/1000., 2)
    #print('%sLength 2D: %s' % (indentation, infos['length_2d'] / 1000.))
    #print('%sLength 3D: %s' % (indentation, infos['length_3d'] / 1000.))
    #infos['start_time'], infos['end_time'] = gpx.get_time_bounds()
    #print('%sStarted: %s' % (indentation, infos['start_time']))
    #print('%sEnded: %s' % (indentation, infos['end_time']))

    return infos
def getInfos(gpx):
    # creates json with infos about gpx track e.g. uphill, downhill, distance etc.
    indentation = '   '
    infos = {}
    infos['uphill'], infos['downhill'] = gpx.get_uphill_downhill()
    infos['uphill'] = int(round(infos['uphill']))
    infos['downhill'] = int(round(infos['downhill']))
    #print('%sTotal uphill: %sm' % (indentation, infos['uphill']))
    #print('%sTotal downhill: %sm' % (indentation, infos['downhill']))
    infos['length_2d'] = round(gpx.length_2d() / 1000., 2)
    infos['length_3d'] = round(gpx.length_3d() / 1000., 2)
    #print('%sLength 2D: %s' % (indentation, infos['length_2d'] / 1000.))
    #print('%sLength 3D: %s' % (indentation, infos['length_3d'] / 1000.))
    #infos['start_time'], infos['end_time'] = gpx.get_time_bounds()
    #print('%sStarted: %s' % (indentation, infos['start_time']))
    #print('%sEnded: %s' % (indentation, infos['end_time']))

    return infos
Exemple #8
0
def current_distance(gpx):
    l2d='{:.3f}'.format(gpx.length_2d() / 1000.)
    print(l2d)
    return l2d
Exemple #9
0
def current_distance(gpx):
    l2d='{:.3f}'.format(gpx.length_2d() / 1000.)
    print(l2d)
    return l2d
Exemple #10
0
except KeyboardInterrupt:
    filename = str(round(time.time() * 1000))
    os.system('clear')
    print('\nGPX file Created : ' + filename + ".gpx")
    file = open(filename + ".gpx", "w+")
    file.write(gpx.to_xml())
    file.close()
    gpx_file = filename + ".gpx"
    shutil.chown(gpx_file, user="******", group="phablet")
    gpx = gpxpy.parse(open(gpx_file))
    indentation = '   '
    info_display = ""
    """
    gpx_part may be a track or segment.
    """
    length_2d = gpx.length_2d()
    length_3d = gpx.length_3d()
    info_display += "\n%sLength 2D: %s" % (indentation,
                                           format_long_length(length_2d))
    info_display += "\n%sLength 3D: %s" % (indentation,
                                           format_long_length(length_3d))
    moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data(
    )
    info_display += "\n%sMoving time: %s" % (indentation,
                                             format_time(moving_time))
    info_display += "\n%sStopped time: %s" % (indentation,
                                              format_time(stopped_time))
    info_display += "\n%sMax speed: %s" % (indentation,
                                           format_speed(max_speed))
    info_display += "\n%sAvg speed: %s" % (
        indentation, format_speed(moving_distance /
Exemple #11
0
def gpx_covid_regulations_check_compliance(gpx_file, domicile):
    d_max = 1.0
    d_runner = 0.0
    gpx = gpxpy.parse(gpx_file)
    for track in gpx.tracks:
        for segment in track.segments:
            for point in segment.points:
                gps_pos = Position_GPS(point.longitude, point.latitude, "")
                distance = domicile.calculateDistanceVolOiseau(gps_pos)
                if distance > d_max and distance > d_runner:
                    d_runner = distance

    #
    # Quelques rappels sur les timezones et conversions de timestamps créés avec une timezone UTC
    #   But de cette manipulation: pas trouvé de documentation sur le package GpxPi pour changer la timezone...
    #   et données Strava utilisent UTC comme Timezone et Paris est à UTC+2 (GMT+1)
    #   donc on utilse la fonction astimezone de la classe datetime :-)
    #
    utc = timezone('UTC')
    paris = timezone('Europe/Paris')
    berlin = timezone('Europe/Berlin')
    tokyo = timezone('Asia/Tokyo')
    new_york = timezone('America/New_York')
    los_angeles = timezone('America/Los_Angeles')
    paris_time = datetime.now(paris)
    berlin_time = datetime.now(berlin)
    tokyo_time = datetime.now(tokyo)
    new_york_time = datetime.now(new_york)
    los_angeles_time = datetime.now(los_angeles)
    utc_time = datetime.now(utc)
    # print("UTC Time", utc_time)
    # print("Europe/Paris", paris_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("Europe/Berlin", berlin_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("Asia/Tokyo", tokyo_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("America/New_York", new_york_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("America/Los_Angeles", los_angeles_time.strftime('%Y-%m-%d_%H-%M-%S'))

    locale.setlocale(locale.LC_TIME, 'fr_FR')
    time_bound = gpx.get_time_bounds()
    #print("Old Timezone", time_bound.start_time.tzinfo)
    start_time = time_bound.start_time.astimezone(paris)
    #print("New Timezone", start_time.tzinfo)
    end_time = time_bound.end_time.astimezone(paris)
    day = start_time.strftime('%A %d %B %Y')
    hour = start_time.strftime('%Hh%M')
    elapsed_time = gpx.get_duration()
    distance2d = gpx.length_2d() / 1000
    distance3d = gpx.length_3d() / 1000
    duration_OK = True
    distance_OK = True
    amende = False
    exceeded_time = 0
    exceeded_distance = 0

    if d_runner > d_max:
        distance_OK = False
        exceeded_distance = d_runner - d_max
    if elapsed_time > 3600:
        duration_OK = False
        exceeded_time = elapsed_time - 3600

    if not (duration_OK and distance_OK):
        amende = True

    return day, hour, amende, distance3d, elapsed_time, distance_OK, duration_OK, exceeded_time, exceeded_distance
Exemple #12
0
for track in args.tracks:
    file_list = file_list + glob.glob(track)

print("Found %d files" % len(file_list))

# Setup output file
merged_gpx = gpxpy.gpx.GPX()

for i, f in enumerate(file_list):
    print("\nProcessing file %d/%d (%s)" %(i+1, len(file_list), f), end="")

    with open(f) as gpx_file:
        gpx = gpxpy.parse(gpx_file)

    point_count = gpx.get_points_no()
    track_length = gpx.length_2d()
    print(" (%d points)" %(point_count), end="")

    if point_count < 50:
        print("\nIgnoring file %s (Point count %d < %d)" %(f, point_count, 50), end="")
        continue

    if track_length < 100:
        print("\nIgnoring file %s (Track length %.0fm < %.0fm)" %(f, track_length, 100), end="")
        continue

    tmp_gpx, split_count = gpx_split(gpx, 500)
    tmp_gpx, removed_segments = gpx_remove_short_segments(tmp_gpx, minimum_point_count=10, minimum_length=40)
    #tmp_gpx = gpx_smooth(tmp_gpx, smooth_count=1)
    tmp_gpx = gpx_simplify(tmp_gpx, 10)