id: geofence-entry-exit-processor
namespace: company.team
description: |
Turns raw device location pings into geofence entry and exit decisions, so a unit that lingers inside a fenced site is noticed instead of lost in a stream of coordinates. A webhook carries the ping payload and a disabled daily schedule stands ready as the fallback sweep. A LoopUntil poller first materializes the ping stream and reads the newest ping for the watched device, a shared workspace then writes the site and state fixtures, and a python step measures the haversine distance to every site center, compares it with the persisted inside or outside state, then derives the event, the dwell minutes and the site. An entry whose dwell already exceeds the threshold posts to Slack, an exit of a high value asset mails the custodian, every other outcome is logged quietly, and each run exposes verdict, event, device_id, dwell_minutes and site as typed outputs.
triggers:
- id: on_location_ping
type: io.kestra.plugin.core.trigger.Webhook
description: Telemetry gateway posts here once per device ping with device_id,
lat, lon and ts in the body.
key: "{{ secret('GEOFENCE_PING_WEBHOOK_KEY') }}"
- id: daily_state_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Disabled daily net that would replay the ping fixture every morning
until someone switches it on.
cron: "0 6 * * *"
disabled: true
inputs:
- id: device_id
type: STRING
defaults: TRK-001
description: Device the poller watches when the webhook body does not name one.
- id: dwell_alert_minutes
type: FLOAT
defaults: 30
description: Minutes inside a fence that turn a detected entry into a Slack alert.
- id: custodian_email
type: STRING
defaults: ops-custodian@example.com
description: Address that receives the mail when a high value asset leaves its fence.
tasks:
- id: poll_latest_ping
type: io.kestra.plugin.core.flow.LoopUntil
description: Materializes the ping stream for the watched device and re-reads it
until a usable ping shows up, so a silent device is not mistaken for an
exit.
condition: "{{ outputs.read_latest_ping.vars.found == true }}"
checkFrequency: { interval: PT5S, maxIterations: 8 }
failOnMaxReached: false
tasks:
- id: read_latest_ping
type: io.kestra.plugin.scripts.python.Script
description: Holds the raw ping stream, picks the newest valid line for the
watched device, and emits the chosen ping plus the full stream for the
geofence step.
taskRunner: { type: io.kestra.plugin.core.runner.Process }
env:
WATCH_DEVICE: "{{ inputs.device_id }}"
script: |
import json
import os
from datetime import datetime
PINGS_TEXT = """{"device_id": "TRK-001", "lat": 40.71400, "lon": -74.00700, "ts": "2026-10-13T08:30:00+00:00"}
{"device_id": "TRK-002", "lat": 40.75830, "lon": -73.98520, "ts": "2026-10-13T08:45:00+00:00"}
{"device_id": "TRK-001", "lat": 40.71300, "lon": -74.00620, "ts": "2026-10-13T09:15:00+00:00"}
{"device_id": "TRK-002", "lat": 40.80000, "lon": -73.95000, "ts": "2026-10-13T09:40:00+00:00"}
{"device_id": "TRK-004", "lat": 40.71260, "lon": -74.00600, "ts": "2026-10-13T09:55:00+00:00"}
{"device_id": "TRK-003", "lat": 40.71290, "lon": -74.00580, "ts": "2026-10-13T10:05:00+00:00"}"""
def stamp(value):
text = str(value or "").strip().replace("Z", "+00:00")
try:
return datetime.fromisoformat(text)
except ValueError:
return None
watch = os.environ.get("WATCH_DEVICE", "").strip()
best = best_key = None
if watch:
for line in PINGS_TEXT.splitlines():
try:
item = json.loads(line)
lat, lon = float(item.get("lat")), float(item.get("lon"))
key = stamp(item.get("ts"))
match = str(item.get("device_id") or "").strip() == watch
except (TypeError, ValueError, AttributeError):
continue
if match and key is not None and (best_key is None or key > best_key):
best = {"device_id": watch, "lat": lat, "lon": lon, "ts": item.get("ts")}
best_key = key
found = best is not None
print("poll read " + ("a ping" if found else "no ping") + " for " + (watch or "nothing"))
print("::" + json.dumps({"outputs": {
"found": found,
"device_id": watch,
"ts": best["ts"] if best else "",
"lat": best["lat"] if best else "",
"lon": best["lon"] if best else "",
"pings_jsonl": PINGS_TEXT,
}}, ensure_ascii=True) + "::")
- id: workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the site and state fixtures written by the
shell step are the exact files the geofence step reads and writes back.
tasks:
- id: write_fixtures
type: io.kestra.plugin.scripts.shell.Commands
description: Writes sites.json with two fenced centers and state.json with the
last known state per device; the ping stream itself arrives from the
poller through its outputs.
commands:
- |
cat > sites.json <<'SITES_EOF'
{"sites": [
{"site": "warehouse", "lat": 40.71277, "lon": -74.00597, "radius_m": 250},
{"site": "retail", "lat": 40.75810, "lon": -73.98550, "radius_m": 500}
]}
SITES_EOF
cat > state.json <<'STATE_EOF'
{"devices": {
"TRK-001": {"state": "outside", "since": "2026-10-13T07:45:00+00:00", "site": "", "asset_class": "standard"},
"TRK-002": {"state": "inside", "since": "2026-10-13T08:20:00+00:00", "site": "retail", "asset_class": "high_value"},
"TRK-003": {"state": "inside", "since": "2026-10-13T09:50:00+00:00", "site": "warehouse", "asset_class": "standard"},
"TRK-004": {"state": "outside", "since": "2026-10-13T06:00:00+00:00", "site": "", "asset_class": "standard"}
}}
STATE_EOF
wc -c sites.json state.json
- id: evaluate_geofence
type: io.kestra.plugin.scripts.python.Script
description: Measures the haversine distance to every site center, runs the
inside or outside state machine and prints the verdict, event,
device_id, dwell_minutes and site payload.
taskRunner: { type: io.kestra.plugin.core.runner.Process }
env:
WATCH_DEVICE: "{{ inputs.device_id }}"
DWELL_ALERT_MINUTES: "{{ inputs.dwell_alert_minutes }}"
PING_DEVICE_ID: "{{ trigger.body.device_id ?? '' }}"
PING_LAT: "{{ trigger.body.lat ?? '' }}"
PING_LON: "{{ trigger.body.lon ?? '' }}"
PING_TS: "{{ trigger.body.ts ?? '' }}"
POLL_DEVICE_ID: "{{ outputs.read_latest_ping.vars.device_id }}"
POLL_LAT: "{{ outputs.read_latest_ping.vars.lat }}"
POLL_LON: "{{ outputs.read_latest_ping.vars.lon }}"
POLL_TS: "{{ outputs.read_latest_ping.vars.ts }}"
PINGS_JSONL: "{{ outputs.read_latest_ping.vars.pings_jsonl }}"
script: |
import json
import math
import os
from datetime import datetime, timezone
SITES_FILE = os.environ.get("SITES_FILE", "sites.json")
STATE_FILE = os.environ.get("STATE_FILE", "state.json")
PINGS_FILE = os.environ.get("PINGS_FILE", "pings.jsonl")
def parse_ts(value):
text = str(value or "").strip().replace("Z", "+00:00")
try:
stamp = datetime.fromisoformat(text)
except ValueError:
return None
return (stamp if stamp.tzinfo else stamp.replace(tzinfo=timezone.utc)).astimezone(timezone.utc)
def as_float(value):
try:
return float(value)
except (TypeError, ValueError):
return None
def read_json(path):
try:
doc = json.load(open(path, encoding="utf-8"))
except (OSError, ValueError):
return None
return doc if isinstance(doc, dict) else None
def haversine(lat1, lon1, lat2, lon2):
radius = 6371000.0
p1, p2 = math.radians(lat1), math.radians(lat2)
dphi, dlam = math.radians(lat2 - lat1), math.radians(lon2 - lon1)
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlam / 2) ** 2
return 2 * radius * math.asin(math.sqrt(a))
def locate(lat, lon, sites):
best, best_distance = None, None
for site in [s for s in sites if isinstance(s, dict)]:
site_lat, site_lon = as_float(site.get("lat")), as_float(site.get("lon"))
radius = as_float(site.get("radius_m"))
if site_lat is None or site_lon is None or radius is None:
continue
distance = haversine(lat, lon, site_lat, site_lon)
if best_distance is None or distance < best_distance:
best, best_distance = site, distance
inside = best if best is not None and best_distance <= as_float(best.get("radius_m")) else None
return inside, best_distance
def emit(verdict, event, device_id, dwell, site):
print("::" + json.dumps({"outputs": {"verdict": verdict, "event": event, "device_id": device_id, "dwell_minutes": float(round(dwell, 2)), "site": site}}, ensure_ascii=True) + "::")
def ping_lines():
content = os.environ.get("PINGS_JSONL", "")
if content.strip():
return content.splitlines()
try:
return open(PINGS_FILE, encoding="utf-8").read().splitlines()
except OSError:
return []
def history_for(device_id, sites):
rows = []
for line in ping_lines():
try:
item = json.loads(line)
row_ts = parse_ts(item.get("ts"))
row_lat, row_lon = as_float(item.get("lat")), as_float(item.get("lon"))
except (TypeError, ValueError, AttributeError):
continue
if None in (row_ts, row_lat, row_lon):
continue
if str(item.get("device_id") or "").strip() != device_id:
continue
row_inside, _ = locate(row_lat, row_lon, sites)
rows.append((row_ts, str(row_inside.get("site")) if row_inside else ""))
return sorted(rows, key=lambda row: row[0])
def main():
watch = os.environ.get("WATCH_DEVICE", "").strip()
threshold = as_float(os.environ.get("DWELL_ALERT_MINUTES"))
threshold = 30.0 if threshold is None else threshold
sites_doc = read_json(SITES_FILE) or {}
sites = sites_doc.get("sites") if isinstance(sites_doc.get("sites"), list) else []
state_doc = read_json(STATE_FILE) or {}
devices = state_doc.get("devices") if isinstance(state_doc.get("devices"), dict) else {}
ping = None
webhook = {"device_id": os.environ.get("PING_DEVICE_ID", "").strip(),
"lat": os.environ.get("PING_LAT"), "lon": os.environ.get("PING_LON"),
"ts": os.environ.get("PING_TS")}
polled = {"device_id": os.environ.get("POLL_DEVICE_ID", "").strip(),
"lat": os.environ.get("POLL_LAT"), "lon": os.environ.get("POLL_LON"),
"ts": os.environ.get("POLL_TS")}
for candidate in (webhook, polled):
ping_id = str(candidate.get("device_id") or "").strip()
lat, lon = as_float(candidate.get("lat")), as_float(candidate.get("lon"))
ts = parse_ts(candidate.get("ts"))
if ping_id and lat is not None and lon is not None and ts is not None:
ping = {"device_id": ping_id, "lat": lat, "lon": lon, "ts": ts}
break
device_id = ping["device_id"] if ping else watch
verdict = note = None
if not sites:
verdict, note = "NO_SIGNAL", "no usable site geometry in " + SITES_FILE
elif ping is None:
verdict, note = "NO_SIGNAL", "no usable ping for " + (device_id or "the watched device")
elif device_id not in devices:
verdict, note = "UNKNOWN_DEVICE", "device " + device_id + " is not provisioned in " + STATE_FILE
if verdict:
print(note)
return emit(verdict, "none", device_id, 0.0, "")
inside, distance = locate(ping["lat"], ping["lon"], sites)
record = devices.get(device_id) if isinstance(devices.get(device_id), dict) else {}
prev_state = str(record.get("state") or "outside").lower()
prev_site = str(record.get("site") or "")
prev_since = parse_ts(record.get("since"))
asset_class = str(record.get("asset_class") or "standard")
site_name = str(inside.get("site")) if inside else ""
current = "inside" if inside else "outside"
session_start, dwell = ping["ts"], 0.0
if inside:
for row_ts, row_site in reversed(history_for(device_id, sites)):
if row_site != site_name:
break
session_start = row_ts
if prev_state == "inside" and prev_site == site_name and prev_since:
session_start = min(session_start, prev_since)
dwell = max(0.0, (ping["ts"] - session_start).total_seconds() / 60.0)
event = "none"
if inside and not (prev_state == "inside" and prev_site == site_name):
event = "entry"
elif not inside and prev_state == "inside":
event = "exit"
verdict = ("DWELL_ALERT" if event == "entry" and dwell > threshold else
"EXIT_ESCALATION" if event == "exit" and asset_class == "high_value" else "OBSERVED")
payload_site = site_name if inside else (prev_site if event == "exit" else "")
devices[device_id] = {"state": current, "site": site_name, "asset_class": asset_class,
"since": session_start.strftime("%Y-%m-%dT%H:%M:%SZ")}
json.dump(state_doc, open(STATE_FILE, "w", encoding="utf-8"), indent=2, sort_keys=True)
print("%s is %s of %s at %.0f m, %s -> %s, dwell %.1f min over %.1f min" % (device_id, current, payload_site or "no site", distance or 0.0, prev_state, current, dwell, threshold))
emit(verdict, event, device_id, dwell, payload_site)
main()
- id: route_dwell_alert
type: io.kestra.plugin.core.flow.If
description: Fires when the entry just detected has already burned more minutes
inside the fence than the dwell threshold allows.
condition: "{{ outputs.evaluate_geofence.vars.event == 'entry' and
outputs.evaluate_geofence.vars.dwell_minutes > inputs.dwell_alert_minutes
}}"
then:
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Posts the device, the site, the dwell and the verdict to the ops
channel so the lingering unit is visible to everyone.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Geofence dwell alert, device {{ outputs.evaluate_geofence.vars.device_id }} has been inside {{ outputs.evaluate_geofence.vars.site }} for {{ outputs.evaluate_geofence.vars.dwell_minutes }} minutes against a limit of {{ inputs.dwell_alert_minutes }}. Verdict {{ outputs.evaluate_geofence.vars.verdict }}, execution {{ execution.id }}."}
else:
- id: route_asset_exit
type: io.kestra.plugin.core.flow.If
description: Second gate for the other escalation, an exit of a high value
asset, which reaches the custodian by mail instead of the channel.
condition: "{{ outputs.evaluate_geofence.vars.event == 'exit' and
outputs.evaluate_geofence.vars.verdict == 'EXIT_ESCALATION' }}"
then:
- id: email_custodian
type: io.kestra.plugin.email.MailSend
description: Tells the custodian which fence was left, when the unit crossed it
and which execution made that call.
from: "{{ secret('SMTP_FROM') }}"
to: "{{ inputs.custodian_email }}"
host: "{{ secret('SMTP_HOST') }}"
username: "{{ secret('SMTP_USERNAME') }}"
password: "{{ secret('SMTP_PASSWORD') }}"
port: 465
subject: "High value asset left the {{ outputs.evaluate_geofence.vars.site }}
fence"
htmlTextContent: |
<p>{{ inputs.custodian_email }},</p>
<p><strong>{{ outputs.evaluate_geofence.vars.device_id }}</strong> exited the <strong>{{ outputs.evaluate_geofence.vars.site }}</strong> fence after {{ outputs.evaluate_geofence.vars.dwell_minutes }} minutes inside, verdict {{ outputs.evaluate_geofence.vars.verdict }}. Execution {{ execution.id }}</p>
else:
- id: log_quiet
type: io.kestra.plugin.core.log.Log
description: Records the routine outcome for entries inside the threshold,
steady inside states and exits of standard stock.
message: "Routine geofence result for {{
outputs.evaluate_geofence.vars.device_id }} - verdict {{
outputs.evaluate_geofence.vars.verdict }}, event {{
outputs.evaluate_geofence.vars.event }}, site {{
outputs.evaluate_geofence.vars.site }}, dwell {{
outputs.evaluate_geofence.vars.dwell_minutes }} minutes."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: verdict
type: STRING
value: "{{ outputs.evaluate_geofence.vars.verdict }}"
- id: event
type: STRING
value: "{{ outputs.evaluate_geofence.vars.event }}"
- id: device_id
type: STRING
value: "{{ outputs.evaluate_geofence.vars.device_id }}"
- id: dwell_minutes
type: FLOAT
value: "{{ outputs.evaluate_geofence.vars.dwell_minutes }}"