STMSTraffic Control

System Documentation

What was built, how it works, how to run it, and precisely what remains for the hardware build. The same material is in the repository under /docs.

1. What this system is

The Smart Traffic Management System (STMS) is a density-responsive traffic signal controller with emergency vehicle preemption, cloud telemetry and a remote operations dashboard. It replaces the fixed-timer logic of a conventional junction with a controller that measures how many vehicles are actually waiting and allocates green time accordingly.

The project has no physical hardware. Instead of stubbing the sensors out, the perception layer is replaced with a microscopic traffic simulator: individual vehicles arrive as a Poisson process, follow a car-following law, form queues, and discharge at realistic saturation flow. The controller reads that model through the same interface it would use to read an IR sensor array. Everything from the sensor interface upwards is working software.

Why this is stronger than a mock-up

Because the vehicles are physically simulated, the system can be measured. A second controller running fixed timings is stepped in lockstep on an identical seeded arrival stream, so the performance difference between the two is an experimental result under controlled conditions rather than an assertion.

2. Architecture

Three tiers, matching the perception / network / application model:

TierResponsibilityImplementationStatus
PerceptionDetect vehicles, queues and emergency vehicles per laneTraffic simulator producing LaneDetection recordsSimulated
NetworkCarry telemetry up and commands downHTTPS JSON, device-key auth, batch upload, command pollingReal
ApplicationStore, visualise, report, controlNext.js App Router, MongoDB via Mongoose, React dashboardReal

The boundary between tier one and tier two is a plain JSON contract. That is the single most important design decision in the project: it is what allows a Raspberry Pi to be dropped in later without touching the algorithm, the API, the database or the dashboard.

Request flow

Edge controller (simulated)
   |
   |  POST /api/telemetry          every 5s, batched, x-device-key
   v
Next.js route handler  ->  validation  ->  repository  ->  MongoDB
                                              |
                                              +--> in-memory store if no MONGODB_URI
   ^
   |  GET /api/overrides           polled every 4s by the controller
   |  PATCH /api/overrides         acknowledgement
   |
Operator dashboard  --POST /api/overrides-->  command queue

Operator commands are deliberately not applied directly in the browser. They are written to the database, polled by the controller, applied, and then acknowledged. The delay visible on screen is genuine command latency, which is what a warden would experience in the field.

3. The control algorithm

The controller is a four-phase, fully-actuated state machine. Phases serve opposing approaches together, which is how real four-way junctions avoid conflicting movements while maximising throughput.

PhaseMovements served
NS_THROUGHNorth and South, through and right turns
NS_LEFTNorth and South, protected left turns
EW_THROUGHEast and West, through and right turns
EW_LEFTEast and West, protected left turns

3.1 Green time proportional to density

The report specifies T proportional to D. That is made physically concrete: the time needed to discharge a queue of D vehicles is the startup lost time plus D saturation headways, clamped between a pedestrian-clearance minimum and a starvation ceiling.

T = clamp(minGreen, startupLostTime + D x saturationHeadway, maxGreen)
T = clamp(8s,       2.0s + D x 2.0s,                           45s)

D is the critical (longest) queue among the lanes the phase serves,
not their sum - the two lanes discharge in parallel.

3.2 Gap-out

Once the minimum green has been served and no vehicle has crossed the stop-bar detector for the gap threshold, the queue has discharged and the green ends early. Every second recovered this way is written to the decision log.

3.3 Phase skipping

A phase with no demand is not served at all. When nothing is waiting anywhere else, the controller rests in its current green rather than cycling through empty approaches. This is the single largest source of improvement over fixed timing.

3.4 Starvation guard

Skipping empty phases risks starving a light approach forever, so phase selection scores three competing pressures and a movement ignored for more than two maximum-green periods is promoted regardless of queue length.

score = queue
      + 0.12 x longestWaitInQueue
      + 0.06 x secondsSinceThisPhaseLastRan
      + 1000 if an emergency vehicle is present

3.5 Emergency preemption

When an emergency vehicle enters the detection zone, the running green is truncated, the junction is cleared through yellow and all-red, and the emergency corridor is held green until the vehicle passes. Two safeguards prevent this from becoming a denial of service on the cross street:

  • A hold ceiling of 30 seconds. A sustained stream of emergency vehicles cannot freeze the cycle indefinitely.
  • A cooldown of 18 seconds between preemptions. During the cooldown an emergency still wins phase selection outright through its scoring bonus - it simply cannot halt the current green.

This was a real bug, found by measurement

The first implementation had no ceiling or cooldown. Under the emergency drill scenario the adaptive controller served 64% fewer vehicles than the fixed baseline, because back-to-back ambulances held the north-south green permanently and starved the cross street. The benchmark harness caught it. After the fix the same scenario serves 15% more vehicles than the baseline.

3.6 Program algorithm (pseudocode)

initialise all approaches to RED
current <- NS_THROUGH,  state <- GREEN

every 0.1 s:
    generate arrivals per lane (Poisson)
    read sensors -> queue, occupancy, stop-bar, longest wait, emergency flag

    case state of
      GREEN:
        if emergency detected and cooldown expired:
            begin preemption, cut to YELLOW toward the emergency phase
        else if preemption held longer than 30 s:
            end preemption, arm cooldown
        else if operator override is holding this phase:
            stay
        else if elapsed >= maxGreen:                  -> YELLOW  (max-out)
        else if elapsed >= minGreen and headway > gap: -> YELLOW  (gap-out)
        else if elapsed >= allocated and no queue:     -> YELLOW
      YELLOW:
        if elapsed >= yellowTime:  -> ALL_RED
      ALL_RED:
        if elapsed >= allRedTime:
            next    <- highest scoring phase with demand
            allocated <- clamp(minGreen, lost + D x headway, maxGreen)
            current <- next,  state <- GREEN

    advance every vehicle under the car-following law
    accumulate delay, stops, throughput, idle green, fuel, CO2

4. The traffic model

Vehicle motion uses a safe-speed car-following rule. Each vehicle computes the distance it may advance - bounded by its leader's rear bumper and, if the signal forbids entry, by the stop line - then takes the fastest speed from which it could still stop within that distance.

allowed  = min( leader.dist - leader.length - minGap,
                distanceToStopLine if the signal forbids entry )

safeSpeed = sqrt( 2 x deceleration x allowed )
speed     = min( freeFlowSpeed x classFactor, safeSpeed )
            bounded by comfortable acceleration and braking rates

This one rule reproduces queue build-up, the startup wave at the beginning of green, and saturation-flow discharge, without any of them being scripted.

ParameterValueSource
Free-flow speed13.9 m/s (50 km/h)Urban default
Saturation headway2.0 s~1800 veh/h/lane
Startup lost time2.0 sDriver reaction at green
Comfortable acceleration2.2 m/s²Passenger comfort
Comfortable deceleration3.5 m/s²Passenger comfort
Minimum stopped gap2.0 mBumper to bumper
Detection zone120 m upstreamSensor array reach
Idle fuel burn0.7 L/hIdling petrol engine
CO₂ per litre2.31 kgPetrol combustion

5. How performance is measured

Two engines are constructed with the same seed and stepped in lockstep. Because arrival generation consumes the random stream in a fixed order, both receive identical vehicles at identical instants. The only difference is the control strategy.

npm run benchmark
npm run benchmark -- --minutes 30 --scenario lopsided --seed 4242

Representative results over 12 simulated minutes per scenario:

ScenarioAvg wait (adaptive)Avg wait (fixed)ChangeVehicles served
Balanced flow19.3 s37.2 s-48.0%+5.0%
Morning rush39.8 s67.7 s-41.3%+22.8%
Lopsided demand17.8 s80.1 s-77.7%+49.6%
Off peak12.6 s29.8 s-57.7%+7.5%
Emergency drill38.4 s51.0 s-24.7%+15.5%

The adaptive controller reduces waiting time in every scenario while serving more vehicles, which rules out the obvious objection that it simply refuses traffic to keep its averages low. The gain is largest under lopsided demand, which is exactly where a fixed timer wastes the most green.

On the metrics

Idle green time counts green displayed to an empty approach while another approach has vehicles waiting. A controller resting in green on a deserted junction at 3am wastes nothing, because there is nobody else to serve; counting that as waste would flatter the fixed baseline and misrepresent both systems.

6. API reference

Method & pathAuthPurpose
GET /api/healthnoneLiveness, storage backend, security configuration
GET /api/intersectionsnoneFleet listing with heartbeat-derived status
GET /api/intersections/:idnoneOne junction plus latest telemetry and incidents
POST /api/telemetrydevice keyIngest one document or a batch of up to 200
GET /api/telemetrynoneTime series for charts, oldest first
POST /api/overridesoperator passcodeQueue an operator command
GET /api/overridesdevice keyController collects pending commands
PATCH /api/overridesdevice keyController acknowledges applied commands
GET /api/incidentsnoneAudit trail, newest first
POST /api/incidentsdevice keyController raises an incident
GET /api/reports/summarynonePlanning report with peak analysis and advice

Two additional routes, /api/edge/telemetry and /api/edge/commands, exist only for the in-browser simulator. A browser cannot safely hold the device secret, so these same-origin routes stand in for a provisioned device during a demo. They perform identical validation and write to the identical store. A real controller uses the device-authenticated routes and never touches them.

Telemetry payload

POST /api/telemetry
x-device-key: <DEVICE_API_KEY>

{
  "intersectionId": "INT-001",
  "deviceId": "RPI-EDGE-001",
  "recordedAt": "2026-09-11T00:23:41.488Z",
  "simTime": 120.4,
  "mode": "adaptive",
  "currentPhase": "NS_THROUGH",
  "signalState": "GREEN",
  "lanes": [
    { "laneId": "N-through", "approach": "N", "movement": "through",
      "vehicleCount": 7, "queueLength": 5, "maxWait": 18.3, "signal": "green" }
  ],
  "metrics": { "avgWaitTime": 19.4, "totalQueue": 9,
               "throughputPerHour": 2148, "vehiclesServed": 54,
               "idleGreenPct": 3.3 },
  "health": { "uptimeSeconds": 120, "sensorsOnline": 8, "sensorsTotal": 8 }
}

7. Database schema

MongoDB, four collections. If MONGODB_URI is absent the repository transparently falls back to a bounded in-memory store, so the application is fully demonstrable with no infrastructure at all.

traffic_logs

FieldTypeDescription
_idObjectIdPrimary key
intersectionIdString (indexed)Which junction reported
deviceIdStringWhich controller reported
recordedAtDate (indexed)Wall-clock time of the reading
simTimeNumberController uptime in seconds
modeStringadaptive | fixed
currentPhaseStringPhase running at capture
signalStateStringGREEN | YELLOW | ALL_RED
lanes[]ArrayOne sub-document per lane (8 per junction)
lanes[].laneIdStringe.g. N-through
lanes[].vehicleCountNumberVehicles in the detection zone
lanes[].queueLengthNumberVehicles standing - the density signal D
lanes[].maxWaitNumberLongest wait in that lane, seconds
lanes[].signalStringred | yellow | green
metricsObjectavgWaitTime, totalQueue, throughput, served, idleGreenPct
healthObjectuptimeSeconds, sensorsOnline, sensorsTotal

A compound index on { intersectionId: 1, recordedAt: -1 } supports the dashboard's dominant query, the most recent N readings for one junction.

intersections

FieldTypeDescription
intersectionIdString (unique)Business key, e.g. INT-001
nameStringHuman-readable junction name
locationObjectaddress, latitude, longitude
deviceIdStringProvisioned controller
controlModeStringadaptive | fixed
statusStringonline | degraded | offline
lastSeenAtDateHeartbeat; over 30s stale reads as offline
sensorsOnline / sensorsTotalNumberHealth of the sensor array

override_commands

FieldTypeDescription
intersectionIdString (indexed)Target junction
actionStringforce_phase | release | set_mode | emergency_preempt
phase / approach / modeStringAction parameters
holdSecondsNumberHow long a forced phase is held (5-120)
issuedByStringOperator identity
statusString (indexed)pending | acknowledged | expired
acknowledgedAtDateWhen the controller confirmed it

incidents

FieldTypeDescription
intersectionIdString (indexed)Where it happened
typeStringemergency_preemption | sensor_fault | max_out | manual_override | congestion_alert
severityStringinfo | warning | critical
approachStringAffected approach, where relevant
messageStringHuman-readable description
responseSecondsNumberEmergency response time
occurredAtDate (indexed)Event timestamp

8. How to use the system

Running it locally

npm install
cp .env.example .env.local     # optional - it runs without this
npm run dev                    # http://localhost:3000

The control room

  • Run / Pause and the 1x-10x speed selector drive the simulation clock.
  • Demand scenarios reseed both engines and restart the comparison. Lopsided Demand is the most persuasive to demonstrate.
  • The sliders retune the controller live: raise Traffic volume until the junction saturates, or widen the gap-out threshold to watch idle green climb.
  • Force phase and Dispatch emergency queue a command through the cloud; expect a few seconds before the controller picks it up. That delay is the real round trip.
  • The decision log explains every phase change - which phase was chosen, why, and how many seconds a gap-out recovered.

Demonstration script

  1. 1.Open the control room and select Lopsided Demand. Let it run for two minutes of simulated time at 5x.
  2. 2.Point at the comparison panel: the adaptive controller is serving roughly 50% more vehicles at a fraction of the waiting time.
  3. 3.Point at the plan view: the fixed baseline would still be giving green to the empty east-west approach. Adaptive is skipping it.
  4. 4.Dispatch an emergency vehicle on N. Watch the running green truncate, the junction clear, and the north-south corridor hold.
  5. 5.Open Analytics to show the same data read back out of the database through the reporting API.
  6. 6.Run npm run benchmark in a terminal for the reproducible headline numbers.

Headless controller

To prove the API works against something other than the browser, run the virtual edge controller. It executes the real control loop, uploads telemetry with its device key, and polls for operator commands.

npm run virtual-edge
npm run virtual-edge -- --url https://your-app.vercel.app --id INT-002

9. What remains: the hardware build

The project is deliberately structured so that the hardware slots into one clearly marked seam. Everything below is what is left to do, and none of it requires changing the algorithm, the API, the database or the dashboard.

9.1 The single integration point

The simulator implements one method, refreshDetections(), which produces one LaneDetection per lane. A hardware build replaces the body of that method with GPIO reads. The controller consumes the same structure either way.

interface LaneDetection {
  laneId: "N-through" | "N-left" | ... ;
  queueLength: number;             // vehicles standing  <- sensor array
  occupancy: number;               // vehicles present   <- sensor array
  stopBarOccupied: boolean;        // stop-bar detector  <- single sensor
  timeSinceLastDetection: number;  // derived on-device
  maxWait: number;                 // derived on-device
  emergencyPresent: boolean;       // siren/strobe or RF beacon
  signal: "red" | "yellow" | "green";
}

9.2 Bill of materials

ComponentQuantityPurpose
Raspberry Pi 4 (2GB+)1 per junctionEdge controller running the control loop
HC-SR04 ultrasonic or IR sensor8-16One or two per lane for queue detection
Stop-bar sensor (inductive or IR)8Gap-out detection at the stop line
8-channel relay board (opto-isolated)2Driving mains LED signal heads
LED traffic signal heads4 (+4 arrow)Physical indication
4G/LTE HAT or Wi-Fi1Uplink to the cloud API
Real-time clock module1Timekeeping across power loss
24V PSU with battery backup1Signals must fail safe, not fail dark
Weatherproof IP65 enclosure1Roadside protection

9.3 Suggested GPIO map

Ultrasonic sensors (BCM numbering)
  N-through  trig 5   echo 6      E-through  trig 23  echo 24
  N-left     trig 12  echo 13     E-left     trig 25  echo 8
  S-through  trig 16  echo 19     W-through  trig 7   echo 1
  S-left     trig 20  echo 26     W-left     trig 0   echo 11

Signal head relays
  N  red 2   amber 3   green 4        E  red 14  amber 15  green 18
  S  red 17  amber 27  green 22       W  red 9   amber 10  green 21

Reserved
  Relay board enable  GPIO 26   (drives all heads to flashing red on fault)

9.4 Remaining work, in order

  1. 1.Sensor driver: read each ultrasonic pair, convert distance to presence, debounce, and calibrate the empty-lane baseline per sensor.
  2. 2.Queue estimation: a single sensor gives presence, not queue length. Either place sensors at 10m intervals as the report describes, or infer queue length from how long presence has persisted at the stop bar.
  3. 3.Port the control loop to the Pi: the algorithm in src/lib/sim/controller.ts is pure and dependency-free, so it can be transliterated to Python directly or run on Node on the Pi unchanged.
  4. 4.Relay driver with an interlock that makes conflicting greens physically impossible, not merely unlikely in software.
  5. 5.Fail-safe behaviour: on sensor loss, controller fault or watchdog timeout, fall back to fixed timing; on total failure, flashing red.
  6. 6.Device provisioning: per-device keys or client certificates rather than one shared DEVICE_API_KEY.
  7. 7.Store-and-forward buffering so telemetry survives a connectivity outage and uploads in a batch when the link returns.
  8. 8.Field calibration of saturation headway and startup lost time against the actual junction, since both vary with local driver behaviour.
  9. 9.Pedestrian phases and push-button demand, which the current four-phase plan does not model.

Safety

Nothing in this project is certified for use on a public road. A deployed traffic controller requires a hardware conflict monitor that forces flashing red when conflicting greens are detected, independently of the software. Software interlocks are necessary but never sufficient.

10. Limitations

  • Single isolated junction. Green-wave coordination across a corridor is not implemented, though the phase-selection interface would extend to it.
  • No pedestrian phases or push-button demand; minimum green stands in as a clearance proxy.
  • Right turns share the through lane rather than having a dedicated movement.
  • Vehicle arrivals are Poisson, which is realistic for free-flowing traffic but does not capture platoons released by an upstream signal.
  • No weather, incident or road-works effects on sensor reliability or capacity.
  • The in-memory fallback store is per-server-instance, so on a multi-instance deployment without MongoDB, different requests may see different data.
  • Emergency vehicles are detected by a flag on the model rather than by siren or strobe recognition, which is the harder half of the real problem.

11. Technology choices

LayerChoiceWhy
FrameworkNext.js 16 (App Router)One codebase for UI and API; deploys to Vercel unchanged
LanguageTypeScript (strict)The control algorithm benefits from exhaustive checking of phase and lane identifiers
DatabaseMongoDB + MongooseTelemetry is a time series of nested lane documents, which maps naturally to documents
StylingTailwind CSS v4Control-room palette expressed as design tokens
VisualisationHTML5 Canvas + hand-built SVG chartsCanvas for per-frame vehicle rendering; SVG charts avoid a heavy dependency and give exact control over mark specs
HostingVercelServerless routes suit a bursty telemetry workload

The charts are hand-built rather than taken from a library so that the colour palette could be validated for colour-vision deficiency: the two series colours were checked for perceptual separation against the dark chart surface rather than chosen by eye.