Schematik build

Skyflight Dogfight Game

ESP32Beginner30 minutes
Photo of Skyflight Dogfight Game

Schematik

Last updated November 19, 2026

What you'll build

Skyflight Dogfight is a 3D plane game. You fly it by tilting a small controller. A motion sensor reads the tilt. A red button fires your guns.

The SSK1 board runs the show. It makes its own WiFi network and sends the game to your browser. No internet or app is needed.

Flying the dogfight with the tilt controller

How it works

  • The board reads the sensor 60 times a second. It sends your tilt to the browser.
  • The board also builds a new island map before each flight. It uses both of its cores for this.
  • The board plans the enemy moves during a fight.
  • Your browser draws the 3D world, the planes and the explosions.

What you need

  • SSK1 board (ESP32-S3)
  • MPU-6050 motion sensor (also sold as GY-521)
  • Push button
  • Breadboard
  • 7 jumper wires
  • USB-C cable

Build it step by step

1. Put the SSK1 on the breadboard

Press the SSK1 into one end of the breadboard. Push gently until all pins sit deep in the holes. Keep the USB-C ports facing out.

The SSK1 on the breadboard

2. Add the motion sensor

Press the MPU-6050 into the middle of the breadboard. Mount it flat and tight. The sensor is your joystick. If it wobbles, your aim wobbles.

The MPU-6050 sensor on the breadboard

3. Add the fire button

Press the button into the far end of the breadboard. Now all three parts are in place.

SSK1, sensor and button in a row

4. Wire the sensor

Connect the sensor to the SSK1 with five wires:

  • VCC → 3V3
  • GND → G
  • SDA → GPIO 8
  • SCL → GPIO 9
  • INT → GPIO 5

Leave XDA, XCL and AD0 empty. INT is optional, but it helps.

Check VCC and GND twice. Swapping them can burn out the sensor.

The first wires between the SSK1 and the sensor

5. Wire the button

Connect one button leg to GPIO 4. Connect the other leg to G. You don't need a resistor.

Has your button got four legs? Use two legs that sit diagonal from each other.

All seven wires in place

6. Plug in and upload

Plug a USB-C cable into the port marked Flashing / Logging. Open this project in Schematik and deploy it to the board.

After each start, hold the controller still for 2 seconds. The board measures the sensor's resting point then.

Plugging in the USB-C cable

7. Fly

  1. On your phone or laptop, join the WiFi network Skyflight-Dogfight. The password is schematik.
  2. Open http://192.168.4.1 in your browser.
  3. Click Let's fly.

Controls

  • Tilt the controller to steer.
  • Press the button to fire.
  • Double-tap the button for a barrel roll. It dodges bullets.
  • No controller? Use WASD to steer, Space to fire and Q/E to roll.

Tips

  • Aim slowly drifting? Press C in the game to reset the sensor. Or restart the board while you hold it still.
  • Page not loading? Make sure you're on the Skyflight-Dogfight network. Then reload the page.
  • First load is slow. The sounds and pictures take a few seconds. After that, it runs smoothly.

Wiring diagram

Wiring diagram for Skyflight Dogfight Game
Loading diagram…

Gather all the parts

QtyComponent
1

MPU-6050 Motion Sensor (GY-521) from the Schematik Starter Kit

The MPU-6050 accelerometer and gyroscope from the Schematik Starter Kit 1, on the blue GY-521 board. It measures tilt and turning speed and talks to the SSK1 over I2C at address 0x68.

1

Push Button

Momentary push button switch

Assemble it in 5 steps

1. Place the parts

Put the SSK1, the motion sensor and the button on a breadboard. Keep the USB cable unplugged while you wire.

  • Mount the sensor flat and tight. It is your joystick. If it wobbles, your aim wobbles.

2. Power the sensor

Connect the sensor's VCC pin to 3V3 on the SSK1. Connect the sensor's GND pin to G.

  • Swapping VCC and GND can burn out the sensor. Check twice before you plug in.

3. Connect the sensor's data wires

SDA goes to GPIO 8. SCL goes to GPIO 9. INT goes to GPIO 5. It's optional, but it helps. Leave XDA, XCL and AD0 empty.

  • The pin names are printed next to each pin on both boards.

4. Wire the fire button

Connect one button leg to GPIO 4. Connect the other leg to G. You don't need a resistor.

  • Has your button got four legs? Use two legs that sit diagonal from each other.

5. Plug in and hold still

Plug a USB-C cable into the port marked Flashing / Logging. After each start, hold the controller still for 2 seconds.

  • If you move it during those 2 seconds, your aim will slowly drift. Press C in the game to fix it.

Review all connections

1. Connections between "imu1" and "ESP32"

Functionimu1ESP32
powerVCC → Power (VCC)3V3
groundGNDGND
i2cSDA → I2C dataGPIO 8
i2cSCL → I2C clockGPIO 9
digitalINT → Optional data-ready interruptGPIO 5

2. Connections between "btn1" and "ESP32"

Functionbtn1ESP32
digitalSIGNAL → Fire button, internal pull-up, pressed = LOWGPIO 4
groundGNDGND

Deploy the firmware

// Schematik Skyflight: Dogfight - hosted on the SSK1 (ESP32-S3, 8 MB flash, 8 MB PSRAM).
//
// The board is web server, controller and battle computer:
//   - joins your WiFi (include/secrets.h) as http://warbird.local, or opens its own network
//     "Skyflight-Dogfight" (password "schematik") at http://192.168.4.1
//   - serves the game from flash (embedded in the firmware: src/web_assets_*.cpp), held in PSRAM
//   - streams "roll,pitch,0,fire" at 60 Hz over a WebSocket on port 81
//   - builds the coast you fly over (lib/battle/theatre.*) on both CPU cores
//   - plans the bandits' moves during a sortie (lib/battle/tactics.*)
//   - /stats shows what it is doing with its RAM, flash and CPU
//
// Tasks:           core  prio  job
//   imu             1     5    MPU6050 at 500 Hz, fused to roll and pitch
//   io              1     4    WebSocket: the 60 Hz stream, reports in, orders out
//   loop (Arduino)  1     2    HTTP
//   worker 0 / 1    0/1   1    planner jobs first, else theatre jobs
//
// Wiring: MPU6050 VCC 3V3, GND G, SDA GPIO 8, SCL GPIO 9, INT GPIO 5; button GPIO 4 <-> G.
#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Preferences.h>
#include <WebSocketsServer.h>
#include <esp_partition.h>
#include "cpu.h"
#include "gen.h"
#include "plan.h"
#include "web_assets.h"
#if __has_include("secrets.h")
#include "secrets.h"
#else
#define HOME_WIFI_SSID ""
#define HOME_WIFI_PASSWORD ""
#endif

#define PIN_SDA 8
#define PIN_SCL 9
#define PIN_INT 5
#define PIN_BTN 4
#define MPU 0x68

static const char *HOSTNAME = "warbird";             // -> http://warbird.local
static const char *AP_SSID = "Skyflight-Dogfight";
static const char *AP_PASS = "schematik";            // >= 8 chars, or nullptr for an open network
static const float GYRO_LSB = 65.5f;                 // +/-500 dps
static const float FUSE_TAU = 0.25f;                 // complementary filter time constant, seconds
static const uint32_t STREAM_US = 1000000 / 60;
static const uint32_t CACHE_BUDGET = 1900 * 1024;    // PSRAM spent on holding game files
// WiFi takes internal RAM in bursts while data waits for air time (measured: up to 70 KB with
// five pages open and a file going out). Below HEAP_PRESSURE the board holds back what can
// wait: file sends pause, pages that are only watching miss stream frames. Below
// HEAP_CRITICAL every optional frame is skipped.
static const uint32_t HEAP_PRESSURE = 62 * 1024, HEAP_CRITICAL = 42 * 1024;
static inline uint32_t freeInternal() { return heap_caps_get_free_size(MALLOC_CAP_INTERNAL); }

WebServer http(80);
WebSocketsServer ws(81);

// ---------------------------------------------------------------- IMU
static SemaphoreHandle_t imuReady;
static void IRAM_ATTR onInt() { BaseType_t woken = pdFALSE; xSemaphoreGiveFromISR(imuReady, &woken); if (woken) portYIELD_FROM_ISR(); }

static float biasX, biasY, roll, pitch;
static bool havePose, mpuOk;
static volatile bool wantCalibrate;
static uint32_t lastSampleUs, imuCount, imuRate, sentCount, sendRate, ioLoops, ioRate;

static void wr(uint8_t reg, uint8_t val) { Wire.beginTransmission(MPU); Wire.write(reg); Wire.write(val); Wire.endTransmission(); }

static bool readRaw(int16_t v[7]) {
  Wire.beginTransmission(MPU); Wire.write(0x3B);
  if (Wire.endTransmission(false) != 0) return false;
  if (Wire.requestFrom(MPU, 14) != 14) return false;
  for (int i = 0; i < 7; i++) v[i] = (Wire.read() << 8) | Wire.read();
  return true;
}

// If the board reset while the sensor was mid-answer, the sensor can hold SDA low for ever.
// Nine clock pulses let it finish its byte and let go.
static void freeBus() {
  pinMode(PIN_SDA, INPUT_PULLUP);
  pinMode(PIN_SCL, OUTPUT_OPEN_DRAIN);
  for (int i = 0; i < 9; i++) { digitalWrite(PIN_SCL, LOW); delayMicroseconds(6); digitalWrite(PIN_SCL, HIGH); delayMicroseconds(6); }
  pinMode(PIN_SCL, INPUT_PULLUP);
}

static bool mpuInit() {
  Wire.beginTransmission(MPU);
  if (Wire.endTransmission() != 0) return false;
  wr(0x6B, 0x01); delay(50);
  wr(0x19, 1);     // 1 kHz / (1 + 1) = 500 Hz
  wr(0x1A, 0x02);  // DLPF 94 Hz: 3 ms delay
  wr(0x1B, 0x08);  // +/-500 dps
  wr(0x1C, 0x00);  // +/-2 g
  wr(0x37, 0x00);  // INT active high, push-pull
  wr(0x38, 0x01);  // data-ready interrupt
  return true;
}

static void calibrate() {
  Serial.println("# calibrating gyro - keep still");
  double sx = 0, sy = 0; int n = 0;
  uint32_t t0 = millis();
  while (n < 300 && millis() - t0 < 4000) {
    int16_t v[7];
    if (readRaw(v)) { sx += v[4]; sy += v[5]; n++; }
    delay(5);
  }
  if (n) { biasX = sx / n; biasY = sy / n; }
  havePose = false;
  Serial.println("# READY");
}

static void sampleImu() {
  int16_t v[7];
  if (!readRaw(v)) return;
  uint32_t now = micros();
  float dt = (now - lastSampleUs) * 1e-6f;
  lastSampleUs = now;
  if (dt <= 0 || dt > 0.05f) dt = 0.002f;
  float ax = v[0], ay = v[1], az = v[2];
  float gx = (v[4] - biasX) / GYRO_LSB, gy = (v[5] - biasY) / GYRO_LSB;
  float accRoll = atan2f(ay, az) * RAD_TO_DEG;
  float accPitch = atan2f(-ax, sqrtf(ay * ay + az * az)) * RAD_TO_DEG;
  if (!havePose || fabsf(accRoll - roll) > 180) { roll = accRoll; pitch = accPitch; havePose = true; }
  float alpha = FUSE_TAU / (FUSE_TAU + dt);
  roll = alpha * (roll + gx * dt) + (1 - alpha) * accRoll;
  pitch = alpha * (pitch + gy * dt) + (1 - alpha) * accPitch;
  imuCount++;
}

// Lowest free internal heap actually seen, sampled 500 to 1500 times a second from the two
// highest priority tasks. (The IDF's own "minimum free" adds up the low marks of several heap
// regions that did not happen at the same moment, so it reads lower than the truth.)
static volatile uint32_t heapLowSeen = UINT32_MAX;
// What was going on at that moment: which HTTP request, which WebSocket step.
static const char *volatile httpDoing = "-", *volatile ioDoing = "-";
static const char *lowHttp = "-", *lowIo = "-";
static uint32_t lowAtMs; static uint8_t lowClients;

static void noteHeap() {
  uint32_t freeNow = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
  if (freeNow < heapLowSeen) { heapLowSeen = freeNow; lowHttp = httpDoing; lowIo = ioDoing; lowAtMs = millis(); lowClients = ws.connectedClients(); }
}

static bool mpuBegin() {
  freeBus();
  Wire.begin(PIN_SDA, PIN_SCL, 400000);
  delay(60);
  if (!mpuInit()) { Wire.end(); return false; }
  calibrate();
  attachInterrupt(PIN_INT, onInt, RISING);
  return true;
}

static void imuTask(void *) {
  for (;;) {
    // No sensor (yet): look for it again every two seconds, so it can be plugged in late.
    if (!mpuOk) { vTaskDelay(pdMS_TO_TICKS(2000)); mpuOk = mpuBegin(); if (mpuOk) Serial.println("# MPU6050 found"); continue; }
    if (wantCalibrate) { wantCalibrate = false; calibrate(); }
    xSemaphoreTake(imuReady, pdMS_TO_TICKS(4));
    sampleImu();
    noteHeap();
  }
}

// ---------------------------------------------------------------- game files
// The game is built into the firmware (src/web_assets_*.cpp, made by web/scripts/embed-firmware.mjs),
// because Schematik flashes firmware only. Each file is one or more parts in flash. The ones
// that fit the budget are joined into PSRAM at boot, which serves them about twice as fast and
// leaves the flash cache to the hot loops; the rest go out part by part straight from flash.
struct Entry { const WebAsset *asset; uint8_t *data; };
static Entry files[WEB_ASSET_MAX];
static int fileCount, cacheCount;
static uint32_t cacheBytes, cacheHits, flashReads;

static Entry *entry(const String &path) {
  for (int i = 0; i < fileCount; i++) if (path == files[i].asset->path) return &files[i];
  return nullptr;
}

// Lists the files (first call), then copies those up to `maxFile` bytes that still fit.
static void loadFiles(uint32_t maxFile) {
  if (!fileCount) for (int i = 0; i < WEB_ASSET_COUNT && i < WEB_ASSET_MAX; i++) files[fileCount++] = {&WEB_ASSETS[i], nullptr};
  for (int i = 0; i < fileCount; i++) {
    Entry *e = &files[i];
    uint32_t size = e->asset->size;
    if (e->data || size > maxFile || cacheBytes + size > CACHE_BUDGET) continue;
    uint8_t *data = (uint8_t *)heap_caps_malloc(size, MALLOC_CAP_SPIRAM);
    if (!data) continue;
    uint32_t at = 0;
    for (int k = 0; k < e->asset->partCount; k++) { memcpy(data + at, e->asset->parts[k].data, e->asset->parts[k].size); at += e->asset->parts[k].size; }
    e->data = data; cacheBytes += size; cacheCount++;
  }
}

static const char *mime(const String &path) {
  if (path.endsWith(".html")) return "text/html";
  if (path.endsWith(".js")) return "text/javascript";
  if (path.endsWith(".css")) return "text/css";
  if (path.endsWith(".svg")) return "image/svg+xml";
  if (path.endsWith(".woff2")) return "font/woff2";
  if (path.endsWith(".woff")) return "font/woff";
  if (path.endsWith(".webp")) return "image/webp";
  if (path.endsWith(".png")) return "image/png";
  if (path.endsWith(".jpg")) return "image/jpeg";
  if (path.endsWith(".m4a")) return "audio/mp4";
  if (path.endsWith(".json")) return "application/json";
  return "application/octet-stream";
}

// Sends a body in small pieces, and waits (up to 0.3 s a piece) while internal RAM is short.
static uint32_t httpWaits;
static bool roomToSend() {
  for (int i = 0; i < 150 && freeInternal() < HEAP_PRESSURE; i++) { if (!i) httpWaits++; delay(2); }
  return true;
}
static void sendBody(const uint8_t *data, size_t size) {
  WiFiClient client = http.client();
  while (size && client.connected() && roomToSend()) {
    size_t sent = client.write(data, size < 2872 ? size : 2872);
    if (!sent) break;
    data += sent; size -= sent;
  }
}

// Serves `path` or its gzip twin, from PSRAM when held there, else from flash.
static bool sendFile(String path) {
  if (path.endsWith("/")) path += "index.html";
  const Entry *e = entry(path + ".gz");
  const bool gzip = e;
  if (!e) e = entry(path);
  if (!e) return false;
  const char *type = mime(path);
  http.sendHeader("Cache-Control", path.startsWith("/a/") ? "max-age=31536000, immutable" : "no-cache");
  if (gzip) http.sendHeader("Content-Encoding", "gzip");
  http.setContentLength(e->asset->size);
  http.send(200, type, "");
  if (e->data) {
    cacheHits++;
    httpDoing = "ram file";
    sendBody(e->data, e->asset->size);
  } else {
    flashReads++;
    httpDoing = "flash file";
    for (int k = 0; k < e->asset->partCount; k++) sendBody(e->asset->parts[k].data, e->asset->parts[k].size);
  }
  httpDoing = "-";
  return true;
}

// Every GET that is not one of the routes below is a game file, or goes home.
class GameFiles : public RequestHandler {
 public:
#if ESP_ARDUINO_VERSION_MAJOR >= 3   // Arduino-ESP32 3.x passes the URI as const String &
  bool canHandle(HTTPMethod method, const String &) override { return method == HTTP_GET; }
  // Arduino-ESP32 3.1+ asks handlers through this overload; the old one above is no longer called.
  bool canHandle(WebServer &, HTTPMethod method, const String &) override { return method == HTTP_GET; }
  bool handle(WebServer &server, HTTPMethod, const String &uri) override {
#else
  bool canHandle(HTTPMethod method, String) override { return method == HTTP_GET; }
  bool handle(WebServer &server, HTTPMethod, String uri) override {
#endif
    if (!sendFile(uri)) { server.sendHeader("Location", "/"); server.send(302, "text/plain", ""); }
    return true;
  }
};

// ---------------------------------------------------------------- workers
static volatile bool sortie;                 // a page is in a sortie right now (reports are coming in)
static uint32_t lastStateMs, reportCount, reportRate;
static volatile uint32_t aloneUntil;
static volatile uint8_t enemiesUp, pilot;      // pilot: the page that is flying (it sends the reports)
static uint32_t heldBack;
static uint32_t planUs[2], genUs[2], planPct[2], genPct[2];
static float usPerRollout;

// Fast working memory, one set per worker, taken at boot before anything can fragment the
// heap: a float tile for erosion and the planner's rollout paths.
static float *workTile[2];
static tactics::Scratch *workScratch[2];

static bool allocateWorkers() {
  for (int i = 0; i < 2; i++) {
    workTile[i] = (float *)heap_caps_malloc(sizeof(float) * theatre::TILE * theatre::TILE, MALLOC_CAP_INTERNAL);
    workScratch[i] = (tactics::Scratch *)heap_caps_calloc(1, sizeof(tactics::Scratch), MALLOC_CAP_INTERNAL);
  }
  return workTile[0] && workTile[1] && workScratch[0] && workScratch[1];
}

// Arduino-ESP32 3.x gives WiFi and the network stack more internal RAM than 2.x did, so with
// both 62 KB tiles in internal RAM too little is left and every stream frame is held back
// (below HEAP_CRITICAL). Once the network is up, move tiles to PSRAM until WiFi has its room.
// Erosion then runs a little slower; the controller stream and the planner are unaffected.
static const uint32_t HEAP_WANTED = HEAP_PRESSURE + 40 * 1024;
static void makeRoomForWifi() {
  size_t bytes = sizeof(float) * theatre::TILE * theatre::TILE;
  for (int i = 1; i >= 0 && freeInternal() < HEAP_WANTED; i--) {
    float *ps = (float *)heap_caps_malloc(bytes, MALLOC_CAP_SPIRAM);
    if (!ps) break;
    heap_caps_free(workTile[i]);
    workTile[i] = ps;
    Serial.printf("# tile %d moved to PSRAM, internal free now %u\n", i, (unsigned)freeInternal());
  }
}

// Times the planner on a made-up four-bandit fight, alone on one core, once at boot.
static float benchUsPerRollout;
static void benchPlanner() {
  static tactics::State s;
  s = tactics::State{};
  s.px = 5; s.py = 40; s.hp = 80; s.wave = 5; s.enemyCount = 4;
  for (int i = 0; i < 4; i++) {
    tactics::Enemy &e = s.enemies[i];
    e.id = i + 1; e.kind = tactics::BANDIT; e.attack = true; e.x = -40 + i * 25; e.y = 30 + i * 12; e.z = -150 - i * 60;
    e.hp = 6; e.hpRatio = 0.8f; e.man = tactics::WEAVE; e.dir = 1; e.manT = 1; e.skill = 0.7f; e.cx = e.x; e.cy = e.y; e.cosP = e.cosP13 = 1;
  }
  static tactics::Plan plan;
  uint32_t t0 = micros();
  plan::planner.begin(s, 8);
  do { for (int j = 0; j < plan::planner.jobCount(); j++) plan::planner.runJob(j, *workScratch[0]); } while (plan::planner.advance());
  plan::planner.finish(plan);
  benchUsPerRollout = plan.rollouts ? (float)(micros() - t0) / plan.rollouts : 0;
  Serial.printf("# planner: %.0f us a rollout (%u rollouts)\n", benchUsPerRollout, (unsigned)plan.rollouts);
}

static void workerTask(void *arg) {
  int id = (int)(intptr_t)arg;
  theatre::Rng rng(esp_random() | 1);
  uint32_t lastRest = micros();
  for (;;) {
    gen::Job job;
    int planJob;
    uint32_t t0 = micros();
    bool worked = true;
    if (plan::claim(planJob)) {
      // A sortie is on: planner jobs outrank everything but the controller stream, so a
      // page loading from the board cannot hold a sweep up.
      vTaskPrioritySet(nullptr, 3);
      plan::run(planJob, *workScratch[id]);
      vTaskPrioritySet(nullptr, 1);
      planUs[id] += micros() - t0;
    } else if (gen::claim(job, id)) { gen::run(job, id, workTile[id], rng); genUs[id] += micros() - t0; }
    else worked = false;
    if (!worked) { vTaskDelay(2); lastRest = micros(); }
    // Let the idle task in now and then: it feeds the watchdog.
    else if (micros() - lastRest > 20000) { vTaskDelay(1); lastRest = micros(); }
  }
}

// ---------------------------------------------------------------- WebSocket
static void onSocket(uint8_t client, WStype_t type, uint8_t *payload, size_t length) {
  if (type == WStype_CONNECTED && millis() < aloneUntil) { ws.disconnect(client); return; }
  if (type == WStype_CONNECTED) {
    Serial.printf("# page connected (client %u, %u total)\n", client, ws.connectedClients());
    if (!mpuOk) ws.sendTXT(client, "# ERROR MPU6050 not found on SDA 8 / SCL 9");
  } else if (type == WStype_DISCONNECTED) {
    Serial.printf("# page disconnected (client %u)\n", client);
  } else if (type == WStype_BIN && length && payload[0] == 'S') {
    // The fight, as the page sees it. The planner works on the newest one.
    static tactics::State state;
    if (tactics::decodeState(payload, length, state)) { plan::report(state, client); lastStateMs = millis(); reportCount++; enemiesUp = state.enemyCount; pilot = client; }
  } else if (type == WStype_TEXT && length) {
    if (payload[0] == 'c') wantCalibrate = true;
    // "s1": a sortie started on the coast this board is serving. Time to build the next one.
    if (payload[0] == 's' && length >= 2 && payload[1] == '1' && gen::phase == gen::REST) gen::start(esp_random());
  }
}

static void ioTask(void *) {
  uint32_t nextSend = micros(), lastWs = 0, lastSecond = millis(), lastNote = 0, notedTheatre = 0;
  for (;;) {
    vTaskDelay(1);
    ioLoops++;
    noteHeap();
    uint32_t now = micros();
    // Every socket check is a round trip to the network task, so not on every pass.
    if (now - lastWs >= 4000) { lastWs = now; ioDoing = "loop"; ws.loop(); ioDoing = "-"; }
    if ((int32_t)(now - nextSend) >= 0) {
      nextSend += STREAM_US;
      if ((int32_t)(now - nextSend) > 50000) nextSend = now + STREAM_US;
      if (havePose && ws.connectedClients()) {
        char line[40];
        snprintf(line, sizeof line, "%.2f,%.2f,0,%d", roll, pitch, digitalRead(PIN_BTN) == LOW ? 1 : 0);
        uint32_t room = freeInternal();
        ioDoing = "stream";
        if (room >= HEAP_PRESSURE) { ws.broadcastTXT(line); sentCount++; }
        else if (room >= HEAP_CRITICAL && sortie) { ws.sendTXT(pilot, line); sentCount++; heldBack++; }   // the pilot comes first
        else heldBack++;
        ioDoing = "-";
      }
    }
    // Orders for the bandits, as soon as a sweep is done.
    static tactics::Plan orders;
    uint8_t client;
    if (plan::take(orders, client) && freeInternal() >= HEAP_CRITICAL) {
      uint8_t frame[8 + tactics::MAX_ENEMIES * 3];
      size_t size = tactics::encodePlan(orders, plan::rolloutRate, frame, sizeof frame);
      if (size) { ioDoing = "orders"; ws.sendBIN(client, frame, size); ioDoing = "-"; }
    }
    uint32_t ms = millis();
    if (ms < aloneUntil && ws.connectedClients()) ws.disconnect();
    sortie = ms - lastStateMs < 1500 && lastStateMs;
    gen::sortie_ = sortie;
    gen::pause_ = sortie && enemiesUp && ms - lastStateMs < 400;
    if (ms - lastSecond >= 1000) {
      uint32_t span = ms - lastSecond;
      lastSecond = ms;
      imuRate = imuCount * 1000 / span; sendRate = sentCount * 1000 / span; ioRate = ioLoops * 1000 / span; reportRate = reportCount * 1000 / span;
      imuCount = sentCount = ioLoops = reportCount = 0;
      if (plan::rolloutCount) usPerRollout = (float)(planUs[0] + planUs[1]) / plan::rolloutCount;
      for (int i = 0; i < 2; i++) { planPct[i] = planUs[i] / (span * 10); genPct[i] = genUs[i] / (span * 10); planUs[i] = genUs[i] = 0; }
      plan::rolloutRate = plan::rolloutCount * 1000 / span; plan::sweepRate = plan::sweepCount * 1000 / span;
      plan::rolloutCount = plan::sweepCount = 0;
      cpu::sample();
    }
    // Tell the pages what the board is up to: twice a second, and at once when a new coast is ready.
    if (ws.connectedClients() && (ms - lastNote >= 500 || notedTheatre != gen::servedId) && freeInternal() >= HEAP_PRESSURE) {
      lastNote = ms; notedTheatre = gen::servedId;
      char note[240];
      snprintf(note, sizeof note, "#{\"theatre\":%u,\"name\":\"%.24s\",\"phase\":\"%s\",\"build\":%.3f,\"c0\":%u,\"c1\":%u,\"heap\":%u,\"sims\":%u,\"samples\":%d}",
        (unsigned)gen::servedId, gen::servedInfo.name, gen::PHASE_NAME[gen::phase], gen::progress(), cpu::busy[0], cpu::busy[1], (unsigned)ESP.getFreeHeap(),
        (unsigned)plan::rolloutRate, plan::samples);
      ioDoing = "note"; ws.broadcastTXT(note); ioDoing = "-";
    }
  }
}

// ---------------------------------------------------------------- logbook
// The squadron's record lives on the board, so it is the same from every phone and laptop.
// Kept in NVS (the settings area), which survives every firmware upload.
static Preferences prefs;
static struct { uint32_t sorties, kills, seconds, best, bestWave; } logbook;

static void loadLogbook() {
  if (!prefs.begin("logbook", true)) return;
  prefs.getBytes("v1", &logbook, sizeof logbook);
  prefs.end();
}

static void sendLogbook() {
  char json[160];
  snprintf(json, sizeof json, "{\"sorties\":%u,\"kills\":%u,\"seconds\":%u,\"best\":%u,\"best_wave\":%u}",
    (unsigned)logbook.sorties, (unsigned)logbook.kills, (unsigned)logbook.seconds, (unsigned)logbook.best, (unsigned)logbook.bestWave);
  http.sendHeader("Cache-Control", "no-store");
  http.send(200, "application/json", json);
}

static uint32_t field(const String &body, const char *key, uint32_t max) {
  int at = body.indexOf(String("\"") + key + "\":");
  if (at < 0) return 0;
  uint32_t v = strtoul(body.c_str() + at + strlen(key) + 3, nullptr, 10);
  return v > max ? max : v;
}

static void addSortie() {
  const String body = http.arg("plain");
  uint32_t score = field(body, "score", 9999999), wave = field(body, "wave", 999), kills = field(body, "kills", 9999), seconds = field(body, "seconds", 36000);
  if (body.length() > 200 || !seconds) { http.send(400, "text/plain", "Bad sortie"); return; }
  logbook.sorties++; logbook.kills += kills; logbook.seconds += seconds;
  if (score > logbook.best) { logbook.best = score; logbook.bestWave = wave; }
  if (prefs.begin("logbook", false)) { prefs.putBytes("v1", &logbook, sizeof logbook); prefs.end(); }
  sendLogbook();
}

// ---------------------------------------------------------------- HTTP
static uint32_t partitionSize(esp_partition_type_t type, esp_partition_subtype_t subtype) {
  const esp_partition_t *p = esp_partition_find_first(type, subtype, nullptr);
  return p ? p->size : 0;
}

static void sendStats() {
  httpDoing = "stats";
  static char json[1700];
  uint32_t heapTotal = ESP.getHeapSize(), heapFree = ESP.getFreeHeap(), psTotal = ESP.getPsramSize(), psFree = ESP.getFreePsram();
  uint32_t fsUsed = 0, fsTotal = 0, sketch = ESP.getSketchSize(), appSize = partitionSize(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY);
  uint32_t chip = ESP.getFlashChipSize();
  // Flash in use: boot loader, tables and settings (first 64 KB) and the firmware, game files included.
  // No filesystem in this edition, so fs_* read 0.
  uint32_t flashUsed = 0x10000 + sketch;
  snprintf(json, sizeof json,
    "{\"heap_free\":%u,\"heap_total\":%u,\"heap_min\":%u,\"heap_low_seen\":%u,\"heap_low_when\":\"%u ms, http %s, ws %s, %u clients\",\"heap_largest\":%u,\"heap_used_pct\":%.1f,"
    "\"psram_free\":%u,\"psram_total\":%u,\"psram_used_pct\":%.1f,"
    "\"fs_used\":%u,\"fs_total\":%u,\"fs_used_pct\":%.1f,\"sketch\":%u,\"app_partition\":%u,\"flash_chip\":%u,\"flash_used_pct\":%.1f,"
    "\"cpu_mhz\":%u,\"core0_pct\":%u,\"core1_pct\":%u,\"planner_pct\":[%u,%u],\"builder_pct\":[%u,%u],"
    "\"imu_hz\":%u,\"io_hz\":%u,\"ws_clients\":%u,\"ws_msgs_per_s\":%u,\"sortie\":%s,"
    "\"planner\":{\"reports_per_s\":%u,\"sweeps_per_s\":%u,\"rollouts_per_s\":%u,\"samples\":%d,\"bandits\":%u,\"sweep_ms\":%.1f,\"us_per_rollout\":%.0f,\"bench_us_per_rollout\":%.0f},"
    "\"held_back\":{\"stream_frames\":%u,\"http_waits\":%u},\"files\":%d,\"cache_files\":%d,\"cache_bytes\":%u,\"cache_hits\":%u,\"flash_reads\":%u,"
    "\"theatre\":{\"id\":%u,\"name\":\"%.24s\",\"seed\":%u,\"bytes\":%u,\"builder\":%u,\"phase\":\"%s\",\"progress\":%.3f,\"droplets\":%u,\"last_build_ms\":%u,\"built\":%u,"
    "\"us_per_droplet_tile\":%.1f,\"us_per_droplet_psram\":%.1f},"
    "\"temp_c\":%.1f,\"rssi\":%d,\"uptime_s\":%u}",
    heapFree, heapTotal, ESP.getMinFreeHeap(), (unsigned)heapLowSeen, (unsigned)lowAtMs, lowHttp, lowIo, lowClients, (unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), 100.0f * (heapTotal - heapFree) / heapTotal,
    psFree, psTotal, 100.0f * (psTotal - psFree) / psTotal,
    fsUsed, fsTotal, 0.0f, sketch, appSize, chip, 100.0f * flashUsed / chip,
    ESP.getCpuFreqMHz(), cpu::busy[0], cpu::busy[1], (unsigned)planPct[0], (unsigned)planPct[1], (unsigned)genPct[0], (unsigned)genPct[1],
    (unsigned)imuRate, (unsigned)ioRate, ws.connectedClients(), (unsigned)sendRate, sortie ? "true" : "false",
    (unsigned)reportRate, (unsigned)plan::sweepRate, (unsigned)plan::rolloutRate, plan::samples, plan::bandits, plan::lastSweepUs / 1000.0f, usPerRollout, benchUsPerRollout,
    (unsigned)heldBack, (unsigned)httpWaits, fileCount, cacheCount, (unsigned)cacheBytes, (unsigned)cacheHits, (unsigned)flashReads,
    (unsigned)gen::servedId, gen::servedInfo.name, (unsigned)gen::servedInfo.seed, (unsigned)gen::servedSize, gen::servedInfo.builder,
    gen::PHASE_NAME[gen::phase], gen::progress(), (unsigned)gen::droplets_, (unsigned)gen::lastBuildMs, (unsigned)gen::built,
    gen::usPerDropTile, gen::usPerDropDirect,
    temperatureRead(), WiFi.RSSI(), (unsigned)(millis() / 1000));
  http.sendHeader("Cache-Control", "no-store");
  http.sendHeader("Access-Control-Allow-Origin", "*");
  http.send(200, "application/json", json);
  httpDoing = "-";
  // /stats?reset starts the low mark again, to measure one thing at a time.
  if (http.hasArg("reset")) heapLowSeen = UINT32_MAX;
  // /stats?alone=30 turns every page away for 30 s, to see what the board does by itself.
  if (http.hasArg("alone")) aloneUntil = millis() + 1000 * constrain(http.arg("alone").toInt(), 1, 120);
}

void setup() {
  Serial.begin(115200);
  cpu::begin();
  bool workers = allocateWorkers();
  if (workers) benchPlanner();
  pinMode(PIN_BTN, INPUT_PULLUP);
  pinMode(PIN_INT, INPUT);
  imuReady = xSemaphoreCreateBinary();


  // The coast: none until the first one is built (about 90 s after boot). Until then the page
  // flies over open sea and picks the coast up when it is ready.
  if (!gen::allocate()) Serial.println("# ERROR no PSRAM for the theatre (is PSRAM enabled? needs qio_opi + BOARD_HAS_PSRAM)");
  loadLogbook();
  // Hold the game files in PSRAM: the page itself first, then the textures, then what fits.
  loadFiles(64 * 1024);
  loadFiles(400 * 1024);
  loadFiles(CACHE_BUDGET);
  Serial.printf("# files: %d, %d of them (%u KB) held in PSRAM\n", fileCount, cacheCount, (unsigned)(cacheBytes / 1024));

  bool joined = false;
  if (strlen(HOME_WIFI_SSID)) {
    WiFi.mode(WIFI_STA);
    WiFi.setHostname(HOSTNAME);
    WiFi.begin(HOME_WIFI_SSID, HOME_WIFI_PASSWORD);
    Serial.printf("# joining WiFi \"%s\"", HOME_WIFI_SSID);
    for (uint32_t t0 = millis(); millis() - t0 < 15000 && WiFi.status() != WL_CONNECTED; delay(250)) Serial.print('.');
    Serial.println();
    joined = WiFi.status() == WL_CONNECTED;
  }
  if (joined) {
    // With an IPv6 address, mDNS can also answer AAAA queries; without one, Chrome waits
    // ~5 s for an AAAA answer before using IPv4. Must be enabled after the link is up.
#if ESP_ARDUINO_VERSION_MAJOR >= 3   // renamed in Arduino-ESP32 3.x
    WiFi.enableIPv6();
#else
    WiFi.enableIpV6();
#endif
    delay(1500);
    Serial.printf("# WiFi joined: open http://%s.local or http://%s\n", HOSTNAME, WiFi.localIP().toString().c_str());
  } else {
    WiFi.disconnect(true);
    WiFi.mode(WIFI_AP);
    WiFi.softAP(AP_SSID, AP_PASS, 6, 0, 4);
    Serial.printf("# WiFi AP \"%s\" (password \"%s\") at http://%s\n", AP_SSID, AP_PASS ? AP_PASS : "", WiFi.softAPIP().toString().c_str());
  }
  WiFi.setSleep(false);  // lowest WebSocket latency
  if (MDNS.begin(HOSTNAME)) { MDNS.addService("http", "tcp", 80); MDNS.addService("ws", "tcp", 81); }

  // The page opens its controller WebSocket by IP, skipping a slow .local lookup.
  http.on("/host", HTTP_GET, [] {
    http.sendHeader("Cache-Control", "no-store");
    http.send(200, "text/plain", (WiFi.getMode() & WIFI_MODE_STA) && WiFi.status() == WL_CONNECTED ? WiFi.localIP().toString() : WiFi.softAPIP().toString());
  });
  http.on("/stats", HTTP_GET, sendStats);
  http.on("/logbook", HTTP_GET, sendLogbook);
  http.on("/logbook", HTTP_POST, addSortie);
  // The coast, straight from PSRAM. Held steady while it is being sent.
  http.on("/theatre.bin", HTTP_GET, [] {
    if (!gen::servedSize) { http.send(503, "text/plain", "No theatre yet"); return; }
    xSemaphoreTake(gen::servedLock, portMAX_DELAY);
    http.sendHeader("Cache-Control", "no-store");
    http.sendHeader("X-Theatre-Id", String(gen::servedId));
    httpDoing = "theatre";
    http.setContentLength(gen::servedSize);
    http.send(200, "application/octet-stream", "");
    sendBody(gen::served, gen::servedSize);
    httpDoing = "-";
    xSemaphoreGive(gen::servedLock);
  });
  http.addHandler(new GameFiles());
  // Fallback: if the core ever skips GameFiles, a GET still gets the game file (or goes home).
  http.onNotFound([] {
    if (http.method() == HTTP_GET) {
      if (!sendFile(http.uri())) { http.sendHeader("Location", "/"); http.send(302, "text/plain", ""); }
      return;
    }
    http.send(404, "text/plain", "Not here");
  });
  http.begin();
  ws.begin();
  ws.onEvent(onSocket);
  ws.enableHeartbeat(3000, 2000, 2);     // drop pages that vanished, so they cannot stall the stream

  for (int attempt = 0; attempt < 3 && !mpuOk; attempt++) mpuOk = mpuBegin();
  if (!mpuOk) Serial.println("# ERROR MPU6050 not found on SDA 8 / SCL 9 (will keep looking)");
  if (workers) makeRoomForWifi();        // before the workers start using the tiles
  xTaskCreatePinnedToCore(imuTask, "imu", 4096, nullptr, 5, nullptr, 1);
  xTaskCreatePinnedToCore(ioTask, "io", 6144, nullptr, 4, nullptr, 1);
  if (workers) {
    xTaskCreatePinnedToCore(workerTask, "work0", 6144, (void *)0, 1, nullptr, 0);
    xTaskCreatePinnedToCore(workerTask, "work1", 6144, (void *)1, 1, nullptr, 1);
  } else Serial.println("# ERROR no RAM for the workers: no new coasts, bandits fly by the page's own rules");
  vTaskPrioritySet(nullptr, 2);          // HTTP outranks the workers
  // A fresh coast for the next sortie.
  if (gen::height) gen::start(esp_random());
}

void loop() {
  http.handleClient();
  while (Serial.available()) if (Serial.read() == 'c') wantCalibrate = true;
  delay(1);
}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik