Technical Documentation

SwanFlow Knowledge Base

Deep dive into the technology powering Perth's real-time traffic intelligence

52 Sensor Sites
48ms Inference Time
90.5% F1 Score
🧠

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, Stirling Highway, Mitchell Freeway, Kwinana Freeway) with directional filtering for accurate flow analysis.

// Corridor grouping example
corridors: {
  'mounts-bay-eastbound': {
    sitePatterns: ['Mounts Bay'],
    directionFilter: 'Eastbound'
  },
  'mitchell-northbound': {
    sitePatterns: ['Mitchell Fwy'],
    directionFilter: 'Northbound'
  }
}

Speed Estimation

Traffic speed is estimated using detection frequency patterns and historical calibration data. Higher detection rates typically correlate with slower traffic due to increased vehicle density.

Flowing 55-65 km/h
Moderate 30-50 km/h
Heavy 15-35 km/h
Gridlock 5-20 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)
  • Freeway multipliers: 1.5x stronger directional bias than arterials
ðŸĪ–

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.

  • 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
  • 2,000+ labeled vehicle images from Perth roads
  • 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
Mitchell Freeway Narrows → Scarborough Beach Rd (2 directions)
18 sites
Kwinana Freeway Narrows → Leach Hwy (2 directions)
12 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"