SwanFlow

Real-time vehicle detection using Edge AI

Simulated Data Phase 1 PoC in development Edge AI vehicle detection
FILTER:

Traffic Flow Algorithm

Core Logic

Vehicle Detection Pipeline

  • Confidence Threshold >0.6 (60%)
  • Aggregation Window 5 seconds
  • Detection Output Heatmap centroids → count

Speed Estimation

Traffic speed is estimated using detection frequency patterns and historical calibration data. Thresholds differ by road type based on posted speed limits.

Arterial Roads (60 km/h limit)

Stirling Highway & Mounts Bay Road

Flowing 50-60 km/h
Moderate 30-50 km/h
Heavy 15-30 km/h
Gridlock <15 km/h

Directional Flow Analysis

Each site tracks both directions independently, enabling accurate commute pattern analysis:

  • Morning peak: Inbound flow dominates (towards CBD)
  • Evening peak: Outbound flow dominates (towards suburbs)

Edge AI & ML Models

Machine Learning

FOMO Architecture

FOMO (Faster Objects, More Objects) is a novel machine learning architecture designed specifically for constrained devices. It outputs a heatmap instead of bounding boxes, enabling much faster inference.

🔒 Privacy-Preserving: The system processes 96x96 grayscale heatmaps, not photographs. No identifiable images are stored or transmitted—only anonymous vehicle detection coordinates.

  • Backbone MobileNetV2 (alpha=0.35)
  • Input Size 96x96 grayscale
  • Output Fully convolutional heatmap
  • Model Size ~50KB (int8 quantized)

Edge Impulse Training Pipeline

1 Data Collection
2 Labeling
3 Training
4 Quantization
5 Deployment
  • Data augmentation: rotation, brightness, Gaussian noise
  • 80/20 train/test split with stratified sampling
  • Cloud-based training on Edge Impulse platform

Performance Targets

Based on similar FOMO deployments and Edge Impulse benchmarks

85-90% Precision Target
90-95% Recall Target
~90% F1 Target
~50ms Inference

Model Quantization

The model is quantized from float32 to int8 for ESP32 deployment, reducing memory footprint by 4x while maintaining >95% of original accuracy.

// TensorFlow Lite Micro inference
TfLiteTensor* input = interpreter->input(0);
// Input: 96x96 grayscale image (9,216 bytes)
// Output: 12x12 heatmap (144 values)

Hardware Architecture

Edge Devices

ESP32-CAM Specifications

  • MCU ESP32-S (240MHz dual-core)
  • RAM 520KB SRAM + 4MB PSRAM
  • Flash 4MB
  • Camera OV2640 (2MP)
  • Connectivity WiFi 802.11 b/g/n

Camera Sensor Details

The OV2640 sensor provides 2 megapixel resolution, but we downsample to 320x240 for optimal inference speed while maintaining sufficient detail for vehicle detection.

  • Max Resolution 1600x1200
  • Operating Resolution 320x240 (QVGA)
  • Frame Rate 10 FPS @ QVGA
  • Lens Angle 120° wide-angle

Power Analysis

Mode Current Power
Active (WiFi + Camera) 310mA 1.55W
Inference Only 180mA 0.90W
Light Sleep 6.7mA 33mW
Deep Sleep 10μA 50μW

Deployment Considerations

  • Weatherproofing: IP65-rated enclosure required for outdoor deployment
  • Power Supply: 5V 2A via solar panel + battery or mains adapter
  • Mounting: 3-4m height, angled 15-30° down towards road
  • Connectivity: WiFi range ~50m; cellular 4G modem for remote sites

Data Pipeline

Backend

Detection to Dashboard Flow

ESP32-CAM
REST API
SQLite DB
Dashboard

SQLite Storage Schema

CREATE TABLE detections (
  id INTEGER PRIMARY KEY,
  site_id INTEGER NOT NULL,
  timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
  vehicle_count INTEGER,
  confidence REAL,
  direction TEXT,
  speed_estimate REAL,
  FOREIGN KEY (site_id) REFERENCES sites(id)
);

CREATE TABLE sites (
  id INTEGER PRIMARY KEY,
  name TEXT UNIQUE NOT NULL,
  description TEXT,
  latitude REAL,
  longitude REAL,
  active BOOLEAN DEFAULT 1
);

API Endpoints

Method Endpoint Description
GET /api/sites List all monitoring sites
GET /api/detections Get recent detections
GET /api/stats/:site Site-specific statistics
GET /api/stats/:site/hourly Hourly breakdown for a site
POST /api/detections Submit new detection (API key required)
GET /health System health check
GET /api/devices Simulated device states
GET /api/incidents Simulated traffic incidents

Data Retention

  • Raw Detections: 30 days rolling window
  • Hourly Aggregates: 1 year retention
  • Daily Summaries: Indefinite storage

Corridor Intelligence

Analytics

Site Grouping Methodology

Sites are organized into logical corridors representing major traffic routes through Perth's western suburbs.

Mounts Bay Road Nedlands → Perth CBD (2 directions)
6 sites
Stirling Highway Claremont → Nedlands (2 directions)
16 sites

Traffic Status Calculation

Corridor status is calculated using weighted averaging across all active sites, with higher weights for sites with more traffic lanes.

function calculateCorridorStatus(sites) {
  const weightedSum = sites.reduce((acc, site) => {
    return acc + (site.speed * site.laneCount);
  }, 0);
  const totalLanes = sites.reduce((acc, s) => acc + s.laneCount, 0);
  return weightedSum / totalLanes;
}

Peak Hour Detection

  • Morning Peak 7:00 AM - 9:30 AM
  • Evening Peak 4:00 PM - 6:30 PM
  • Weekend Pattern 10:00 AM - 2:00 PM (shopping)
  • Holiday Adjustment Reduced multipliers

Future: Predictive Capabilities

Coming in v2.0:

  • 15-minute traffic predictions using LSTM neural network
  • Event-based surge detection (concerts, sports games)
  • Weather-adjusted forecasting
  • Personalized commute recommendations

Deployment & Infrastructure

DevOps

Cloud Hosting Architecture

  • Frontend Vercel (Global CDN)
  • Backend API Docker on VPS (Sydney, always-on)
  • Database SQLite (persistent Docker volume)
  • SSL Let's Encrypt (auto-renewal)

Backend Configuration

# Docker deployment on VPS
docker run -d \
  --name swanflow-api \
  --restart unless-stopped \
  --network donnacha-network \
  -e NODE_ENV=production \
  -e SIMULATE_FREEWAY=true \
  -v swanflow_data:/app/data \
  swanflow-api

Frontend Configuration

  • Vercel Edge Network for global CDN delivery
  • Automatic HTTPS/SSL certificates
  • Git-based deployments (auto-deploy on push)
  • Environment variable management
  • Custom domain support (swanflow.com.au)

Monitoring & Health

Health Endpoint /api/health
Uptime Docker auto-restart
Alerts Discord webhook
Logging Docker logs

Deployment Commands

# Deploy frontend to Vercel
git push origin master  # Auto-deploys via GitHub integration

# View backend logs on VPS
ssh root@your-vps "docker logs swanflow-api --tail 50"

# Restart backend
ssh root@your-vps "docker restart swanflow-api"

# Health check
curl https://api.swanflow.com.au/health

Main Roads WA Integration

Live Data

Real-Time Incident Data

SwanFlow integrates live incident and roadworks data from Main Roads Western Australia's public ArcGIS REST API, demonstrating how citizen-augmented monitoring complements official infrastructure.

  • Data Source Main Roads WA ArcGIS API
  • Update Frequency Real-time (15-second refresh)
  • Coverage Perth Metro + Regional WA
  • Data Types Incidents, Roadworks, Closures

API Endpoints

// Incidents API
const INCIDENTS_URL = 'https://services2.arcgis.com/cHGEnmsJ165IBJRM/arcgis/rest/services/WebEoc_RoadIncidents/FeatureServer/1/query';

// Roadworks API
const ROADWORKS_URL = 'https://services2.arcgis.com/cHGEnmsJ165IBJRM/arcgis/rest/services/WebEoc_RoadworksPlanned/FeatureServer/0/query';

// Fields returned
outFields: "Location,IncidentTy,ClosureTyp,TrafficCon,TrafficImp,Road,Region,Suburb,EntryDate,UpdateDate,SeeMoreUrl"

Incident Types

  • Crashes — Multi-vehicle collisions, single-vehicle incidents
  • Breakdowns — Disabled vehicles blocking lanes
  • Hazards — Debris, oil spills, fallen trees
  • Roadworks — Planned maintenance with lane closures
  • Closures — Full road closures and detours

Map Visualization

Incidents appear as orange markers on the SwanFlow map with interactive popups showing:

  • Incident type badge (Maintenance, Crash, Hazard)
  • Location and affected road
  • Traffic impact and closure details
  • Estimated completion time
  • Link to Main Roads WA for updates

Complementary Monitoring

🤝 Citizen + Official: Main Roads WA operates 1,400+ Smart Freeway sensors. SwanFlow complements this with arterial road monitoring where freeway sensors don't reach—demonstrating how citizen data can augment professional infrastructure.

Main Roads WA Freeways + Major Incidents
SwanFlow Arterial Roads + Flow Data

Data Attribution

All incident and roadworks data is provided by Main Roads Western Australia via their public ArcGIS REST API. SwanFlow displays this data to enhance traffic awareness alongside our citizen-collected vehicle counts.

  • Data source: Main Roads WA (https://www.mainroads.wa.gov.au)
  • API access: Public (no authentication required)
  • License: Open data for public use