-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPagesHandlers.cpp
More file actions
341 lines (311 loc) · 14.7 KB
/
PagesHandlers.cpp
File metadata and controls
341 lines (311 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
* WaterTankController project
* Copyright (c) 2026 Fedir Vilhota <fredy31415@gmail.com>
* This software is released under the MIT License.
* See the LICENSE file in the project root for full license information.
*/
#include "PagesHandlers.h"
#include "TankMonitor.h"
#include "RelayControl.h"
#include "html_templates.h"
#include <WiFi.h>
#include <time.h>
#include <LittleFS.h>
// Helper to format float to string with 2 decimals without using dtostrf/snprintf
static String formatFloat(float val) {
int intPart = (int)val;
int fracPart = (int)((val - intPart) * 100);
if (fracPart < 0) fracPart = -fracPart;
return String(intPart) + "." + (fracPart < 10 ? "0" : "") + String(fracPart);
}
PagesHandlers::PagesHandlers(TankMonitor& tank_, RelayControl& relay_, Config& configRef)
: tank(tank_), relay(relay_), _config(configRef)
{}
void PagesHandlers::initPagesHandlers(AsyncWebServer& webServer) {
setupHomePageHandler(webServer);
setupVolumesHandler(webServer);
setupSensorDataHandler(webServer);
setupRelayStatesHandler(webServer);
setupSetRelayHandler(webServer);
setupSetRelayModeHandler(webServer);
setupLogsListHandler(webServer);
setupLogChartHandler(webServer);
setupLogDownloadHandler(webServer);
setupSetNumZonesHandler(webServer);
setupStatusHandler(webServer);
}
void PagesHandlers::setupHomePageHandler(AsyncWebServer& webServer) {
webServer.on("/", HTTP_GET, [this](AsyncWebServerRequest *request){
String html = String(HTML_HOME_PAGE);
html.replace("{DATE}", __DATE__);
html.replace("{TIME}", __TIME__);
html.replace("{TIME}", __TIME__);
html.replace("{DISTANCE}", formatFloat(tank.getDistance()));
html.replace("{VOLUME}", formatFloat(tank.getCurrentVolume()));
html.replace("{RATE}", formatFloat(tank.getAvgRate()));
html.replace("{ESTIMATED}", formatFloat(tank.getEstimatedTime()));
html.replace("{IP}", WiFi.localIP().toString());
html.replace("%PIN_REL1_VAL%", String(relay.getRelayPin(1)));
html.replace("%PIN_REL2_VAL%", String(relay.getRelayPin(2)));
html.replace("%PIN_REL3_VAL%", String(relay.getRelayPin(3)));
html.replace("%PIN_REL4_VAL%", String(relay.getRelayPin(4)));
String options = "";
for (int i = 1; i <= 10; ++i) {
options += "<option value='" + String(i) + "'";
if (i == _config.getNumZones()) options += " selected";
options += ">" + String(i) + "</option>";
}
html.replace("__OPTIONS__", options);
request->send(200, "text/html; charset=UTF-8", html);
});
}
void PagesHandlers::setupVolumesHandler(AsyncWebServer& webServer) {
webServer.on("/volumes", HTTP_GET, [this](AsyncWebServerRequest *request){
String volumesStr = tank.getVolumesCsv();
request->send(200, "text/plain", volumesStr);
});
}
void PagesHandlers::setupSensorDataHandler(AsyncWebServer& webServer) {
webServer.on("/sensor_data", HTTP_GET, [this](AsyncWebServerRequest *request){
String response = "{";
response += "\"distance\": " + formatFloat(tank.getDistance());
response += ",\"volume\": " + formatFloat(tank.getCurrentVolume());
response += ",\"rate\": " + formatFloat(tank.getAvgRate());
response += ",\"estimated\": " + formatFloat(tank.getEstimatedTime());
response += "}";
request->send(200, "application/json", response);
});
}
void PagesHandlers::setupRelayStatesHandler(AsyncWebServer& webServer) {
webServer.on("/relay_states", HTTP_GET, [this](AsyncWebServerRequest *request){
String json = relay.getStatesJson(2); // реалізуйте цей метод у RelayControl
request->send(200, "application/json", json);
});
}
void PagesHandlers::setupSetRelayHandler(AsyncWebServer& webServer) {
webServer.on("/set_relay", HTTP_GET, [this](AsyncWebServerRequest *request){
if (request->hasParam("pin") && request->hasParam("state")) {
int relayPin = request->getParam("pin")->value().toInt();
bool targetState = (request->getParam("state")->value() == "on");
bool ok = relay.setRelay(relayPin, targetState); // реалізуйте цей метод
if (ok) request->send(200, "text/plain", "OK");
else request->send(403, "text/plain", "Forbidden or invalid pin.");
} else {
request->send(400, "text/plain", "Missing 'pin' or 'state' parameter.");
}
});
}
void PagesHandlers::setupSetRelayModeHandler(AsyncWebServer& webServer) {
webServer.on("/set_relay_mode", HTTP_GET, [this](AsyncWebServerRequest *request){
if (request->hasParam("pin") && request->hasParam("mode")) {
int relayPin = request->getParam("pin")->value().toInt();
String modeStr = request->getParam("mode")->value();
int mode = 1;
if (modeStr == "manual") mode = 0;
else if (modeStr == "auto") mode = 1;
//else if (modeStr == "prog") mode = 2;
bool ok = relay.setControlMode(relayPin, mode); // реалізуйте цей метод
if (ok) request->send(200, "text/plain", "Mode updated.");
else request->send(400, "text/plain", "Invalid pin or mode.");
} else {
request->send(400, "text/plain", "Missing 'pin' or 'mode' parameter.");
}
});
}
void PagesHandlers::setupLogsListHandler(AsyncWebServer& webServer) {
webServer.on("/logs", HTTP_GET, [](AsyncWebServerRequest *request){
String html = String(HTML_LOGS_LIST_HEAD);
File root = LittleFS.open("/");
File file = root.openNextFile();
while (file) {
String fname = file.name();
if(fname.startsWith("log_") && fname.endsWith(".csv")) {
String date = fname.substring(4, 14); // YYYY-MM-DD
html += "<li><a href=\"/log?date=" + date + "\">" + date + "</a> | ";
html += "<a href=\"/download_log?date=" + date + "\">Завантажити CSV</a></li>";
}
file = root.openNextFile();
}
html += "</ul></body></html>";
request->send(200, "text/html; charset=utf-8", html);
});
}
void PagesHandlers::setupLogChartHandler(AsyncWebServer& webServer) {
webServer.on("/log", HTTP_GET, [](AsyncWebServerRequest *request){
if (!request->hasParam("date")) {
request->send(400, "text/plain", "Параметр date відсутній");
return;
}
String date = request->getParam("date")->value();
String filename = "/log_" + date + ".csv";
if (!LittleFS.exists(filename)) {
request->send(404, "text/plain", "Файл не знайдено");
return;
}
// Зчитуємо дані для JS
File file = LittleFS.open(filename, "r");
String data = "[";
bool first = true;
int lastTimeInMinutes = -1; // Час попереднього запису в хвилинах від початку дня
while (file.available()) {
String line = file.readStringUntil('\n');
line.trim();
String t = line.substring(0, line.indexOf(','));
String v = line.substring(line.indexOf(',')+1);
int vi = v.toInt(); // Optimized: remove toFloat/roundf since log is integer
int H, M, S = 0;
if (t.length() == 5) { // HH:MM
H = t.substring(0,2).toInt();
M = t.substring(3,5).toInt();
} else if (t.length() == 8) { // HH:MM:SS
H = t.substring(0,2).toInt();
M = t.substring(3,5).toInt();
S = t.substring(6,8).toInt();
} else if (t.length() == 19) {
H = t.substring(11,13).toInt();
M = t.substring(14,16).toInt();
S = t.substring(17,19).toInt();
} else {
continue;
}
// Перевірка: пропускаємо записи з часом, меншим за попередній
// (це означає, що запис був до синхронізації NTP)
int currentTimeInMinutes = H * 60 + M;
if (lastTimeInMinutes != -1 && currentTimeInMinutes < lastTimeInMinutes) {
// Пропускаємо цей запис
continue;
}
lastTimeInMinutes = currentTimeInMinutes;
int y = date.substring(0,4).toInt();
int m = date.substring(5,7).toInt() - 1; // JS: 0=січень!
int d = date.substring(8,10).toInt();
if (!first) data += ",";
data += "[Date.UTC(" + String(y) + "," + String(m) + "," + String(d) + "," + String(H) + "," + String(M) + "," + String(S) + ")," + String(vi) + "]";
first = false;
}
data += "]";
file.close();
String html = String(HTML_LOG_CHART_TEMPLATE);
html.replace("{DATE}", date);
html.replace("{DATA}", data);
request->send(200, "text/html; charset=utf-8", html);
});
}
void PagesHandlers::setupSetNumZonesHandler(AsyncWebServer& webServer) {
webServer.on("/setNumZones", HTTP_GET, [this](AsyncWebServerRequest *request){ // <--- Додаємо [this]
if (request->hasParam("value")) {
int nz = request->getParam("value")->value().toInt();
_config.setNumZones(nz); // збережи в об’єкті
_config.save(); // збережи у файл
}
request->send(200, "text/plain", "OK");
});
}
void PagesHandlers::setupLogDownloadHandler(AsyncWebServer& webServer) {
webServer.on("/download_log", HTTP_GET, [](AsyncWebServerRequest *request){
if (!request->hasParam("date")) {
request->send(400, "text/plain", "Параметр date відсутній");
return;
}
String date = request->getParam("date")->value();
String filename = "/log_" + date + ".csv";
if (!LittleFS.exists(filename)) {
request->send(404, "text/plain", "Файл не знайдено");
return;
}
// Відправляємо файл для завантаження
// Відправляємо файл для завантаження
request->send(LittleFS, filename, "text/csv; charset=UTF-8", true);
});
}
void PagesHandlers::setupStatusHandler(AsyncWebServer& webServer) {
webServer.on("/api/status", HTTP_GET, [this](AsyncWebServerRequest *request){
// 1. Timestamp
time_t now = time(nullptr);
struct tm *tm_struct = localtime(&now);
// Manual ISO 8601 formatting to ensure correct format
char timeStr[32];
snprintf(timeStr, sizeof(timeStr), "%04d-%02d-%02dT%02d:%02d:%02d+02:00",
tm_struct->tm_year + 1900,
tm_struct->tm_mon + 1,
tm_struct->tm_mday,
tm_struct->tm_hour,
tm_struct->tm_min,
tm_struct->tm_sec);
// 2. Sensors
String sensors = "[";
sensors += "{\"name\":\"distance\",\"value\":\"" + formatFloat(tank.getDistance()) + "\"},";
sensors += "{\"name\":\"volume\",\"value\":\"" + formatFloat(tank.getCurrentVolume()) + "\"},";
sensors += "{\"name\":\"rate\",\"value\":\"" + formatFloat(tank.getAvgRate()) + "\"},";
sensors += "{\"name\":\"estimated\",\"value\":\"" + formatFloat(tank.getEstimatedTime()) + "\"}";
sensors += "]";
// 3. Relays
String relays = "[";
for(int i=1; i<=RelayControl::RELAY_COUNT; i++) {
if(i > 1) relays += ",";
int pin = relay.getRelayPin(i);
String name = pin == 8 ? "Будинок" : ( pin == 10 ? "Свердловина" : String(pin));
relays += "{";
relays += "\"name\":\"" + name + "\",";
relays += "\"pin\":" + String(pin) + ",";
relays += "\"num\":" + String(i) + ",";
relays += "\"state\":" + String(relay.getRelay(i) ? "true" : "false") + ",";
relays += "\"mode\":" + String(relay.getControlMode(i));
relays += "}";
}
relays += "]";
// 4. Logs (Hourly Averages)
String logs = "[";
// Calculate date string for filename: log_YYYY-MM-DD.csv
String dateStr = String(tm_struct->tm_year + 1900) + "-" +
((tm_struct->tm_mon + 1 < 10) ? "0" : "") + String(tm_struct->tm_mon + 1) + "-" +
((tm_struct->tm_mday < 10) ? "0" : "") + String(tm_struct->tm_mday);
String filename = "/log_" + dateStr + ".csv";
if (LittleFS.exists(filename)) {
File file = LittleFS.open(filename, "r");
long hourlySum[24] = {0};
int hourlyCount[24] = {0};
while(file.available()) {
String line = file.readStringUntil('\n');
line.trim();
if(line.length() == 0) continue;
// Format: HH:MM,VAL or HH:MM:SS,VAL
int commaIdx = line.indexOf(',');
if(commaIdx > 0) {
String timePart = line.substring(0, commaIdx);
String valPart = line.substring(commaIdx+1);
// Extract hour
// HH:MM ot HH:MM:SS, so first 2 chars are hour
// Assuming standard format from Log.cpp
if(timePart.length() >= 2) {
int h = timePart.substring(0, 2).toInt();
if(h >= 0 && h < 24) {
hourlySum[h] += valPart.toInt();
hourlyCount[h]++;
}
}
}
}
file.close();
bool first = true;
for(int i=0; i<24; i++) {
if(hourlyCount[i] > 0) {
if(!first) logs += ",";
logs += "{\"Time\":" + String(i) + ",\"Volume\":" + String(hourlySum[i] / hourlyCount[i]) + "}";
first = false;
}
}
}
logs += "]";
// Construct final JSON
String json = "{";
json += "\"status\":\"ok\",";
json += "\"message\":\"Service is running smoothly\",";
json += "\"timestamp\":\"" + String(timeStr) + "\",";
json += "\"sensors\":" + sensors + ",";
json += "\"relays\":" + relays + ",";
json += "\"logs\":" + logs;
json += "}";
request->send(200, "application/json", json);
});
}