Skip to content

Instantly share code, notes, and snippets.

@RedBlaze42
Last active September 10, 2022 14:40
Show Gist options
  • Save RedBlaze42/2290b63e69f404080dbed93a277a1d6b to your computer and use it in GitHub Desktop.
Save RedBlaze42/2290b63e69f404080dbed93a277a1d6b to your computer and use it in GitHub Desktop.
LiveGraph
import plotly.graph_objects as go
import dash
from dash import dcc
from dash.dependencies import Input, Output
from dash import html
from functools import partial
import serial
class LiveGraph():
def __init__(self, update_interval=1):
self.app = dash.Dash()
self.app.layout = html.Div([
dcc.Graph(id='live-update-graph', style={"width": "99vw", "height": "95vh"}),
dcc.Interval(
id='interval-component',
interval=update_interval*1000, # in milliseconds
n_intervals=0
)
])
def start(self):
self.app.run_server(debug=True)
def update_function(self, function):
return self.app.callback(
Output('live-update-graph', 'figure'),
[Input('live-update-graph', 'figure'),
Input('interval-component', 'n_intervals')]
)(function)
def main_serial():
live_graph = LiveGraph()
live_graph.ser = None
def read_serial_data():
if live_graph.ser is None: live_graph.ser = serial.Serial("COM5", 9600, timeout=0.3)
ser = live_graph.ser
output = list()
while ser.in_waiting > 0:
new_line = ser.readline().decode("utf-8")
print(new_line)
output.append(new_line.split(","))
return output
data = dict(x=[], y=[], mode="lines")
@live_graph.update_function
def update(fig, n):
new_data = read_serial_data()
data["x"].extend([line[0] for line in new_data])
data["y"].extend([line[1] for line in new_data])
return {
'data': [data],
'layout': {
'uirevision': 1,
}
}
live_graph.start()
def main_carte():
import re
gps_regex = re.compile(f"T,(?:.*?,)(-?\d+\.\d+),(-?\d+\.\d+),(?:.*?,){8}")
live_graph = LiveGraph()
live_graph.i = 0
live_graph.data = dict(long=list(), lat=list())
with open("test_gps.txt", "r") as f:
gps_pos = re.findall(gps_regex, f.read())
live_graph.gps_lat = [lat for lat, long in gps_pos]
live_graph.gps_long = [long for lat, long in gps_pos]
@live_graph.update_function
def update(fig, n):
live_graph.i += 1
if live_graph.i > 60:
live_graph.i = 0
window_end = int(len(live_graph.gps_lat)*live_graph.i/60)
live_graph.data["long"] = live_graph.gps_long[:window_end]
live_graph.data["lat"] = live_graph.gps_lat[:window_end]
fig = go.Figure(go.Scattermapbox(
lat=live_graph.data["lat"],
lon=live_graph.data["long"],
mode='lines+markers'
))
fig.update_layout(mapbox_style="open-street-map",
margin={"r":0,"t":0,"l":0,"b":0},
uirevision=1
)
return fig.to_dict()
live_graph.start()
if __name__ == "__main__":
main_serial()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment