Build a GPS fleet tracking system with Python, Django and AI
A GPS fleet tracking system built in Python and Django with an AI coding assistant: a live map on free OpenStreetMap tiles, speeding, idling and zone alerts, trips with speed-coloured routes, and a fuel check that flags suspicious fills. Below: how trackers talk to the server, the rules and the code that matters, the two mistakes the AI made, and how to track your own phone with the free Traccar Client app.
1. How GPS tracking works
- A tracker in the vehicle, or a phone, gets a GPS fix every few seconds.
- It sends a small report: device ID, latitude, longitude, time and speed. The free Traccar Client app (Android and iPhone) uses the open OsmAnd protocol: an HTTP POST with form fields
id,lat,lon,timestamp,speed,bearing. - The Django app saves it as a position at
/api/osmand/. - Each new position runs through the alert rules.
- The map in the browser asks for the latest positions every 5 seconds (Leaflet + OpenStreetMap, no paid map service).
2. The data model
- Vehicle: name, registration, driver, device ID (what the tracker sends), its own speed limit, an optional zone, normal km per litre.
- Zone: a circle on the map (centre and radius in metres).
- Position: vehicle, time on the device, latitude, longitude, speed in km/h, heading, ignition (unknown for phones).
- Alert: vehicle, type, start, end, worst value (top speed, idle minutes or km outside the zone).
- FuelFill: vehicle, litres, price, odometer at the pump.
3. The knots trap
In the OsmAnd protocol, speed is in knots by default (the Traccar Client source converts metres per second to knots before sending). 1 knot = 1.852 km/h, so 27 knots is 50 km/h. Store km/h and convert once, when the report arrives:
knots = _float(params, "speed") or 0.0
heading = _float(params, "bearing")
if heading is None:
heading = _float(params, "heading")
ignition = params.get("ignition") # only trackers wired to the vehicle know this
ignition = None if ignition in (None, "") else ignition.lower() in ("1", "true", "on")
return {
"device_id": device_id,
"recorded_at": parse_timestamp(params.get("timestamp")),
"lat": lat,
"lon": lon,
"speed_kmh": round(knots * KNOTS_TO_KMH, 1),
"heading": heading,
"ignition": ignition,
Phones cannot report ignition, so it is stored as unknown, never as “off”.
4. Three alert rules
- Speeding: more than 5 km/h over the vehicle’s own limit, two reports in a row (one bad GPS reading cannot trigger it). Closes when the speed is back at or under the limit.
- Idling: ignition on and under 3 km/h for 5 minutes. A parked vehicle’s GPS drifts at 1–2 km/h, so testing for exactly 0 would never fire.
- Leaving a zone: the distance from the zone centre (haversine formula) is larger than its radius.
Each rule opens one alert when the problem starts and closes it when it ends: ten minutes of speeding is one alert, not two hundred.
def check_speeding(pos):
v = pos.vehicle
limit = v.speed_limit_kmh + settings.FLEET_SPEED_TOLERANCE_KMH
alert = open_alert(v, Alert.SPEEDING)
if pos.speed_kmh > limit:
if alert:
if pos.speed_kmh > alert.peak:
alert.peak = pos.speed_kmh
alert.save(update_fields=["peak"])
return
n = settings.FLEET_SPEEDING_MIN_READINGS
recent = list(v.positions.filter(recorded_at__lte=pos.recorded_at).order_by("-recorded_at")[:n])
if len(recent) == n and all(p.speed_kmh > limit for p in recent):
Alert.objects.create(
vehicle=v, kind=Alert.SPEEDING, started_at=recent[-1].recorded_at,
lat=pos.lat, lon=pos.lon, peak=max(p.speed_kmh for p in recent),
)
elif alert and pos.speed_kmh <= v.speed_limit_kmh:
# Close only once back at or under the limit itself. Closing as soon as the speed dips
# under limit + tolerance split one stretch of speeding into several alerts.
alert.ended_at = pos.recorded_at
alert.save(update_fields=["ended_at"])
def idle_since(pos):
def idle_since(pos):
"""When the engine-on, standing-still stretch that ends at `pos` began (or None)."""
if pos.ignition is not True or pos.speed_kmh >= STANDING_STILL_KMH:
return None
start = pos.recorded_at
earlier = pos.vehicle.positions.filter(recorded_at__lt=start).order_by("-recorded_at")
for p in earlier.iterator():
if p.ignition is not True or p.speed_kmh >= STANDING_STILL_KMH:
break
start = p.recorded_at
return start
5. The two mistakes the AI made
- Duplicates were saved twice. The app resends reports after a network drop. The AI’s code caught the database’s “duplicate” error to ignore repeats, but no database rule made a duplicate an error, so the error never happened and both copies were saved. A test (send the same report twice, expect one row) caught it. Fix: a unique rule on vehicle + time:
ordering = ["recorded_at"] # one report per vehicle per moment: a resent report is a duplicate constraints = [ models.UniqueConstraint(fields=["vehicle", "recorded_at"], name="one_position_per_moment"), ] - One speeding incident became two alerts. The alert opened above limit + 5 and closed as soon as the speed dipped back under that same line, so a small dip ended it and the next report opened a new one. Seen in the seeded data, not in a test. Fix: close only at or under the limit itself (hysteresis, like a thermostat).
Both were quiet: nothing crashed. Test the rules, then look at real data before you trust a dashboard.
6. The fuel check
Economy is measured fill to fill: kilometres on the odometer since the previous fill, divided by the litres put in. A fill under 75% of the vehicle’s normal economy is flagged for someone to ask about it, for example a leak, or a fuel card used for another vehicle.
def economy(fills):
"""fills: one vehicle's fills, any order. Returns rows oldest first with km, km/l and a flag."""
fills = sorted(fills, key=lambda f: f.odometer_km)
rows = []
for prev, cur in zip(fills, fills[1:]):
km = cur.odometer_km - prev.odometer_km
kmpl = (Decimal(km) / cur.litres).quantize(Decimal("0.1")) if cur.litres else None
normal = cur.vehicle.expected_km_per_litre
rows.append({
"fill": cur,
"km": km,
"km_per_litre": kmpl,
"flag": kmpl is not None and kmpl < normal * FLAG_BELOW,
})
return rows
7. Track your own phone
- On your PC:
python manage.py migrate,python manage.py seed_demofor sample vehicles, andpython manage.py createsuperuserfor an admin login. - Find your PC’s Wi-Fi address with
ipconfig(Windows), for example 192.168.1.20. - Allow it, in the same PowerShell window:
$env:DJANGO_ALLOWED_HOSTS = "192.168.1.20"(in Command Prompt:set DJANGO_ALLOWED_HOSTS=192.168.1.20), thenpython manage.py runserver 0.0.0.0:8000. If the phone cannot connect, allow Python through Windows Firewall on private networks. - Install Traccar Client on your phone. Server URL:
http://192.168.1.20:8000/api/osmand/. Frequency: 10 seconds while testing. - In the admin, add a vehicle whose device ID is the app’s device identifier. Start the app and go for a walk.
8. Before you use it on real vehicles
- Location is personal data. Tell drivers what is tracked and when, and check your local law. Many companies track only during working hours.
- Use HTTPS and set
FLEET_INGEST_KEY, then add?key=...to the tracker URL, so only your trackers can send positions. - Hardware trackers use their own protocols. The free, open source Traccar server supports more than 200 of them and can forward positions to an app like this.
- Decide how long to keep history and delete older positions. A report every 10 seconds is about 3 million rows per vehicle per year.
Map data © OpenStreetMap contributors. The demo’s vehicles, drivers and fuel data are simulated, on real roads in Islamabad and Rawalpindi.