From 6c1a62e09da32c2b5a7794eb7b54c3f99526ad8c Mon Sep 17 00:00:00 2001 From: Wolfgang Hottgenroth Date: Wed, 12 Mar 2025 21:13:24 +0100 Subject: [PATCH] nicer graph --- src/ntp_routes.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/ntp_routes.py b/src/ntp_routes.py index 8858510..622f5a5 100644 --- a/src/ntp_routes.py +++ b/src/ntp_routes.py @@ -168,3 +168,60 @@ def plot_png(): return Response(img_io, mimetype='image/png') + +@app.route('/plot2.png') +def plot2_png(): + dbh = psycopg.connect() + engine = sqlalchemy.create_engine("postgresql+psycopg://", creator=lambda: dbh) + query = """ + select time_bucket('5 minutes', time) as bucket, + attributes->>'Label' as device, + avg(cast(values->'rootdisp'->>'value' as float)) as rootdisp, + max(cast(values->'stratum'->>'value' as int)) as stratum + from measurements + where time >= date_trunc('day', now()) AND time < date_trunc('day', now()) + '1 day'::interval and + application = 'SNMP' and attributes->>'Label' IN ('harrison', 'david') + group by bucket, attributes->>'Label' + order by bucket, attributes->>'Label' + """ + df = pd.read_sql(query, con=engine) + + df['rootdisp'] = df['rootdisp'] / 1e6 + + + # Extract date for title + plot_date = df['bucket'].dt.date.iloc[0] if not df.empty else "Unknown Date" + + # Create figure with two side-by-side subplots + fig, axes = plt.subplots(1, 2, figsize=(15, 5), sharex=True) + + for i, device in enumerate(['harrison', 'david']): + ax1 = axes[i] + ax2 = ax1.twinx() + + device_df = df[df['device'] == device] + + ax1.plot(device_df['bucket'], device_df['rootdisp'], 'r-', label='Root Dispersion') + ax1.set_xlabel('Time') + ax1.set_ylabel('Root Dispersion (ms)', color='r') + ax1.tick_params(axis='y', labelcolor='r') + + ax2.plot(device_df['bucket'], device_df['stratum'], 'b--', label='Stratum') + ax2.set_ylabel('Stratum', color='b') + ax2.tick_params(axis='y', labelcolor='b') + ax2.set_yticks(range(int(device_df['stratum'].min()), int(device_df['stratum'].max()) + 1)) + + ax1.set_title(f'{device.capitalize()}') + + ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) + fig.autofmt_xdate(rotation=45) + + fig.suptitle(f'NTP Server Comparison - {plot_date}') + fig.tight_layout() + + img_io = io.BytesIO() + plt.savefig(img_io, format='png') + img_io.seek(0) + plt.close(fig) + + return Response(img_io, mimetype='image/png')