# main.ino

- Project: [esp32-SSD1322-example](https://flashesp.com/explore/Bk3L3SdXayZk5DEAFxFtC.md) by Mikrobot.pl
- Board: ESP32 Dev Module
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/Bk3L3SdXayZk5DEAFxFtC/files/Di5UdlxHveuEnVdjprnnY

```cpp
#include <Arduino.h>
#include <U8g2lib.h>

#include <WiFi.h>
#include <WiFiManager.h>

#include <HTTPClient.h>
#include <WiFiClientSecure.h>

#include <ArduinoJson.h>

// ============================================================
// SSD1322 256x64 OLED (8080 8-bit parallel) wiring for ESP32
// ============================================================
//
// Display pins (from your pinout):
//  1  Vss      -> GND
//  2  VBAT     -> 3V3 (recommended)
//  3  NC       -> not connected
//  4  DB0      -> GPIO32
//  5  DB1      -> GPIO33
//  6  DB2      -> GPIO25
//  7  DB3      -> GPIO26
//  8  DB4      -> GPIO27
//  9  DB5      -> GPIO14
// 10  DB6      -> GPIO13
// 11  DB7      -> GPIO22
// 12  /RD      -> 3V3 (tie HIGH, we never read from the display)
// 13  /WR      -> GPIO21  (U8g2 calls this "enable")
// 14  DC       -> GPIO16
// 15  /RESET   -> GPIO17
// 16  /CS      -> GPIO4
//
// Notes:
// - /RD MUST be HIGH (3V3), otherwise writes may not work.
// - Power the module from 3V3 first (safer for ESP32 logic levels).
// ============================================================

// Data bus pins (DB0..DB7)
static const uint8_t D0 = 32;
static const uint8_t D1 = 33;
static const uint8_t D2 = 25;
static const uint8_t D3 = 26;
static const uint8_t D4 = 27;
static const uint8_t D5 = 14;
static const uint8_t D6 = 13;
static const uint8_t D7 = 22;

// Control pins
static const uint8_t PIN_WR  = 21;  // Display pin 13 (/WR) -> "enable" in U8g2
static const uint8_t PIN_CS  = 4;   // Display pin 16 (/CS)
static const uint8_t PIN_DC  = 16;  // Display pin 14 (DC)
static const uint8_t PIN_RST = 17;  // Display pin 15 (/RESET)

// SSD1322 256x64, full framebuffer, 8080 8-bit interface
U8G2_SSD1322_NHD_256X64_F_8080 u8g2(
  U8G2_R0,
  D0, D1, D2, D3, D4, D5, D6, D7,
  PIN_WR, PIN_CS, PIN_DC, PIN_RST
);

// ============================================================
// TfL settings (London Underground)
// ============================================================
// Victoria Underground Station StopPoint ID:
static const char* STOPPOINT_ID = "940GZZLUVIC";

// Optional: TfL Unified API key (recommended for rate limits).
// Leave empty to try without a key.
static const char* TFL_APP_KEY  = "";

// ============================================================
// Data model
// ============================================================
struct Arrival {
  String lineName;
  String destinationName;
  String platformName;
  int timeToStationSec;
};

static const int MAX_ARR = 12;
Arrival arrivals[MAX_ARR];
int arrivalsCount = 0;

// Refresh interval for TfL data
unsigned long lastFetchMs = 0;
const unsigned long FETCH_INTERVAL_MS = 30000; // 30 seconds

// Error/debug info shown on screen
String lastError = "";
int lastHttpCode = 0;
String lastBodyPreview = "";

// ============================================================
// UI state
// ============================================================
enum Page : uint8_t { PAGE_WIFI = 0, PAGE_ARR = 1 };
Page page = PAGE_WIFI;

// How long to keep WiFi status page visible after connecting
unsigned long pageHoldUntilMs = 0;

// ============================================================
// Helpers
// ============================================================
static String shortLine(const String& s) {
  // Shorten line names to fit the small display
  String t = s;
  t.toLowerCase();
  if (t.startsWith("victoria")) return "V";
  if (t.startsWith("district")) return "D";
  if (t.startsWith("circle"))   return "C";
  if (t.startsWith("hammersmith")) return "H";
  return s.substring(0, min((int)s.length(), 2));
}

static int minutesCeil(int sec) {
  // Convert seconds to minutes (ceil)
  if (sec <= 0) return 0;
  return (sec + 59) / 60;
}

static String trimPlatform(String p) {
  p.trim();
  p.replace("Platform", "P");
  p.replace("  ", " ");
  p.trim();
  if (p.length() > 14) p = p.substring(0, 14);
  return p;
}

static String trimDest(String d) {
  d.trim();
  d.replace("Underground Station", "");
  d.replace(" (H&C Line)", "");
  d.replace("  ", " ");
  d.trim();
  if (d.length() > 16) d = d.substring(0, 16);
  return d;
}

static void sortArrivalsByTime() {
  // Simple sort by timeToStationSec ascending
  for (int i = 0; i < arrivalsCount - 1; i++) {
    for (int j = i + 1; j < arrivalsCount; j++) {
      if (arrivals[j].timeToStationSec < arrivals[i].timeToStationSec) {
        Arrival tmp = arrivals[i];
        arrivals[i] = arrivals[j];
        arrivals[j] = tmp;
      }
    }
  }
}

// ============================================================
// OLED rendering
// ============================================================
void drawWifiInfo(const char* footer = nullptr) {
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_5x8_tr);

  u8g2.drawStr(0, 8, "WiFi:");

  if (WiFi.status() == WL_CONNECTED) {
    String ssid = WiFi.SSID();
    IPAddress ip = WiFi.localIP();
    int rssi = WiFi.RSSI();

    u8g2.drawStr(0, 20, ("SSID: " + ssid).c_str());

    char ipbuf[32];
    snprintf(ipbuf, sizeof(ipbuf), "IP: %u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
    u8g2.drawStr(0, 32, ipbuf);

    char rssibuf[32];
    snprintf(rssibuf, sizeof(rssibuf), "RSSI: %d dBm", rssi);
    u8g2.drawStr(0, 44, rssibuf);

    if (footer) u8g2.drawStr(0, 56, footer);
    else u8g2.drawStr(0, 56, "Fetching TfL...");
  } else {
    u8g2.drawStr(0, 20, "NOT CONNECTED");
    u8g2.drawStr(0, 32, "AP: ESP32-Victoria");
    u8g2.drawStr(0, 44, "Open to setup WiFi");
    if (footer) u8g2.drawStr(0, 56, footer);
  }

  u8g2.sendBuffer();
}

void drawArrivals() {
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_5x8_tr);

  u8g2.drawStr(0, 8, "Victoria - next trains (TfL)");

  if (WiFi.status() != WL_CONNECTED) {
    u8g2.drawStr(0, 24, "WiFi disconnected.");
    u8g2.drawStr(0, 36, "Back to WiFi...");
    u8g2.sendBuffer();
    return;
  }

  if (!lastError.isEmpty()) {
    // Show error + HTTP code + short response preview (helps spot HTML / rate limits)
    u8g2.drawStr(0, 20, ("ERR: " + lastError).c_str());

    char hbuf[24];
    snprintf(hbuf, sizeof(hbuf), "HTTP: %d", lastHttpCode);
    u8g2.drawStr(0, 32, hbuf);

    String p = lastBodyPreview;
    p.replace("\n", " ");
    p.replace("\r", " ");
    p.trim();
    if (p.length() > 28) p = p.substring(0, 28);

    u8g2.drawStr(0, 44, p.c_str());
    u8g2.drawStr(0, 56, "Retrying...");
    u8g2.sendBuffer();
    return;
  }

  if (arrivalsCount == 0) {
    u8g2.drawStr(0, 24, "No arrivals data.");
    u8g2.drawStr(0, 36, "Wait / refresh...");
    u8g2.sendBuffer();
    return;
  }

  // Show up to 4 items (fits 64px height nicely)
  int y = 20;
  int shown = min(arrivalsCount, 4);

  for (int i = 0; i < shown; i++) {
    int m = minutesCeil(arrivals[i].timeToStationSec);

    String line = String(m) + "m " + shortLine(arrivals[i].lineName) + " ";
    String dest = trimDest(arrivals[i].destinationName);
    String plat = trimPlatform(arrivals[i].platformName);

    line += dest + " (" + plat + ")";

    if (line.length() > 40) line = line.substring(0, 40);
    u8g2.drawStr(0, y, line.c_str());
    y += 11;
  }

  unsigned long age = (millis() - lastFetchMs) / 1000;
  char foot[32];
  snprintf(foot, sizeof(foot), "Updated %lus ago", age);
  u8g2.drawStr(0, 63, foot);

  u8g2.sendBuffer();
}

// ============================================================
// TfL fetch logic
// ============================================================
bool fetchTfLArrivals() {
  lastError = "";
  lastHttpCode = 0;
  lastBodyPreview = "";
  arrivalsCount = 0;

  WiFiClientSecure client;
  client.setInsecure(); // Simplest approach on ESP32 (no certificate pinning)

  HTTPClient https;

  String url = "https://api.tfl.gov.uk/StopPoint/";
  url += STOPPOINT_ID;
  url += "/Arrivals";

  if (TFL_APP_KEY && strlen(TFL_APP_KEY) > 0) {
    url += "?app_key=";
    url += TFL_APP_KEY;
  }

  if (!https.begin(client, url)) {
    lastError = "http begin() failed";
    return false;
  }

  https.setTimeout(12000);

  int httpCode = https.GET();
  lastHttpCode = httpCode;

  if (httpCode <= 0) {
    lastError = "http GET failed";
    https.end();
    return false;
  }

  String payload = https.getString();
  https.end();

  // Preview first bytes for debugging (HTML errors / rate limits)
  lastBodyPreview = payload.substring(0, min((int)payload.length(), 120));

  if (httpCode != 200) {
    lastError = "non-200";
    return false;
  }

  // TfL returns a JSON array: [ {...}, {...} ... ]
  // Use a reasonably large doc for busy stations like Victoria.
  DynamicJsonDocument doc(80000);

  DeserializationError err = deserializeJson(doc, payload);
  if (err) {
    lastError = "json parse failed";
    return false;
  }

  if (!doc.is<JsonArray>()) {
    lastError = "unexpected json";
    return false;
  }

  JsonArray arr = doc.as<JsonArray>();

  for (JsonObject o : arr) {
    if (arrivalsCount >= MAX_ARR) break;

    Arrival &a = arrivals[arrivalsCount];

    // ArduinoJson 7: extract as String/int safely
    a.lineName = o["lineName"].isNull() ? "" : o["lineName"].as<String>();
    a.destinationName = o["destinationName"].isNull() ? "" : o["destinationName"].as<String>();
    a.platformName = o["platformName"].isNull() ? "" : o["platformName"].as<String>();
    a.timeToStationSec = o["timeToStation"].isNull() ? 0 : o["timeToStation"].as<int>();

    // Skip empty/invalid entries
    if (a.timeToStationSec > 0 && a.destinationName.length() > 0) {
      arrivalsCount++;
    }
  }

  sortArrivalsByTime();
  lastFetchMs = millis();
  return true;
}

// ============================================================
// WiFiManager setup
// ============================================================
void setupWiFiManager() {
  WiFi.mode(WIFI_STA);

  WiFiManager wm;
  wm.setConfigPortalTimeout(180); // 3 minutes portal timeout

  drawWifiInfo("Connecting / portal...");
  bool ok = wm.autoConnect("ESP32-Victoria");

  if (ok && WiFi.status() == WL_CONNECTED) {
    page = PAGE_WIFI;
    pageHoldUntilMs = millis() + 12000; // keep WiFi page visible for 12s
    drawWifiInfo("Connected. Loading TfL...");
  } else {
    page = PAGE_WIFI;
    pageHoldUntilMs = millis() + 99999999UL;
    drawWifiInfo("Setup WiFi via AP");
  }
}

// ============================================================
// Arduino entry points
// ============================================================
void setup() {
  u8g2.begin();
  u8g2.setContrast(255);

  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x10_tr);
  u8g2.drawStr(0, 24, "Boot...");
  u8g2.drawStr(0, 40, "WiFi + TfL Arrivals");
  u8g2.sendBuffer();

  setupWiFiManager();

  // Fetch once immediately to show data sooner
  if (WiFi.status() == WL_CONNECTED) {
    fetchTfLArrivals();
  }
}

void loop() {
  // If disconnected, return to WiFi page
  if (WiFi.status() != WL_CONNECTED) {
    page = PAGE_WIFI;
    pageHoldUntilMs = millis() + 99999999UL;
    drawWifiInfo("Disconnected");
    delay(300);
    return;
  }

  // After the hold time, switch to arrivals page
  if (page == PAGE_WIFI && millis() > pageHoldUntilMs) {
    page = PAGE_ARR;
  }

  // Refresh TfL data periodically (only on arrivals page)
  if (page == PAGE_ARR) {
    if (lastFetchMs == 0 || (millis() - lastFetchMs > FETCH_INTERVAL_MS)) {
      fetchTfLArrivals();
    }
    drawArrivals();
  } else {
    drawWifiInfo("Hold...");
  }

  delay(150);
}
```
