-
Notifications
You must be signed in to change notification settings - Fork 0
/
cat-feeder.ino
820 lines (646 loc) · 21.6 KB
/
cat-feeder.ino
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
#include <NTPClient.h>
#include <AltSerialGraphicLCD.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#include <FS.h>
#include <ArduinoOTA.h>
// #include <WiFiClientSecure.h>
#include "config.h"
// Set web server port number to 80
WiFiServer webServer(80);
// Variable to store the HTTP request
String header;
unsigned int totalFed = 0;
unsigned int toFeed = 0;
unsigned int feedAmount = 2;
unsigned long lastFed = 0;
unsigned long lastScreenUpdate = 0;
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
#define SERIAL_TX_DPIN D1
#define SERIAL_RX_DPIN D2
// Initialize an instance of the SoftwareSerial library
SoftwareSerial serial(SERIAL_RX_DPIN,SERIAL_TX_DPIN);
// Create an instance of the GLCD class named glcd. This instance is used to
// call all the subsequent GLCD functions. The instance is called with a
// reference to the software serial object.
GLCD glcd(serial);
char buffer[22]; // Character buffer for strings
#if defined(DEBUG_TELNET)
WiFiServer telnetServer(23);
WiFiClient telnetClient;
#define DEBUG_PRINT(x) telnetClient.print(x)
#define DEBUG_PRINTLN(x) telnetClient.println(x)
#elif defined(DEBUG_SERIAL)
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
#if defined(GRAPHITE)
WiFiUDP graphiteUDP;
unsigned long lastGraphiteUpdate = 0;
#endif
///////////////////////////////////////////////////////////////////////////
// TELNET
///////////////////////////////////////////////////////////////////////////
/*
Function called to handle Telnet clients
https://www.youtube.com/watch?v=j9yW10OcahI
*/
#if defined(DEBUG_TELNET)
void handleTelnet(void) {
if (telnetServer.hasClient()) {
if (!telnetClient || !telnetClient.connected()) {
if (telnetClient) {
telnetClient.stop();
}
telnetClient = telnetServer.available();
} else {
telnetServer.available().stop();
}
}
}
#endif
///////////////////////////////////////////////////////////////////////////
// WiFi
///////////////////////////////////////////////////////////////////////////
/*
Function called to setup the connection to the WiFi AP
*/
void setupWiFi() {
updateLine2("WiFi Connecting... ");
DEBUG_PRINT("Connecting to ");
DEBUG_PRINT(WIFI_SSID);
DEBUG_PRINT("...");
WiFi.mode(WIFI_STA);
WiFi.hostname(HA_ID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
DEBUG_PRINT(".");
}
DEBUG_PRINTLN("connected");
// Print local IP address
DEBUG_PRINT("IP address: ");
DEBUG_PRINTLN(WiFi.localIP());
updateLine2("WiFi Connected ");
randomSeed(micros());
}
///////////////////////////////////////////////////////////////////////////
// MQTT
///////////////////////////////////////////////////////////////////////////
String mqttTopic(const char* topic) {
return String("homeassistant/light/") + String(HA_ID) + String("/") + String(topic);
}
void mqttRegister() {
StaticJsonBuffer<400> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["name"] = HA_NAME;
root["schema"] = "json";
root["unique_id"] = HA_ID;
root["command_topic"] = mqttTopic("set");
root["brightness"] = true;
root["state_topic"] = mqttTopic("state");
String output;
root.printTo(output);
boolean result = mqttClient.beginPublish(mqttTopic("config").c_str(), output.length(), true);
if (result) {
result = mqttClient.write((unsigned char*)output.c_str(), output.length());
}
if (result) {
result = mqttClient.endPublish();
}
if (result) {
DEBUG_PRINTLN("registered");
} else {
DEBUG_PRINTLN("registration failed");
}
}
void mqttPublish(const char* topic, const char* msg) {
mqttClient.publish(mqttTopic("state").c_str(), msg);
}
void mqttReconnect() {
// Loop until we're reconnected
if (!mqttClient.connected()) {
DEBUG_PRINT("Attempting MQTT connection...");
// Attempt to connect
if (mqttClient.connect(MQTT_CLIENTID, MQTT_USER, MQTT_PASS, mqttTopic("config").c_str(), 1, 1, "")) {
DEBUG_PRINTLN("connected");
// Once connected, publish an announcement...
mqttRegister();
// ... and resubscribe
mqttClient.subscribe(mqttTopic("set").c_str());
} else {
DEBUG_PRINT("failed, rc=");
DEBUG_PRINT(mqttClient.state());
}
}
}
void mqttCallback(char* topic, byte* p_payload, unsigned int p_length) {
String payload;
for (uint8_t i = 0; i < p_length; i++) {
payload.concat((char)p_payload[i]);
}
DEBUG_PRINT("Message arrived [");
DEBUG_PRINT(topic);
DEBUG_PRINT("] (");
DEBUG_PRINT(p_length);
DEBUG_PRINT(") ");
DEBUG_PRINTLN(payload);
// feed cat if payload is "ON"
StaticJsonBuffer<300> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(p_payload);
if (!root.success()) {
DEBUG_PRINTLN("ERROR: parseObject() failed");
return;
}
if (root.containsKey("brightness") && root["brightness"].is<int>()) {
feedAmount = (root["brightness"].as<int>() + 1) / 64;
}
if (root.containsKey("state") && root["state"].as<String>() == String("ON")) {
toFeed += feedAmount;
}
}
///////////////////////////////////////////////////////////////////////////
// OTA
///////////////////////////////////////////////////////////////////////////
#if defined(OTA)
/*
Function called to setup OTA updates
*/
void setupOTA() {
ArduinoOTA.setHostname(HA_ID);
DEBUG_PRINT(F("INFO: OTA hostname sets to: "));
DEBUG_PRINTLN(HA_ID);
#if defined(OTA_PORT)
ArduinoOTA.setPort(OTA_PORT);
DEBUG_PRINT(F("INFO: OTA port sets to: "));
DEBUG_PRINTLN(OTA_PORT);
#endif
#if defined(OTA_PASSWORD)
ArduinoOTA.setPassword((const char *)OTA_PASSWORD);
DEBUG_PRINT(F("INFO: OTA password sets to: "));
DEBUG_PRINTLN(OTA_PASSWORD);
#endif
ArduinoOTA.onStart([]() {
DEBUG_PRINTLN(F("INFO: OTA starts"));
});
ArduinoOTA.onEnd([]() {
DEBUG_PRINTLN(F("INFO: OTA ends"));
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
DEBUG_PRINT(F("INFO: OTA progresses: "));
DEBUG_PRINT(progress / (total / 100));
DEBUG_PRINTLN(F("%"));
});
ArduinoOTA.onError([](ota_error_t error) {
DEBUG_PRINT(F("ERROR: OTA error: "));
DEBUG_PRINTLN(error);
if (error == OTA_AUTH_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA auth failed"));
else if (error == OTA_BEGIN_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA begin failed"));
else if (error == OTA_CONNECT_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA connect failed"));
else if (error == OTA_RECEIVE_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA receive failed"));
else if (error == OTA_END_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA end failed"));
});
ArduinoOTA.begin();
}
/*
Function called to handle OTA updates
*/
void handleOTA() {
ArduinoOTA.handle();
}
#endif
///////////////////////////////////////////////////////////////////////////
// LCD
///////////////////////////////////////////////////////////////////////////
String formatTime(unsigned long rawTime) {
unsigned long localTime = rawTime + (TZ_OFFSET * 3600);
unsigned long hours = (localTime % 86400L) / 3600;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
unsigned long minutes = (localTime % 3600) / 60;
String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);
unsigned long seconds = localTime % 60;
String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
return hoursStr + ":" + minuteStr + ":" + secondStr;
}
void initScreen(const char* msg) {
serial.begin(115200);
glcd.reset();
updateTitle();
updateLine2(msg);
}
void redrawScreen() {
glcd.clearScreen();
updateTitle();
updateTime();
updateTotalFed();
updateLastFed();
}
void updateTitle() {
glcd.setString(64, 0, GLCD_FONT_CENTER, HA_NAME);
// snprintf(buffer, sizeof(buffer), "%s", HA_NAME);
// glcd.setXY(0, 0);
// glcd.printStr(buffer);
}
void updateTime() {
snprintf(buffer, sizeof(buffer), "Time: %s", formatTime(timeClient.getEpochTime()).c_str());
glcd.setXY(0, 10);
glcd.printStr(buffer);
}
void updateLine2(const char* content) {
snprintf(buffer, sizeof(buffer), "%s", content);
glcd.setXY(0, 10);
glcd.printStr(buffer);
}
void updateLastFed() {
const char* tmpl = "Last Fed: %d%s ago ";
if (lastFed > 0) {
unsigned long ago = timeClient.getEpochTime() - lastFed;
if (ago < 60 * 60 * 20) {
snprintf(buffer, sizeof(buffer), "Last Fed: %s ", formatTime(lastFed).c_str());
} else if (ago < 60 * 60 * 48) {
snprintf(buffer, sizeof(buffer), tmpl, ago / 60 / 60, "h");
} else {
snprintf(buffer, sizeof(buffer), tmpl, ago / 60 / 60 / 24, "d");
}
} else {
snprintf(buffer, sizeof(buffer), "Not Fed Yet ");
}
glcd.setXY(0, 20);
glcd.printStr(buffer);
}
void updateTotalFed() {
snprintf(buffer, sizeof(buffer), "Total Fed: %d", totalFed);
glcd.setXY(0, 30);
glcd.printStr(buffer);
}
void updateFeeding(boolean feeding) {
glcd.setXY(0, 40);
if (feeding) {
glcd.printStr("Feeding...");
} else {
glcd.printStr(" ");
}
}
void updateError() {
glcd.setXY(0, 40);
glcd.printStr("ERROR! ");
}
///////////////////////////////////////////////////////////////////////////
// HTTP
///////////////////////////////////////////////////////////////////////////
void sendPageHeader(WiFiClient http_client) {
// Display the HTML web page
http_client.println("<!DOCTYPE html><html>");
http_client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
http_client.println("<title>Cat Feeder</title>");
http_client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
http_client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
http_client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
http_client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
http_client.println(".button2 {background-color: #77878A;}</style></head>");
// Web Page Heading
http_client.println("<body><h1>Cat Feeder</h1>");
}
void sendPageFooter(WiFiClient http_client) {
http_client.println("</body></html>");
// The HTTP response ends with another blank line
http_client.println();
}
void handleConnection(WiFiClient http_client) {
// Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (http_client.connected()) { // loop while the client's connected
if (http_client.available()) { // if there's bytes to read from the client,
char c = http_client.read(); // read a byte, then
// Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// turns the GPIOs on and off
if (header.indexOf("GET /feed ") >= 0) {
DEBUG_PRINTLN("Requested Feed");
toFeed++;
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
http_client.println("HTTP/1.1 302 Redirect");
http_client.println("Location: /");
http_client.println("Content-type: text/html");
http_client.println("Connection: close");
http_client.println();
sendPageHeader(http_client);
http_client.println("<p>Feeding</p>");
sendPageFooter(http_client);
// Break out of the while loop
break;
}
if (header.indexOf("GET /reset ") >= 0) {
DEBUG_PRINTLN("Requested Reset");
lastFed = 0;
SPIFFS.remove("/lastFed.txt");
updateLastFed();
totalFed = 0;
SPIFFS.remove("/totalFed.txt");
updateTotalFed();
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
http_client.println("HTTP/1.1 302 Redirect");
http_client.println("Location: /");
http_client.println("Content-type: text/html");
http_client.println("Connection: close");
http_client.println();
sendPageHeader(http_client);
http_client.println("<p>Reset</p>");
sendPageFooter(http_client);
// Break out of the while loop
break;
}
if (header.indexOf("GET /metrics ") >= 0) {
DEBUG_PRINTLN("Requested Metrics");
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
http_client.println("HTTP/1.1 200 OK");
http_client.println("Content-type: text/plain; version=0.0.4");
http_client.println("Connection: close");
http_client.println();
char mbuffer[100];
snprintf(mbuffer, sizeof(mbuffer), "cat_feeder_total_fed{name=\"%s\"} %d", HA_ID, totalFed);
http_client.println(mbuffer);
snprintf(mbuffer, sizeof(mbuffer), "cat_feeder_last_fed{name=\"%s\"} %d", HA_ID, lastFed);
http_client.println(mbuffer);
// Break out of the while loop
break;
}
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
http_client.println("HTTP/1.1 200 OK");
http_client.println("Content-type: text/html");
http_client.println("Connection: close");
http_client.println();
sendPageHeader(http_client);
// Display current state, and FEED button
http_client.println("<p>Total Fed " + String(totalFed) + "</p>");
http_client.println("<p>Last Feed " + formatTime(lastFed) + "</p>");
http_client.println("<p><a href=\"/feed\"><button class=\"button\">FEED</button></a></p>");
sendPageFooter(http_client);
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
http_client.stop();
// Serial.println("Client disconnected.");
// Serial.println("");
}
// Hosted Metrics
void submitMetrics(unsigned int ts) {
// Use WiFiClientSecure class to create TLS connection
WiFiClient client;
DEBUG_PRINT("connecting to ");
DEBUG_PRINTLN(HM_HOST);
// Serial.printf("Using fingerprint '%s'\n", fingerprint);
// client.setFingerprint(fingerprint);
if (!client.connect(HM_HOST, 80)) {
DEBUG_PRINTLN("connection failed");
return;
}
String url = "/metrics";
DEBUG_PRINT("requesting URL: ");
DEBUG_PRINTLN(url);
String body = String("[") +
"{\"name\":\"" + GRAPHITE_PREFIX + "." + HA_ID + ".total_fed\",\"interval\":" + GRAPHITE_INTERVAL + ",\"value\":" + totalFed + ",\"mtype\":\"counter\",\"time\":" + ts + "}" +
"," +
"{\"name\":\"" + GRAPHITE_PREFIX + "." + HA_ID + ".last_fed\",\"interval\":" + GRAPHITE_INTERVAL + ",\"value\":" + lastFed + ",\"mtype\":\"timestamp\",\"time\":" + ts + "}" +
"]";
String request = String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + HM_HOST + "\r\n" +
"Authorization: Basic " + HM_AUTH + "\r\n" +
"User-Agent: CatFeeder\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Connection: close\r\n\r\n" +
body;
DEBUG_PRINTLN(request);
DEBUG_PRINTLN();
client.print(request);
DEBUG_PRINTLN("request sent");
DEBUG_PRINTLN();
while (client.connected() || client.available()) {
if (client.available()) {
String line = client.readStringUntil('\n');
DEBUG_PRINTLN(line);
}
yield();
}
client.stop();
DEBUG_PRINTLN("closing connection");
}
///////////////////////////////////////////////////////////////////////////
// Feeder
///////////////////////////////////////////////////////////////////////////
void feed(int numToFeed) {
int numSegments = 0;
int prevState = digitalRead(PIN_INPUT);
int currState;
updateFeeding(true);
DEBUG_PRINT("Feeding ");
DEBUG_PRINTLN(numToFeed);
mqttPublish("state", (String("{\"state\":\"ON\",\"brightness\":") + (numToFeed * 64) + "}").c_str());
digitalWrite(PIN_OUTPUT, HIGH);
unsigned long startTime = millis();
while (true) {
currState = digitalRead(PIN_INPUT);
if (currState == LOW && prevState == HIGH) {
totalFed++;
numSegments++;
if (numSegments >= numToFeed) {
break;
}
updateTotalFed();
}
/*
Serial.print("Prev ");
Serial.print(prevState);
Serial.print(" Curr ");
Serial.print(currState);
Serial.print(" Num ");
Serial.print(numSegments);
Serial.println();
*/
// if the motor has been running too long without triggering the switch, assume there is a fault
if (millis() - startTime > numToFeed * 1800) {
digitalWrite(PIN_OUTPUT, LOW);
updateError();
DEBUG_PRINTLN("Error");
return;
}
prevState = currState;
delay(10);
}
digitalWrite(PIN_OUTPUT, LOW);
lastFed = timeClient.getEpochTime();
File f = SPIFFS.open("/lastFed.txt", "w");
if (f) {
DEBUG_PRINT("Updating lastFed.txt: ");
DEBUG_PRINTLN(lastFed);
f.print(lastFed);
f.close();
}
f = SPIFFS.open("/totalFed.txt", "w");
if (f) {
DEBUG_PRINT("Updating totalFed.txt: ");
DEBUG_PRINTLN(totalFed);
f.print(totalFed);
f.close();
}
redrawScreen();
DEBUG_PRINT("Fed ");
DEBUG_PRINTLN(numSegments);
mqttPublish("state", "{\"state\":\"OFF\"}");
}
///////////////////////////////////////////////////////////////////////////
// Setup
///////////////////////////////////////////////////////////////////////////
void setup() {
pinMode(PIN_INPUT, INPUT_PULLUP); // enable internal pullup
pinMode(PIN_OUTPUT, OUTPUT);
digitalWrite(PIN_OUTPUT, LOW);
delay(100);
Serial.begin(74880);
#if defined(DEBUG_TELNET)
telnetServer.begin();
telnetServer.setNoDelay(true);
#endif
DEBUG_PRINTLN("Cat Feeder 0.1");
DEBUG_PRINTLN();
initScreen("Starting...");
yield();
setupWiFi();
#if defined(OTA)
setupOTA();
#endif
yield();
// Initialize a NTPClient to get time
timeClient.begin();
// update time
if (!timeClient.update()) {
yield();
timeClient.forceUpdate();
}
yield();
webServer.begin();
yield();
mqttClient.setServer(MQTT_SERVER, 1883);
mqttClient.setCallback(mqttCallback);
yield();
SPIFFS.begin();
yield();
File f;
f = SPIFFS.open("/lastFed.txt", "r");
if (f) {
DEBUG_PRINT("Reading lastFed.txt: ");
lastFed = (unsigned long)f.parseFloat();
f.close();
DEBUG_PRINTLN(lastFed);
}
yield();
f = SPIFFS.open("/totalFed.txt", "r");
if (f) {
DEBUG_PRINT("Reading totalFed.txt: ");
totalFed = (unsigned int)f.parseInt();
f.close();
DEBUG_PRINTLN(totalFed);
}
yield();
redrawScreen();
}
///////////////////////////////////////////////////////////////////////////
// Loop
///////////////////////////////////////////////////////////////////////////
void loop() {
#if defined(OTA)
handleOTA();
yield();
#endif
#if defined(DEBUG_TELNET)
// handle the Telnet connection
handleTelnet();
yield();
#endif
// Handle web requests
WiFiClient http_client = webServer.available();
if (http_client) {
handleConnection(http_client);
}
yield();
// handle mqtt
if (!mqttClient.connected()) {
mqttReconnect();
}
yield();
if (mqttClient.connected()) {
mqttClient.loop();
}
yield();
// update time
if (!timeClient.update()) {
yield();
timeClient.forceUpdate();
}
yield();
// update screen
if (millis() / 1000 > lastScreenUpdate / 1000) {
lastScreenUpdate = millis();
redrawScreen();
}
yield();
#if defined(GRAPHITE)
unsigned long currTime = timeClient.getEpochTime();
if (currTime / GRAPHITE_INTERVAL > lastGraphiteUpdate / GRAPHITE_INTERVAL) {
graphiteUDP.beginPacket(GRAPHITE_HOST, GRAPHITE_PORT);
char msgBuffer[100];
snprintf(msgBuffer, sizeof(msgBuffer), "%s.%s.%s %d %d\n", GRAPHITE_PREFIX, HA_ID, "total_fed", totalFed, currTime);
graphiteUDP.write(msgBuffer);
snprintf(msgBuffer, sizeof(msgBuffer), "%s.%s.%s %d %d\n", GRAPHITE_PREFIX, HA_ID, "last_fed", lastFed, currTime);
graphiteUDP.write(msgBuffer);
graphiteUDP.endPacket();
yield();
submitMetrics(currTime - currTime % GRAPHITE_INTERVAL);
lastGraphiteUpdate = currTime;
}
#endif
// feed cat
if (toFeed > 0) {
feed(toFeed);
toFeed = 0;
}
delay(10);
}