Spaces:
Sleeping

File size: 2,606 Bytes
37cac80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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"
        )