Spaces:
Sleeping

cell-gps / dead_reckoning.py
DeftDaedalus's picture
Upload 5 files
37cac80 verified
Raw History Blame Contribute Delete
2.61 kB
import math
import time
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Fix:
lat: float
lon: float
accuracy_km: float
timestamp: float = field(default_factory=time.time)
source: str = "tower" # "tower", "dead_reckoning", "fingerprint"
def move_position(lat: float, lon: float,
bearing_deg: float, distance_km: float) -> tuple[float, float]:
"""
Given a starting point, bearing (degrees from north), and distance,
return the new lat/lon. Uses haversine-based formula.
"""
R = 6371.0 # Earth radius in km
bearing = math.radians(bearing_deg)
lat1 = math.radians(lat)
lon1 = math.radians(lon)
lat2 = math.asin(
math.sin(lat1) * math.cos(distance_km / R) +
math.cos(lat1) * math.sin(distance_km / R) * math.cos(bearing)
)
lon2 = lon1 + math.atan2(
math.sin(bearing) * math.sin(distance_km / R) * math.cos(lat1),
math.cos(distance_km / R) - math.sin(lat1) * math.sin(lat2)
)
return (math.degrees(lat2), math.degrees(lon2))
class DeadReckoner:
"""
Keeps a history of fixes and extrapolates position
when no tower data is available.
"""
def __init__(self):
self.history: list[Fix] = []
def add_fix(self, fix: Fix):
self.history.append(fix)
# Only keep last 10 fixes
if len(self.history) > 10:
self.history = self.history[-10:]
def estimate_now(self,
speed_kmh: float = 0,
bearing_deg: float = 0) -> Optional[Fix]:
"""
Extrapolate from last known fix using speed + bearing + elapsed time.
If speed=0, just returns the last fix with degraded accuracy.
"""
if not self.history:
return None
last = self.history[-1]
elapsed_hours = (time.time() - last.timestamp) / 3600.0
distance_km = speed_kmh * elapsed_hours
if distance_km > 0:
new_lat, new_lon = move_position(
last.lat, last.lon, bearing_deg, distance_km
)
else:
new_lat, new_lon = last.lat, last.lon
# Accuracy degrades over time — add ~0.2km per minute of uncertainty
elapsed_minutes = elapsed_hours * 60
degraded_accuracy = last.accuracy_km + (elapsed_minutes * 0.2)
return Fix(
lat=new_lat,
lon=new_lon,
accuracy_km=degraded_accuracy,
source="dead_reckoning"
)