#include <RTClib.h> // Define RTC_DS1307 and DateTime
#include "my_lcd.h"
#include "my_wifi.h"
#include "PsychicMqttClient.h"
MyLCD lcd;
RTC_DS1307 rtc;
MyWiFi wifi;
PsychicMqttClient mqttClient;
bool topicInited = false;
const char MQTTserver[] = "mqtt://mqtt-dashboard.com";
void mqttNgeeAnnLED1(
const char *topic,
const char *payload,
int retain,
int qos,
bool dup
) {
Serial.printf("Received Topic: %s\r\n", topic);
Serial.printf("Received Payload: %s\r\n", payload);
Serial.printf("Received retain: %d\r\n", retain);
Serial.printf("Received qos: %d\r\n", qos);
Serial.printf("Receoved dup: %d\r\n", dup);
}
void mqttNgeeAnnLED2(
const char *topic,
const char *payload,
int retain,
int qos,
bool dup
) {
Serial.printf("Received Topic: %s\r\n", topic);
Serial.printf("Received Payload: %s\r\n", payload);
Serial.printf("Received retain: %d\r\n", retain);
Serial.printf("Received qos: %d\r\n", qos);
Serial.printf("Receoved dup: %d\r\n", dup);
}
bool subscribe_topics() {
Serial.printf("Subscribing to: %s\r\n", "NgeeAnn/LED1");
mqttClient.onTopic("NgeeAnn/LED1", 1, mqttNgeeAnnLED1);
Serial.printf("Subscribing to: %s\r\n", "NgeeAnn/LED2");
mqttClient.onTopic("NgeeAnn/LED2", 2, mqttNgeeAnnLED2);
return true;
}
void setup() {
Serial.begin(115200);
lcd.begin();
if (!rtc.begin()) { // Time is critial
Serial.println(F("Error: RTC not found!"));
lcd.print("RTC not found!");
while (1); // Halt if RTC fails
}
wifi.begin(&rtc);
}
void loop() {
if (wifi.isTimeSynched()) { // Connected and time synched
if (!topicInited) {
mqttClient.setServer(MQTTserver);
Serial.printf("Set MQTT = %s\r\n", MQTTserver);
if (subscribe_topics())
topicInited = true;
}
if (!mqttClient.connected()) {
Serial.printf("Connect to %s\r\n", MQTTserver);
mqttClient.connect();
}
}
lcd.display("ESP32-DevKitC-v4", "Hello, World!", "Ngee Ann Poly");
delay(2000);
lcd.clear();
DateTime now = rtc.now(); char dtbuf[21] = "YYYY-MM-DD hh:mm:ss";
now.toString(dtbuf); lcd.datetime(dtbuf);
if (wifi.isTimeSynched()) {
lcd.alarm(1, "Temp UL1:", "40.6", 0);
lcd.alarm(2, "Curr UL2:", "60.0", "A");
}
delay(2000);
mqttClient.publish("NgeeAnn/Temp", 2, 1, "40.6");
mqttClient.publish("NgeeAnn/Curr", 1, 1, "60.6");
}
LCD (20x4) (I2C)
DS1307 RTC