forked from MITHaystack/srt-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
345 lines (302 loc) · 10.4 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
"""app.py
Dash Small Radio Telescope Web App Dashboard
"""
import dash
try:
from dash import dcc
except:
import dash_core_components as dcc
try:
from dash import html
except:
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State, ClientsideFunction
import flask
import plotly.io as pio
import numpy as np
from time import time
from pathlib import Path
import base64
from .layouts import monitor_page, system_page # , figure_page
from .layouts.sidebar import generate_sidebar
from .messaging.status_fetcher import StatusThread
from .messaging.command_dispatcher import CommandThread
from .messaging.spectrum_fetcher import SpectrumThread
def generate_app(config_dir, config_dict):
"""Generates App and Server Objects for Hosting Dashboard
Parameters
----------
config_dir : str
Path to the Configuration Directory
config_dict : dict
Configuration Directory (Output of YAML Parser)
Returns
-------
(server, app)
"""
config_dict["CONFIG_DIR"] = config_dir
# Set Up Flash and Dash Objects
server = flask.Flask(
__name__
) # these messages "127.0.0.1 - - [16/Mar/2024 12:10:13] "POST / HTTP/1.1" 200 -"" are generated by Flask
app = dash.Dash(
__name__,
server=server,
external_stylesheets=[dbc.themes.BOOTSTRAP],
meta_tags=[
{"name": "viewport", "content": "width=device-width, initial-scale=1"}
],
)
app.title = "SRT Dashboard"
# Start Listening for Radio and Status Data
status_thread = StatusThread(port=5555)
status_thread.start()
command_thread = CommandThread(port=5556)
command_thread.start()
history_length = config_dict["SPECTRUM_HISTORY_LENGTH"]
raw_spectrum_thread = SpectrumThread(port=5561, history_length=history_length)
raw_spectrum_thread.start()
cal_spectrum_thread = SpectrumThread(port=5563, history_length=history_length)
cal_spectrum_thread.start()
# Dictionary of Pages and matching URL prefixes
pages = {
"Monitor Page": "monitor-page",
"System Page": "system-page",
# "Figure Page": "figure-page"
}
if "DASHBOARD_REFRESH_MS" in config_dict.keys():
refresh_time = config_dict["DASHBOARD_REFRESH_MS"] # ms
else:
refresh_time = 1000
pio.templates.default = "seaborn" # Style Choice for Graphs
curfold = Path(__file__).parent.absolute()
# Generate Sidebar Objects
side_title = "Small Radio Telescope"
image_filename = curfold.joinpath(
"images", "MIT_HO_logo_landscape.png"
) # replace with your own image
# Check if file is there and if not put in a single pixel image.
if image_filename.exists():
encoded_image = base64.b64encode(open(image_filename, "rb").read())
else:
encoded_image = b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
side_content = {
"Status": dcc.Markdown(id="sidebar-status"),
"Pages": html.Div(
[
html.H4("Pages"),
dbc.Nav(
[
dbc.NavLink(
page_name,
href=f"/{pages[page_name]}",
id=f"{pages[page_name]}-link",
)
for page_name in pages
],
vertical=True,
pills=True,
),
]
),
"Image": html.Div(
[
html.A(
[
html.Img(
src="data:image/png;base64,{}".format(
encoded_image.decode()
),
style={"height": "100%", "width": "100%"},
)
],
href="https://www.haystack.mit.edu/",
)
]
),
}
sidebar = generate_sidebar(side_title, side_content)
# Build Dashboard Framework
content = html.Div(id="page-content")
layout = html.Div(
[
dcc.Location(id="url"),
sidebar,
content,
dcc.Interval(id="interval-component", interval=refresh_time, n_intervals=0),
html.Div(id="output-clientside"),
],
id="mainContainer",
style={
"height": "100vh",
"min_height": "100vh",
"width": "100%",
"display": "inline-block",
},
)
app.layout = layout # Set App Layout to Dashboard Framework
app.validation_layout = html.Div(
[
layout,
monitor_page.generate_layout(),
system_page.generate_layout(),
# figure_page.generate_layout()
]
) # Necessary for Allowing Other Files to Create Callbacks
# Create Resizing JS Script Callback
app.clientside_callback(
ClientsideFunction(namespace="clientside", function_name="resize"),
Output("output-clientside", "children"),
[Input("page-content", "children")],
)
# Create Callbacks for Monitoring Page Objects
monitor_page.register_callbacks(
app,
config_dict,
status_thread,
command_thread,
raw_spectrum_thread,
cal_spectrum_thread,
)
# Create Callbacks for System Page Objects
system_page.register_callbacks(app, config_dict, status_thread)
# # Create Callbacks for figure page callbacks
# figure_page.register_callbacks(app,config_dict, status_thread)
# Activates Downloadable Saves - Caution
if config_dict["DASHBOARD_DOWNLOADS"]:
@server.route("/download/<path:path>")
def download(path):
"""Serve a file from the upload directory."""
return flask.send_from_directory(
Path(config_dict["SAVE_DIRECTORY"]).expanduser(),
path,
as_attachment=True,
)
@app.callback(
[Output(f"{pages[page_name]}-link", "active") for page_name in pages],
[Input("url", "pathname")],
)
def toggle_active_links(pathname):
"""Sets the Page Links to Highlight to Current Page
Parameters
----------
pathname : str
Current Page Pathname
Returns
-------
list
Sparse Bool List Which is True Only on the Proper Page Link
"""
if pathname == "/":
# Treat page 1 as the homepage / index
return tuple([i == 0 for i, _ in enumerate(pages)])
return [pathname == f"/{pages[page_name]}" for page_name in pages]
@app.callback(
Output("sidebar", "className"),
[Input("sidebar-toggle", "n_clicks")],
[State("sidebar", "className")],
)
def toggle_classname(n, classname):
"""Changes Sidebar's className When it is Collapsed
Notes
-----
As per the Dash example this is based on, changing the sidebar's className
changes the CSS that applying to it, allowing for hiding the sidebar
Parameters
----------
n
Num Clicks on Button
classname : str
Current Classname
Returns
-------
"""
if n and classname == "":
return "collapsed"
return ""
@app.callback(
Output("sidebar-status", "children"),
[Input("interval-component", "n_intervals")],
)
def update_status_display(n):
"""Updates the Status Part of the Sidebar
Parameters
----------
n : int
Number of Intervals that Have Occurred (Unused)
Returns
-------
str
Content for the Sidebar, Formatted as Markdown
"""
status = status_thread.get_status()
if status is None:
az = el = np.nan
az_offset = el_offset = np.nan
cf = np.nan
bandwidth = np.nan
status_string = "SRT Not Connected"
vlsr = np.nan
rec_status = "No"
else:
az = status["motor_azel"][0]
el = status["motor_azel"][1]
az_offset = status["motor_offsets"][0]
el_offset = status["motor_offsets"][1]
cf = status["center_frequency"]
bandwidth = status["bandwidth"]
vlsr = status["vlsr"]
rec_status = "No"
if "None" not in status["radio_save_task"]:
rec_status = "Yes"
time_dif = time() - status["time"]
if time_dif > 5:
status_string = "SRT Daemon Not Available"
elif status["queue_size"] == 0 and status["queued_item"] == "None":
status_string = "SRT Inactive"
else:
status_string = "SRT In Use!"
if rec_status == "No":
status_string = f"""
# {status_string}
- Currently recording: No"""
if rec_status == "Yes":
status_string = f"""
# {status_string}
- Currently recording: **Yes**"""
status_string = f"""
#### {status_string}
- Motor Az, El: {az:.1f}, {el:.1f} deg
- Motor Offsets: {az_offset:.1f}, {el_offset:.1f} deg
- Center Frequency: {cf / pow(10, 6)} MHz
- Bandwidth: {bandwidth / pow(10, 6)} MHz
- VLSR: {vlsr:.1f} km/s
"""
return status_string
@app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def render_page_content(pathname):
"""Renders the Correct Content of the Page Portion
Parameters
----------
pathname : str
URL Path Requested
Returns
-------
Content of page-content
"""
if pathname in ["/", f"/{pages['Monitor Page']}"]:
return monitor_page.generate_layout()
elif pathname == f"/{pages['System Page']}":
return system_page.generate_layout()
# elif pathname == f"/{pages['Figure Page']}":
# return figure_page.generate_layout()
# If the user tries to reach a different page, return a 404 message
return dbc.Jumbotron(
[
html.H1("404: Not found", className="text-danger"),
html.Hr(),
html.P(f"The pathname {pathname} was not recognised..."),
]
)
return server, app