Created
October 21, 2026 00:04
-
-
Save xssfox/a3d73f4e9d0b86ce5ec1f43cd3239df5 to your computer and use it in GitHub Desktop.
pylivetrack.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| import argparse | |
| from html.parser import HTMLParser | |
| import logging | |
| import time | |
| import traceback | |
| import numpy as np | |
| import matplotlib as mpl | |
| import matplotlib.pyplot as plt | |
| from matplotlib.animation import FuncAnimation | |
| from matplotlib import _pylab_helpers | |
| logger = logging.getLogger(__name__) | |
| logging.basicConfig( level=logging.DEBUG) | |
| parser = argparse.ArgumentParser( | |
| prog='pylivetrack', | |
| description='Monitors livetrack') | |
| parser.add_argument('url') | |
| args = parser.parse_args() | |
| class CSRFFinder(HTMLParser): | |
| def __init__(self, *args, **kwargs): | |
| self.csrf = None | |
| super().__init__( *args, **kwargs ) | |
| def handle_starttag(self, tag, attrs): | |
| if tag == 'meta' and ('name', 'csrf-token') in attrs: | |
| for (attr, value) in attrs: | |
| if attr == 'content': | |
| self.csrf = value | |
| logging.info("Found CSRF") | |
| points = 100 | |
| mpl.rcParams['toolbar'] = 'None' | |
| plt.rcParams['axes.facecolor'] = 'black' | |
| plt.rcParams["figure.figsize"] = (6,10) | |
| plt.show() | |
| def pause(interval, focus_figure=True): | |
| backend = mpl.rcParams['backend'] | |
| figManager = _pylab_helpers.Gcf.get_active() | |
| if figManager is not None: | |
| canvas = figManager.canvas | |
| if canvas.figure.stale: | |
| canvas.draw() | |
| if focus_figure: | |
| plt.show(block=False) | |
| canvas.start_event_loop(interval) | |
| return | |
| # No on-screen figure is active, so sleep() is all we need. | |
| import time | |
| time.sleep(interval) | |
| class Plot(): | |
| def __init__(self): | |
| self.fig, self.ax = plt.subplots(4) | |
| self.fig.patch.set_facecolor("black") | |
| self.xdata, self.speed, self.hr, self.cad = list(range(0,points)), [0]*points, [0]*points, [0]*points | |
| self.ln_hr, = self.ax[0].plot([], [],color="white") | |
| self.ln_speed, = self.ax[1].plot([], [],color="white") | |
| self.ln_cad, = self.ax[2].plot([], [],color="white") | |
| self.d_txt = self.ax[3].text(0.05, 0.9, "Ridden: 0", fontsize=24, | |
| verticalalignment='top',color="white") | |
| self.ani = FuncAnimation(self.fig, self.update, frames=[1], | |
| init_func=self.plt_init, blit=True, interval=50, repeat=False) | |
| def plt_init(self): | |
| self.hr_title = self.ax[0].set_title('Heart Rate (bpm)', fontsize=24, color="white") | |
| self.ax[0].set_xlim(0, points) | |
| self.ax[0].set_ylim(40, 200) | |
| self.ax[0].spines['bottom'].set_visible(False) | |
| self.ax[0].spines['top'].set_visible(False) | |
| self.ax[0].spines['right'].set_visible(False) | |
| self.ax[0].spines['left'].set_color("white") | |
| self.ax[0].tick_params(axis='both', which='major', labelsize=22, color="white", labelcolor="white") | |
| self.speed_title = self.ax[1].set_title('Speed (km/hr?)', fontsize=24, color="white") | |
| self.ax[1].set_xlim(0, points) | |
| self.ax[1].set_ylim(0, 50) | |
| self.ax[1].spines['top'].set_visible(False) | |
| self.ax[0].spines['bottom'].set_visible(False) | |
| self.ax[1].spines['right'].set_visible(False) | |
| self.ax[1].spines['left'].set_color("white") | |
| self.ax[1].tick_params(axis='both', which='major', labelsize=22, color="white", labelcolor="white") | |
| self.cad_title = self.ax[2].set_title('Cadence (per min)', fontsize=24, color="white") | |
| self.ax[2].set_xlim(0, points) | |
| self.ax[2].set_ylim(0, 120) | |
| self.ax[2].spines['top'].set_visible(False) | |
| self.ax[0].spines['bottom'].set_visible(False) | |
| self.ax[2].spines['right'].set_visible(False) | |
| self.ax[2].spines['left'].set_color("white") | |
| self.ax[2].tick_params(axis='both', which='major', labelsize=22, color="white", labelcolor="white") | |
| self.ax[0].axes.get_xaxis().set_visible(False) | |
| self.ax[1].axes.get_xaxis().set_visible(False) | |
| self.ax[2].axes.get_xaxis().set_visible(False) | |
| return self.ln_hr, self.ln_speed, self.ln_cad | |
| def add_hr(self, hr): | |
| logging.info(self.xdata) | |
| logging.info(self.hr ) | |
| self.hr += hr | |
| self.hr = self.hr[-points:] | |
| self.ln_hr.set_data(self.xdata, self.hr) | |
| try: | |
| self.hr_title.set_text(f'Heart Rate: {self.hr[-1]:.0f} bpm') | |
| except AttributeError: | |
| pass | |
| def add_speeds(self, speeds): | |
| self.speed += speeds | |
| self.speed = self.speed[-points:] | |
| self.ln_speed.set_data(self.xdata, self.speed) | |
| try: | |
| self.speed_title.set_text(f'Speed: {self.speed[-1]:.0f} km/hr') | |
| except AttributeError: | |
| pass | |
| def add_cad(self, cad): | |
| self.cad += cad | |
| self.cad = self.cad[-points:] | |
| self.ln_cad.set_data(self.xdata, self.cad) | |
| try: | |
| self.cad_title.set_text(f'Cadence: {self.cad[-1]:.0f} /min') | |
| except AttributeError: | |
| pass | |
| def set_distance(self, d): | |
| self.d_txt.set_text(f"Ridden: {d:.2f} km") | |
| def update(self, frame): | |
| print(frame) | |
| return self.ln_hr, self.ln_speed, self.ln_cad, self.d_txt, self.cad_title, self.speed_title, self.hr_title | |
| a_plot = Plot() | |
| plt.pause(0.001) | |
| plt.show(block=False) | |
| while 1: | |
| try: | |
| csrfparser = CSRFFinder() | |
| s = requests.Session() | |
| r = s.get(args.url, allow_redirects=True) | |
| logging.info(print(r.url)) | |
| session = r.url.split("/")[4] | |
| url_token = r.url.split("/")[6] | |
| csrfparser.feed(r.text) | |
| if csrfparser.csrf: | |
| logging.info(csrfparser.csrf) | |
| params= { | |
| "token": url_token | |
| } | |
| while 1: | |
| trackpoints = s.get( | |
| f"https://livetrack.garmin.com/api/sessions/{session}/track-points/common", | |
| params=params, | |
| headers={ | |
| "livetrack-csrf-token": csrfparser.csrf, | |
| "Accept": "*/*" | |
| }, | |
| timeout=10 | |
| ).json()['trackPoints'] | |
| logging.info(trackpoints) | |
| a_plot.add_speeds([x['speed']*3.6 for x in trackpoints if 'speed' in x]) | |
| a_plot.add_hr([x['heartRateBeatsPerMin'] for x in trackpoints if 'heartRateBeatsPerMin' in x]) | |
| a_plot.add_cad([x['cadenceCyclesPerMin'] for x in trackpoints if 'cadenceCyclesPerMin' in x]) | |
| if "distanceMeters" in trackpoints[-1]: | |
| a_plot.set_distance(trackpoints[-1]["distanceMeters"]/1000) | |
| params['begin'] = trackpoints[-1]['dateTime'] | |
| plt.draw() | |
| pause(10, False) | |
| #plt.pause(5) | |
| #time.sleep(5) | |
| else: | |
| logging.critical("Failed to get CSRF token") | |
| except KeyboardInterrupt: | |
| raise | |
| except: | |
| traceback.print_exc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment