-
Notifications
You must be signed in to change notification settings - Fork 0
/
moisture+relay+webserver
462 lines (444 loc) · 18.5 KB
/
moisture+relay+webserver
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoMqttClient.h>
#include <ArduinoJson.h>
#include <Preferences.h>
#define NUM_SENSORS 6
void parseCommaSeparatedValues(String csv, int array[], int arraySize);
struct Config {
String ssid = "ssid";
String wifi_password = "password";
String mqtt_server = "mqtt_address";
String mqtt_username = "mqtt_username";
String mqtt_password = "mqtt_pass";
String clientID = "sensor";
String mqtt_topic = "domoticz/in";
int SensorPin[NUM_SENSORS] = { 0, 0, 0, 0, 0, 0 };
int rawRange[2] = { 2830, 890 }; // Dry-wet
int scaleRange[2] = { 200, 0 }; // Dry-wet
int relayPin = 26;
int WetLimit = 100;
long relayOnTime = 10;
unsigned long pollTime = 60;
int Samples = 10;
int NoOfSensor = 3;
int sensorIdx[NUM_SENSORS] = { 0, 0, 0, 0, 0, 0 };
};
Config config;
Preferences preferences;
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
AsyncWebServer server(80);
int lastPublishedValues[NUM_SENSORS] = { 0 };
unsigned long relayOffTime = 0;
bool relayOn = false;
int mapSensorValue(int rawValue) {
return map(rawValue, config.rawRange[0], config.rawRange[1], config.scaleRange[0], config.scaleRange[1]);
}
void saveConfig() {
preferences.begin("config", false);
preferences.putString("ssid", config.ssid);
preferences.putString("wifi_password", config.wifi_password);
preferences.putString("mqtt_server", config.mqtt_server);
preferences.putString("mqtt_username", config.mqtt_username);
preferences.putString("mqtt_password", config.mqtt_password);
preferences.putString("clientID", config.clientID);
preferences.putString("mqtt_topic", config.mqtt_topic);
preferences.putInt("relayPin", config.relayPin);
preferences.putInt("WetLimit", config.WetLimit);
preferences.putInt("relayOnTime", config.relayOnTime);
preferences.putInt("pollTime", config.pollTime);
preferences.putInt("Samples", config.Samples);
preferences.putInt("NoOfSensor", config.NoOfSensor);
String sensorPinsCSV = "";
for (int i = 0; i < NUM_SENSORS; i++) {
sensorPinsCSV += String(config.SensorPin[i]);
if (i < NUM_SENSORS - 1) sensorPinsCSV += ",";
}
preferences.putString("SensorPin", sensorPinsCSV);
String sensorIdxCSV = "";
for (int i = 0; i < NUM_SENSORS; i++) {
sensorIdxCSV += String(config.sensorIdx[i]);
if (i < NUM_SENSORS - 1) sensorIdxCSV += ",";
}
preferences.putString("sensorIdx", sensorIdxCSV);
preferences.putInt("rawRangeMin", config.rawRange[0]);
preferences.putInt("rawRangeMax", config.rawRange[1]);
preferences.putInt("scaleRangeMin", config.scaleRange[0]);
preferences.putInt("scaleRangeMax", config.scaleRange[1]);
preferences.end();
}
void loadConfig() {
preferences.begin("config", true);
config.ssid = preferences.getString("ssid", config.ssid);
config.wifi_password = preferences.getString("wifi_password", config.wifi_password);
config.mqtt_server = preferences.getString("mqtt_server", config.mqtt_server);
config.mqtt_username = preferences.getString("mqtt_username", config.mqtt_username);
config.mqtt_password = preferences.getString("mqtt_password", config.mqtt_password);
config.clientID = preferences.getString("clientID", config.clientID);
config.mqtt_topic = preferences.getString("mqtt_topic", config.mqtt_topic);
config.relayPin = preferences.getInt("relayPin", config.relayPin);
config.WetLimit = preferences.getInt("WetLimit", config.WetLimit);
config.relayOnTime = preferences.getInt("relayOnTime", config.relayOnTime);
config.pollTime = preferences.getInt("pollTime", config.pollTime);
config.Samples = preferences.getInt("Samples", config.Samples);
config.NoOfSensor = preferences.getInt("NoOfSensor", config.NoOfSensor);
String sensorPinsCSV = preferences.getString("SensorPin", "");
if (!sensorPinsCSV.isEmpty()) {
parseCommaSeparatedValues(sensorPinsCSV, config.SensorPin, NUM_SENSORS);
}
String sensorIdxCSV = preferences.getString("sensorIdx", "");
if (!sensorIdxCSV.isEmpty()) {
parseCommaSeparatedValues(sensorIdxCSV, config.sensorIdx, NUM_SENSORS);
}
config.rawRange[0] = preferences.getInt("rawRangeMin", config.rawRange[0]);
config.rawRange[1] = preferences.getInt("rawRangeMax", config.rawRange[1]);
config.scaleRange[0] = preferences.getInt("scaleRangeMin", config.scaleRange[0]);
config.scaleRange[1] = preferences.getInt("scaleRangeMax", config.scaleRange[1]);
preferences.end();
}
void connectToWiFi() {
Serial.print("Connecting to WiFi: ");
Serial.println(config.ssid);
WiFi.begin(config.ssid.c_str(), config.wifi_password.c_str());
unsigned long startTime = millis();
while (WiFi.status() != WL_CONNECTED && millis() - startTime < 30000) {
delay(500);
Serial.print(".");
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("Failed to connect to WiFi. Creating an ad-hoc network...");
WiFi.mode(WIFI_AP);
IPAddress local_IP(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
if (!WiFi.softAPConfig(local_IP, gateway, subnet)) {
Serial.println("AP Config Failed");
return;
}
bool apSuccess = WiFi.softAP("Plants");
if (apSuccess) {
Serial.print("Ad-hoc network SSID: 'Plants' with IP: ");
Serial.println(WiFi.softAPIP());
} else {
Serial.println("Failed to create ad-hoc network. Please check the configuration and device capabilities.");
}
}
}
void connectToMQTT() {
mqttClient.setId(config.clientID.c_str());
mqttClient.setUsernamePassword(config.mqtt_username.c_str(), config.mqtt_password.c_str());
int attempts = 0;
while (!mqttClient.connect(config.mqtt_server.c_str(), 1883) && attempts < 3) {
Serial.print(".");
delay(5000);
attempts++;
}
if (attempts < 3) {
Serial.println("\nConnected to MQTT");
} else {
Serial.println("\nFailed to connect to MQTT, proceeding without MQTT functionality.");
}
}
void publishSensorValues(int sensorIdx, int value) {
int domoticzIdx = -1;
for (int i = 0; i < NUM_SENSORS; i++) {
if (config.sensorIdx[i] == sensorIdx) {
domoticzIdx = sensorIdx;
lastPublishedValues[i] = value;
break;
}
}
if (domoticzIdx != -1) {
DynamicJsonDocument doc(1024);
doc["idx"] = domoticzIdx;
doc["nvalue"] = value;
doc["svalue"] = String(value);
String payload;
serializeJson(doc, payload);
if (!config.mqtt_topic.isEmpty()) {
// Publish to the configured MQTT topic
mqttClient.beginMessage(config.mqtt_topic);
mqttClient.print(payload);
mqttClient.endMessage();
} else {
// If MQTT topic is empty, use Home Assistant discovery format
String stateTopic = "homeassistant/" + config.clientID + "/sensor" + String(sensorIdx) + "/state";
DynamicJsonDocument haDoc(1024);
haDoc["moisture"] = value;
String haPayload;
serializeJson(haDoc, haPayload);
mqttClient.beginMessage(stateTopic);
mqttClient.print(haPayload);
mqttClient.endMessage();
}
} else {
Serial.println("MQTT topic is empty, cannot publish sensor values to Domoticz.");
}
}
void connectToNetwork() {
connectToWiFi();
connectToMQTT();
}
void parseAndSetSensorPins(String sensorPins) {
int pinsArray[NUM_SENSORS];
parseCommaSeparatedValues(sensorPins, pinsArray, NUM_SENSORS);
for (int i = 0; i < NUM_SENSORS; i++) {
config.SensorPin[i] = pinsArray[i];
}
}
void parseAndSetSensorIdxs(String sensorIdxs) {
int idxsArray[NUM_SENSORS];
parseCommaSeparatedValues(sensorIdxs, idxsArray, NUM_SENSORS);
for (int i = 0; i < NUM_SENSORS; i++) {
config.sensorIdx[i] = idxsArray[i];
}
}
void parseCommaSeparatedValues(String csv, int array[], int arraySize) {
int idx = 0;
int lastIdx = 0;
for (int i = 0; i <= csv.length(); i++) {
// Check for end of string or comma
if (i == csv.length() || csv[i] == ',') {
if (idx < arraySize) {
array[idx++] = csv.substring(lastIdx, i).toInt();
}
lastIdx = i + 1; // Move past the comma
}
}
}
void publishMQTTDiscoveryConfig() {
for (int i = 0; i < NUM_SENSORS; i++) {
DynamicJsonDocument configDoc(1024);
String configTopic = "homeassistant/sensor/" + config.clientID + "_sensor" + String(i) + "/config";
configDoc["name"] = "Plant_Sensor " + String(i);
configDoc["device_class"] = "moisture";
configDoc["unit_of_measurement"] = "%";
configDoc["state_topic"] = "homeassistant/" + config.clientID + "/sensor" + String(i) + "/state";
configDoc["value_template"] = "{{ value_json.moisture }}";
String configPayload;
serializeJson(configDoc, configPayload);
mqttClient.beginMessage(configTopic);
mqttClient.print(configPayload);
mqttClient.endMessage();
}
}
void pollAndPublishSensors() {
int sensorsAtOrAboveThreshold = 0;
for (int i = 0; i < NUM_SENSORS; i++) {
int sum = 0;
for (int j = 0; j < config.Samples; j++) {
sum += analogRead(config.SensorPin[i]);
}
int average = sum / config.Samples;
Serial.printf("Immediate Poll - Sensor %d Raw Moisture: %d\n", i, average);
int processedValue = mapSensorValue(average);
publishSensorValues(config.sensorIdx[i], processedValue);
if (processedValue >= config.WetLimit) {
sensorsAtOrAboveThreshold++;
}
}
if (sensorsAtOrAboveThreshold >= config.NoOfSensor && !relayOn) {
triggerRelayForInterval();
Serial.println("Manual polling triggered irrigation.");
}
}
void setupWebServer() {
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
String html = "<html><body><h1>Plant Monitoring System</h1>"
"<h2>Sensor Readings</h2><ul>";
for (int i = 0; i < NUM_SENSORS; i++) {
html += "<li>Sensor " + String(i) + ": " + String(lastPublishedValues[i]) + "</li>";
}
html += "</ul>"
"<form action='/submit' method='POST'>"
"SSID: <input type='text' name='ssid' value='"
+ config.ssid + "'><br>"
"WiFi Password: <input type='password' name='wifiPassword' value='"
+ config.wifi_password + "'><br>"
"Sensor Pins (comma-separated): <input type='text' name='sensorPins' value='";
for (int i = 0; i < 6; i++) {
html += String(config.SensorPin[i]);
if (i < 5) html += ",";
}
html += "'><br>"
"Sensor IDXs (comma-separated): <input type='text' name='sensorIdxs' value='";
for (int i = 0; i < 6; i++) {
html += String(config.sensorIdx[i]);
if (i < 5) html += ",";
}
html += "'><br>"
"MQTT Server: <input type='text' name='mqttServer' value='"
+ config.mqtt_server + "'><br>"
"MQTT Topic: (Leave empty for HA Discovery) <input type='text' name='mqttTopic' value='"
+ config.mqtt_topic + "'><br>"
"MQTT Username: <input type='text' name='mqttUsername' value='"
+ config.mqtt_username + "'><br>"
"MQTT Password: <input type='password' name='mqttPassword' value='"
+ config.mqtt_password + "'><br>"
"Client ID: <input type='text' name='clientID' value='"
+ config.clientID + "'><br>"
"Raw Value Range (dry-wet)(comma-separated): <input type='text' name='rawRange' value='"
+ String(config.rawRange[0]) + "," + String(config.rawRange[1]) + "'><br>"
"Scale Range (dry-wet)(comma-separated): <input type='text' name='scaleRange' value='"
+ String(config.scaleRange[0]) + "," + String(config.scaleRange[1]) + "'><br>"
"Relay Pin: <input type='text' name='relayPin' value='"
+ String(config.relayPin) + "'><br>"
"Moisture Threshold: <input type='text' name='WetLimit' value='"
+ String(config.WetLimit) + "'><br>"
"Relay On Time: <input type='text' name='relayOnTime' value='"
+ String(config.relayOnTime) + "'><br>"
"Number of sensors required to trigger irrigation: <input type='text' name='NoOfSensor' value='"
+ String(config.NoOfSensor) + "'><br>"
"Poll Interval (minutes): <input type='text' name='pollTime' value='"
+ String(config.pollTime) + "'><br>"
"Number of Samples: <input type='text' name='numSamples' value='"
+ String(config.Samples) + "'><br>"
"<input type='submit' value='Update'>"
"</form>"
"<form action='/pollSensors' method='POST'>"
"<input type='submit' value='Poll Sensors Now'>"
"</form>"
"<form action='/triggerRelay' method='POST'>"
"<input type='submit' value='Trigger Relay'>"
"</form></body></html>";
request->send(200, "text/html", html);
});
server.on("/pollSensors", HTTP_POST, [](AsyncWebServerRequest *request) {
pollAndPublishSensors();
request->send(200, "text/html", "<p>Sensors polled successfully. Redirecting...</p><script>setTimeout(function(){window.location.href='/'}, 3000);</script>");
});
server.on("/triggerRelay", HTTP_POST, [](AsyncWebServerRequest *request) {
triggerRelayForInterval();
request->send(200, "text/html", "<p>Relay triggered. Redirecting...</p><script>setTimeout(function(){window.location.href='/'}, 3000);</script>");
});
server.on("/submit", HTTP_POST, [](AsyncWebServerRequest *request) {
String tempSensorPins, tempSensorIdxs;
if (request->hasParam("ssid", true)) {
config.ssid = request->getParam("ssid", true)->value();
}
if (request->hasParam("wifiPassword", true)) {
config.wifi_password = request->getParam("wifiPassword", true)->value();
}
if (request->hasParam("mqttServer", true)) {
config.mqtt_server = request->getParam("mqttServer", true)->value();
}
if (request->hasParam("sensorIdxs", true)) {
tempSensorIdxs = request->getParam("sensorIdxs", true)->value();
parseAndSetSensorIdxs(tempSensorIdxs); // Use improved parsing function
}
if (request->hasParam("mqttTopic", true)) {
config.mqtt_topic = request->getParam("mqttTopic", true)->value();
}
if (request->hasParam("mqttUsername", true)) {
config.mqtt_username = request->getParam("mqttUsername", true)->value();
}
if (request->hasParam("mqttPassword", true)) {
config.mqtt_password = request->getParam("mqttPassword", true)->value();
}
if (request->hasParam("clientID", true)) {
config.clientID = request->getParam("clientID", true)->value();
}
if (request->hasParam("relayPin", true)) {
config.relayPin = request->getParam("relayPin", true)->value().toInt();
}
if (request->hasParam("WetLimit", true)) {
config.WetLimit = request->getParam("WetLimit", true)->value().toInt();
}
if (request->hasParam("rawRange", true)) {
String rawRange = request->getParam("rawRange", true)->value();
int rangeArray[2];
parseCommaSeparatedValues(rawRange, rangeArray, 2);
config.rawRange[0] = rangeArray[0];
config.rawRange[1] = rangeArray[1];
}
if (request->hasParam("scaleRange", true)) {
String scaleRange = request->getParam("scaleRange", true)->value();
int rangeArray[2];
parseCommaSeparatedValues(scaleRange, rangeArray, 2);
config.scaleRange[0] = rangeArray[0];
config.scaleRange[1] = rangeArray[1];
}
if (request->hasParam("relayOnTime", true)) {
config.relayOnTime = request->getParam("relayOnTime", true)->value().toInt();
}
if (request->hasParam("NoOfSensor", true)) {
config.NoOfSensor = request->getParam("NoOfSensor", true)->value().toInt();
}
if (request->hasParam("pollTime", true)) {
config.pollTime = request->getParam("pollTime", true)->value().toInt();
}
if (request->hasParam("numSamples", true)) {
config.Samples = request->getParam("numSamples", true)->value().toInt();
}
if (request->hasParam("sensorPins", true)) {
String sensorPins = request->getParam("sensorPins", true)->value();
parseAndSetSensorPins(sensorPins);
}
saveConfig();
request->send(200, "text/html", "<p>Settings updated. The device will restart now.</p><script>setTimeout(function(){window.location.href='/'}, 3000);</script>");
delay(100);
ESP.restart();
});
}
void triggerRelayForInterval() {
digitalWrite(config.relayPin, HIGH);
relayOn = true;
relayOffTime = millis() + config.relayOnTime * 1000; // Use the configured relay on time
Serial.println("Relay triggered!");
}
void setup() {
Serial.begin(9600);
loadConfig();
connectToNetwork();
pinMode(config.relayPin, OUTPUT);
digitalWrite(config.relayPin, LOW);
setupWebServer();
server.begin();
if (config.mqtt_topic.isEmpty()) {
publishMQTTDiscoveryConfig();
}
}
void loop() {
static unsigned long lastSensorPollTime = 0;
unsigned long pollIntervalMillis = static_cast<unsigned long>(config.pollTime) * 60000UL;
if (!mqttClient.connected()) {
connectToMQTT();
}
mqttClient.poll();
if (relayOn && millis() >= relayOffTime) {
digitalWrite(config.relayPin, LOW);
relayOn = false;
}
if (millis() - lastSensorPollTime > pollIntervalMillis) {
lastSensorPollTime = millis();
int sensorsAtOrAboveThreshold = 0;
for (int i = 0; i < NUM_SENSORS; i++) {
int sum = 0;
for (int j = 0; j < config.Samples; j++) {
sum += analogRead(config.SensorPin[i]);
}
int average = sum / config.Samples;
Serial.printf("Sensor %d Raw Moisture: %d\n", i, average);
int processedValue = mapSensorValue(average);
if (processedValue != lastPublishedValues[i]) {
lastPublishedValues[i] = processedValue;
Serial.printf("Sensor %d Mapped Moisture: %d\n", i, processedValue);
publishSensorValues(config.sensorIdx[i], processedValue);
}
if (processedValue >= config.WetLimit) {
sensorsAtOrAboveThreshold++;
}
}
if (sensorsAtOrAboveThreshold >= config.NoOfSensor && !relayOn) {
triggerRelayForInterval();
}
}
}