#include <RTClib.h> // Define RTC_DS1307 and DateTime
#include "my_lcd.h"
#include "my_wifi.h"
#include "PsychicMqttClient.h"
#include <DHT.h>
MyLCD lcd;
DHT dht(32, DHT22);
RTC_DS1307 rtc;
MyWiFi wifi;
PsychicMqttClient mqttClient;
bool topicInited = false;
const char *tbHost = "mqtt://mqtt.eu.thingsboard.cloud:1883";
const char *tbuser = "hello6460";
const char *tbpass = "world";
void serialize(char *telemetry, const char *humd, const char *temp) {
String payload = "{";
payload += "\"humidity\":";
payload += humd;
payload += ",";
payload += "\"temperature\":";
payload += temp;
payload += "}";
payload.toCharArray(telemetry, 256);
return;
}
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);
dht.begin();
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() {
float h = dht.readHumidity(); // Relative humidity
float c = dht.readTemperature(); // Celsius
char h_sz[8];
char c_sz[8];
char telemtry[256];
if (isnan(h) || isnan(c)) {
Serial.println(F("Failed to read from DHT sensor!"));
}
else {
dtostrf(h, 5, 1, h_sz); // Width 5, 1 dp
dtostrf(c, 5, 1, c_sz); // Width 5, 1 dp
serialize(telemtry, h_sz, c_sz);
}
if (wifi.isTimeSynched()) { // Connected and time synched
if (!topicInited) {
mqttClient.setCredentials(tbuser, tbpass);
mqttClient.setServer(tbHost);
Serial.printf("Set MQTT = %s\r\n", tbHost);
// if (subscribe_topics())
topicInited = true;
}
if (!mqttClient.connected()) {
Serial.printf("Connect to %s\r\n", tbHost);
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);
lcd.alarm(1, "Temp:", c_sz, 0);
lcd.alarm(2, "Humd:", h_sz, 0);
delay(2000);
mqttClient.publish("v1/devices/me/telemetry", 2, 1, telemtry);
}
LCD (20x4) (I2C)
DS1307 RTC