SwanFlow

Real-time vehicle detection using Edge AI

SIMULATED DATA - Phase 1 of PoC is in development | Hardware deployment at Mounts Bay Road coming soon | Real-time Edge AI vehicle detection | SIMULATED DATA - Phase 1 of PoC is in development | Hardware deployment at Mounts Bay Road coming soon | Real-time Edge AI vehicle detection
FILTER:

Traffic Flow Algorithm

Core Logic

Vehicle Detection Pipeline

  • Frame Capture 320x240 @ 10 FPS
  • Inference Time ~50ms per frame
  • Confidence Threshold >0.6 (60%)
  • Aggregation Window 5 seconds

Corridor Aggregation

Sites are grouped into corridors (Mounts Bay Road, Stirling Highway) with directional filtering for accurate flow analysis.

// Corridor grouping example
corridors: {
  'mounts-bay-eastbound': {
    sitePatterns: ['Mounts Bay'],
    directionFilter: 'Eastbound'
  },
  'stirling-southbound': {
    sitePatterns: ['Stirling Hwy'],
    directionFilter: 'Southbound'
  }
}

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
  • Will collect 2,000+ images for ML training
  • Data augmentation: rotation, brightness, Gaussian noise
  • 80/20 train/test split with stratified sampling
  • Cloud-based training on Edge Impulse platform

Performance Metrics

89% Precision
92% Recall
90.5% F1 Score
48ms 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
POST /api/detection Submit new detection
GET /api/health System health check

Data Retention

  • Raw Detections: 30 days rolling window
  • Hourly Aggregates: 1 year retention
  • Daily Summaries: Indefinite storage
  • Automatic Cleanup: Nightly cron job at 3:00 AM AWST

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

VPS Architecture

  • Provider Vultr (Sydney, AU)
  • Instance 4 vCPU, 8GB RAM, 160GB SSD
  • OS Ubuntu 22.04 LTS
  • Monthly Cost ~AU$60

Docker Container Setup

services:
  api:
    build: ./backend/api
    ports:
      - "3000:3000"
    volumes:
      - ./data:/app/data
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./ssl:/etc/ssl/certs
    depends_on:
      - api

Nginx Configuration

  • Reverse proxy to Node.js API on port 3000
  • SSL/TLS termination with Let's Encrypt certificates
  • Gzip compression for static assets
  • Rate limiting: 100 requests/minute per IP
  • CORS headers for dashboard API access

Monitoring & Health

Health Endpoint /api/health
Uptime 99.9% SLA
Alerts Discord webhook
Logging Docker logs

Deployment Commands

# Deploy frontend updates
scp frontend/web-dashboard/* root@45.77.233.102:/var/www/swanflow/

# Restart API container
ssh root@45.77.233.102 "cd /opt/swanflow && docker compose restart api"

# View logs
ssh root@45.77.233.102 "docker logs -f swanflow-api --tail 100"

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)
  • Updates: Real-time via ArcGIS Feature Service
  • License: Open data for public use