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 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
|
#include <ArduinoJson.h> #include <Preferences.h> #include <PubSubClient.h> #include <WiFi.h> #include <WiFiClientSecure.h> #include <time.h>
#define MQTT_BROKER "xxx.hivemq.cloud" #define MQTT_PORT 8883 #define MQTT_USER "name" #define MQTT_PASS "password" #define MQTT_CLIENT "autofeed-esp32"
#define TOPIC_CMD "autofeed/cmd" #define TOPIC_STATUS "autofeed/status"
#define PWM1_PIN 14 #define PWM2_PIN 27 #define PUMP_IN_PIN 19 #define PUMP_OUT_PIN 18 #define WATER_LOW_PIN 17 #define WATER_HIGH_PIN 16
#define NTP_SERVER "pool.ntp.org" #define GMT_OFFSET 28800 #define DST_OFFSET 0
WiFiClientSecure espClient; PubSubClient mqtt(espClient); Preferences prefs;
struct MotorConfig { bool enabled; int runSeconds; int intervalDays; String times[10]; int timeCount; } motorCfg = {false, 30, 1, {}, 0};
struct PumpInConfig { bool enabled; } pumpInCfg = {false};
struct PumpOutConfig { bool enabled; int onSeconds; int offSeconds; } pumpOutCfg = {false, 30, 30};
bool motorRunning = false; unsigned long motorStartTime = 0;
bool pumpInRunning = false; unsigned long pumpInStartTime = 0; bool pumpOutRunning = false; unsigned long pumpOutCycleStart = 0; bool pumpOutCycleState = false;
bool waterLow = false; bool waterHigh = false;
unsigned long lastStatusReport = 0; const unsigned long STATUS_INTERVAL = 10000;
unsigned long lastScheduleCheck = 0; const unsigned long SCHEDULE_INTERVAL = 30000;
unsigned long lastMqttReconnect = 0; const unsigned long MQTT_RECONNECT_INTERVAL = 5000;
bool scheduledToday[10] = {false}; int lastCheckedDay = -1;
void setupWiFi(); void setupMQTT(); void mqttCallback(char *topic, byte *payload, unsigned int length); void reconnectMQTT(); void handleMotorSchedule(); void updateMotor(); void updatePumpIn(); void updatePumpOut(); void reportStatus(); void applyCommand(const char *json); void saveConfig(); void loadConfig(); void stopMotor(); void startMotor();
void setup() { Serial.begin(115200); Serial.println("\n=== Autofeed 2.2 启动 ===");
pinMode(PWM1_PIN, OUTPUT); pinMode(PWM2_PIN, OUTPUT); pinMode(PUMP_IN_PIN, OUTPUT); pinMode(PUMP_OUT_PIN, OUTPUT); pinMode(WATER_LOW_PIN, INPUT); pinMode(WATER_HIGH_PIN, INPUT);
digitalWrite(PWM1_PIN, LOW); digitalWrite(PWM2_PIN, LOW); digitalWrite(PUMP_IN_PIN, LOW); digitalWrite(PUMP_OUT_PIN, LOW);
loadConfig();
setupWiFi();
configTime(GMT_OFFSET, DST_OFFSET, NTP_SERVER); Serial.println("等待 NTP 时间同步..."); struct tm timeinfo; int retries = 0; while (!getLocalTime(&timeinfo) && retries < 20) { delay(500); Serial.print("."); retries++; } if (retries < 20) { Serial.println("\nNTP 同步成功!"); Serial.printf("当前时间: %04d-%02d-%02d %02d:%02d:%02d\n", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec); } else { Serial.println("\nNTP 同步失败, 将持续重试"); }
setupMQTT(); }
void loop() { if (WiFi.status() != WL_CONNECTED) { Serial.println("WiFi 断开, 重新连接..."); WiFi.reconnect(); delay(5000); return; }
if (!mqtt.connected()) { unsigned long now = millis(); if (now - lastMqttReconnect > MQTT_RECONNECT_INTERVAL) { lastMqttReconnect = now; reconnectMQTT(); } } mqtt.loop();
waterLow = digitalRead(WATER_LOW_PIN) == HIGH; waterHigh = digitalRead(WATER_HIGH_PIN) == HIGH;
handleMotorSchedule(); updateMotor(); updatePumpIn(); updatePumpOut();
unsigned long now = millis(); if (now - lastStatusReport >= STATUS_INTERVAL) { lastStatusReport = now; reportStatus(); } }
void setupWiFi() { prefs.begin("wifi", true); String ssid = prefs.getString("ssid", ""); String pass = prefs.getString("pass", ""); prefs.end();
if (ssid.length() > 0) { Serial.printf("尝试连接已保存的 WiFi: %s\n", ssid.c_str()); WiFi.begin(ssid.c_str(), pass.c_str());
int timeout = 0; while (WiFi.status() != WL_CONNECTED && timeout < 20) { delay(500); Serial.print("."); timeout++; }
if (WiFi.status() == WL_CONNECTED) { Serial.printf("\nWiFi 已连接! IP: %s\n", WiFi.localIP().toString().c_str()); return; } Serial.println("\n已保存的 WiFi 连接失败, 启动 SmartConfig..."); }
WiFi.mode(WIFI_STA); WiFi.beginSmartConfig(SC_TYPE_ESPTOUCH_V2); Serial.println("等待 SmartConfig 配网... (请使用 ESPTouch App)");
while (!WiFi.smartConfigDone()) { delay(500); Serial.print("."); } Serial.println("\nSmartConfig 配网完成!");
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.printf("\nWiFi 已连接! IP: %s\n", WiFi.localIP().toString().c_str());
prefs.begin("wifi", false); prefs.putString("ssid", WiFi.SSID()); prefs.putString("pass", WiFi.psk()); prefs.end(); Serial.println("WiFi 凭据已保存"); }
void setupMQTT() { espClient.setInsecure(); mqtt.setServer(MQTT_BROKER, MQTT_PORT); mqtt.setCallback(mqttCallback); mqtt.setBufferSize(1024); reconnectMQTT(); }
void reconnectMQTT() { if (mqtt.connected()) return;
Serial.print("连接 MQTT..."); if (mqtt.connect(MQTT_CLIENT, MQTT_USER, MQTT_PASS)) { Serial.println("成功!"); mqtt.subscribe(TOPIC_CMD); Serial.printf("已订阅: %s\n", TOPIC_CMD); reportStatus(); } else { Serial.printf("失败, rc=%d\n", mqtt.state()); } }
void mqttCallback(char *topic, byte *payload, unsigned int length) { char json[1024]; if (length >= sizeof(json)) length = sizeof(json) - 1; memcpy(json, payload, length); json[length] = '\0';
Serial.printf("收到 [%s]: %s\n", topic, json);
if (String(topic) == TOPIC_CMD) { applyCommand(json); } }
void applyCommand(const char *json) { JsonDocument doc; DeserializationError err = deserializeJson(doc, json); if (err) { Serial.printf("JSON 解析失败: %s\n", err.c_str()); return; }
if (doc.containsKey("motor")) { JsonObject motor = doc["motor"]; if (motor.containsKey("enabled")) { motorCfg.enabled = motor["enabled"].as<bool>(); if (!motorCfg.enabled) { stopMotor(); } } if (motor.containsKey("runSeconds")) { motorCfg.runSeconds = motor["runSeconds"].as<int>(); } if (motor.containsKey("schedule")) { JsonObject schedule = motor["schedule"]; if (schedule.containsKey("intervalDays")) { motorCfg.intervalDays = schedule["intervalDays"].as<int>(); if (motorCfg.intervalDays < 1) motorCfg.intervalDays = 1; } if (schedule.containsKey("times")) { JsonArray times = schedule["times"]; motorCfg.timeCount = 0; for (int i = 0; i < times.size() && i < 10; i++) { motorCfg.times[i] = times[i].as<String>(); motorCfg.timeCount++; } for (int i = 0; i < 10; i++) { scheduledToday[i] = false; } } } }
if (doc.containsKey("pumpIn")) { JsonObject pumpIn = doc["pumpIn"]; if (pumpIn.containsKey("enabled")) { pumpInCfg.enabled = pumpIn["enabled"].as<bool>(); if (!pumpInCfg.enabled) { digitalWrite(PUMP_IN_PIN, LOW); pumpInRunning = false; } } }
if (doc.containsKey("pumpOut")) { JsonObject pumpOut = doc["pumpOut"]; if (pumpOut.containsKey("enabled")) { pumpOutCfg.enabled = pumpOut["enabled"].as<bool>(); if (!pumpOutCfg.enabled) { digitalWrite(PUMP_OUT_PIN, LOW); pumpOutRunning = false; } else { pumpOutCycleStart = millis(); pumpOutCycleState = true; digitalWrite(PUMP_OUT_PIN, HIGH); pumpOutRunning = true; } } if (pumpOut.containsKey("onSeconds")) { pumpOutCfg.onSeconds = pumpOut["onSeconds"].as<int>(); } if (pumpOut.containsKey("offSeconds")) { pumpOutCfg.offSeconds = pumpOut["offSeconds"].as<int>(); } }
saveConfig(); Serial.println("配置已更新并保存");
reportStatus(); }
void handleMotorSchedule() { if (!motorCfg.enabled || motorCfg.timeCount == 0) return; if (motorRunning) return;
unsigned long now = millis(); if (now - lastScheduleCheck < SCHEDULE_INTERVAL) return; lastScheduleCheck = now;
struct tm timeinfo; if (!getLocalTime(&timeinfo)) return;
int today = timeinfo.tm_yday;
if (today != lastCheckedDay) { lastCheckedDay = today; for (int i = 0; i < 10; i++) { scheduledToday[i] = false; } }
if (today % motorCfg.intervalDays != 0) return;
char currentTime[6]; snprintf(currentTime, sizeof(currentTime), "%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min);
for (int i = 0; i < motorCfg.timeCount; i++) { if (scheduledToday[i]) continue;
if (motorCfg.times[i] == String(currentTime)) { Serial.printf("调度触发: %s\n", currentTime); scheduledToday[i] = true; startMotor(); break; } } }
void startMotor() { if (motorRunning) return; Serial.println("电机启动 (正转)"); digitalWrite(PWM1_PIN, HIGH); digitalWrite(PWM2_PIN, LOW); motorRunning = true; motorStartTime = millis(); }
void stopMotor() { Serial.println("电机停止"); digitalWrite(PWM1_PIN, LOW); digitalWrite(PWM2_PIN, LOW); motorRunning = false; }
void updateMotor() { if (!motorRunning) return;
unsigned long elapsed = millis() - motorStartTime; if (elapsed >= (unsigned long)motorCfg.runSeconds * 1000UL) { stopMotor(); reportStatus(); } }
void updatePumpIn() { if (!pumpInCfg.enabled) { if (pumpInRunning) { digitalWrite(PUMP_IN_PIN, LOW); pumpInRunning = false; } return; }
if (waterHigh) { if (pumpInRunning) { Serial.println("水位已满, 进水泵停止"); digitalWrite(PUMP_IN_PIN, LOW); pumpInRunning = false; } } else if (waterLow) { if (!pumpInRunning) { Serial.println("水位低, 进水泵启动"); digitalWrite(PUMP_IN_PIN, HIGH); pumpInRunning = true; pumpInStartTime = millis(); } }
if (pumpInRunning) { if (millis() - pumpInStartTime > 180000UL) { Serial.println( "!!! 警告: 进水超时(3分钟), 自动关闭并禁用[所有]水泵系统 !!!");
digitalWrite(PUMP_IN_PIN, LOW); pumpInRunning = false; pumpInCfg.enabled = false;
digitalWrite(PUMP_OUT_PIN, LOW); pumpOutRunning = false; pumpOutCfg.enabled = false;
saveConfig(); reportStatus(); } } }
void updatePumpOut() { if (!pumpOutCfg.enabled) { if (pumpOutRunning) { digitalWrite(PUMP_OUT_PIN, LOW); pumpOutRunning = false; } return; }
unsigned long now = millis(); unsigned long elapsed = now - pumpOutCycleStart;
if (pumpOutCycleState) { if (elapsed >= (unsigned long)pumpOutCfg.onSeconds * 1000UL) { pumpOutCycleState = false; pumpOutCycleStart = now; digitalWrite(PUMP_OUT_PIN, LOW); pumpOutRunning = false; Serial.println("循环泵: 关闭"); } } else { if (elapsed >= (unsigned long)pumpOutCfg.offSeconds * 1000UL) { pumpOutCycleState = true; pumpOutCycleStart = now; digitalWrite(PUMP_OUT_PIN, HIGH); pumpOutRunning = true; Serial.println("循环泵: 开启"); } } }
void reportStatus() { if (!mqtt.connected()) return;
struct tm timeinfo; char timeStr[30] = "N/A"; if (getLocalTime(&timeinfo)) { strftime(timeStr, sizeof(timeStr), "%Y-%m-%dT%H:%M:%S+08:00", &timeinfo); }
JsonDocument doc;
JsonObject motor = doc["motor"].to<JsonObject>(); motor["enabled"] = motorCfg.enabled; motor["running"] = motorRunning; motor["runSeconds"] = motorCfg.runSeconds; JsonObject schedule = motor["schedule"].to<JsonObject>(); schedule["intervalDays"] = motorCfg.intervalDays; JsonArray times = schedule["times"].to<JsonArray>(); for (int i = 0; i < motorCfg.timeCount; i++) { times.add(motorCfg.times[i]); }
JsonObject pumpIn = doc["pumpIn"].to<JsonObject>(); pumpIn["enabled"] = pumpInCfg.enabled; pumpIn["running"] = pumpInRunning;
JsonObject pumpOut = doc["pumpOut"].to<JsonObject>(); pumpOut["enabled"] = pumpOutCfg.enabled; pumpOut["running"] = pumpOutRunning; pumpOut["onSeconds"] = pumpOutCfg.onSeconds; pumpOut["offSeconds"] = pumpOutCfg.offSeconds;
doc["waterLow"] = waterLow; doc["waterHigh"] = waterHigh; doc["time"] = timeStr; doc["wifi"] = (WiFi.status() == WL_CONNECTED);
char buf[512]; serializeJson(doc, buf, sizeof(buf)); mqtt.publish(TOPIC_STATUS, buf); }
void saveConfig() { prefs.begin("config", false);
prefs.putBool("mEnabled", motorCfg.enabled); prefs.putInt("mRunSec", motorCfg.runSeconds); prefs.putInt("mIntDays", motorCfg.intervalDays); prefs.putInt("mTimeCnt", motorCfg.timeCount); for (int i = 0; i < motorCfg.timeCount; i++) { char key[8]; snprintf(key, sizeof(key), "mT%d", i); prefs.putString(key, motorCfg.times[i]); }
prefs.putBool("piEnabled", pumpInCfg.enabled);
prefs.putBool("poEnabled", pumpOutCfg.enabled); prefs.putInt("poOnSec", pumpOutCfg.onSeconds); prefs.putInt("poOffSec", pumpOutCfg.offSeconds);
prefs.end(); }
void loadConfig() { prefs.begin("config", true);
motorCfg.enabled = prefs.getBool("mEnabled", false); motorCfg.runSeconds = prefs.getInt("mRunSec", 30); motorCfg.intervalDays = prefs.getInt("mIntDays", 1); motorCfg.timeCount = prefs.getInt("mTimeCnt", 0); for (int i = 0; i < motorCfg.timeCount && i < 10; i++) { char key[8]; snprintf(key, sizeof(key), "mT%d", i); motorCfg.times[i] = prefs.getString(key, ""); }
pumpInCfg.enabled = prefs.getBool("piEnabled", false);
pumpOutCfg.enabled = prefs.getBool("poEnabled", false); pumpOutCfg.onSeconds = prefs.getInt("poOnSec", 30); pumpOutCfg.offSeconds = prefs.getInt("poOffSec", 30);
prefs.end(); Serial.println("配置已从 Flash 加载"); }
|