//PSI3542-2024 ATIVIDADE 5.1 THERMOSTAT
#include <WiFi.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN 15
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
#define SECRET_MQTT_USERNAME "HCU0DhsCMxQYLQk7MgYGAwg"
#define SECRET_MQTT_CLIENT_ID "HCU0DhsCMxQYLQk7MgYGAwg"
#define SECRET_MQTT_PASSWORD "pBYVBwqYr4XMcVzW247qES40"
DHT dht(DHTPIN, DHTTYPE);
const char* mqtt_server = "mqtt3.thingspeak.com";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
float temp = 0;
float hum = 0;
int value = 0;
float toffset;
float hist = 1;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived topic=[");
Serial.print(topic);
Serial.print("] ");
Serial.print("length=[");
Serial.print(length);
Serial.print("] ");
Serial.print("payload=[");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("] ");
if (strcmp(topic, "channels/2658533/subscribe/fields/field3") == 0) {
Serial.print("power=");
Serial.println((char)payload[0]);
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(2, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(2, HIGH); // Turn the LED off by making the voltage HIGH
}
}
else if (strcmp(topic, "channels/2658533/subscribe/fields/field4") == 0){
toffset = atof((char *)payload);
Serial.print("temperature offset=");
Serial.println(toffset);
}
}
void reconnect() {
//Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(SECRET_MQTT_CLIENT_ID, SECRET_MQTT_USERNAME, SECRET_MQTT_PASSWORD)) {
Serial.println("Connected");
// Once connected, publish an announcement...
// ... and resubscribe
client.subscribe("channels/2658533/subscribe/fields/field3");
client.subscribe("channels/2658533/subscribe/fields/field4");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void temperature_control(float t){
if (t >= (toffset + hist)){
digitalWrite(2, LOW);
}
else if(t <= (toffset - hist)){
digitalWrite(2, HIGH);
}
}
void setup() {
pinMode(2, OUTPUT); // Initialize the BUILTIN_LED pin as an output
dht.begin();
Serial.begin(115200);
// ATIVIDADE 6
//WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wm;
// reset settings - wipe stored credentials for testing
// these are stored by the esp library
// wm.resetSettings();
// Automatically connect using saved credentials,
// if connection fails, it starts an access point with the specified name ( "AutoConnectAP"),
// if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect())
// then goes into a blocking loop awaiting configuration and will return success result
bool res;
// res = wm.autoConnect(); // auto generated AP name from chipid
// res = wm.autoConnect("AutoConnectAP"); // anonymous ap
res = wm.autoConnect("AP-15471290","password"); // password protected ap
if(!res) {
Serial.println("Failed to connect");
// ESP.restart();
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
// FIM DA ATIVIDADE 6
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (!client.connected()) {
reconnect();
}
unsigned long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
String temp = String(temperature, 2);
String hum = String(humidity, 1);
// Prepare data string for ThingSpeak
String data = "field1=" + temp + "&field2=" + hum + "&status=MQTTPUBLISH";
Serial.println(data);
char dataChar[100];
data.toCharArray(dataChar, 100);
client.publish("channels/2658533/publish", dataChar);
temperature_control(temperature);
}
client.loop();
}