Files
slate32/src/main.cpp
T
2026-08-06 15:28:44 -04:00

115 lines
2.3 KiB
C++

#include <SD.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <XPT2046_Touchscreen.h>
#include <new>
#include "heaplog.h"
#include "host/lua_host.h"
#include "net.h"
#include "settings.h"
static constexpr int SD_CS = 5;
static constexpr int SD_SCK = 18;
static constexpr int SD_MOSI = 23;
static constexpr int SD_MISO = 19;
static constexpr int TOUCH_CS = 33;
SET_LOOP_TASK_STACK_SIZE(16 * 1024);
TFT_eSPI tft;
SPIClass touchSpi(HSPI);
SPIClass& sdSpi = SPI;
XPT2046_Touchscreen touch(TOUCH_CS);
LuaHost host(tft, touch);
static bool halted = false;
static void fallbackScreen(const char* message) {
tft.resetViewport();
tft.setRotation(0);
tft.fillScreen(TFT_WHITE);
tft.setTextSize(1);
tft.setTextColor(TFT_RED, TFT_WHITE);
tft.drawString(message, 10, 10);
tft.setTextColor(TFT_BLACK, TFT_WHITE);
tft.drawString("expected /.lua/apps/Home/main.lua", 10, 34);
Serial.printf("halted: %s\n", message);
halted = true;
}
// Auto Dim
constexpr uint32_t kDimAfterMs = 10000;
constexpr int kBacklightChannel = 0;
uint32_t lastTouchMs = 0;
bool dimmed = false;
void updateBacklight() {
if (touch.touched())
lastTouchMs = millis();
bool idle = millis() - lastTouchMs > kDimAfterMs;
if (idle == dimmed)
return;
dimmed = idle;
ledcWrite(kBacklightChannel, dimmed ? 20 : 255);
}
void setup() {
Serial.begin(115200);
// OOM Logging
std::set_new_handler([]() {
logHeap("oom");
Serial.println("[fatal] out of memory");
Serial.flush();
ESP.restart();
});
// Start TFT
tft.begin();
tft.setRotation(0);
tft.fillScreen(TFT_WHITE);
touchSpi.begin(14, 12, 13, TOUCH_CS);
touch.begin(touchSpi);
// TFT Dimming
ledcSetup(kBacklightChannel, 5000, 8);
ledcAttachPin(TFT_BL, kBacklightChannel);
ledcWrite(kBacklightChannel, 255);
lastTouchMs = millis();
// SD Card
sdSpi.begin(SD_SCK, SD_MISO, SD_MOSI, SD_CS);
if (!SD.begin(SD_CS, sdSpi)) {
fallbackScreen("SD card mount failed");
return;
}
// Load Settings & Initialize Network
settings.load();
net::begin();
if (!host.begin())
fallbackScreen("home failed to start");
}
void loop() {
// Halted
if (halted) {
delay(100);
return;
}
// Auto Dim & Net / Lua Loop
updateBacklight();
net::loop();
host.loop();
// Failed Lua Main
if (!host.running())
fallbackScreen("home failed to start");
// Yield
delay(1);
}