-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathroutes.py
More file actions
246 lines (199 loc) · 8.63 KB
/
Copy pathroutes.py
File metadata and controls
246 lines (199 loc) · 8.63 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
from flask import Blueprint, render_template, request, jsonify, send_from_directory, abort, Response, current_app
from flask_login import login_required
from werkzeug.utils import secure_filename
from PIL import Image
from io import BytesIO
import os
import time
import base64
import json
import state
bp = Blueprint('routes', __name__)
@bp.route('/')
@login_required
def dashboard():
return render_template(
'index.html',
status=state.drone_status,
latest_image=state.latest_image,
logs=state.mission_log[-100:],
)
@bp.route('/map')
@login_required
def map_view():
# Proste renderowanie strony z mapą i przyciskami
return render_template('map.html')
@bp.route('/missions')
@login_required
def missions_view():
return render_template('missions.html')
@bp.route('/api/status', methods=['GET', 'POST'])
@login_required
def handle_status():
if request.method == 'POST':
new_data = request.get_json(silent=True)
if new_data:
state.drone_status.update(new_data)
state.drone_status['last_update'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
return jsonify({'success': True, 'status': state.drone_status})
return jsonify({**state.drone_status, 'latest_image': state.latest_image})
@bp.route('/api/image', methods=['POST'])
@login_required
def upload_image():
if 'image' not in request.files:
return jsonify({'success': False, 'error': 'No image provided'}), 400
file = request.files['image']
if file.filename == '':
return jsonify({'success': False, 'error': 'Empty filename'}), 400
filename = secure_filename(f"{int(time.time())}_{file.filename}")
filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
state.latest_image = {
'filename': filename,
'timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
'size': os.path.getsize(filepath),
}
state.log_message(current_app, 'info', f'New image received: {filename}')
return jsonify({'success': True, 'image': state.latest_image})
@bp.route('/images/<path:filename>')
@login_required
def serve_image(filename):
if '..' in filename or filename.startswith('/'):
abort(400)
return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename)
@bp.route('/api/log', methods=['GET', 'POST', 'DELETE'])
@login_required
def handle_log():
if request.method == 'POST':
data = request.get_json(silent=True)
if data and 'message' in data:
level = data.get('level', 'info')
state.log_message(current_app, level, data['message'])
return jsonify({'success': True})
return jsonify({'success': False, 'error': 'Invalid log data'}), 400
if request.method == 'DELETE':
state.mission_log = []
return jsonify({'success': True})
return jsonify({'logs': state.mission_log[-100:]})
@bp.route('/api/missions/start', methods=['POST'])
@login_required
def start_mission():
data = request.get_json(silent=True) or {}
mission = data.get("mission")
# Logging for debugging
current_app.logger.info(f"[MISSION START] Request received for mission {mission}")
if mission is None:
current_app.logger.error("[MISSION START] Mission ID not provided")
return jsonify({'success': False, 'error': 'Mission is required'}), 400
try:
mission = int(mission)
except Exception:
current_app.logger.error(f"[MISSION START] Invalid mission type: {type(mission)}")
return jsonify({'success': False, 'error': 'Mission must be an integer'}), 400
client = current_app.config.get("MQTT_CLIENT")
current_app.logger.info(f"[MISSION START] MQTT Client: {client}")
if not client:
current_app.logger.error("[MISSION START] MQTT client not available!")
return jsonify({'success': False, 'error': 'MQTT client not available'}), 503
topic = current_app.config.get("MQTT_MISSION_TOPIC", "drone/mission/start")
qos = int(current_app.config.get("MQTT_MISSION_QOS", 0))
retain = bool(current_app.config.get("MQTT_MISSION_RETAIN", False))
payload = {"mission": mission, "command": "start"}
current_app.logger.info(f"[MISSION START] Publishing to {topic}")
current_app.logger.info(f"[MISSION START] Payload: {json.dumps(payload)}")
current_app.logger.info(f"[MISSION START] QoS: {qos}, Retain: {retain}")
try:
info = client.publish(topic, json.dumps(payload), qos=qos, retain=retain)
current_app.logger.info(f"[MISSION START] Publish result: rc={info.rc}")
if info.rc != 0:
current_app.logger.error(f"[MISSION START] MQTT publish failed with rc={info.rc}")
return jsonify({'success': False, 'error': f'MQTT publish failed (rc={info.rc})'}), 502
except Exception as exc:
current_app.logger.error(f"[MISSION START] Exception during publish: {exc}")
return jsonify({'success': False, 'error': str(exc)}), 502
state.log_message(current_app, "info", f"Mission {mission} start requested")
current_app.logger.info(f"[MISSION START] Mission {mission} start request logged successfully")
return jsonify({'success': True, 'mission': mission})
@bp.route('/api/telemetry', methods=['POST'])
@login_required
def telemetry_endpoint():
data = request.get_json(silent=True)
if not data:
return jsonify({'success': False, 'error': 'No data provided'}), 400
if 'status' in data:
state.drone_status.update(data['status'])
state.drone_status['last_update'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
if 'image' in data and data['image']:
try:
img_data = data['image'].split(',', 1)[1]
img = Image.open(BytesIO(base64.b64decode(img_data)))
filename = f"{int(time.time())}_drone_capture.jpg"
filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
img.save(filepath, 'JPEG', quality=85)
state.latest_image = {
'filename': filename,
'timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
'size': os.path.getsize(filepath),
}
except Exception as exc:
state.log_message(current_app, 'error', f'Failed to process image: {exc}')
if 'logs' in data:
for log_entry in data['logs']:
level = log_entry.get('level', 'info')
state.log_message(current_app, level, log_entry.get('message', ''))
return jsonify({'success': True})
@bp.route('/api/images', methods=['GET', 'DELETE'])
@login_required
def images_api():
folder = current_app.config['UPLOAD_FOLDER']
if request.method == 'DELETE':
errors = []
for filename in os.listdir(folder):
try:
os.remove(os.path.join(folder, filename))
except Exception as exc:
errors.append(f"{filename}: {exc}")
if errors:
state.log_message(current_app, 'error', f'Image delete errors: {errors}')
return jsonify({'success': False, 'error': errors}), 500
state.log_message(current_app, 'info', 'Gallery cleared')
return jsonify({'success': True})
images = sorted(os.listdir(folder), reverse=True)
return jsonify({'images': images})
@bp.route('/healthz')
def healthz():
return jsonify({'status': 'ok'})
# --- Video feed (best-effort; Render likely doesn't provide camera) ---
try:
import cv2
_CV2_AVAILABLE = True
except Exception:
cv2 = None
_CV2_AVAILABLE = False
def generate_frames():
if not _CV2_AVAILABLE:
raise RuntimeError('OpenCV is not available in the environment')
camera = cv2.VideoCapture(0)
if not camera.isOpened():
raise RuntimeError('Camera access unavailable')
while True:
success, frame = camera.read()
if not success:
break
ret, buffer = cv2.imencode('.jpg', frame)
if not ret:
break
frame_bytes = buffer.tobytes()
yield (b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + frame_bytes + b"\r\n")
@bp.route('/video_feed')
@login_required
def video_feed():
if not _CV2_AVAILABLE:
state.log_message(current_app, 'error', 'OpenCV nie jest dostępne w środowisku')
return jsonify({'success': False, 'error': 'OpenCV nie jest dostępne na serwerze'}), 503
try:
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
except Exception as exc:
state.log_message(current_app, 'error', f'Błąd strumienia wideo: {exc}')
return jsonify({'success': False, 'error': str(exc)}), 503