← Back to the chapter · Next detail →

Technical detail · Capstone Projects: Selection and Fleet Tracking

Detect geofence transitions

3.7.0.1 Geofence Implementation

Containment says where a device is now. Entry and exit require comparing that result with its previous state. This engine stores state for each device-and-geofence pair, establishes the first observation without a transition alert, and emits alerts on later changes. Shapely uses x, y coordinates, so the input latitude/longitude tuples become longitude/latitude pairs.

from shapely.geometry import Point, Polygon

class GeofenceEngine:
    def __init__(self):
        self.geofences = {}
        self.device_states = {}  # Track inside/outside state

    def add_geofence(self, name, coordinates, alert_on):
        """
        coordinates: List of (lat, lon) tuples
        alert_on: 'entry', 'exit', or 'both'
        """
        self.geofences[name] = {
            'polygon': Polygon((lon, lat) for lat, lon in coordinates),
            'alert_on': alert_on
        }

    def check_position(self, device_id, lat, lon):
        """Check if device triggers any geofence alerts."""
        point = Point(lon, lat)  # Note: Shapely uses (x, y) = (lon, lat)
        alerts = []

        for name, geofence in self.geofences.items():
            was_inside = self.device_states.get((device_id, name), None)
            is_inside = geofence['polygon'].contains(point)

            if was_inside is not None:
                if not was_inside and is_inside and geofence['alert_on'] in ('entry', 'both'):
                    alerts.append({'type': 'entry', 'geofence': name})
                elif was_inside and not is_inside and geofence['alert_on'] in ('exit', 'both'):
                    alerts.append({'type': 'exit', 'geofence': name})

            self.device_states[(device_id, name)] = is_inside

        return alerts

← Back to the chapter · Next detail →