#include <WiFi.h> /* Header para uso das funcionalidades de wi-fi do ESP32 */
#include <PubSubClient.h> /* Header para uso da biblioteca PubSubClient */
#include <ESP32Servo.h>
#include "DHTesp.h"
#include "Secrets.h"
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#define LED1_PIN 15
#define SERVO_PIN 23
#define DHT_PIN 13 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
#define BUTTONUP_PIN 14
#define BUTTONDN_PIN 12
#define BUTTONLED1_PIN 22
#define ID_MQTT "fiaptst0_Cliente_MQTT"
#define TOPSUB_L1_CTRL "fiaptst/home00/luz1_ctrl"
#define TOPSUB_MOT1_CTRL "fiaptst/home00/mot1_ctrl"
#define TOPPUB_L1_STS "fiaptst/home00/luz1_sts"
#define TOPPUB_MOT1_STS "fiaptst/home00/mot1_sts"
#define TOPPUB_TEMP1 "fiaptst/home00/temperatura"
#define TOPPUB_UMID1 "fiaptst/home00/umidade"
float humidity, temperature;
int pos = 0; // variable to store the servo position
int but_up_ant; // the previous state of button
int but_up_sts; // the current state of button
int but_dn_ant; // the previous state of button
int but_dn_sts; // the current state of button
int but_led1_ant; // the previous state of button
int but_led1_sts; // the current state of buttonString rcvmsg;
bool led1_sts;
String led1_status;
String rcvmsg;
String rcvtopic;
DHTesp mydht;
Servo myservo;
WiFiClientSecure net = WiFiClientSecure();
PubSubClient client(net);
//===================================================================
void connectAWS()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.println("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
// Configure WiFiClientSecure to use the AWS IoT device credentials
net.setCACert(AWS_CERT_CA);
net.setCertificate(AWS_CERT_CRT);
net.setPrivateKey(AWS_CERT_PRIVATE);
// Connect to the MQTT broker on the AWS endpoint we defined earlier
client.setServer(AWS_IOT_ENDPOINT, 8883);
// Create a message handler
client.setCallback(messageHandler);
Serial.println("Connecting to AWS IOT");
while (!client.connect(THINGNAME))
{
Serial.print(".");
delay(100);
}
if (!client.connected())
{
Serial.println("AWS IoT Timeout!");
return;
}
// Subscribe to a topic
//client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC);
client.subscribe(TOPSUB_L1_CTRL);
client.subscribe(TOPSUB_MOT1_CTRL);
Serial.println("AWS IoT Connected!");
}
//===================================================================
void publishMessage()
{
StaticJsonDocument<200> doc_t;
doc_t["temperature"] = temperature;
char jsonBuffer_t[512];
serializeJson(doc_t, jsonBuffer_t); // print to client
client.publish(TOPPUB_TEMP1, jsonBuffer_t);
StaticJsonDocument<200> doc_h;
doc_h["humidity"] = humidity;
char jsonBuffer_h[512];
serializeJson(doc_h, jsonBuffer_h); // print to client
client.publish(TOPPUB_UMID1, jsonBuffer_h);
StaticJsonDocument<200> doc_l;
doc_l["led1"] = led1_status;
char jsonBuffer_l[512];
serializeJson(doc_l, jsonBuffer_l); // print to client
client.publish(TOPPUB_L1_STS, jsonBuffer_l);
StaticJsonDocument<200> doc_m;
doc_m["posmot"] = String(pos);
char jsonBuffer_m[512];
serializeJson(doc_m, jsonBuffer_m); // print to client
client.publish(TOPPUB_MOT1_STS, jsonBuffer_m);
}
//void publishMessage()
//{
// StaticJsonDocument<200> doc;
// doc["humidity"] = h;
// doc["temperature"] = t;
// doc["motpos"] = String(pos);
// doc["led1"] = led1_status;
// char jsonBuffer[512];
// serializeJson(doc, jsonBuffer); // print to client
//
// client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer);
//}
//===================================================================
void messageHandler(char* topic, byte* payload, unsigned int length)
{
Serial.print("incoming: ");
Serial.println(topic);
StaticJsonDocument<200> doc;
deserializeJson(doc, payload);
const char* message = doc["message"];
Serial.println(message);
rcvtopic = topic;
rcvmsg = message;
}
//===================================================================
void setup()
{
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(LED1_PIN, OUTPUT);
pinMode(BUTTONUP_PIN, INPUT_PULLUP);
pinMode(BUTTONDN_PIN, INPUT_PULLUP);
pinMode(BUTTONLED1_PIN, INPUT_PULLUP);
but_up_sts = digitalRead(BUTTONUP_PIN); // read new state
but_dn_sts = digitalRead(BUTTONDN_PIN); // read new state
but_led1_sts = digitalRead(BUTTONLED1_PIN); // read new state
myservo.attach(SERVO_PIN); // attaches the servo
mydht.setup(DHT_PIN, DHTesp::DHT22);
myservo.write(pos); // movimenta motor para posicao inicial
delay(10);
Serial.print("Conectando-se na rede");
Serial.println("Aguarde...");
connectAWS();
}
//===================================================================
void loop()
{
if(rcvtopic == "fiaptst/home00/luz1_ctrl" )
{
if (rcvmsg == "1") { // comando de acender
if (led1_sts == false) { // se led1 apagado
led1_sts = !led1_sts; // inverte status para acender
digitalWrite(LED1_PIN, led1_sts); // acende led1
}
}
else { // comando de apagar (qqer dif "1")
if (led1_sts == true) { // se led1 aceso
led1_sts = !led1_sts; // inverte statua para apagar
digitalWrite(LED1_PIN, led1_sts); // apaga led1
}
}
}
if(rcvtopic == "fiaptst/home00/mot1_ctrl" ) {
if ((rcvmsg == "0" ||
rcvmsg == "30" ||
rcvmsg == "45" ||
rcvmsg == "90" ||
rcvmsg == "120" ||
rcvmsg == "150" ||
rcvmsg == "180") &&
(rcvmsg != String(pos))) {
pos = rcvmsg.toInt(); // aceita o que foi recebido como nova posicao
myservo.write(pos); // movimenta o motor para a posicao 'pos'
delay(100); // aguarda 15ms para movimento do motor
}
}
rcvmsg = "";
rcvtopic = "";
//Le todos botoes ---------------------------------------------
but_up_ant = but_up_sts; // save the last state
but_up_sts = digitalRead(BUTTONUP_PIN); // read new state
but_dn_ant = but_dn_sts; // save the last state
but_dn_sts = digitalRead(BUTTONDN_PIN); // read new state
but_led1_ant = but_led1_sts; // save the last state
but_led1_sts = digitalRead(BUTTONLED1_PIN); // read new state
//-------------------------------------------------------------
// verifica botao UP
if(but_up_ant == HIGH && but_up_sts == LOW) {
Serial.println("The UP-button is pressed");
if (pos > 0) { // nao sobe se posicao atual ja eh 0 graus
pos = pos - 30; // nova posicao = posicao atual - 30 graus
myservo.write(pos); // movimenta motor para nova posicao
delay(50); // aguarda 50ms para movimento do motor
}
}
// verifica botao DOWN
if(but_dn_ant == HIGH && but_dn_sts == LOW) {
Serial.println("The DN-button is pressed");
if (pos < 180) { // nao desce se posicao atual ja eh 180 graus
pos = pos + 30; // nova posicao = posicao atual + 30 graus
myservo.write(pos); // movimenta motor para nova posicao
delay(50); // aguarda 50ms para movimento do motor
}
}
// verifica botao LED1
if(but_led1_ant == HIGH && but_led1_sts == LOW) {
Serial.println("The button 1L is pressed");
// toggle state of LED
led1_sts = !led1_sts;
// control LED arccoding to the toggled state
digitalWrite(LED1_PIN, led1_sts);
delay(10);
}
TempAndHumidity data = mydht.getTempAndHumidity();
humidity = data.humidity;
temperature = data.temperature;
Serial.println("Temp: " + String(temperature, 2) + "°C" +
" - Humidity: " + String(humidity, 1) + "%"
" - LedStatus: " + String(led1_sts) +
" - Pos_Motor: " + String(pos));
if(led1_sts) {
led1_status = "1";
}
else{
led1_status = "0";
}
publishMessage();
client.loop();
delay(1000); //* Agurda 1 segundo para próximo envio */
}