#include <DHTesp.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
// ======================================================
// CONFIGURAÇÃO WI-FI
// ======================================================
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
// ======================================================
// ENDEREÇO DO DJANGO
// ======================================================
const char* SERVIDOR_DJANGO =
"https://cooling-relocation-gage-optimum.trycloudflare.com/api/dados/";
// ======================================================
// PINOS
// ======================================================
const int DHT_PIN = 15;
const int LED_VERDE = 2;
const int LED_VERMELHO = 4;
const int BUZZER = 5;
const int BOTAO_PORTA = 18;
// ======================================================
// SENSOR
// ======================================================
DHTesp dht;
// ======================================================
// ESTADO DA PORTA
// ======================================================
bool portaAberta = false;
int estadoBotaoAnterior = HIGH;
// ======================================================
// CONTROLO DO TEMPO DA PORTA
// ======================================================
unsigned long tempoInicioPorta = 0;
const unsigned long TEMPO_ALERTA_PORTA = 10000;
// ======================================================
// TEMPORIZADOR DE ENVIO
// ======================================================
unsigned long ultimoEnvio = 0;
const unsigned long INTERVALO_ENVIO = 5000;
// ======================================================
// CONECTAR AO WI-FI
// ======================================================
void conectarWiFi() {
Serial.println();
Serial.println("A ligar ao Wi-Fi...");
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD,
6
);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Wi-Fi ligado!");
Serial.print("Endereco IP: ");
Serial.println(
WiFi.localIP()
);
Serial.println(
"------------------------------"
);
}
// ======================================================
// ENVIAR DADOS PARA DJANGO
// ======================================================
void enviarDados(
float temperatura,
float humidade,
bool porta,
unsigned long tempoPorta,
String estado,
bool alertaTemperatura,
bool alertaPorta
) {
// ----------------------------------------------------
// VERIFICAR WI-FI
// ----------------------------------------------------
if (WiFi.status() != WL_CONNECTED) {
Serial.println(
"Wi-Fi nao esta ligado."
);
return;
}
// ----------------------------------------------------
// CLIENTE HTTPS
// ----------------------------------------------------
WiFiClientSecure clienteSeguro;
// Para ambiente de demonstração/Wokwi.
// Não valida o certificado HTTPS.
clienteSeguro.setInsecure();
// ----------------------------------------------------
// CLIENTE HTTP
// ----------------------------------------------------
HTTPClient http;
Serial.println();
Serial.println(
"A ligar ao Django..."
);
Serial.println(
SERVIDOR_DJANGO
);
// ----------------------------------------------------
// INICIAR CONEXÃO
// ----------------------------------------------------
if (!http.begin(
clienteSeguro,
SERVIDOR_DJANGO
)) {
Serial.println(
"Erro ao iniciar conexao HTTPS."
);
return;
}
// ----------------------------------------------------
// CONFIGURAÇÕES HTTP
// ----------------------------------------------------
http.addHeader(
"Content-Type",
"application/json"
);
http.setTimeout(10000);
// ----------------------------------------------------
// CRIAR JSON
// ----------------------------------------------------
StaticJsonDocument<400> documento;
documento["temperatura"] =
temperatura;
documento["humidade"] =
humidade;
documento["porta_aberta"] =
porta;
documento["tempo_porta_aberta"] =
tempoPorta / 1000;
documento["estado"] =
estado;
documento["alerta_temperatura"] =
alertaTemperatura;
documento["alerta_porta"] =
alertaPorta;
// ----------------------------------------------------
// CONVERTER JSON PARA TEXTO
// ----------------------------------------------------
String json;
serializeJson(
documento,
json
);
// ----------------------------------------------------
// MOSTRAR DADOS
// ----------------------------------------------------
Serial.println();
Serial.println(
"A enviar dados para Django..."
);
Serial.println(
json
);
// ----------------------------------------------------
// FAZER POST
// ----------------------------------------------------
int codigoResposta =
http.POST(json);
// ----------------------------------------------------
// VERIFICAR RESPOSTA
// ----------------------------------------------------
if (codigoResposta > 0) {
Serial.print(
"Codigo HTTP: "
);
Serial.println(
codigoResposta
);
String resposta =
http.getString();
Serial.print(
"Resposta Django: "
);
Serial.println(
resposta
);
} else {
Serial.print(
"Erro no envio: "
);
Serial.println(
http.errorToString(
codigoResposta
)
);
}
// ----------------------------------------------------
// ENCERRAR CONEXÃO
// ----------------------------------------------------
http.end();
Serial.println(
"------------------------------"
);
}
// ======================================================
// SETUP
// ======================================================
void setup() {
Serial.begin(115200);
// ----------------------------------------------------
// DHT22
// ----------------------------------------------------
dht.setup(
DHT_PIN,
DHTesp::DHT22
);
// ----------------------------------------------------
// LEDs
// ----------------------------------------------------
pinMode(
LED_VERDE,
OUTPUT
);
pinMode(
LED_VERMELHO,
OUTPUT
);
// ----------------------------------------------------
// BUZZER
// ----------------------------------------------------
pinMode(
BUZZER,
OUTPUT
);
// ----------------------------------------------------
// BOTÃO
// ----------------------------------------------------
pinMode(
BOTAO_PORTA,
INPUT_PULLUP
);
// ----------------------------------------------------
// ESTADO INICIAL
// ----------------------------------------------------
digitalWrite(
LED_VERDE,
LOW
);
digitalWrite(
LED_VERMELHO,
LOW
);
noTone(
BUZZER
);
// ----------------------------------------------------
// MENSAGEM INICIAL
// ----------------------------------------------------
Serial.println(
"=============================="
);
Serial.println(
" SISTEMA IoT DE SAUDE PUBLICA "
);
Serial.println(
" MONITORIZACAO CADEIA DE FRIO "
);
Serial.println(
"=============================="
);
// ----------------------------------------------------
// WI-FI
// ----------------------------------------------------
conectarWiFi();
}
// ======================================================
// LOOP
// ======================================================
void loop() {
// ====================================================
// VERIFICAR WI-FI
// ====================================================
if (
WiFi.status() != WL_CONNECTED
) {
conectarWiFi();
}
// ====================================================
// LER BOTÃO DA PORTA
// ====================================================
int estadoBotao =
digitalRead(
BOTAO_PORTA
);
if (
estadoBotao == LOW &&
estadoBotaoAnterior == HIGH
) {
portaAberta =
!portaAberta;
if (portaAberta) {
tempoInicioPorta =
millis();
Serial.println();
Serial.println(
">>> PORTA ABERTA <<<"
);
} else {
tempoInicioPorta = 0;
Serial.println();
Serial.println(
">>> PORTA FECHADA <<<"
);
}
delay(200);
}
estadoBotaoAnterior =
estadoBotao;
// ====================================================
// LER DHT22
// ====================================================
TempAndHumidity dados =
dht.getTempAndHumidity();
float temperatura =
dados.temperature;
float humidade =
dados.humidity;
// ====================================================
// TEMPO DA PORTA
// ====================================================
unsigned long tempoAberta = 0;
if (portaAberta) {
tempoAberta =
millis() -
tempoInicioPorta;
}
// ====================================================
// DETERMINAR ALERTA DE TEMPERATURA
// ====================================================
bool alertaTemperatura =
false;
bool alertaPorta =
false;
if (
temperatura > 8
) {
alertaTemperatura =
true;
}
// ====================================================
// DETERMINAR ALERTA DA PORTA
// ====================================================
if (
portaAberta &&
tempoAberta >=
TEMPO_ALERTA_PORTA
) {
alertaPorta =
true;
}
// ====================================================
// DETERMINAR ESTADO
// ====================================================
String estadoSistema =
"NORMAL";
// ----------------------------------------------------
// CRÍTICO
// ----------------------------------------------------
if (
alertaTemperatura ||
alertaPorta
) {
estadoSistema =
"CRITICO";
digitalWrite(
LED_VERDE,
LOW
);
digitalWrite(
LED_VERMELHO,
HIGH
);
tone(
BUZZER,
1000
);
}
// ----------------------------------------------------
// ATENÇÃO
// ----------------------------------------------------
else if (
temperatura > 7 ||
portaAberta
) {
estadoSistema =
"ATENCAO";
digitalWrite(
LED_VERDE,
LOW
);
digitalWrite(
LED_VERMELHO,
HIGH
);
noTone(
BUZZER
);
}
// ----------------------------------------------------
// NORMAL
// ----------------------------------------------------
else {
estadoSistema =
"NORMAL";
digitalWrite(
LED_VERDE,
HIGH
);
digitalWrite(
LED_VERMELHO,
LOW
);
noTone(
BUZZER
);
}
// ====================================================
// MOSTRAR TEMPERATURA
// ====================================================
Serial.println();
Serial.print(
"Temperatura: "
);
Serial.print(
temperatura,
1
);
Serial.println(
" °C"
);
// ====================================================
// MOSTRAR HUMIDADE
// ====================================================
Serial.print(
"Humidade: "
);
Serial.print(
humidade,
1
);
Serial.println(
" %"
);
// ====================================================
// MOSTRAR PORTA
// ====================================================
if (portaAberta) {
Serial.print(
"Porta: ABERTA | "
);
Serial.print(
tempoAberta / 1000
);
Serial.println(
" segundos"
);
} else {
Serial.println(
"Porta: FECHADA"
);
}
// ====================================================
// MOSTRAR ESTADO
// ====================================================
Serial.print(
"Estado: "
);
Serial.println(
estadoSistema
);
// ====================================================
// ENVIAR PARA DJANGO
// ====================================================
if (
millis() - ultimoEnvio >=
INTERVALO_ENVIO
) {
ultimoEnvio =
millis();
enviarDados(
temperatura,
humidade,
portaAberta,
tempoAberta,
estadoSistema,
alertaTemperatura,
alertaPorta
);
}
// ====================================================
// SEPARADOR
// ====================================================
Serial.println(
"=============================="
);
delay(500);
}