/*
ESP32 LVGL Smart Display 2.4" - Work Control Offline Queue
Display driver: TFT_eSPI (ILI9341) + touch supported by TFT_eSPI.
Storage: LittleFS (internal flash) so no microSD is required.
IMPORTANT:
1. Configure TFT_eSPI User_Setup.h for YOUR board/display/touch pins.
2. Calibrate touch using tft.setTouch() values below.
3. Change WIFI_SSID, WIFI_PASSWORD, API_BASE and API_KEY.
4. API_BASE must use the PC LAN IP, never localhost.
5. PHP API should accept START/STOP in the same order they are queued.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <TFT_eSPI.h>
#include <LittleFS.h>
#include <Preferences.h>
#include <time.h>
TFT_eSPI tft = TFT_eSPI();
Preferences prefs;
// ---------------- USER CONFIGURATION ----------------
const char* WIFI_SSID = "NAMA_WIFI";
const char* WIFI_PASSWORD = "PASSWORD_WIFI";
// Example: http://192.168.1.10/work-control-api
const char* API_BASE = "http://192.168.1.10/work-control-api";
const char* API_KEY = "GANTI_DENGAN_TOKEN_PHP_API";
const char* DEVICE_ID = "ESP32-001";
const char* QUEUE_FILE = "/events.json";
// TFT_eSPI touch calibration. These are placeholders.
// Run TFT_eSPI Touch_calibrate example and copy the values here.
uint16_t touchCalData[5] = { 300, 3600, 300, 3600, 1 };
// Relay output: verify your relay module's active level before connecting.
// Set RELAY_PIN to the actual GPIO supported by your board.
#define RELAY_PIN 26
#define RELAY_ACTIVE_LEVEL LOW
#define RELAY_INACTIVE_LEVEL HIGH
// Optional physical buttons. Set to -1 if not used.
#define START_BUTTON_PIN -1
#define STOP_BUTTON_PIN -1
// ----------------------------------------------------
struct SpkItem {
String nomor;
String nama;
};
SpkItem spkItems[30];
int spkCount = 0;
int selectedIndex = -1;
bool running = false;
String runningSpk = "";
bool wifiConnected = false;
String lastMessage = "Memulai...";
unsigned long lastWifiCheck = 0;
unsigned long lastSync = 0;
unsigned long lastListRefresh = 0;
unsigned long lastTouch = 0;
uint32_t eventCounter = 0;
const int SCREEN_W = 240;
const int SCREEN_H = 320;
String jsonEscape(const String& s) {
String out;
for (size_t i = 0; i < s.length(); i++) {
char c = s[i];
if (c == '"' || c == '\\') out += '\\';
if (c == '\n' || c == '\r') continue;
out += c;
}
return out;
}
String makeEventId() {
eventCounter++;
prefs.putUInt("eventCounter", eventCounter);
char num[12];
snprintf(num, sizeof(num), "%06lu", (unsigned long)eventCounter);
return String(DEVICE_ID) + "-" + String(num);
}
String localTimestamp() {
struct tm timeinfo;
if (getLocalTime(&timeinfo, 50)) {
char buf[25];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
return String(buf);
}
return "UNSYNCED";
}
void setMessage(const String& msg) {
lastMessage = msg;
drawScreen();
}
bool loadQueue(JsonDocument& doc) {
if (!LittleFS.exists(QUEUE_FILE)) {
doc.to<JsonArray>();
return true;
}
File f = LittleFS.open(QUEUE_FILE, "r");
if (!f) return false;
DeserializationError err = deserializeJson(doc, f);
f.close();
return !err;
}
bool saveQueue(JsonDocument& doc) {
File f = LittleFS.open(QUEUE_FILE, "w");
if (!f) return false;
size_t written = serializeJson(doc, f);
f.close();
return written > 0;
}
int pendingCount() {
DynamicJsonDocument doc(8192);
if (!loadQueue(doc)) return 0;
JsonArray arr = doc.as<JsonArray>();
return arr.size();
}
bool queueEvent(const String& action, const String& nomorSpk) {
DynamicJsonDocument doc(8192);
if (!loadQueue(doc)) {
lastMessage = "Gagal membaca queue";
return false;
}
JsonArray arr = doc.as<JsonArray>();
JsonObject item = arr.createNestedObject();
item["event_id"] = makeEventId();
item["device_id"] = DEVICE_ID;
item["nomor_spk"] = nomorSpk;
item["action"] = action;
item["event_time"] = localTimestamp();
item["synced"] = false;
if (!saveQueue(doc)) {
lastMessage = "Gagal simpan offline";
return false;
}
return true;
}
bool apiRequest(const String& url, const String& method,
const String& body, String& response) {
if (WiFi.status() != WL_CONNECTED) return false;
HTTPClient http;
http.setTimeout(5000);
if (!http.begin(url)) return false;
http.addHeader("X-API-Key", API_KEY);
http.addHeader("Content-Type", "application/json");
int code = -1;
if (method == "GET") code = http.GET();
else code = http.POST(body);
response = http.getString();
http.end();
return code >= 200 && code < 300;
}
void fetchSpkList() {
if (WiFi.status() != WL_CONNECTED) return;
String response;
String url = String(API_BASE) + "/spk.php?action=list";
if (!apiRequest(url, "GET", "", response)) {
lastMessage = "Gagal ambil daftar SPK";
return;
}
DynamicJsonDocument doc(12288);
if (deserializeJson(doc, response)) {
lastMessage = "Format JSON SPK salah";
return;
}
JsonArray data = doc["data"].as<JsonArray>();
spkCount = 0;
for (JsonObject row : data) {
if (spkCount >= 30) break;
spkItems[spkCount].nomor = row["nomor_spk"] | "";
spkItems[spkCount].nama = row["nama_pekerjaan"] | "";
if (spkItems[spkCount].nomor.length()) spkCount++;
}
if (selectedIndex >= spkCount) selectedIndex = -1;
lastMessage = "Daftar SPK diperbarui";
drawScreen();
}
void syncQueue() {
if (WiFi.status() != WL_CONNECTED) return;
DynamicJsonDocument doc(8192);
if (!loadQueue(doc)) return;
JsonArray arr = doc.as<JsonArray>();
if (arr.size() == 0) return;
// Process only the first event. Preserve order for START then STOP.
JsonObject item = arr[0];
String eventId = item["event_id"] | "";
String action = item["action"] | "";
String nomor = item["nomor_spk"] | "";
String device = item["device_id"] | DEVICE_ID;
DynamicJsonDocument bodyDoc(512);
bodyDoc["nomor_spk"] = nomor;
bodyDoc["device_id"] = device;
bodyDoc["event_id"] = eventId;
// event_time is retained locally. The current PHP API may use server NOW()
// unless you update it to accept this field.
bodyDoc["event_time"] = item["event_time"] | "UNSYNCED";
String body;
serializeJson(bodyDoc, body);
String endpoint = String(API_BASE) + "/spk.php?action=" + action.toLowerCase();
String response;
if (apiRequest(endpoint, "POST", body, response)) {
arr.remove(0);
saveQueue(doc);
lastMessage = action + " tersinkron";
} else {
lastMessage = "Sync tertunda: " + action;
}
drawScreen();
}
void startWork() {
if (running) {
setMessage("Masih ada SPK berjalan");
return;
}
if (selectedIndex < 0 || selectedIndex >= spkCount) {
setMessage("Pilih SPK dahulu");
return;
}
String nomor = spkItems[selectedIndex].nomor;
if (!queueEvent("START", nomor)) {
setMessage("START gagal disimpan");
return;
}
running = true;
runningSpk = nomor;
digitalWrite(RELAY_PIN, RELAY_ACTIVE_LEVEL);
setMessage(WiFi.status() == WL_CONNECTED ? "START tersimpan, sync..." : "START OFFLINE tersimpan");
syncQueue();
}
void stopWork() {
if (!running) {
setMessage("Tidak ada SPK berjalan");
return;
}
String nomor = runningSpk;
if (!queueEvent("STOP", nomor)) {
setMessage("STOP gagal disimpan");
return;
}
running = false;
runningSpk = "";
digitalWrite(RELAY_PIN, RELAY_INACTIVE_LEVEL);
setMessage(WiFi.status() == WL_CONNECTED ? "STOP tersimpan, sync..." : "STOP OFFLINE tersimpan");
syncQueue();
}
void drawButton(int x, int y, int w, int h, uint16_t color, const String& label) {
tft.fillRoundRect(x, y, w, h, 8, color);
tft.drawRoundRect(x, y, w, h, 8, TFT_WHITE);
tft.setTextColor(TFT_WHITE, color);
tft.setTextDatum(MC_DATUM);
tft.drawString(label, x + w / 2, y + h / 2, 2);
}
void drawScreen() {
tft.fillScreen(TFT_BLACK);
tft.setTextDatum(TL_DATUM);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.drawString("WORK CONTROL", 8, 6, 4);
uint16_t wifiColor = WiFi.status() == WL_CONNECTED ? TFT_GREEN : TFT_RED;
tft.fillCircle(218, 17, 6, wifiColor);
tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);
tft.drawString(WiFi.status() == WL_CONNECTED ? "ONLINE" : "OFFLINE", 8, 38, 2);
tft.drawString("Pilih SPK:", 8, 60, 2);
for (int i = 0; i < spkCount && i < 5; i++) {
int y = 82 + i * 29;
uint16_t bg = (i == selectedIndex) ? TFT_DARKCYAN : TFT_DARKGREY;
tft.fillRoundRect(6, y, 228, 25, 4, bg);
tft.setTextColor(TFT_WHITE, bg);
String label = spkItems[i].nomor;
if (spkItems[i].nama.length()) label += " - " + spkItems[i].nama;
if (label.length() > 29) label = label.substring(0, 29) + "...";
tft.drawString(label, 11, y + 6, 1);
}
tft.setTextColor(TFT_YELLOW, TFT_BLACK);
tft.drawString(running ? "RUNNING: " + runningSpk : "STATUS: READY", 8, 235, 2);
drawButton(8, 258, 108, 42, TFT_DARKGREEN, "START");
drawButton(124, 258, 108, 42, TFT_MAROON, "STOP");
tft.setTextColor(TFT_CYAN, TFT_BLACK);
tft.drawString("Pending: " + String(pendingCount()), 8, 306, 1);
tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);
tft.drawRightString(lastMessage.substring(0, 26), 232, 306, 1);
}
void handleTouch() {
uint16_t x, y;
if (!tft.getTouch(&x, &y)) return;
if (millis() - lastTouch < 350) return;
lastTouch = millis();
if (y >= 82 && y < 227) {
int index = (y - 82) / 29;
if (index >= 0 && index < spkCount && index < 5 && !running) {
selectedIndex = index;
drawScreen();
}
return;
}
if (y >= 258 && y <= 302) {
if (x < 120) startWork();
else stopWork();
}
}
void connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
lastMessage = "Menghubungkan WiFi...";
drawScreen();
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, RELAY_INACTIVE_LEVEL);
if (START_BUTTON_PIN >= 0) pinMode(START_BUTTON_PIN, INPUT_PULLUP);
if (STOP_BUTTON_PIN >= 0) pinMode(STOP_BUTTON_PIN, INPUT_PULLUP);
prefs.begin("work-control", false);
eventCounter = prefs.getUInt("eventCounter", 0);
if (!LittleFS.begin(true)) {
Serial.println("LittleFS mount gagal");
}
tft.init();
tft.setRotation(0); // portrait 240x320; change if your board needs rotation 1/3
tft.setTouch(touchCalData);
drawScreen();
connectWiFi();
// Indonesia WIB (UTC+7). Change TZ if needed.
configTzTime("WIB-7", "pool.ntp.org", "time.google.com");
}
void loop() {
handleTouch();
if (START_BUTTON_PIN >= 0 && digitalRead(START_BUTTON_PIN) == LOW) {
startWork();
delay(300);
}
if (STOP_BUTTON_PIN >= 0 && digitalRead(STOP_BUTTON_PIN) == LOW) {
stopWork();
delay(300);
}
if (millis() - lastWifiCheck > 10000) {
lastWifiCheck = millis();
if (WiFi.status() != WL_CONNECTED) {
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
}
if (WiFi.status() == WL_CONNECTED) {
if (millis() - lastListRefresh > 60000 || spkCount == 0) {
lastListRefresh = millis();
fetchSpkList();
}
if (millis() - lastSync > 5000) {
lastSync = millis();
syncQueue();
}
}
delay(20);
}
Loading
esp32-2432s028r
esp32-2432s028r