-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
276 lines (230 loc) · 9.65 KB
/
Copy pathapp.py
File metadata and controls
276 lines (230 loc) · 9.65 KB
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
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2025 Sun Devil Rocketry
import atexit
import threading
import json
from flask import Flask, request, Response, jsonify
from flask_cors import CORS
from hardware import serial_connection, sensor_sentry, serial_lock, background_lifecycle_lock, firmware # Objects from hardware.py
from serial import SerialException
from threads import poll_dashboard_dump
from typing import List, Dict
from util import make_safe_number
# BaseController
from SDECv2 import BaseController, Controller, Firmware, create_controllers, create_firmwares
# SerialController
from SDECv2 import SerialObj
# Sensor
from SDECv2 import SensorSentry
# Parser
from SDECv2 import Telemetry, Parser, create_configs
# Sensor utility
from SDECv2 import create_sensors
app = Flask(__name__)
CORS(app)
# Globals for polling dashboard dump
stop_event = threading.Event()
telemetry_obj = Telemetry()
dashboard_dump_thread = threading.Thread(
target=poll_dashboard_dump,
args=(serial_connection, stop_event, telemetry_obj),
daemon=True
)
@app.route("/ping")
def ping():
with serial_lock():
serial_connection.send(b"\x01")
data = serial_connection.read()
if data == b"\x05" or data == b'\x10': #should not hardcode
return Response("Ping response received", status=200)
else:
return Response("Ping failed", status=400)
@app.route("/comports")
def comports():
try:
with serial_lock():
comports = serial_connection.available_comports()
if comports:
# If there's an existing connection,
# prune the other comports from the
# list since the API only supports one at a time
port = serial_connection.get_port_name()
if port:
comports = { port: comports[port] }
return jsonify(comports), 200
else:
return Response("No ports present.", 204)
except Exception as e:
return Response(str(e), 500)
@app.route("/comports/active")
def active_comports():
port = ""
try:
with serial_lock():
port = serial_connection.get_port_name()
if not port:
return Response("No connection present.", 204)
else:
return Response(port, 200)
except Exception as e:
return Response(str(e), 500)
@app.route("/connect", methods=["POST"])
def connect():
# Set up handling for request
connected = False
data = request.get_json(silent=True)
if not data: return Response("Missing POST JSON data", status=400)
name = data.get("comport")
timeout = data.get("timeout", 5)
if not name: return Response("Missing 'comport' field", status=400)
try:
timeout = int(timeout)
except (TypeError, ValueError):
return Response("Invalid timeout value", status=400)
# Initialize a new connection if one does not exist
try:
with serial_lock():
# This check can cause a race condition. It needs to be in the lock.
if serial_connection.target is not None:
connected = True
else:
# Initialize and connect in this block
serial_connection.init_comport(name=name, baudrate=921600, timeout=timeout)
if not serial_connection.open_comport(): return Response("Failed to open comport", status=400)
# send connect opcode
serial_connection.connect()
if( serial_connection.target is None ):
return Response("Serial connection failed.", status=400)
else:
connected = True
except SerialException as e:
return Response("Serial connection error", status=400)
# Return connection status
if connected and serial_connection.target is not None:
# Robustness: Check if the requested port is not the open one
if serial_connection.get_port_name() != name:
return Response("Another connection is already open", 400)
return jsonify({
"controller": {
"firmware": serial_connection.target.firmware.name,
"name": serial_connection.target.controller.name
},
"status": "connected"
})
else: # Shouldn't get here -- protective case
return Response("Serial connection failed (server-side error).", status=500)
@app.route("/disconnect")
def disconnect():
with serial_lock():
if not serial_connection.close_comport(): return Response("Failed to close comport", status=400)
return Response("Disconnected", status=200)
@app.route("/wireless-stats")
def wireless_stats():
if serial_connection.target is None:
return Response("Not connected to a target.", status=400)
elif serial_connection.target.firmware.id == b'\x11':
return telemetry_obj.get_latest_wireless_stats()
else:
return Response("No wireless target available.", status=204)
@app.route("/dashboard-dump", methods=["GET", "POST"])
def dashboard_dump():
global dashboard_dump_thread
if request.method == "GET":
return jsonify(telemetry_obj.get_latest_dashboard_dump())
elif request.method == "POST":
data = request.get_json(silent=True)
if not data: return Response("Missing POST JSON data", status=400)
start = data.get("start")
stop = data.get("stop")
if bool(start) == bool(stop): return Response("Only start XOR stop can be set", status=400)
with background_lifecycle_lock():
if start:
if dashboard_dump_thread.is_alive(): # Protective case
return Response("Polling was already running", status=200)
else:
stop_event.clear()
dashboard_dump_thread = threading.Thread(
target=poll_dashboard_dump,
args=(serial_connection, stop_event, telemetry_obj),
daemon=True
)
dashboard_dump_thread.start()
return Response("Dashboard-dump poll started", status=200)
elif stop:
if not dashboard_dump_thread.is_alive(): # Protective case
return Response("Polling was already stopped", status=200)
else:
stop_event.set()
return Response("Dashboard-dump poll stopped", status=200)
return Response("Invalid condition", status=400)
@app.route("/sensor-dump")
def sensor_dump():
with serial_lock():
sensor_dump = sensor_sentry.dump(serial_connection)
data_dict = {}
for sensor, readout in sensor_dump.items():
val = make_safe_number(readout)
data_dict[sensor.short_name] = val
return data_dict
@app.route("/sensor-poll")
def sensor_poll():
polls = int(request.args.get("count", 0)) # Poll count takes priority
time = int(request.args.get("time", 0))
def do_poll():
with serial_lock():
if polls:
iterator = sensor_sentry.poll(serial_connection, count=polls)
elif time:
iterator = sensor_sentry.poll(serial_connection, timeout=time)
else:
iterator = sensor_sentry.poll(serial_connection, count=10) # No given values defaults to 10 polls
for poll in iterator:
for sensor, readout in poll.items():
val = readout if readout is not None else 0.0
yield f"{sensor.name}: {val:.2f} {sensor.unit}"
return Response(do_poll(), mimetype="text/plain")
@app.route("/preset", methods=["GET", "POST"])
def preset():
if serial_connection.target is None:
return Response("No device connected!", 400)
elif serial_connection.target.controller.id != b"\x05": # Check if FC
return Response("The device is not a flight computer!", 400)
try:
if request.method == "GET": # DOWNLOAD
with serial_lock():
appa_preset_config = create_configs.appa_preset_config()
appa_parser = Parser(
preset_config=appa_preset_config,
preset_data=None
)
appa_parser.download_preset(serial_connection, path="SDECv2/a_output/temp_download.json")
with open("SDECv2/a_output/temp_download.json", "r") as f:
downloaded_preset = json.load(f)
return Response(json.dumps(downloaded_preset, sort_keys=False), 200, mimetype="application/json")
elif request.method == "POST": # UPLOAD
content = json.loads(request.data.decode("utf-8"))
if not content:
return Response("You must POST a json.", 400)
with serial_lock():
appa_preset_config = create_configs.appa_preset_config()
appa_parser = Parser(
preset_config=appa_preset_config,
preset_data=None
)
with open("SDECv2/a_input/temp_upload.json", "w") as f:
json.dump(content, f)
appa_parser.upload_preset(serial_connection, path="SDECv2/a_input/temp_upload.json")
return Response("Successful upload!", 200)
except Exception as e:
return Response(str(e), 500)
@app.route("/")
def default():
return "Hello, welcome to the SDECv2 API"
@atexit.register
def shutdown():
try: serial_connection.close_comport()
except: pass
stop_event.set()
if dashboard_dump_thread.is_alive(): dashboard_dump_thread.join()
if __name__ == "__main__":
app.run()