/*
WORK CONTROL - CYD + HTML Web Server + LCD Touch + DS1307 + Relay + Offline Queue
Required Wokwi libraries.txt:
Adafruit GFX Library
Adafruit ILI9341
XPT2046_Touchscreen
ArduinoJson
RTClib
Hardware:
TFT: CS15 DC2 MOSI13 MISO12 SCK14
Touch: CS33 IRQ36 MOSI32 MISO39 SCK25
RTC DS1307: SDA27 SCL22, VCC 5V, GND GND
Relay IN26 (adjust active level to your module)
RGB LED: R4 G16 B17 active LOW
Browser: connect phone/PC to same WiFi, open http://ESP32_IP/
HTML UI:
- Layar List : daftar SPK dari API, search, status online/offline, jam RTC, tombol menu (gear)
- Layar Detail: info SPK terpilih, tombol START/STOP, waktu transaksi dari RTC DS1307
- Layar WiFi : info koneksi (mode/SSID/IP) + form ganti SSID & password (device restart setelah simpan)
- Jika WiFi tersimpan gagal connect, device otomatis masuk AP mode "WorkControl-Setup" (192.168.4.1)
agar WiFi baru bisa diatur dari layar WiFi di atas.
*/
#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <XPT2046_Touchscreen.h>
#include <RTClib.h>
#include <LittleFS.h>
#include <Preferences.h>
#define TFT_CS 15
#define TFT_DC 2
#define TFT_MOSI 13
#define TFT_MISO 12
#define TFT_SCK 14
#define TOUCH_CS 33
#define TOUCH_IRQ 36
#define TOUCH_MOSI 32
#define TOUCH_MISO 39
#define TOUCH_SCK 25
#define RTC_SDA 27
#define RTC_SCL 22
#define RELAY_PIN 26
#define RELAY_ON LOW
#define RELAY_OFF HIGH
#define LED_R 4
#define LED_G 16
#define LED_B 17
const char* WIFI_SSID_DEFAULT = "Wokwi-GUEST";
const char* WIFI_PASSWORD_DEFAULT = "";
const char* AP_SSID = "WorkControl-Setup";
// Berdasarkan endpoint yang Anda berikan sebelumnya:
const char* REMOTE_API = "";
const char* API_KEY = "";
const char* DEVICE_ID = "ESP32-001";
Adafruit_ILI9341 tft(TFT_CS, TFT_DC);
SPIClass touchSPI(HSPI);
XPT2046_Touchscreen touch(TOUCH_CS, TOUCH_IRQ);
RTC_DS1307 rtc;
WebServer server(80);
Preferences prefs;
struct Spk { String no; String name; String status; String deviceId; };
Spk spks[30];
int spkCount=0, selected=-1;
bool rtcOK=false, running=false, apMode=false;
String runningSpk="", lastMsg="Starting";
uint32_t eventNo=0;
unsigned long lastSync=0, lastFetch=0, lastTouch=0, lastWifiTry=0;
const char INDEX_HTML[] PROGMEM = R"HTML(
<!doctype html>
<html lang="id"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#10213a"><title>Work Control</title>
<style>
*{box-sizing:border-box}body{margin:0;background:#f2f5fa;color:#17243a;font:15px system-ui,Segoe UI,sans-serif}
.bar{background:#10213a;color:white;padding:14px max(16px,calc((100% - 760px)/2));display:flex;justify-content:space-between;align-items:center;gap:10px}
.brand{font-weight:800;letter-spacing:.5px}.brand small{display:block;color:#aebdd0;font-size:10px;letter-spacing:1.5px}
.barRight{display:flex;align-items:center;gap:14px}
.net{font-size:12px;display:flex;align-items:center;gap:6px}
.dot{width:8px;height:8px;border-radius:50%;background:#53d98c;display:inline-block}
.dot.off{background:#e06565}
.clockTop{font-variant-numeric:tabular-nums;font-weight:700;font-size:14px}
.gear{background:#1c3156;border:1px solid #2c4875;color:white;border-radius:9px;width:34px;height:34px;font-size:16px;cursor:pointer}
.wrap{max-width:760px;margin:20px auto;padding:0 15px}
.screen{display:none}.screen.active{display:block}
.card{background:white;border:1px solid #e1e7ef;border-radius:16px;padding:18px;box-shadow:0 8px 25px #1c355410;margin-bottom:16px}
.title{font-weight:800;margin-bottom:13px;display:flex;align-items:center;gap:10px}
.back{background:#eef2f8;border:1px solid #dde4ee;border-radius:9px;width:34px;height:34px;cursor:pointer;font-size:16px}
.search{width:100%;padding:13px;border:1px solid #dce4ee;border-radius:10px;font:inherit;margin-bottom:12px}
.list{display:grid;gap:8px;max-height:460px;overflow:auto}
.spk{border:1px solid #e0e7ef;background:white;border-radius:11px;padding:12px;text-align:left;cursor:pointer;display:flex;justify-content:space-between;align-items:center;gap:10px}
.spk:active{background:#f4f8ff}
.spk b{display:block;font-size:13px}
.spk span{display:block;color:#718096;font-size:12px;margin-top:4px}
.badge{font-size:10px;font-weight:800;padding:4px 9px;border-radius:99px;white-space:nowrap}
.b-ready{background:#e9f8ef;color:#16834d}.b-running{background:#eaf2ff;color:#245bc0}.b-other{background:#fdeeea;color:#c0392b}
.empty{color:#8290a3;padding:22px;text-align:center;font-size:13px}
.detailHead{text-align:center;padding:10px 0 4px}
.detailHead b{font-size:19px;display:block}
.detailHead span{color:#718096;font-size:13px}
.statusPill{display:inline-block;margin-top:10px;padding:7px 16px;border-radius:99px;font-weight:800;font-size:12px}
.rtcClock{text-align:center;margin:18px 0}
.rtcClock strong{font-size:40px;font-variant-numeric:tabular-nums;display:block}
.rtcClock small{color:#718096;letter-spacing:1px}
.buttons{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin-top:6px}
button.action{border:0;border-radius:11px;padding:16px;color:white;font-weight:800;font-size:14px;cursor:pointer}
button:disabled{opacity:.35;cursor:not-allowed}
.start{background:#159957}.stop{background:#d94343}
.hint{font-size:12px;color:#52647b;text-align:center;margin-top:14px;min-height:16px}
.pending{font-size:12px;color:#52647b;text-align:center;margin-top:6px}
.wifiInfo{display:grid;gap:8px;font-size:13px;margin-bottom:14px}
.wifiInfo div{display:flex;justify-content:space-between;border-bottom:1px solid #edf0f5;padding:8px 0}
.wifiInfo b{color:#17243a}
label{display:block;font-size:12px;color:#52647b;margin:10px 0 5px;font-weight:700}
input[type=text],input[type=password]{width:100%;padding:12px;border:1px solid #dce4ee;border-radius:10px;font:inherit}
.save{width:100%;margin-top:16px;background:#3478e5;border:0;color:white;border-radius:11px;padding:14px;font-weight:800;cursor:pointer}
.apNote{background:#fff6e6;color:#8a5a00;border:1px solid #ffe3a3;border-radius:10px;padding:10px 12px;font-size:12px;margin-bottom:12px}
</style></head><body>
<header class="bar">
<div class="brand">WORK CONTROL<small>ESP32 · PRODUCTION FLOOR</small></div>
<div class="barRight">
<div class="clockTop" id="clockTop">--:--:--</div>
<div class="net"><span class="dot" id="netDot"></span><span id="netText">Menghubungkan...</span></div>
<button class="gear" id="gearBtn" title="Pengaturan WiFi">⚙</button>
</div>
</header>
<main class="wrap">
<section id="scr-list" class="screen active">
<div class="card">
<div class="title">Daftar SPK</div>
<input class="search" id="q" placeholder="Cari nomor SPK / nama pekerjaan...">
<div class="list" id="list"><div class="empty">Mengambil daftar SPK...</div></div>
</div>
</section>
<section id="scr-detail" class="screen">
<div class="card">
<div class="title"><button class="back" id="backFromDetail">←</button><span>Detail SPK</span></div>
<div class="detailHead">
<b id="dNo">-</b>
<span id="dName">-</span>
<div class="statusPill" id="dStatus">-</div>
</div>
<div class="rtcClock">
<strong id="dClock">--:--:--</strong>
<small id="dDate">RTC DS1307</small>
</div>
<div class="buttons">
<button class="action start" id="dStart" disabled>▶ START</button>
<button class="action stop" id="dStop" disabled>■ STOP</button>
</div>
<div class="hint" id="dHint">Waktu transaksi diambil langsung dari RTC DS1307 di ESP32.</div>
<div class="pending">Antrean offline: <b id="dPending">0</b></div>
</div>
</section>
<section id="scr-wifi" class="screen">
<div class="card">
<div class="title"><button class="back" id="backFromWifi">←</button><span>Pengaturan WiFi</span></div>
<div class="apNote" id="apNote" style="display:none">Perangkat sedang dalam mode Access Point (konfigurasi). Sambungkan HP/PC ke WiFi "<b id="apNoteSsid"></b>" lalu buka 192.168.4.1</div>
<div class="wifiInfo">
<div><span>Mode</span><b id="wMode">-</b></div>
<div><span>SSID Terhubung</span><b id="wSsid">-</b></div>
<div><span>Alamat IP</span><b id="wIp">-</b></div>
</div>
<label>Nama WiFi (SSID) baru</label>
<input type="text" id="wNewSsid" placeholder="Nama WiFi">
<label>Password WiFi</label>
<input type="password" id="wNewPass" placeholder="Kosongkan jika WiFi tanpa password">
<button class="save" id="wSave">Simpan & Restart Perangkat</button>
<div class="hint" id="wHint"></div>
</div>
</section>
</main>
<script>
let spks=[],detail=null,statusInfo={},screen='list';
const $=id=>document.getElementById(id);
async function api(path,opts={}){const r=await fetch(path,opts);const j=await r.json();if(!r.ok||j.success===false)throw Error(j.message||'Request gagal');return j}
function nav(name){document.querySelectorAll('.screen').forEach(s=>s.classList.remove('active'));$('scr-'+name).classList.add('active');screen=name;if(name==='wifi')loadWifi();if(name==='detail')renderDetail();}
$('gearBtn').onclick=()=>nav('wifi');
$('backFromDetail').onclick=()=>nav('list');
$('backFromWifi').onclick=()=>nav('list');
function badge(s,dev){
if(s==='RUNNING'){return dev && statusInfo.device_id && dev===statusInfo.device_id?'<span class="badge b-running">RUNNING (alat ini)</span>':'<span class="badge b-other">RUNNING (alat lain)</span>'}
return '<span class="badge b-ready">READY</span>';
}
function renderList(){
const q=$('q').value.toLowerCase();
const rows=spks.filter(s=>(s.nomor_spk+' '+(s.nama_pekerjaan||'')).toLowerCase().includes(q));
$('list').innerHTML=rows.length?rows.map(s=>`<button class="spk" data-no="${encodeURIComponent(s.nomor_spk)}"><span><b>${s.nomor_spk}</b><span>${s.nama_pekerjaan||''}</span></span>${badge(s.status,s.device_id)}</button>`).join(''):'<div class="empty">SPK tidak ditemukan.</div>';
document.querySelectorAll('.spk').forEach(b=>b.onclick=()=>{
const no=decodeURIComponent(b.dataset.no);
detail=spks.find(s=>s.nomor_spk===no);
nav('detail');
});
}
async function loadSpks(){
try{const j=await api('/api/spk');spks=j.data||[];renderList();
if(detail){const fresh=spks.find(s=>s.nomor_spk===detail.nomor_spk);if(fresh)detail=fresh;if(screen==='detail')renderDetail();}
}catch(e){}
}
$('q').addEventListener('input',renderList);
function renderDetail(){
if(!detail)return;
$('dNo').textContent=detail.nomor_spk;
$('dName').textContent=detail.nama_pekerjaan||'';
const runningHere=statusInfo.running && statusInfo.running_spk===detail.nomor_spk;
const pill=$('dStatus');
if(runningHere){pill.textContent='● SEDANG BERJALAN';pill.style.background='#eaf2ff';pill.style.color='#245bc0'}
else if(detail.status==='RUNNING'){pill.textContent='● RUNNING DI ALAT LAIN';pill.style.background='#fdeeea';pill.style.color='#c0392b'}
else {pill.textContent='● READY';pill.style.background='#e9f8ef';pill.style.color='#16834d'}
$('dStart').disabled=!!statusInfo.running||detail.status==='RUNNING';
$('dStop').disabled=!runningHere;
$('dPending').textContent=statusInfo.pending||0;
}
$('dStart').onclick=async()=>{
if(!detail)return;$('dStart').disabled=true;
try{const j=await api('/api/start',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({nomor_spk:detail.nomor_spk})});
$('dHint').textContent='START tercatat: '+j.event_time;await pollStatus();await loadSpks();renderDetail();
}catch(e){$('dHint').textContent=e.message;$('dStart').disabled=false}
};
$('dStop').onclick=async()=>{
$('dStop').disabled=true;
try{const j=await api('/api/stop',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});
$('dHint').textContent='STOP tercatat: '+j.event_time;await pollStatus();await loadSpks();renderDetail();
}catch(e){$('dHint').textContent=e.message;$('dStop').disabled=false}
};
async function pollStatus(){
try{
const j=await api('/api/status');
statusInfo=j;
$('clockTop').textContent=j.time||'--:--:--';
$('dClock').textContent=j.time||'--:--:--';
$('dDate').textContent=(j.date||'')+' · DS1307';
$('netDot').classList.remove('off');$('netText').textContent=j.wifi_connected?'ONLINE':'AP MODE';
if(!j.wifi_connected){$('netDot').classList.add('off')}
if(screen==='detail')renderDetail();
}catch(e){$('netDot').classList.add('off');$('netText').textContent='OFFLINE'}
}
async function loadWifi(){
$('wHint').textContent='';
try{
const j=await api('/api/wifi');
$('wMode').textContent=j.ap_mode?'Access Point (setup)':'Terhubung ke WiFi';
$('wSsid').textContent=j.ssid||'-';
$('wIp').textContent=j.ip||'-';
$('apNote').style.display=j.ap_mode?'block':'none';
$('apNoteSsid').textContent=j.ssid||'';
}catch(e){$('wHint').textContent=e.message}
}
$('wSave').onclick=async()=>{
const ssid=$('wNewSsid').value.trim();
const password=$('wNewPass').value;
if(!ssid){$('wHint').textContent='SSID wajib diisi';return}
$('wSave').disabled=true;$('wHint').textContent='Menyimpan...';
try{
await api('/api/wifi',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ssid,password})});
$('wHint').textContent='Tersimpan. Perangkat sedang restart, sambungkan ke WiFi baru lalu buka ulang halaman ini.';
}catch(e){$('wHint').textContent=e.message;$('wSave').disabled=false}
};
async function tick(){await pollStatus()}
loadSpks();pollStatus();
setInterval(tick,1000);
setInterval(loadSpks,15000);
</script></body></html>
)HTML";
String nowStamp() {
if (!rtcOK) return "RTC_ERROR";
DateTime n=rtc.now(); char b[24];
snprintf(b,sizeof(b),"%04d-%02d-%02d %02d:%02d:%02d",
n.year(),n.month(),n.day(),n.hour(),n.minute(),n.second());
return String(b);
}
String nowTime() {
if (!rtcOK) return "--:--:--";
DateTime n=rtc.now(); char b[12];
snprintf(b,sizeof(b),"%02d:%02d:%02d",n.hour(),n.minute(),n.second());
return String(b);
}
void led() {
digitalWrite(LED_R, running?HIGH:(WiFi.status()==WL_CONNECTED?HIGH:LOW));
digitalWrite(LED_G, running?LOW:HIGH);
digitalWrite(LED_B, (WiFi.status()==WL_CONNECTED||apMode)?LOW:HIGH);
}
int pendingCount() {
if(!LittleFS.exists("/queue.json")) return 0;
File f=LittleFS.open("/queue.json","r"); if(!f)return 0;
DynamicJsonDocument d(12288); auto e=deserializeJson(d,f); f.close();
return e?0:d.size();
}
bool loadQueue(DynamicJsonDocument& d) {
if(!LittleFS.exists("/queue.json")) { d.to<JsonArray>(); return true; }
File f=LittleFS.open("/queue.json","r"); if(!f)return false;
auto e=deserializeJson(d,f); f.close(); return !e;
}
bool saveQueue(DynamicJsonDocument& d) {
File f=LittleFS.open("/queue.tmp","w"); if(!f)return false;
serializeJson(d,f); f.close();
LittleFS.remove("/queue.json");
return LittleFS.rename("/queue.tmp","/queue.json");
}
String newId() {
char b[12]; snprintf(b,sizeof(b),"%06lu",(unsigned long)++eventNo);
prefs.putUInt("eventNo",eventNo); return String(DEVICE_ID)+"-"+b;
}
bool queueEvent(String action,String spk) {
DynamicJsonDocument d(12288); if(!loadQueue(d))return false;
JsonObject o=d.as<JsonArray>().createNestedObject();
o["event_id"]=newId(); o["device_id"]=DEVICE_ID; o["nomor_spk"]=spk;
o["action"]=action; o["event_time"]=nowStamp();
return saveQueue(d);
}
bool remoteRequest(String url,String method,String body,String& response) {
if(WiFi.status()!=WL_CONNECTED)return false;
HTTPClient h; h.setTimeout(7000);
// GET (list SPK) aman di-redirect otomatis; POST (start/stop) sengaja TIDAK
// di-follow karena 301 bisa mengubah method/body dan membuat event ganda.
const char* hdrs[]={"Location"};
h.collectHeaders(hdrs,1);
if(method=="GET") h.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
int code=-1;
if(url.startsWith("https://")) {
WiFiClientSecure c; c.setInsecure();
if(!h.begin(c,url))return false;
} else if(!h.begin(url)) return false;
h.addHeader("X-API-Key",API_KEY);
h.addHeader("Content-Type","application/json");
code=(method=="GET")?h.GET():h.POST(body);
response=h.getString();
if(code==301||code==302||code==307||code==308){
Serial.printf("Remote redirect %d -> Location: %s\n",code,h.header("Location").c_str());
Serial.println("Perbaiki REMOTE_API agar menunjuk langsung ke URL tujuan di atas.");
}
h.end();
Serial.printf("Remote HTTP %d: %s\n",code,response.c_str());
return code>=200 && code<300;
}
void fetchSpks() {
if(WiFi.status()!=WL_CONNECTED)return;
String response;
if(!remoteRequest(String(REMOTE_API)+"?action=list","GET","",response))return;
DynamicJsonDocument d(20000);
if(deserializeJson(d,response))return;
JsonArray a=d["data"].as<JsonArray>(); if(a.isNull())return;
String old=selected>=0&&selected<spkCount?spks[selected].no:"";
spkCount=0; selected=-1;
for(JsonObject r:a) {
if(spkCount>=30)break;
String no=r["nomor_spk"]|"";
if(!no.length())continue;
spks[spkCount]={no,String((const char*)(r["nama_pekerjaan"]|"")),
String((const char*)(r["status"]|"READY")),
String((const char*)(r["device_id"]|""))};
if(no==old)selected=spkCount;
spkCount++;
}
}
void syncOne() {
if(WiFi.status()!=WL_CONNECTED)return;
DynamicJsonDocument d(12288); if(!loadQueue(d))return;
JsonArray a=d.as<JsonArray>(); if(!a.size())return;
JsonObject e=a[0];
DynamicJsonDocument b(768);
b["nomor_spk"]=e["nomor_spk"]; b["device_id"]=e["device_id"];
b["event_id"]=e["event_id"]; b["event_time"]=e["event_time"];
String body, response; serializeJson(b,body);
String action=e["action"]|"";
if(remoteRequest(String(REMOTE_API)+"?action="+action,"POST",body,response)) {
a.remove(0); saveQueue(d); lastMsg=action+" synced";
}
}
void drawLCD() {
tft.fillScreen(ILI9341_BLACK);
tft.setTextColor(ILI9341_WHITE); tft.setTextSize(2);
tft.setCursor(8,7); tft.print("WORK CONTROL");
tft.setTextSize(1); tft.setCursor(8,30);
tft.setTextColor(ILI9341_CYAN); tft.print(nowTime());
tft.setCursor(150,30);
tft.setTextColor(apMode?ILI9341_YELLOW:(WiFi.status()==WL_CONNECTED?ILI9341_GREEN:ILI9341_RED));
tft.print(apMode?"AP MODE":(WiFi.status()==WL_CONNECTED?"ONLINE":"OFFLINE"));
tft.drawFastHLine(5,45,230,ILI9341_DARKGREY);
tft.setTextColor(ILI9341_WHITE); tft.setTextSize(1); tft.setCursor(8,53); tft.print("PILIH SPK (5 pertama)");
for(int i=0;i<5;i++) {
int y=70+i*31;
uint16_t c=(i==selected)?ILI9341_DARKCYAN:0x4208;
tft.fillRoundRect(6,y,228,27,4,c);
if(i<spkCount) {
tft.setTextColor(ILI9341_WHITE); tft.setCursor(11,y+9);
String s=spks[i].no+" "+spks[i].name; if(s.length()>36)s=s.substring(0,36);
tft.print(s);
}
}
tft.setTextColor(ILI9341_YELLOW); tft.setCursor(8,232);
tft.print(running?"RUNNING: "+runningSpk:"READY - pilih SPK");
tft.fillRoundRect(8,254,105,43,7,ILI9341_DARKGREEN);
tft.fillRoundRect(127,254,105,43,7,ILI9341_MAROON);
tft.setTextColor(ILI9341_WHITE); tft.setTextSize(2);
tft.setCursor(30,268);tft.print("START"); tft.setCursor(151,268);tft.print("STOP");
tft.setTextSize(1);tft.setCursor(8,307);tft.print("Queue: ");tft.print(pendingCount());
tft.setCursor(90,307);tft.print(lastMsg.substring(0,23));
}
void recordHistory(String action,String no,String stamp);
void doStart() {
if(running||selected<0||selected>=spkCount||!rtcOK)return;
String no=spks[selected].no;
if(!queueEvent("START",no)){lastMsg="Queue save failed";drawLCD();return;}
recordHistory("START",no,nowStamp());
running=true;runningSpk=no;prefs.putBool("running",true);prefs.putString("runningSpk",no);
digitalWrite(RELAY_PIN,RELAY_ON);lastMsg="START "+nowTime();syncOne();led();drawLCD();
}
void doStop() {
if(!running||!rtcOK)return;
if(!queueEvent("STOP",runningSpk)){lastMsg="Queue save failed";drawLCD();return;}
recordHistory("STOP",runningSpk,nowStamp());
String ended=runningSpk;running=false;runningSpk="";
prefs.putBool("running",false);prefs.remove("runningSpk");
digitalWrite(RELAY_PIN,RELAY_OFF);lastMsg="STOP "+nowTime();syncOne();led();drawLCD();
}
void sendJson(int code,DynamicJsonDocument& d){String s;serializeJson(d,s);server.send(code,"application/json",s);}
void handleRoot(){server.send_P(200,"text/html; charset=utf-8",INDEX_HTML);}
void handleSpk(){
DynamicJsonDocument d(12000);JsonArray a=d.createNestedArray("data");
for(int i=0;i<spkCount;i++){
JsonObject o=a.createNestedObject();
o["nomor_spk"]=spks[i].no;o["nama_pekerjaan"]=spks[i].name;
o["status"]=spks[i].status;o["device_id"]=spks[i].deviceId;
}
d["success"]=true;sendJson(200,d);
}
void handleStatus(){
DynamicJsonDocument d(1024);d["success"]=true;d["time"]=nowTime();d["date"]=nowStamp();
d["running"]=running;d["running_spk"]=runningSpk;d["pending"]=pendingCount();
d["device_id"]=DEVICE_ID;d["ap_mode"]=apMode;d["wifi_connected"]=WiFi.status()==WL_CONNECTED;
d["ip"]=apMode?WiFi.softAPIP().toString():WiFi.localIP().toString();
d["ssid"]=apMode?String(AP_SSID):WiFi.SSID();
sendJson(200,d);
}
void handleStart(){
if(!server.hasArg("plain")){server.send(400,"application/json","{\"success\":false,\"message\":\"Body kosong\"}");return;}
DynamicJsonDocument in(512);if(deserializeJson(in,server.arg("plain"))){server.send(400,"application/json","{\"success\":false,\"message\":\"JSON tidak valid\"}");return;}
String no=in["nomor_spk"]|"";
int idx=-1;for(int i=0;i<spkCount;i++)if(spks[i].no==no)idx=i;
if(running||idx<0||!rtcOK){server.send(409,"application/json","{\"success\":false,\"message\":\"SPK tidak valid, sedang running, atau RTC tidak siap\"}");return;}
selected=idx;doStart();
DynamicJsonDocument out(512);out["success"]=running;out["event_time"]=nowStamp();out["message"]=lastMsg;sendJson(running?200:500,out);
}
void handleStop(){
if(!running||!rtcOK){server.send(409,"application/json","{\"success\":false,\"message\":\"Tidak ada pekerjaan berjalan atau RTC error\"}");return;}
doStop();DynamicJsonDocument out(512);out["success"]=!running;out["event_time"]=nowStamp();out["message"]=lastMsg;sendJson(!running?200:500,out);
}
void handleHistory(){
DynamicJsonDocument d(12000);JsonArray out=d.createNestedArray("data");
if(LittleFS.exists("/history.json")){File f=LittleFS.open("/history.json","r");if(f){deserializeJson(d,f);f.close();}}
d["success"]=true;sendJson(200,d);
}
void recordHistory(String action,String no,String stamp){
DynamicJsonDocument d(8192);JsonArray a;
if(LittleFS.exists("/history.json")){File f=LittleFS.open("/history.json","r");if(f){deserializeJson(d,f);f.close();}}
if(d.is<JsonArray>())a=d.as<JsonArray>();else a=d.to<JsonArray>();
JsonObject o=a.createNestedObject();o["action"]=action;o["nomor_spk"]=no;o["event_time"]=stamp;
while(a.size()>30)a.remove(0);
File f=LittleFS.open("/history.json","w");if(f){serializeJson(d,f);f.close();}
}
void handleWifiGet(){
DynamicJsonDocument d(384);
d["success"]=true;d["ap_mode"]=apMode;
d["ssid"]=apMode?String(AP_SSID):WiFi.SSID();
d["ip"]=apMode?WiFi.softAPIP().toString():WiFi.localIP().toString();
sendJson(200,d);
}
void handleWifiPost(){
if(!server.hasArg("plain")){server.send(400,"application/json","{\"success\":false,\"message\":\"Body kosong\"}");return;}
DynamicJsonDocument in(384);
if(deserializeJson(in,server.arg("plain"))){server.send(400,"application/json","{\"success\":false,\"message\":\"JSON tidak valid\"}");return;}
String ssid=in["ssid"]|""; String pass=in["password"]|"";
if(ssid.length()==0){server.send(422,"application/json","{\"success\":false,\"message\":\"SSID wajib diisi\"}");return;}
prefs.putString("w_ssid",ssid); prefs.putString("w_pass",pass);
DynamicJsonDocument out(256); out["success"]=true; out["message"]="Tersimpan, perangkat akan restart...";
sendJson(200,out);
delay(800);
ESP.restart();
}
// wrap actions so both local touch and browser write activity history
void setupServer(){
server.on("/",HTTP_GET,handleRoot);
server.on("/api/spk",HTTP_GET,handleSpk);
server.on("/api/status",HTTP_GET,handleStatus);
server.on("/api/start",HTTP_POST,handleStart);
server.on("/api/stop",HTTP_POST,handleStop);
server.on("/api/history",HTTP_GET,handleHistory);
server.on("/api/wifi",HTTP_GET,handleWifiGet);
server.on("/api/wifi",HTTP_POST,handleWifiPost);
server.begin();
}
bool getTouch(int& x,int& y){
if(!touch.touched())return false;TS_Point p=touch.getPoint();
x=map(constrain(p.x,200,3850),200,3850,0,239);
y=map(constrain(p.y,200,3850),200,3850,0,319);
return true;
}
bool connectWiFi(){
String ssid=prefs.getString("w_ssid",WIFI_SSID_DEFAULT);
String pass=prefs.getString("w_pass",WIFI_PASSWORD_DEFAULT);
if(ssid.length()==0)return false;
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(),pass.c_str());
unsigned long t0=millis();
while(WiFi.status()!=WL_CONNECTED && millis()-t0<15000){ delay(250); }
return WiFi.status()==WL_CONNECTED;
}
void startAPMode(){
apMode=true;
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_SSID);
lastMsg="AP mode: "+String(AP_SSID);
}
void setup(){
Serial.begin(115200);
pinMode(RELAY_PIN,OUTPUT);digitalWrite(RELAY_PIN,RELAY_OFF);
pinMode(LED_R,OUTPUT);pinMode(LED_G,OUTPUT);pinMode(LED_B,OUTPUT);
prefs.begin("workctl",false);eventNo=prefs.getUInt("eventNo",0);
LittleFS.begin(true);
SPI.begin(TFT_SCK,TFT_MISO,TFT_MOSI,TFT_CS);tft.begin();tft.setRotation(0);
touchSPI.begin(TOUCH_SCK,TOUCH_MISO,TOUCH_MOSI,TOUCH_CS);touch.begin(touchSPI);touch.setRotation(0);
Wire.begin(RTC_SDA,RTC_SCL);rtcOK=rtc.begin();
if(rtcOK&&!rtc.isrunning())rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
running=prefs.getBool("running",false);runningSpk=prefs.getString("runningSpk","");
// Safety: after reboot relay remains OFF; unresolved running session is shown to operator.
if(running)lastMsg="Recovered: verify STOP";
if(!connectWiFi()) startAPMode();
setupServer();drawLCD();
}
void loop(){
server.handleClient();
if(!apMode && WiFi.status()==WL_CONNECTED){
if(millis()-lastFetch>60000||lastFetch==0){lastFetch=millis();fetchSpks();drawLCD();}
if(millis()-lastSync>5000){lastSync=millis();syncOne();}
} else if(!apMode && WiFi.status()!=WL_CONNECTED){
// coba sambung ulang berkala tanpa memblokir loop
if(millis()-lastWifiTry>30000||lastWifiTry==0){lastWifiTry=millis();WiFi.reconnect();}
}
int x,y;
if(getTouch(x,y)&&millis()-lastTouch>350){
lastTouch=millis();
if(y>=70&&y<225&&!running){int i=(y-70)/31;if(i<spkCount&&i<5)selected=i;drawLCD();}
else if(y>=254&&y<300){if(x<120)doStart();else doStop();}
}
led();delay(5);
}
Loading
esp32-2432s028r
esp32-2432s028r