-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
408 lines (344 loc) · 13.2 KB
/
Copy pathapp.py
File metadata and controls
408 lines (344 loc) · 13.2 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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#!/usr/bin/env python3
"""
FlyCharts - Enhanced Flask Application with SimConnect and SimBrief Integration
"""
from flask import Flask, jsonify, send_file, send_from_directory, Response, request
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import logging
import os
import time
import threading
from datetime import datetime
import requests
import xml.etree.ElementTree as ET
# SimConnect imports with error handling
try:
from SimConnect import SimConnect, AircraftRequests
SIMCONNECT_AVAILABLE = True
except ImportError:
SIMCONNECT_AVAILABLE = False
logging.warning("SimConnect library not available")
# Initialize Flask app
app = Flask(__name__, static_folder='.')
app.config['SECRET_KEY'] = 'flycharts-secret-key-2024'
# Enable CORS
CORS(app)
# Initialize SocketIO
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('flycharts.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# SimBrief API configuration
SIMBRIEF_API_URL = "https://www.simbrief.com/api/xml.fetcher.php"
class SimConnectManager:
def __init__(self):
self.sm = None
self.aq = None
self.connected = False
self.update_thread = None
self.running = False
self.last_position = None
def connect(self):
"""Connect to SimConnect"""
if not SIMCONNECT_AVAILABLE:
return {
"success": False,
"message": "SimConnect library not installed",
"connected": False,
"timestamp": datetime.now().isoformat()
}
try:
self.sm = SimConnect()
self.aq = AircraftRequests(self.sm, _time=500) # 500ms cache
# Test connection
test_data = self.aq.get("PLANE_LATITUDE")
self.connected = True
self.start_update_loop()
logger.info("Successfully connected to SimConnect")
return {
"success": True,
"message": "Connected to SimConnect successfully",
"connected": True,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"Failed to connect to SimConnect: {e}")
self.connected = False
return {
"success": False,
"message": f"Failed to connect: {str(e)}",
"connected": False,
"timestamp": datetime.now().isoformat()
}
def disconnect(self):
"""Disconnect from SimConnect"""
try:
self.running = False
if self.update_thread and self.update_thread.is_alive():
self.update_thread.join(timeout=3)
if self.sm:
self.sm.exit()
self.sm = None
self.aq = None
self.connected = False
self.last_position = None
logger.info("Disconnected from SimConnect")
return {
"success": True,
"message": "Disconnected successfully",
"connected": False,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"Error during disconnect: {e}")
return {
"success": False,
"message": f"Disconnect error: {str(e)}",
"connected": self.connected,
"timestamp": datetime.now().isoformat()
}
def get_status(self):
"""Get current connection status"""
return {
"connected": self.connected,
"simconnect_available": SIMCONNECT_AVAILABLE,
"last_position": self.last_position,
"timestamp": datetime.now().isoformat()
}
def get_aircraft_title(self):
title = self.aq.get("TITLE")
if isinstance(title, bytes):
return title.decode(errors="ignore")
return title or ""
def get_aircraft_position(self):
"""Get current aircraft position and details"""
if not self.connected or not self.aq:
return None
try:
# Get position data
latitude = self.aq.get("PLANE_LATITUDE")
longitude = self.aq.get("PLANE_LONGITUDE")
altitude = self.aq.get("PLANE_ALTITUDE")
heading = self.aq.get("PLANE_HEADING_DEGREES_MAGNETIC")
airspeed = self.aq.get("AIRSPEED_TRUE")
ground_speed = self.aq.get("GROUND_VELOCITY")
vertical_speed = self.aq.get("VERTICAL_SPEED")
# Get aircraft details
aircraft_title = self.get_aircraft_title()
atc_id = self.aq.get("ATC_ID")
if latitude is not None and longitude is not None:
position_data = {
"latitude": float(latitude),
"longitude": float(longitude),
"altitude": float(altitude or 0),
"heading": float(heading or 0),
"airspeed": float(airspeed or 0),
"ground_speed": float(ground_speed or 0),
"vertical_speed": float(vertical_speed or 0),
"aircraft_title": str(aircraft_title or "Unknown"),
"atc_id": str(atc_id or ""),
"timestamp": datetime.now().isoformat()
}
self.last_position = position_data
return position_data
return None
except Exception as e:
logger.error(f"Error getting aircraft position: {e}")
return None
def start_update_loop(self):
"""Start background update loop"""
if self.update_thread and self.update_thread.is_alive():
return
self.running = True
self.update_thread = threading.Thread(target=self._update_loop, daemon=True)
self.update_thread.start()
def _update_loop(self):
"""Background loop for real-time updates"""
while self.running and self.connected:
try:
position = self.get_aircraft_position()
if position:
# Emit to all connected clients
socketio.emit('aircraft_position_update', position)
time.sleep(0.5) # Update every second
except Exception as e:
logger.error(f"Error in update loop: {e}")
time.sleep(2)
# Global SimConnect manager
simconnect_manager = SimConnectManager()
# Routes
@app.route('/')
def serve_index():
"""Serve main index page"""
return send_file('index.html')
@app.route('/health')
def health_check():
"""Health check endpoint"""
status = simconnect_manager.get_status()
return jsonify({
"status": "Backend running",
"simconnect_available": status["simconnect_available"],
"simconnect_connected": status["connected"],
"timestamp": status["timestamp"]
})
# Legacy endpoints (backward compatibility)
@app.route('/aircraft/position', methods=['GET'])
def get_aircraft_position_legacy():
"""Legacy aircraft position endpoint"""
position = simconnect_manager.get_aircraft_position()
if position:
return jsonify(position)
else:
return jsonify({"error": "No position data available"}), 500
@app.route('/aircraft/type', methods=['GET'])
def get_aircraft_type_legacy():
"""Legacy aircraft type endpoint"""
position = simconnect_manager.get_aircraft_position()
if position and position.get('aircraft_title'):
return jsonify({"type": position['aircraft_title']})
else:
return jsonify({"error": "No aircraft data available"}), 500
# New SimConnect API endpoints
@app.route('/api/simconnect/connect', methods=['POST'])
def connect_simconnect():
"""Connect to SimConnect"""
result = simconnect_manager.connect()
socketio.emit('simconnect_status', result)
return jsonify(result)
@app.route('/api/simconnect/disconnect', methods=['POST'])
def disconnect_simconnect():
"""Disconnect from SimConnect"""
result = simconnect_manager.disconnect()
socketio.emit('simconnect_status', result)
return jsonify(result)
@app.route('/api/simconnect/status', methods=['GET'])
def get_simconnect_status():
"""Get SimConnect status"""
return jsonify(simconnect_manager.get_status())
@app.route('/api/aircraft/position', methods=['GET'])
def get_aircraft_position_api():
"""Get current aircraft position"""
position = simconnect_manager.get_aircraft_position()
if position:
return jsonify({"success": True, "data": position})
else:
return jsonify({"success": False, "message": "No position data available"})
@app.route('/api/simbrief/fetch', methods=['POST'])
def fetch_simbrief_plan():
"""Fetch the latest SimBrief flight plan for a given Pilot ID"""
try:
data = request.get_json()
pilot_id = data.get('pilotId')
if not pilot_id:
logger.error("Pilot ID is required")
return jsonify({
"success": False,
"message": "Pilot ID is required"
}), 400
logger.info(f"Fetching SimBrief flight plan for Pilot ID: {pilot_id}")
# Prepare API request
params = {
"userid": pilot_id,
"type": "OFP",
"output": "XML"
}
response = requests.get(SIMBRIEF_API_URL, params=params, timeout=10)
if response.status_code != 200:
logger.error(f"SimBrief API request failed with status {response.status_code}: {response.text[:500]}")
return jsonify({
"success": False,
"message": f"SimBrief API request failed with status {response.status_code}"
}), response.status_code
# Verify XML content
try:
xml_content = response.text
ET.fromstring(xml_content) # Validate XML
logger.info(f"Successfully fetched SimBrief flight plan for Pilot ID: {pilot_id}")
return jsonify({
"success": True,
"xml": xml_content
})
except ET.ParseError as e:
logger.error(f"Invalid XML response from SimBrief: {e}")
return jsonify({
"success": False,
"message": "Invalid XML response from SimBrief"
}), 500
except Exception as e:
logger.error(f"Error fetching SimBrief flight plan: {e}")
return jsonify({
"success": False,
"message": f"Error fetching flight plan: {str(e)}"
}), 500
# WebSocket events
@socketio.on('connect')
def handle_connect():
"""Handle WebSocket connection"""
logger.info(f"Client connected: {request.sid}")
# Send current status
status = simconnect_manager.get_status()
emit('simconnect_status', status)
# Send current position if available
if status['last_position']:
emit('aircraft_position_update', status['last_position'])
@socketio.on('disconnect')
def handle_disconnect():
"""Handle WebSocket disconnection"""
logger.info(f"Client disconnected: {request.sid}")
@socketio.on('request_status')
def handle_status_request():
"""Handle status request"""
status = simconnect_manager.get_status()
emit('simconnect_status', status)
@socketio.on('request_position')
def handle_position_request():
"""Handle position request"""
position = simconnect_manager.get_aircraft_position()
if position:
emit('aircraft_position_update', position)
# Static file serving
@app.route('/favicon.ico')
def serve_favicon_ico():
"""Suppress favicon requests"""
return Response(status=204)
@app.route('/<path:path>')
def serve_static(path):
"""Serve static files"""
if os.path.exists(path):
return send_from_directory('.', path)
return jsonify({"error": "File not found"}), 404
# Error handlers
@app.errorhandler(404)
def not_found_error(error):
return jsonify({"error": "Not Found"}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({"error": "Internal Server Error"}), 500
if __name__ == '__main__':
logger.info("Starting FlyCharts application...")
# Try to auto-connect on startup if available
if SIMCONNECT_AVAILABLE:
logger.info("Attempting auto-connect to SimConnect...")
simconnect_manager.connect()
try:
socketio.run(
app,
host='0.0.0.0',
port=5500,
debug=True,
allow_unsafe_werkzeug=True
)
except KeyboardInterrupt:
logger.info("Application stopped by user")
simconnect_manager.disconnect()
except Exception as e:
logger.error(f"Failed to start application: {e}")
raise