#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "PubSubClient.h"
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
#include <ArduinoJson.h>
#define wifi_ssid "Wokwi-GUEST"
#define wifi_senha ""
const char *mqtt_servidor = "ac15cc038fc44e1d89ea8ff01708c3bd.s1.eu.hivemq.cloud";
const int mqtt_porta = 8883;
const char *mqtt_usuario = "hivemq.webclient.1763425147712";
const char *mqtt_senha = "L4v#lKDrQ08<1S&gEo,m";
const char *topico = "monitoreo/puerta-acceso1332";
const char *topico_log = "monitoreo/puerta-acceso1332/log";
// Formato do documento JSON:
// { "bloquear": "f", "desbloquear": "f", "abrir": "f", "senha": "123456" }
DynamicJsonDocument json_doc(128);
WiFiClientSecure clienteEsp;
PubSubClient cliente(clienteEsp);
#define NUM_LIN 4
#define NUM_COL 4
#define LIB 14
#define NEG 12
char teclas[NUM_LIN][NUM_COL] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte pinos_lin[NUM_LIN] = {19, 18, 5, 17};
byte pinos_col[NUM_COL] = {16, 4, 0, 2};
Servo servo;
Keypad teclado = Keypad(makeKeymap(teclas), pinos_lin, pinos_col, NUM_LIN, NUM_COL);
LiquidCrystal_I2C lcd(0x27, 16, 2);
String senha;
String chave = "246802";
int cursor = 7;
boolean inicio = true;
boolean bloquear_teclado = false;
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
pinMode(LIB, OUTPUT);
pinMode(NEG, OUTPUT);
servo.attach(13);
setup_wifi();
clienteEsp.setInsecure();
cliente.setServer(mqtt_servidor, mqtt_porta);
cliente.setCallback(callback_mqtt);
delay(2000);
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Conectando a ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_senha);
// Aguardar a conexão
int tentar = 0;
while (WiFi.status() != WL_CONNECTED && tentar < 40) {
delay(500);
Serial.print(".");
tentar++;
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println("\nFalha na conexão ao Wi-Fi");
while (1) {
delay(1000);
}
}
Serial.println("\nConectado. IP: ");
Serial.println(WiFi.localIP());
}
void conectar_mqtt() {
while (!cliente.connected()) {
if (cliente.connect("ClaudioESP32", mqtt_usuario, mqtt_senha)) {
Serial.println("MQTT: Conectado");
cliente.subscribe(topico);
}
else {
Serial.print("Erro MQTT: ");
Serial.println(cliente.state());
delay(2000);
}
}
}
void callback_mqtt(char* topico, byte* payload, unsigned int length) {
char mensagem[length];
Serial.print("MQTT: Recebido: ");
Serial.print("Mensagem: ");
for (int i = 0; i < length; i++) {
mensagem[i] = (char) payload[i];
Serial.print(mensagem[i]);
}
Serial.println();
DeserializationError erro = deserializeJson(json_doc, mensagem);
if (erro) {
Serial.print("Erro JSON: ");
Serial.println(erro.f_str());
}
else {
// Implementar as 4 funcionalidades solicitadas na atividade.
const char *bloquear = json_doc["bloquear"];
if (String (bloquear) == "v") {
bloquear_teclado = true;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("** Bloqueado **");
digitalWrite(NEG, HIGH);
}
//if ...
//if ...
const char *nova_senha = json_doc["senha"];
if (String(nova_senha) != "") {
Serial.print("Nova senha:");
Serial.println(nova_senha);
chave = String(nova_senha);
}
}
}
void publicar_mqtt(String acesso, String senha_usada) {
// Implementação da etapa 6.
Serial.println("MQTT: Enviando");
String conteudo = acesso + ", " + senha_usada;
cliente.publish(topico_log, conteudo.c_str(), true);
cliente.disconnect();
}
void reset() {
delay(3000);
inicio = true;
digitalWrite(NEG, LOW);
digitalWrite(LIB, LOW);
servo.write(0);
senha = "";
cursor = 7;
}
void loop() {
conectar_mqtt();
cliente.loop(); // Monitoramento do callback
if (inicio) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Bem-vindo!");
lcd.setCursor(0, 1);
lcd.print("Senha:");
inicio = false;
}
if (!bloquear_teclado) {
char tecla = teclado.getKey();
if (tecla) { // Se houve tecla pressionada
senha += tecla;
lcd.setCursor(cursor, 1);
lcd.print(tecla);
cursor++;
if (cursor == 13) { // Terminou de digitar a senha de 6 dígitos
if (senha == chave) {
publicar_mqtt("Acesso liberado", senha);
digitalWrite(LIB, HIGH);
digitalWrite(NEG, LOW);
servo.write(180);
reset();
}
else {
publicar_mqtt("Acesso negado", senha);
digitalWrite(LIB, LOW);
digitalWrite(NEG, HIGH);
servo.write(0);
reset();
}
}
}
}
}