Skip to content

Commit f866bcd

Browse files
committed
- all the api connection done except update time
1 parent 3ec74d8 commit f866bcd

File tree

2 files changed

+135
-3
lines changed

2 files changed

+135
-3
lines changed

Project_Mina.ino

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ private:
3030
byte pin;
3131
String name;
3232
int relayNum; // Added to track relay number
33+
unsigned long timerStart; // When timer was started
34+
int timerDuration; // Duration in seconds
35+
bool timerActive; // If timer is currently running
3336

3437
void loadFromPreferences()
3538
{
@@ -66,7 +69,8 @@ private:
6669
}
6770

6871
public:
69-
Relay(byte pinNumber, int num) : pin(pinNumber), relayNum(num) // Simplified constructor
72+
Relay(byte pinNumber, int num) : pin(pinNumber), relayNum(num),
73+
timerStart(0), timerDuration(0), timerActive(false) // Simplified constructor
7074
{
7175
pinMode(pin, OUTPUT);
7276
loadFromPreferences();
@@ -119,6 +123,19 @@ public:
119123
name = newName;
120124
saveToPreferences();
121125
}
126+
127+
// Add timer methods
128+
void setTimer(int duration, bool start) {
129+
timerDuration = duration;
130+
timerActive = start;
131+
if (start) {
132+
timerStart = millis();
133+
}
134+
}
135+
136+
int getTimerDuration() { return timerDuration; }
137+
bool isTimerActive() { return timerActive; }
138+
unsigned long getTimerStart() { return timerStart; }
122139
};
123140

124141
// Initialize preferences once
@@ -285,6 +302,85 @@ void setup()
285302
relays[modeIndex-1]->setMode(newMode);
286303
request->send(200, "text/plain", "Mode updated");
287304
});
305+
306+
// Add timer endpoint
307+
String timerEndpoint = "/api/led" + String(i) + "/timer";
308+
server.on(timerEndpoint.c_str(), HTTP_POST, [](AsyncWebServerRequest *request) {},
309+
NULL, [modeIndex](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t /*index*/, size_t /*total*/) {
310+
StaticJsonDocument<200> doc;
311+
DeserializationError error = deserializeJson(doc, (const char*)data, len);
312+
313+
if (error) {
314+
request->send(400, "text/plain", "Invalid JSON");
315+
return;
316+
}
317+
318+
if (!doc.containsKey("duration") || !doc.containsKey("state")) {
319+
request->send(400, "text/plain", "Missing duration or state field");
320+
return;
321+
}
322+
323+
int duration = doc["duration"].as<int>();
324+
bool state = doc["state"].as<bool>();
325+
326+
if (!state) {
327+
// Deactivate timer
328+
relays[modeIndex-1]->setTimer(0, false);
329+
request->send(200, "text/plain", "Timer stopped");
330+
return;
331+
}
332+
333+
if (duration <= 0) {
334+
request->send(400, "text/plain", "Invalid duration");
335+
return;
336+
}
337+
338+
// Set timer with provided duration
339+
relays[modeIndex-1]->setTimer(duration, true);
340+
request->send(200, "text/plain", "Timer started");
341+
});
342+
343+
// Add schedule endpoint
344+
String scheduleEndpoint = "/api/led" + String(i) + "/schedule";
345+
server.on(scheduleEndpoint.c_str(), HTTP_POST, [](AsyncWebServerRequest *request) {},
346+
NULL, [modeIndex](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t /*index*/, size_t /*total*/) {
347+
StaticJsonDocument<200> doc;
348+
DeserializationError error = deserializeJson(doc, (const char*)data, len);
349+
350+
if (error) {
351+
request->send(400, "text/plain", "Invalid JSON");
352+
return;
353+
}
354+
355+
if (!doc.containsKey("onTime") || !doc.containsKey("offTime")) {
356+
request->send(400, "text/plain", "Missing time fields");
357+
return;
358+
}
359+
360+
String onTimeStr = doc["onTime"].as<String>();
361+
String offTimeStr = doc["offTime"].as<String>();
362+
363+
// Convert time strings to integers (e.g., "14:30" -> 1430)
364+
int onTime = (onTimeStr.substring(0,2).toInt() * 100) + onTimeStr.substring(3,5).toInt();
365+
int offTime = (offTimeStr.substring(0,2).toInt() * 100) + offTimeStr.substring(3,5).toInt();
366+
367+
if (onTime < 0 || onTime > 2359 || offTime < 0 || offTime > 2359) {
368+
request->send(400, "text/plain", "Invalid time values");
369+
return;
370+
}
371+
372+
relays[modeIndex-1]->setTimes(onTime, offTime);
373+
request->send(200, "text/plain", "Schedule updated");
374+
});
375+
376+
// Add schedule GET endpoint
377+
String scheduleGetEndpoint = "/api/led" + String(i) + "/schedule";
378+
server.on(scheduleGetEndpoint.c_str(), HTTP_GET, [modeIndex](AsyncWebServerRequest *request) {
379+
AsyncResponseStream *response = request->beginResponseStream("application/json");
380+
response->print("{\"onTime\": " + String(relays[modeIndex-1]->getOnTime()) +
381+
", \"offTime\": " + String(relays[modeIndex-1]->getOffTime()) + "}");
382+
request->send(response);
383+
});
288384
}
289385

290386
// Toggle endpoints for each relay

data/index.html

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -991,6 +991,35 @@ <h3 class="led-title" id="ledName_4">LED 4</h3>
991991
});
992992
}
993993

994+
// Add this function after syncModesFromServer
995+
function fetchScheduleTimes() {
996+
[1, 2, 3, 4].forEach(ledId => {
997+
fetch(`/api/led${ledId}/schedule`)
998+
.then(response => {
999+
if (!response.ok) throw new Error('Network response was not ok');
1000+
return response.json();
1001+
})
1002+
.then(schedule => {
1003+
const onTimeInput = document.querySelector(`#onTime_${ledId}`);
1004+
const offTimeInput = document.querySelector(`#offTime_${ledId}`);
1005+
1006+
// Convert integer times back to HH:MM format
1007+
if (schedule.onTime) {
1008+
const hours = Math.floor(schedule.onTime / 100).toString().padStart(2, '0');
1009+
const minutes = (schedule.onTime % 100).toString().padStart(2, '0');
1010+
onTimeInput.value = `${hours}:${minutes}`;
1011+
}
1012+
1013+
if (schedule.offTime) {
1014+
const hours = Math.floor(schedule.offTime / 100).toString().padStart(2, '0');
1015+
const minutes = (schedule.offTime % 100).toString().padStart(2, '0');
1016+
offTimeInput.value = `${hours}:${minutes}`;
1017+
}
1018+
})
1019+
.catch(error => console.error(`Error fetching schedule for LED ${ledId}:`, error));
1020+
});
1021+
}
1022+
9941023
// Function to initialize LED controls
9951024
function setupLED(ledId) {
9961025
const led = {
@@ -1061,7 +1090,13 @@ <h3 class="led-title" id="ledName_4">LED 4</h3>
10611090
body: JSON.stringify({ onTime, offTime })
10621091
});
10631092
})
1064-
.catch(error => console.error('Error:', error));
1093+
.then(() => {
1094+
alert('Schedule set successfully!');
1095+
})
1096+
.catch(error => {
1097+
console.error('Error:', error);
1098+
alert('Failed to set schedule');
1099+
});
10651100
};
10661101

10671102
// Timer mode handler
@@ -1219,7 +1254,8 @@ <h3 class="led-title" id="ledName_4">LED 4</h3>
12191254
fetchVersion();
12201255
fetchLEDNames();
12211256
fetchLEDStates();
1222-
initModesFromServer(); // Add this line before setupLED
1257+
initModesFromServer();
1258+
fetchScheduleTimes(); // Add this line
12231259
[1, 2, 3, 4].forEach(setupLED);
12241260
setInterval(checkConnection, 5000);
12251261
checkConnection();

0 commit comments

Comments
 (0)