-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
300 lines (254 loc) · 9.93 KB
/
app.py
File metadata and controls
300 lines (254 loc) · 9.93 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
"""
GNSS Satellite Tracker - Python Backend
Real-time tracking of GPS, GLONASS, Galileo, and BeiDou satellites
"""
from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
from datetime import datetime, timedelta
import requests
from skyfield.api import load, EarthSatellite, wgs84
from skyfield.timelib import Time
import numpy as np
from functools import lru_cache
import time
app = Flask(__name__)
CORS(app)
# GNSS Constellation Configuration
GNSS_GROUPS = {
'gps-ops': {'name': 'GPS (USA)', 'color': '#00FF00'},
'glonass-ops': {'name': 'GLONASS (Russia)', 'color': '#FF4444'},
'galileo': {'name': 'Galileo (EU)', 'color': '#4444FF'},
'beidou': {'name': 'BeiDou (China)', 'color': '#FFFF00'}
}
# Cache configuration
CACHE_DURATION = 300 # 5 minutes
tle_cache = {}
ts = load.timescale()
@lru_cache(maxsize=128)
def fetch_tle_data(group):
"""Fetch TLE data from CelesTrak with caching"""
cache_key = f'tle_{group}'
current_time = time.time()
# Check cache
if cache_key in tle_cache:
cached_data, cached_time = tle_cache[cache_key]
if current_time - cached_time < CACHE_DURATION:
return cached_data
# Fetch fresh data
url = f'https://celestrak.org/NORAD/elements/gp.php?GROUP={group}&FORMAT=tle'
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
tle_data = response.text
tle_cache[cache_key] = (tle_data, current_time)
return tle_data
except Exception as e:
print(f"Error fetching TLE for {group}: {e}")
return None
def parse_tle(tle_text, group):
"""Parse TLE data into satellite objects"""
lines = tle_text.strip().split('\n')
satellites = []
for i in range(0, len(lines) - 2, 3):
try:
name = lines[i].strip()
line1 = lines[i + 1]
line2 = lines[i + 2]
if line1.startswith('1 ') and line2.startswith('2 '):
satellite = EarthSatellite(line1, line2, name, ts)
satellites.append({
'name': name,
'satellite': satellite,
'group': group,
'line1': line1,
'line2': line2
})
except Exception as e:
continue
return satellites
def calculate_satellite_position(satellite_obj, time_obj):
"""Calculate satellite position at given time"""
try:
geocentric = satellite_obj.at(time_obj)
subpoint = wgs84.subpoint(geocentric)
# Get position in ECEF coordinates
position = geocentric.position.km
velocity = geocentric.velocity.km_per_s
return {
'latitude': subpoint.latitude.degrees,
'longitude': subpoint.longitude.degrees,
'altitude': subpoint.elevation.km,
'position': {
'x': float(position[0]),
'y': float(position[1]),
'z': float(position[2])
},
'velocity': {
'x': float(velocity[0]),
'y': float(velocity[1]),
'z': float(velocity[2])
},
'speed': float(np.linalg.norm(velocity))
}
except Exception as e:
return None
def calculate_orbit_path(satellite_obj, start_time, num_points=180):
"""Calculate orbital path for visualization"""
try:
# Calculate orbital period (approximate)
mean_motion = satellite_obj.model.no_kozai # radians per minute
period_minutes = (2 * np.pi) / mean_motion
time_step = period_minutes / num_points
orbit_points = []
for i in range(num_points + 1):
future_time = start_time + timedelta(minutes=i * time_step)
t = ts.utc(future_time.year, future_time.month, future_time.day,
future_time.hour, future_time.minute, future_time.second)
geocentric = satellite_obj.at(t)
position = geocentric.position.km
orbit_points.append({
'x': float(position[0]),
'y': float(position[1]),
'z': float(position[2])
})
return orbit_points
except Exception as e:
return []
@app.route('/')
def index():
"""Serve main page"""
return render_template('index.html')
@app.route('/api/satellites')
def get_satellites():
"""Get all GNSS satellites with current positions"""
try:
time_str = request.args.get('time', None)
if time_str:
target_time = datetime.fromisoformat(time_str.replace('Z', '+00:00'))
else:
target_time = datetime.utcnow()
t = ts.utc(target_time.year, target_time.month, target_time.day,
target_time.hour, target_time.minute, target_time.second)
all_satellites = []
for group, info in GNSS_GROUPS.items():
tle_data = fetch_tle_data(group)
if not tle_data:
continue
satellites = parse_tle(tle_data, group)
for sat in satellites:
position_data = calculate_satellite_position(sat['satellite'], t)
if position_data:
all_satellites.append({
'name': sat['name'],
'group': group,
'groupName': info['name'],
'color': info['color'],
'position': position_data['position'],
'latitude': position_data['latitude'],
'longitude': position_data['longitude'],
'altitude': position_data['altitude'],
'velocity': position_data['velocity'],
'speed': position_data['speed'],
'tle': {
'line1': sat['line1'],
'line2': sat['line2']
}
})
return jsonify({
'satellites': all_satellites,
'count': len(all_satellites),
'timestamp': target_time.isoformat()
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/satellite/<int:index>/orbit')
def get_satellite_orbit(index):
"""Get orbital path for a specific satellite"""
try:
time_str = request.args.get('time', None)
if time_str:
target_time = datetime.fromisoformat(time_str.replace('Z', '+00:00'))
else:
target_time = datetime.utcnow()
# Get all satellites to find the one at the given index
all_satellites = []
for group in GNSS_GROUPS.keys():
tle_data = fetch_tle_data(group)
if tle_data:
satellites = parse_tle(tle_data, group)
all_satellites.extend(satellites)
if index >= len(all_satellites):
return jsonify({'error': 'Satellite index out of range'}), 404
satellite = all_satellites[index]['satellite']
orbit_path = calculate_orbit_path(satellite, target_time)
return jsonify({
'orbit': orbit_path,
'points': len(orbit_path)
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/constellations')
def get_constellations():
"""Get list of available GNSS constellations"""
return jsonify({
'constellations': [
{
'id': key,
'name': value['name'],
'color': value['color']
}
for key, value in GNSS_GROUPS.items()
]
})
@app.route('/api/satellite/<int:index>/info')
def get_satellite_info(index):
"""Get detailed information for a specific satellite"""
try:
time_str = request.args.get('time', None)
if time_str:
target_time = datetime.fromisoformat(time_str.replace('Z', '+00:00'))
else:
target_time = datetime.utcnow()
t = ts.utc(target_time.year, target_time.month, target_time.day,
target_time.hour, target_time.minute, target_time.second)
# Get all satellites
all_satellites = []
for group in GNSS_GROUPS.keys():
tle_data = fetch_tle_data(group)
if tle_data:
satellites = parse_tle(tle_data, group)
all_satellites.extend(satellites)
if index >= len(all_satellites):
return jsonify({'error': 'Satellite index out of range'}), 404
sat = all_satellites[index]
satellite_obj = sat['satellite']
# Calculate position and orbit
position_data = calculate_satellite_position(satellite_obj, t)
orbit_path = calculate_orbit_path(satellite_obj, target_time)
# Calculate orbital period
mean_motion = satellite_obj.model.no_kozai
period_minutes = (2 * np.pi) / mean_motion
return jsonify({
'name': sat['name'],
'group': sat['group'],
'groupName': GNSS_GROUPS[sat['group']]['name'],
'color': GNSS_GROUPS[sat['group']]['color'],
'position': position_data,
'orbit': orbit_path,
'period': period_minutes,
'tle': {
'line1': sat['line1'],
'line2': sat['line2']
}
})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
print("🛰️ GNSS Satellite Tracker - Python Backend")
print("=" * 50)
print("Starting server on http://localhost:5000")
print("Available GNSS constellations:")
for key, value in GNSS_GROUPS.items():
print(f" - {value['name']}")
print("=" * 50)
app.run(debug=True, host='0.0.0.0', port=5000)