Skip to content

Commit

Permalink
refactor: refacoring for cleaner code
Browse files Browse the repository at this point in the history
  • Loading branch information
TheAveron committed Aug 31, 2024
1 parent a95d62f commit 59ecb4a
Show file tree
Hide file tree
Showing 10 changed files with 248 additions and 234 deletions.
58 changes: 29 additions & 29 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
import os
from datetime import UTC, datetime

from datetime import datetime, timezone
from dotenv import load_dotenv
from flask import (Flask, flash, jsonify, redirect, render_template, request,
session, url_for)
from flask import (
Flask, flash, jsonify, redirect, render_template, request,
session, url_for
)
from flask_socketio import SocketIO
from modules import (
init_db, start_reminder_checker, fetch_tle_data, get_logged_in_user,
register_user, verify_user, login_user, logout_user, get_current_position,
get_iss_crew, get_future_positions, get_iss_info, get_next_passes, add_reminder
)

from modules import *

# Load environment variables
load_dotenv()

# Flask app and SocketIO initialization
app = Flask(__name__)

app.secret_key = os.environ["TOKEN"]
app.secret_key = os.getenv("TOKEN")
socketio = SocketIO(app)

# Initialize database and start background processes
init_db()
start_reminder_checker()
TLE = fetch_tle_data()


@app.route("/")
def index():
"""Render the home page with the current user's ID."""
user_id = get_logged_in_user()
return render_template("index.html", user_id=user_id)


@app.route("/register", methods=["GET", "POST"])
def register():
"""Handle user registration."""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
Expand All @@ -40,9 +46,9 @@ def register():

return render_template("register.html")


@app.route("/login", methods=["GET", "POST"])
def login():
"""Handle user login."""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
Expand All @@ -57,45 +63,43 @@ def login():

return render_template("login.html")


@app.route("/logout")
def logout():
"""Log out the current user."""
logout_user()
flash("You have been logged out.", "info")
return redirect(url_for("index"))


@app.route("/iss-now")
def iss_now():
"""Return the current position of the ISS."""
current_position = get_current_position(TLE)
return jsonify(current_position)


@app.route("/iss-crew")
def iss_crew():
iss_crew = get_iss_crew()
return jsonify(iss_crew[0], iss_crew[1])

"""Return the current crew members on the ISS."""
iss_crew_data, status_code = get_iss_crew()
return jsonify(iss_crew_data), status_code

@app.route("/future-trajectory")
def future_trajectory():
start_time = datetime.now(UTC)
duration = float(
request.args.get("duration", 3600)
) # Default to 1 hour if no duration provided
"""Return the future trajectory of the ISS."""
start_time = datetime.now(timezone.utc)
duration = float(request.args.get("duration", 3600)) # Default to 1 hour
interval = 60 # Calculate every 60 seconds
future_positions = get_future_positions(TLE, start_time, duration, interval)
return jsonify(future_positions)


@app.route("/iss-info")
def iss_info():
"""Return detailed information about the ISS."""
info = get_iss_info(TLE)
return jsonify(info)


@app.route("/next-passes", methods=["GET"])
def next_passes():
"""Return the next passes of the ISS over a given location."""
lat = request.args.get("lat", type=float)
lon = request.args.get("lon", type=float)
if lat is None or lon is None:
Expand All @@ -104,18 +108,14 @@ def next_passes():
passes = get_next_passes(TLE, lat, lon, num_passes=3)
return jsonify(passes)


@app.route("/add-reminder", methods=["POST"])
def add_reminder_route():
"""Add a reminder for a specific ISS pass time."""
user_id = request.form["user_id"]
pass_time = request.form[
"pass_time"
] # Expecting ISO format: '2024-08-30T10:15:00Z'
pass_time = request.form["pass_time"] # ISO format: '2024-08-30T10:15:00Z'
add_reminder(user_id, pass_time)

return jsonify({"status": "success"}), 200


if __name__ == "__main__":
app.run(debug=False)
socketio.run(app)
2 changes: 1 addition & 1 deletion modules/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .database import *
from .iss_info import get_iss_crew
from .iss_info import *
from .iss_tracker import *
from .reminder_service import *
from .tle_fetcher import *
Expand Down
55 changes: 32 additions & 23 deletions modules/database.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,42 @@
import sqlite3

DATABASE_FILE = "database.db"

def init_db():
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS iss_reminders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
pass_time DATETIME,
notified BOOLEAN DEFAULT 0
)
"""
)
Initializes the database by creating the necessary tables if they do not exist.
"""
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()

cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
# Create iss_reminders table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS iss_reminders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
pass_time DATETIME,
notified BOOLEAN DEFAULT 0
)
"""
)
"""
)
conn.commit()
conn.close()

# Create users table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
"""
)

conn.commit()


def get_db_connection():
conn = sqlite3.connect("database.db")
return conn
"""
Returns a new connection to the database.
"""
return sqlite3.connect(DATABASE_FILE)
11 changes: 7 additions & 4 deletions modules/iss_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@


def get_iss_crew():
# Placeholder for ISS crew data logic
"""
Fetch and return the list of crew members currently aboard the ISS.
"""
try:
response = requests.get("http://api.open-notify.org/astros.json")
response.raise_for_status()
data = response.json()

# Filter the crew members aboard the ISS
iss_crew = [person for person in data["people"] if person["craft"] == "ISS"]
# Extract crew members aboard the ISS
iss_crew = [person for person in data.get("people", []) if person.get("craft") == "ISS"]

return {"crew": iss_crew}, 200
except requests.RequestException as e:

except requests.RequestException:
return {"error": "Error fetching ISS crew data"}, 500
99 changes: 42 additions & 57 deletions modules/iss_tracker.py
Original file line number Diff line number Diff line change
@@ -1,97 +1,82 @@
from datetime import UTC, datetime, timedelta

from datetime import datetime, timedelta, timezone
import ephem


def observer_setup(lat="40.7128", lon="-74.0060"):
# Create an Observer object
def observer_setup(lat="40.7128", lon="-74.0060", elevation=10):
"""
Set up an observer with given latitude, longitude, and elevation.
"""
observer = ephem.Observer()

# Set the observer's location
observer.lat = lat
observer.lon = lon
observer.elevation = 10

observer.date = datetime.now(UTC)

observer.elevation = elevation
observer.date = datetime.now(timezone.utc)
return observer


def get_current_position(tle):
satellite = ephem.readtle(tle[0], tle[1], tle[2])
satellite.compute(observer_setup())
"""
Get the current latitude and longitude of the satellite.
"""
observer = observer_setup()
satellite = ephem.readtle(*tle)
satellite.compute(observer)
return {
"lat": satellite.sublat * 180.0 / ephem.pi,
"lon": satellite.sublong * 180.0 / ephem.pi,
}


def get_future_positions(tle, start_time, duration, interval):
satellite = ephem.readtle(tle[0], tle[1], tle[2])
"""
Get satellite positions at regular intervals over a specified duration.
"""
satellite = ephem.readtle(*tle)
positions = []
current_time = start_time

while current_time <= start_time + timedelta(seconds=duration):
satellite.compute(current_time)
positions.append(
{
"lat": satellite.sublat * 180.0 / ephem.pi,
"lon": satellite.sublong * 180.0 / ephem.pi,
}
)
positions.append({
"lat": satellite.sublat * 180.0 / ephem.pi,
"lon": satellite.sublong * 180.0 / ephem.pi,
})
current_time += timedelta(seconds=interval)

return positions


def get_iss_info(tle):
# Create a satellite object from the TLE data
satellite = ephem.readtle(tle[0], tle[1], tle[2])

# Compute the current position of the satellite
satellite.compute(observer_setup()) # Use the current UTC time

# Get latitude and longitude of the ISS
latitude = satellite.sublat * 180.0 / ephem.pi # Convert from radians to degrees
longitude = satellite.sublong * 180.0 / ephem.pi # Convert from radians to degrees
"""
Get current information about the ISS including position, altitude, and speed.
"""
observer = observer_setup()
satellite = ephem.readtle(*tle)
satellite.compute(observer)

# Calculate altitude in kilometers
altitude_km = satellite.elevation / 1000.0 # ephem returns elevation in meters

# Calculate speed in km/h
speed_kmh = abs(
satellite.range_velocity / 1000.0 * 3600.0
) # ephem returns range_velocity in m/s

# Return the data as JSON
return {
"latitude": latitude,
"longitude": longitude,
"altitude": round(altitude_km, 2),
"speed": round(speed_kmh, 2),
"latitude": satellite.sublat * 180.0 / ephem.pi,
"longitude": satellite.sublong * 180.0 / ephem.pi,
"altitude": round(satellite.elevation / 1000.0, 2), # Convert to km
"speed": round(abs(satellite.range_velocity) / 1000.0 * 3600.0, 2), # Convert to km/h
"timestamp": datetime.utcnow().isoformat() + "Z",
}


def get_next_passes(tle, observer_lat, observer_lon, num_passes=3):
iss = ephem.readtle(tle[0], tle[1], tle[2])

Paris = {
"lat": "48.864716",
"Lon": "2.349014",
}
observer = observer_setup(Paris["lat"], Paris["Lon"])

"""
Get the next passes of the ISS over a specified observer location.
"""
observer = observer_setup(lat=observer_lat, lon=observer_lon)
satellite = ephem.readtle(*tle)
passes = []

for _ in range(num_passes):
next_pass = observer.next_pass(iss)
print(next_pass)
passes.append(
{
"rise_time": next_pass[0].datetime().strftime("%Y-%m-%d %H:%M:%S UTC"),
"set_time": next_pass[4].datetime().strftime("%Y-%m-%d %H:%M:%S UTC"),
}
)
next_pass = observer.next_pass(satellite)
passes.append({
"rise_time": next_pass[0].datetime().strftime("%Y-%m-%d %H:%M:%S UTC"),
"set_time": next_pass[4].datetime().strftime("%Y-%m-%d %H:%M:%S UTC"),
})
observer.date = next_pass[4] + ephem.minute # Move time forward

return passes
Loading

0 comments on commit 59ecb4a

Please sign in to comment.