You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Star0Β (0)You must be signed in to star a repository
About
AI-powered stray animal detection system for safer roads. StrayGuard-Mobile combines real-time animal detection, crowd-sourced risk heatmaps, and intelligent speed assistance to help reduce road accidents involving cattle, dogs, goats, and other stray animals on Indian highways.
StrayGuardβMobile is a smartphone-based AI dashcam and Intelligent Speed Assistance (ISA) system that detects stray animals on Indian roads in real time, crowd-sources GPS-tagged detection events to a cloud backend, and advises drivers to reduce speed when entering data-driven danger zones.
A lightweight ESP32 motor rig acts as a hardware simulation to demonstrate the future concept of automatic vehicle speed reduction via OBD-II/CAN β without requiring real vehicle integration in the prototype.
Free-roaming cattle, dogs, goats and other animals are a persistent hazard on Indian highways, contributing significantly to crashes β especially at night and during dawn/dusk when visibility is low.
Existing Countermeasure
Why It Fails
Static warning signs
Drivers habituate and ignore them
Random speed breakers
Impractical on 60β80 km/h corridors; slow all traffic
Fencing
Prohibitively expensive at scale; no dynamic alerting
NHAI SMS pilots
One alert per stretch entry; no per-detection event intelligence
There is no low-cost, scalable, driver-owned system that detects animals from the vehicle's perspective, accumulates collective risk intelligence, and advises the correct safe speed in real time.
The Physics Argument
KE = Β½mvΒ² β a 20% reduction in collision speed reduces kinetic energy by 36%. A 30% reduction cuts it by 51%. ISA compliance in danger zones directly reduces crash severity even when a collision still occurs.
β¨ Key Features
π On-Device AI Animal Detection
Lightweight INT8 TFLite model running at ~3β5 fps on the phone
Detects cattle, buffalo, dogs, goats, sheep and horses using the rear camera
ROI filtering discards sky-band and far-lane false positives
Privacy by design β no raw frames ever leave the device
πΊοΈ Crowd-Sourced Risk Heatmaps
Each valid detection is converted into an anonymised GPS-tagged event and uploaded to the backend
Backend aggregates events into spatial/temporal hotspots via the Danger-Zone Engine (DZE)
Any smartphone user passively contributes to a self-improving risk map
π¦ Intelligent Speed Assistance (ISA)
App polls /danger-zone every ~3 s with current GPS position
Colour-coded ISA banners (green / amber / red) and audio alerts based on risk level
4-state hysteresis machine prevents banner flicker at zone boundaries
π Authority-Facing Web Dashboard
Next.js 14 dashboard for NHAI / city bodies / NGOs
Live detection heatmaps with time slider, danger-zone polygons, KPI cards
Time-series and day-of-week analytics, CSV export, admin DZE control panel
π§ Hardware Simulation (ESP32 RC Car)
ESP32 + L298N + DC motors physically demonstrate auto-slowdown
App sends speed_command (0β100%) over Wi-Fi when an animal is detected or a danger zone is entered
Faithfully simulates the OBD-II / CAN control loop for hackathon demo purposes
π οΈ Tech Stack
Layer
Technology
Purpose
Mobile App
Flutter (Android) Β· Riverpod Β· TFLite
AI dashcam, ISA overlay, event uploader
Backend API
Node.js 20 LTS Β· Express 4 Β· TypeScript
Event ingestion, DZE scheduling, REST API
ORM
Prisma 5
Schema management & migrations
Database
PostgreSQL 16 Β· PostGIS 3.4
Spatial queries, zone clustering, heatmaps
Dashboard
Next.js 14 Β· React Β· Leaflet Β· Recharts
Heatmap, zone map, analytics for authorities
Hardware Sim
ESP32 DevKit Β· L298N Β· DC motors Β· PlatformIO
RC car speed simulation over Wi-Fi/BLE
ML Pipeline
Python Β· PyTorch / TensorFlow β TFLite INT8
Animal detection model training & export
Monorepo
Turborepo
Shared types, parallel builds, consistent tooling
CI/CD
GitHub Actions
Backend tests, dashboard build, Flutter tests
Deployment
Render.com (API) Β· Vercel (Dashboard)
Hackathon prototype hosting
π§± System Architecture
Layered Architecture
flowchart TB
subgraph Device_Layer["π± Device Layer β Flutter App (Android)"]
DC["π₯ AI Dashcam\nCamera + TFLite"]
ISA["π¦ ISA Module\nGPS + /danger-zone API"]
UPL["π€ Event Uploader\nSQLite offline buffer"]
end
subgraph Cloud_Layer["βοΈ Cloud Layer β Node.js + Postgres/PostGIS"]
API["π REST API\nExpress + Zod validation"]
DB[("ποΈ PostgreSQL + PostGIS\ndetections Β· danger_zones Β· devices")]
DZE["βοΈ Danger-Zone Engine\nDBSCAN + risk scoring"]
end
subgraph Stakeholder_Layer["π₯ Stakeholder Layer"]
DASH["π Next.js Dashboard\nNHAI / NGOs / Researchers"]
ESP["π ESP32 RC Car Rig\nL298N + DC Motors"]
end
DC -->|DetectionEvent| UPL
UPL -->|"POST /detections"| API
ISA -->|"GET /danger-zone"| API
API --> DB
DZE --> DB
DB --> DZE
DASH -->|"GET /danger-zones"| API
DC -->|speed_command| ESP
ISA -->|speed_command| ESP
style Device_Layer fill:#1a3a5c,color:#fff
style Cloud_Layer fill:#1a4a2a,color:#fff
style Stakeholder_Layer fill:#4a1a1a,color:#fff
erDiagram
devices {
int id PK
varchar device_hash UK
timestamptz first_seen
timestamptz last_seen
varchar app_version
bigint event_count
}
detections {
bigint id PK
int device_id FK
timestamptz detected_at
timestamptz received_at
geometry geom
real speed_kmph
real heading_deg
varchar animal_class
real confidence
float[] bbox_norm
varchar app_version
}
danger_zones {
int id PK
varchar zone_code UK
geometry polygon
varchar segment_label
varchar risk_level
real risk_score
int recommended_speed_kmph
varchar active_from
varchar active_to
varchar dominant_animal
int detection_count_30d
int free_flow_speed
boolean is_active
}
admin_users {
int id PK
varchar email UK
varchar password_hash
varchar role
}
devices ||--o{ detections : "contributes"
node >= 20 LTS
flutter >= 3.19
docker + docker-compose # for local PostgreSQL/PostGIS
python 3.10+ # ML pipeline only
PlatformIO # ESP32 firmware flashing
1. Clone the Repository
git clone https://github.com/JayeshJadhav28/StrayGuard.git
cd StrayGuard
2. Install Node Dependencies
npm install # installs backend + dashboard via Turborepo workspaces
3. Start Local Database (Docker)
docker-compose up -d db
# PostgreSQL 16 + PostGIS 3.4 on localhost:5432
4. Configure & Run Backend
cd apps/backend
cp .env.example .env
# Edit .env β set DATABASE_URL, API_KEY_DEVICE, JWT_SECRET
npx prisma migrate dev
npm run dev
# β http://localhost:3000
5. Run Next.js Dashboard
cd apps/dashboard
cp .env.example .env # set NEXT_PUBLIC_API_URL=http://localhost:3000
npm run dev
# β http://localhost:4000
6. Run Flutter App
cd apps/mobile
flutter pub get
flutter run # requires Android device or emulator
Grant Camera, Location and Internet permissions when prompted.
7. Flash ESP32 Firmware (Optional)
cd apps/hardware-sim
pio run --target upload
# ESP32 starts as Wi-Fi AP: SSID "StrayGuard-Sim" / pass "demo1234"# HTTP endpoint: http://192.168.4.1/speed?speed=<0-100>
π§ͺ Testing Strategy
Unit Tests
ID
Component
Scenario
Pass Criterion
UT01
TFLite model
100 annotated test images
mAP > 0.72 @ IoU 0.5
UT02
ROI filter
50 bboxes: 30 road / 20 sky
100% correct accept/reject
UT03
Event schema
50 valid + 20 malformed batches
Valid accepted; malformed β 400
UT04
DZE risk scoring
2,000 synthetic points
Within Β±0.05 of expected score
UT05
Speed formula
25 risk_score Γ free_flow combos
Within Β±2 km/h; floor enforced
UT06
ISA hysteresis
GPS jitter crossing boundary 30Γ
Advisory fires only after 2Γ inside
UT07
Offline buffer
500 events, network off β on
All 500 uploaded; zero duplicates
UT08
ESP32 HTTP API
POST /speed values 0, 30, 80, 100
Correct PWM duty; response 200
Integration Tests
ID
Scope
Pass Criterion
IT01
App β Backend
Events in DB within 15s; lat/lon correct
IT02
DZE β DB
Zone upserted with valid PostGIS polygon
IT03
App β /danger-zone
ISA advisory within 6s of GPS crossing
IT04
DZE update β App
App shows updated recommended_speed within 2 min
IT05
App β ESP32
Motor duty drops; HTTP confirms new speed
IT06
Backend β Dashboard
Density points visible in heatmap within 30s
System / End-to-End Tests
ID
Scenario
Pass Criterion
SYS01
Animal detected β full flow
Bbox overlay + audio alert + event in DB + ESP32 slows
SYS02
No animal β no false alert
Zero false detections over 3-minute empty road
SYS03
Human ignored
Detection logged; no driver alert fired
SYS04
Night detection
Recall > 60% under low-light conditions
SYS05
Offline resilience
All 50 buffered events upload on reconnect; no crash
SYS06
Zone entry + ISA
ISA banner within 6s; speed bar correct colour
SYS07
Speed breach escalation
Amber at +10 km/h; red + TTS at +20 km/h
SYS08
Dashcam + ISA simultaneous
Both bbox overlay AND ISA banner visible together
Performance Benchmarks
Metric
Target
TFLite inference (mid-range Android)
< 250 ms median
TFLite inference (budget Android)
< 500 ms 95th percentile
Detection β in-app alert
< 600 ms
Event upload latency (connected)
< 15 s detection β DB record
/danger-zone API response
< 300 ms at 100 concurrent
DZE full run (30-day dataset)
< 120 s
ISA zone entry latency
< 6 s from GPS boundary cross
Battery drain (dashcam active, 1 hr)
< 25% on mid-range phone
π’ Deployment
Hackathon Demo Targets
Component
Platform
URL / Notes
Backend API
Render.com (free tier)
https://strayguard-api.onrender.com
Web Dashboard
Vercel (free tier)
https://strayguard.vercel.app
Database
Render.com Postgres + PostGIS
Managed, PostGIS extension enabled
Flutter APK
Sideloaded
flutter build apk --release
ESP32
Local Wi-Fi AP
StrayGuard-Sim @ 192.168.4.1
CI/CD (GitHub Actions)
jobs:
backend-test:
services:
postgres:
image: postgis/postgis:16-3.4steps:
- run: cd apps/backend && npm ci && npm testdashboard-build:
steps:
- run: cd apps/dashboard && npm ci && npm run buildflutter-test:
steps:
- uses: subosito/flutter-action@v2
- run: cd apps/mobile && flutter test
Live Demo Script (5β7 min)
1. Open app β show live dashcam preview at normal drive speed
2. Move animal cut-out in front of camera β bbox overlay + alert appears instantly
3. Show dashboard β detection count increments, new point on heatmap
4. Simulate GPS entering pre-seeded danger zone β ISA advisory appears within 3s
5. App sends speed_command to ESP32 β RC car slows from 80% to 40% duty cycle
6. Clear hazard β app returns to OUTSIDE_ZONE; RC car resumes normal speed
7. Show dashboard risk map and zone polygons; discuss future OBD-II roadmap
π£οΈ Roadmap
Phase
Feature
Details
P1
OBD-II / CAN integration
Auto-slowdown on real vehicles via ELM327 adapter
P1
Android Auto / CarPlay
Larger ISA UI on in-car infotainment screen
P2
Federated learning
Improve model without sharing raw images
P2
NHAI SMS / API integration
Push zone data to official highway alert systems
P3
iOS App Store release
After Stage-1 pilot testing
P3
ISO 26262 pathway
Safety case documentation for OEM adoption
OBD-II / CAN Future Architecture
StrayGuard App (phone)
β Bluetooth Classic (SPP)
βΌ
ELM327-compatible OBD-II adapter
(plugged into car's OBD-II port)
β CAN bus message (vehicle-specific PID)
βΌ
Vehicle ECU
β reduces throttle / applies light braking
βΌ
Vehicle decelerates to recommended_speed
The ESP32 demo validates the same logical control loop. Replacing the ESP32 HTTP endpoint with a Bluetooth OBD-II CAN write is the remaining engineering work.
πΉ Demo Video
A full demo video showing the app, dashboard and ESP32 rig in action:
The video covers: (1) normal drive at 80% motor speed, (2) detection triggering an app alert, (3) ESP32 visible slowdown to 40%, (4) recovery once the hazard clears.
π₯ Contributors
Team StrayGuard Lab
Dnyanshree Institute of Engineering and Technology
Contributions, issues and feature requests are welcome β please use the GitHub Issues and Pull Requests tabs.
π License
This project is licensed under the MIT License β see the LICENSE file for details.
AI-powered stray animal detection system for safer roads. StrayGuard-Mobile combines real-time animal detection, crowd-sourced risk heatmaps, and intelligent speed assistance to help reduce road accidents involving cattle, dogs, goats, and other stray animals on Indian highways.