#include <Arduino.h>
#include <FS.h>
#include <EEPROM.h>
#include <LittleFS.h>
#define SPIFFS LittleFS
// Importando Librerias para el Servidor
#include <WiFi.h>
#include <AsyncTCP.h>
#include <WiFiMulti.h>
// Importando Librerias para el Socket IO
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <WebSocketsClient.h>
#include <SocketIOclient.h>
#include <ArduinoJson.h>
// Importando Librerias para la Pantalla
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SH110X.h>
//#include <BluetoothSerial.h>
const unsigned char logo_icono [] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xc7, 0xf1, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0x03, 0xe0, 0x7f, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xfc, 0x03, 0xe0, 0x0f, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xe0, 0x01, 0xc0, 0x03, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0x80, 0x00, 0x80, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7f, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x01, 0xc3, 0x80, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0x80, 0x00, 0x03, 0xe3, 0x80, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0x80, 0x00, 0x06, 0x33, 0x80, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0xc0, 0x00, 0x0c, 0x1f, 0x80, 0x01, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0xc0, 0x00, 0x18, 0x0f, 0x80, 0x01, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0xc0, 0x00, 0x71, 0xc7, 0x80, 0x01, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0xc0, 0x00, 0xe3, 0xe3, 0x80, 0x01, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0f, 0xe0, 0x01, 0x87, 0xf0, 0xc0, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0f, 0xe0, 0x03, 0x0f, 0xf8, 0x60, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0f, 0xe0, 0x06, 0x3f, 0xfe, 0x30, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0xf0, 0x0c, 0x7f, 0xff, 0x18, 0x07, 0xf0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0xf0, 0x00, 0xff, 0xff, 0x80, 0x07, 0xf0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0xf0, 0x00, 0xff, 0xff, 0x80, 0x07, 0xf0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0xf8, 0x00, 0xff, 0xff, 0x80, 0x0f, 0xe0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0xf8, 0x00, 0xfc, 0x1f, 0x80, 0x0f, 0xe0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0xfc, 0x00, 0xfc, 0x1f, 0x80, 0x1f, 0xe0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0xfc, 0x00, 0xfc, 0x1f, 0x80, 0x1f, 0xc0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x00, 0xfc, 0x1f, 0x80, 0x3f, 0xc0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0xfc, 0x1f, 0x80, 0x3f, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xfc, 0x1f, 0x80, 0x7f, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xc0, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x01, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xe0, 0x00, 0x00, 0x03, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xf0, 0x00, 0x00, 0x07, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xf8, 0x00, 0x00, 0x0f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xfc, 0x00, 0x80, 0x1f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xfe, 0x00, 0xc0, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0x01, 0xc0, 0x7f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0x83, 0xe0, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xc3, 0xf1, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xf7, 0xf7, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
#define SHORT_PRESS_TIME 500
const bool Reset_PIN = true;
byte lastStateRT = LOW;
byte currentStateRT;
uint64_t pressedTimeRT = 0;
uint64_t releasedTimeRT = 0;
byte lastStateOP = LOW;
byte currentStateOP;
uint64_t pressedTimeOP = 0;
uint64_t releasedTimeOP = 0;
bool bluetoothActivado = false;
byte lastStateBT = LOW;
byte currentStateBT;
uint64_t pressedTimeBT = 0;
uint64_t releasedTimeBT = 0;
byte _WifiMode = 0; // 1 - Access Point ( Configuration ) | 2 - Station
String _SSID = "";
String _PASS = "";
String _SERVER = "";
String _PORT = "";
String _MAC = "";
byte _startINI = 0;
#define DISPLAY_WIDTH 128 // OLED display Ancho PX
#define DISPLAY_HEIGHT 64 // OLED display Alto PX
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define I2C_ADDRESS 0x3C // Adafruit OLED's Address: 0x3D for 128x64, 0x3C for 128x32 (0x3C Typically eBay OLED's 64)
Adafruit_SH1106G DisplayOLED = Adafruit_SH1106G(DISPLAY_WIDTH, DISPLAY_HEIGHT, &Wire, OLED_RESET);
/* ESP32-Wroom DevkitV1
* Pinout <--> Definitions
*/
const byte PIN_RESET = 5; // Button Clear Memory
const byte PIN_BLUETOOTH = 2; // Button Activate/Desactivate Bluetooth
const byte PIN_OPEN_RELAY = 14; // Button Open Relay
const byte PIN_RELAY = 18; // Pin IN Relay
const byte LED_AZUL = 8;
const byte PIN_LED_AZUL = 25;
const byte PIN_LED_VERDE = 26;
const byte PIN_LED_ROJO = 27;
const char* APP_NAME = "ResGuard";
const char* VERSION = "2.0.2 - 2024";
const char* HOSTNAME = "ResGuard-AP";
const char* PASSWORD = "";
IPAddress WifiIP;
// IPAddress ip(192,168,1,60);
// IPAddress gateway(192,168,1,60);
// IPAddress subnet(255,255,255,0);
AsyncWebServer webServer(80);
AsyncWebSocket webSocket("/ws");
SocketIOclient socketIO;
// BluetoothSerial serialBT;
void grabar(int addr, String a) {
int tamano = a.length(); char inchar[50];
a.toCharArray(inchar, tamano+1);
for (int i = 0; i < tamano; i++) { EEPROM.write(addr+i, inchar[i]); }
for (int i = tamano; i < 50; i++) { EEPROM.write(addr+i, 255); }
EEPROM.commit();
}
String leer(int addr) {
byte lectura; String strlectura;
for (int i = addr; i < addr+50; i++) {
lectura = EEPROM.read(i);
if (lectura != 255) { strlectura += (char)lectura; }
} return strlectura;
}
String GetSSID() {
char ssid[50];
leer(0).toCharArray(ssid, 50);
String _ssid(ssid);
//if( _ssid.length() > 0 ) {
Serial.print("SSID: \t\t");
Serial.print("("); Serial.print(_ssid.length());
Serial.print(") \t"); Serial.println(_ssid);
//} return _ssid;
return _ssid;
}
void SetSSID(String valor) {
grabar(0,valor);
}
String GetPASS() {
char pass[50];
leer(50).toCharArray(pass, 50);
String _pass(pass);
Serial.print("PASS: \t\t");
Serial.print("("); Serial.print(_pass.length());
Serial.print(") \t"); Serial.println(_pass);
return _pass;
}
void SetPASS(String valor) {
grabar(50,valor);
}
String GetServer() {
char server[50];
leer(100).toCharArray(server, 50);
String _server(server);
Serial.print("Server API: \t");
Serial.print("("); Serial.print(_server.length());
Serial.print(") \t"); Serial.println(_server);
return _server;
}
void SetServer(String valor) {
grabar(100,valor);
}
String GetPort() {
char port[50];
leer(150).toCharArray(port, 50);
String _port(port);
Serial.print("Port: \t\t");
Serial.print("("); Serial.print(_port.length());
Serial.print(") \t"); Serial.println(_port);
return _port;
}
void SetPort(String valor) {
grabar(150,valor);
}
String GetMAC() {
char mac[50];
leer(200).toCharArray(mac, 50);
String _mac(mac);
if( _mac.length() == 0 ) { _mac = WiFi.macAddress(); grabar(200,_mac); }
Serial.print("MAC: \t\t");
Serial.print("("); Serial.print(_mac.length());
Serial.print(") \t"); Serial.println(_mac);
return _mac;
}
void SetMAC(String valor) {
grabar(200,valor);
}
void ClearMemo() {
_WifiMode = 0;
grabar( 0,"");
grabar( 50,"");
grabar(100,"");
grabar(150,"");
}
void LedBlink(byte pin, byte ciclo, byte speed) {
for (byte i = 1; i <= ciclo; i++) {
byte state = !digitalRead(pin);
digitalWrite(pin,state);
delay(speed);
} digitalWrite(pin,LOW);
}
String GetBodyContent(uint8_t *data, size_t len) {
String content = "";
for (size_t i = 0; i < len; i++) {
content.concat((char)data[i]);
} return content;
}
void onEventSocketIO_START() {
DynamicJsonDocument doc(2048);
JsonArray array = doc.to<JsonArray>();
String output; array.add("message");
JsonObject param1 = array.createNestedObject();
param1["state"] = "START";
param1["from"] = "ESP32";
param1["device"] = _MAC;
param1["ssid"] = _SSID;
param1["pass"] = _PASS;
param1["medio"] = "Hardware";
serializeJson(doc, output);
socketIO.sendEVENT(output);
Serial.println(output);
}
void onEventSocketIO_RESET() {
DynamicJsonDocument doc(1024);
JsonArray array = doc.to<JsonArray>();
String output; array.add("message");
JsonObject param1 = array.createNestedObject();
param1["state"] = "RESET";
param1["from"] = "ESP32";
param1["device"] = _MAC;
param1["medio"] = "Hardware";
serializeJson(doc, output);
LedBlink(PIN_LED_AZUL,6,100);
socketIO.sendEVENT(output);
Serial.println(output);
}
void onEventSocketIO_OPEN() {
DynamicJsonDocument doc(1024);
JsonArray array = doc.to<JsonArray>();
String output; array.add("message");
JsonObject param1 = array.createNestedObject();
param1["state"] = "OPEN";
param1["from"] = "ESP32";
param1["device"] = _MAC;
param1["medio"] = "Hardware";
serializeJson(doc, output);
LedBlink(PIN_LED_AZUL,6,100);
socketIO.sendEVENT(output);
Serial.println(output);
}
void ResetConfig() {
if ( Reset_PIN ) {
ClearMemo();
onEventSocketIO_RESET();
digitalWrite(PIN_LED_ROJO, HIGH);
digitalWrite(PIN_LED_VERDE, HIGH);
digitalWrite(PIN_LED_AZUL, HIGH);
LedBlink(PIN_LED_VERDE,6,200);
ESP.restart();
}
}
void OpenRelay() {
digitalWrite(PIN_RELAY, LOW);
LedBlink(PIN_LED_ROJO,4,100);
digitalWrite(PIN_RELAY, HIGH);
onEventSocketIO_OPEN();
LedBlink(PIN_LED_VERDE,4,100);
digitalWrite(PIN_LED_VERDE, LOW);
digitalWrite(PIN_RELAY, LOW);
}
void Wifi_Scanner() {
byte n = WiFi.scanNetworks();
LedBlink(PIN_LED_VERDE,6,80);
if( n == 0 ) {
Serial.println("\n");
Serial.print("No Se Encontraron Redes");
Serial.println("\n");
} else {
Serial.print("\nRedes Encontradas: ");
Serial.print("("); Serial.print(n); Serial.print(") ");
Serial.println("\n------------------------------------");
for (byte i = 0; i < n; ++i) {
//WiFi.encryptionType 5:WEP 2:WPA/PSK 4:WPA2/PSK 7:Open Network 8:WPA/WPA2/PSK
String channel(WiFi.channel(i)); if( channel.length()==1 ){ channel = (" " + channel); }
String encrypt(WiFi.encryptionType(i)); if( encrypt.length()==1 ){ encrypt = (" " + encrypt); }
String data = (String(i+1) + ":\t CH(" + channel + ") \t ENC(" + encrypt + ")\t (" + WiFi.RSSI(i) + ")\t " + WiFi.SSID(i));
Serial.print(data + "\r\n"); delay(10);
}
}
}
void DisplayAbout() {
DisplayOLED.clearDisplay();
DisplayOLED.setTextColor(SH110X_WHITE);
DisplayOLED.setTextSize(4);
DisplayOLED.setCursor(20, 8);
DisplayOLED.print(APP_NAME);
DisplayOLED.drawLine(10, 40, DisplayOLED.width()-10, 40, SH110X_WHITE);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(28, 45);
DisplayOLED.print(VERSION);
DisplayOLED.display();
}
void DisplayInitial() {
DisplayOLED.begin(I2C_ADDRESS, true);
DisplayOLED.clearDisplay();
DisplayOLED.drawBitmap(0, 0, logo_icono, 128, 64, SH110X_WHITE);
DisplayOLED.display();
delay(2000);
DisplayOLED.clearDisplay();
}
void DisplayStart() {
_MAC = GetMAC();
DisplayOLED.clearDisplay();
DisplayOLED.setTextColor(SH110X_WHITE);
DisplayOLED.setCursor(0, 0);
DisplayOLED.setTextSize(2);
DisplayOLED.println(APP_NAME);
DisplayOLED.drawLine(0, 17, DisplayOLED.width(), 17, SH110X_WHITE);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(14, 22);
DisplayOLED.println(_MAC);
DisplayOLED.display();
}
void DisplaySaving() {
DisplayOLED.clearDisplay();
DisplayOLED.setTextColor(SH110X_WHITE);
DisplayOLED.setCursor(0, 0);
DisplayOLED.setTextSize(2);
DisplayOLED.println(APP_NAME);
DisplayOLED.drawLine(0, 17, DisplayOLED.width(), 17, SH110X_WHITE);
DisplayOLED.setCursor(0, 24);
DisplayOLED.setTextSize(1);
DisplayOLED.println(F("Guardando ..."));
DisplayOLED.display();
}
void DisplayConfig() {
DisplayOLED.clearDisplay();
DisplayOLED.setTextColor(SH110X_WHITE);
DisplayOLED.setCursor(0, 0);
DisplayOLED.setTextSize(2);
DisplayOLED.print(APP_NAME);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(100, 7);
DisplayOLED.println(F("STA"));
DisplayOLED.drawLine(0, 17, DisplayOLED.width(), 17, SH110X_WHITE);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(14, 22);
DisplayOLED.println(_MAC);
DisplayOLED.setCursor(0, 32);
DisplayOLED.print(F("SSID :"));
DisplayOLED.println(_SSID);
DisplayOLED.print(F("PASS :"));
DisplayOLED.println(_PASS);
DisplayOLED.print(F("API :"));
DisplayOLED.println(_SERVER);
DisplayOLED.print(F("PORT :"));
DisplayOLED.println(_PORT);
DisplayOLED.display();
}
void DisplayWifiAP() {
DisplayOLED.clearDisplay();
DisplayOLED.setTextColor(SH110X_WHITE);
DisplayOLED.setCursor(0, 0);
DisplayOLED.setTextSize(2);
DisplayOLED.print(APP_NAME);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(100, 7);
DisplayOLED.println(F("AP"));
DisplayOLED.drawLine(0, 17, DisplayOLED.width(), 17, SH110X_WHITE);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(14, 22);
DisplayOLED.println(_MAC);
DisplayOLED.setCursor(0, 34);
DisplayOLED.print(F("SSID :"));
DisplayOLED.println(HOSTNAME);
DisplayOLED.print(F("PASS :"));
DisplayOLED.println(PASSWORD);
DisplayOLED.print(F("IP :"));
DisplayOLED.println(WifiIP);
DisplayOLED.display();
}
void DisplayError() {
DisplayOLED.clearDisplay();
DisplayOLED.setTextColor(SH110X_WHITE);
DisplayOLED.setCursor(0, 0);
DisplayOLED.setTextSize(2);
DisplayOLED.print(APP_NAME);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(44, 120);
DisplayOLED.println(F("STA"));
DisplayOLED.drawLine(0, 17, DisplayOLED.width(), 17, SH110X_WHITE);
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(0, 22);
DisplayOLED.print(F("SSID :"));
DisplayOLED.println(_SSID);
DisplayOLED.setCursor(0, 32);
DisplayOLED.print(F("PASS :"));
DisplayOLED.println(_PASS);
DisplayOLED.setCursor(16, 45);
DisplayOLED.setTextSize(2);
DisplayOLED.cp437(true);
DisplayOLED.write(173);
DisplayOLED.write(173);
DisplayOLED.print(F("ERROR!!"));
DisplayOLED.display();
}
void onListenerReset() {
currentStateRT = digitalRead(PIN_RESET);
if (lastStateRT == HIGH && currentStateRT == LOW)
pressedTimeRT = millis();
else if (lastStateRT == LOW && currentStateRT == HIGH) {
releasedTimeRT = millis();
uint64_t pressDurationRT = (releasedTimeRT - pressedTimeRT);
if ( pressDurationRT < SHORT_PRESS_TIME ) {
Serial.println("PIN Button Reset !!");
ResetConfig();
}
}
lastStateRT = currentStateRT;
}
void onListenerOpenRelay() {
currentStateOP = digitalRead(PIN_OPEN_RELAY);
if (lastStateOP == HIGH && currentStateOP == LOW)
pressedTimeOP = millis();
else if (lastStateOP == LOW && currentStateOP == HIGH) {
releasedTimeOP = millis();
uint64_t pressDurationOP = (releasedTimeOP - pressedTimeOP);
if ( pressDurationOP < SHORT_PRESS_TIME ) {
Serial.println("PIN Button OPEN Relay !!");
OpenRelay(); onEventSocketIO_OPEN();
}
}
lastStateOP = currentStateOP;
}
void onListenerBluetooth() {
currentStateBT = digitalRead(PIN_BLUETOOTH);
if (lastStateBT == HIGH && currentStateBT == LOW)
pressedTimeBT = millis();
else if (lastStateBT == LOW && currentStateBT == HIGH) {
releasedTimeBT = millis();
uint64_t pressDurationBT = (releasedTimeBT - pressedTimeBT);
if ( pressDurationBT < SHORT_PRESS_TIME ) {
Serial.println("PIN Button Bluetooth !!");
bluetoothActivado = !bluetoothActivado;
/*if( bluetoothActivado ){
serialBT.begin("ResGuard-BT [ " + _MAC + " ]");
Serial.println("Bluetooth habilitado");
} else {
serialBT.end();
Serial.println("Bluetooth deshabilitado");
}*/
}
}
lastStateBT = currentStateBT;
}
void ProcessRequest(AsyncWebSocketClient *client, String request) {
Serial.println("ProcessRequest() : ");
Serial.println(request);
StaticJsonDocument<200> json;
DeserializationError json_error = deserializeJson(json, request);
if( json_error ) { return; }
String command = json["command"];
bool error = (bool)json["error"];
if( command == "Scanner" ) Wifi_Scanner();
if( command == "Save" and error == true ) {
LedBlink(PIN_LED_ROJO,6,80);
}
if( command == "Save" and error == false ) {
WiFi.softAPdisconnect(true);
_WifiMode = 0;
SetSSID(json["ssid"]);
SetPASS(json["pass"]);
SetServer(json["server"]);
SetPort(json["port"]);
Serial.println("Configuración Guardada ...");
//DisplaySaving();
LedBlink(PIN_LED_AZUL,6,80);
bluetoothActivado = false;
//serialBT.end();
delay(600);
ESP.restart();
}
}
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
if(type == WS_EVT_CONNECT){
//Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
client->ping();
} else if(type == WS_EVT_DISCONNECT){
//Serial.printf("ws[%s][%u] disconnect: %u\n", server->url(), client->id());
} else if(type == WS_EVT_ERROR){
//Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data);
} else if(type == WS_EVT_PONG){
//Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len)?(char*)data:"");
} else if(type == WS_EVT_DATA){
AwsFrameInfo * info = (AwsFrameInfo*)arg;
String msg = "";
if(info->final && info->index == 0 && info->len == len){
if(info->opcode == WS_TEXT){
for(size_t i=0; i < info->len; i++) {
msg += (char) data[i];
}
} else {
char buff[3];
for(size_t i=0; i < info->len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
if(info->opcode == WS_TEXT) ProcessRequest(client, msg);
} else {
if(info->opcode == WS_TEXT){
for(size_t i=0; i < len; i++) {
msg += (char) data[i];
}
} else {
char buff[3];
for(size_t i=0; i < len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
//Serial.printf("%s\n",msg.c_str());
if((info->index + len) == info->len){
if(info->final){
if(info->message_opcode == WS_TEXT)
ProcessRequest(client, msg);
}
}
}
}
}
void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
String dataString = GetBodyContent(payload, length);
const int _ini = dataString.indexOf("{");
const int _fin = dataString.lastIndexOf("]");
const int _len = (dataString.length()-1);
String jsonString = dataString.substring(_ini,_len);
if( jsonString.length() > 10 ){
Serial.println("\nsocketIOEvent()");
Serial.print("Size : ");
Serial.println(jsonString.length());
Serial.println(jsonString);
StaticJsonDocument<800> json;
DeserializationError error = deserializeJson(json, jsonString);
if( error ) { return; }
String tipo = json["tipo"];
String state = json["state"];
String from = json["from"];
String device = json["device"];
Serial.println(state);
Serial.println(from);
Serial.println(device);
Serial.println(_MAC);
//LedBlink(LED_BUILTIN,6,120);
//digitalWrite(LED_BUILTIN, HIGH);
if( device == _MAC ){
DisplayOLED.clearDisplay();
DisplayOLED.setTextColor(SH110X_WHITE);
DisplayOLED.setCursor(0, 0);
DisplayOLED.setTextSize(2);
DisplayOLED.println(F("Event IO"));
DisplayOLED.drawLine(0, 17, DisplayOLED.width(), 17, SH110X_WHITE);
DisplayOLED.setCursor(0, 21);
DisplayOLED.setTextSize(2);
DisplayOLED.println(tipo);
DisplayOLED.setCursor(0, 38);
DisplayOLED.setTextSize(1);
DisplayOLED.println(device);
DisplayOLED.setCursor(0, 47);
DisplayOLED.println(_MAC);
DisplayOLED.display();
if( state == "OPEN" ){
DisplayOLED.setTextSize(1);
DisplayOLED.setCursor(0, 56);
DisplayOLED.println(F("RELAY - OPEN"));
DisplayOLED.display();
Serial.println("RELAY OPEN (OK)");
OpenRelay();
}
}
}
delay(2000);
DisplayConfig();
}
void Wifi_STA() {
Serial.println("Modo: Conexión ( Wifi - STA ) Station\n");
int ccx = 0;
WiFi.mode(WIFI_STA);
WiFi.begin(_SSID, _PASS);
while (WiFi.status() != WL_CONNECTED and ccx < 65) {
Serial.print("."); ++ccx;
DisplayOLED.fillRect(0, 48, (ccx * 2), 10, SH110X_WHITE);
DisplayOLED.display();
digitalWrite(PIN_LED_VERDE, HIGH); delay(100);
digitalWrite(PIN_LED_VERDE, LOW); delay(100);
onListenerReset();
}
digitalWrite(PIN_LED_VERDE, LOW);
if (ccx < 65) {
_WifiMode = 2; ccx = 0;
WifiIP = WiFi.localIP();
Serial.println("\n");
Serial.println("WiFi ------------------- [Conectado][ OK ]");
Serial.print("http://");
Serial.print(WifiIP);
Serial.println("/");
Serial.println("Socket-IO -------------- [Conectado][ OK ]");
Serial.print("http://");
Serial.print(_SERVER);
Serial.print(":");
Serial.println(_PORT);
socketIO.begin(_SERVER, (int)_PORT.toInt());
socketIO.onEvent(socketIOEvent);
Serial.println("\n----------------------------------------");
if( _MAC.length() == 0 ) { _MAC = WiFi.macAddress(); SetMAC(_MAC); }
LedBlink(PIN_LED_AZUL,10,200);
DisplayConfig();
digitalWrite(LED_AZUL, HIGH);
// digitalWrite(LED_BUILTIN, HIGH);
} else {
Serial.println("\nError to Connect ...");
digitalWrite(PIN_LED_ROJO, HIGH); ccx = 0;
DisplayError();
Wifi_Scanner();
LedBlink(PIN_LED_ROJO,12,100);
while ( ccx < 4000 ) {
onListenerReset(); ++ccx;
} ESP.restart();
}
}
void Wifi_AP() {
Serial.println("Modo: Configuración ( Wifi - AP ) Access Point\n");
_WifiMode = 1;
WiFi.mode(WIFI_AP);
while(!WiFi.softAP(HOSTNAME, PASSWORD)) { Serial.print("."); delay(100); }
WifiIP = WiFi.softAPIP();
Serial.print("HostName ----> : ");
Serial.println(HOSTNAME);
Serial.print("Password ----> : ");
Serial.println(PASSWORD);
Serial.print("Acces Point IP : ");
Serial.println(WifiIP);
//webServer.serveStatic("/", SPIFFS, "/").setDefaultFile("setup.html");
webServer.serveStatic("/", LittleFS, "/", "max-age=67890").setDefaultFile("setup.html");
webServer.begin();
webSocket.onEvent(onWsEvent);
webServer.addHandler(&webSocket);
bluetoothActivado = true;
//serialBT.begin("ResGuard-BT [ " + _MAC + " ]");
Serial.println("\n----------------------------------------");
Serial.println("HTTP --------- [Server Started][ OK ]");
Serial.println("WebSocket ---- [Server Started][ OK ]\t");
}
void setup() {
Serial.begin(115200);
Serial.println("\n\n");
Serial.println(F("Iniciando!"));
_startINI = 0;
Serial.println(F("1- Preparando GPIO"));
pinMode(LED_BUILTIN, OUTPUT);
//pinMode(LED_AZUL, OUTPUT);
pinMode(PIN_LED_ROJO, OUTPUT);
pinMode(PIN_LED_VERDE, OUTPUT);
pinMode(PIN_LED_AZUL, OUTPUT);
pinMode(PIN_RELAY, OUTPUT);
pinMode(PIN_OPEN_RELAY, INPUT_PULLUP);
pinMode(PIN_BLUETOOTH, INPUT_PULLUP);
pinMode(PIN_RESET, INPUT_PULLUP);
delay(200);
Serial.println(F("2- Iniciando EEPROM"));
EEPROM.begin(512);
LittleFS.begin();
Serial.println(F("3- Inicializando GPIO -> LOW"));
digitalWrite(PIN_LED_ROJO, LOW);
digitalWrite(PIN_LED_VERDE, LOW);
digitalWrite(PIN_LED_AZUL, LOW);
digitalWrite(PIN_RELAY, LOW);
Serial.println(F("4- Iniciando Pantalla OLED"));
digitalWrite(LED_BUILTIN, HIGH);
//digitalWrite(LED_AZUL, HIGH);
DisplayInitial();
Serial.println("-------------------------------------------------------------------- 1");
DisplayStart(); delay(800);
_SSID = GetSSID();
_PASS = GetPASS();
_SERVER = GetServer();
_PORT = GetPort();
_MAC = GetMAC();
Serial.println("-------------------------------------------------------------------- 2");
LedBlink(PIN_LED_VERDE,6,120);
if( _SSID.length() == 0 or _PASS.length() == 0 ){
digitalWrite(LED_BUILTIN, LOW);
//digitalWrite(LED_AZUL, LOW);
Wifi_AP();
DisplayWifiAP();
digitalWrite(LED_BUILTIN, HIGH);
//digitalWrite(LED_AZUL, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
//digitalWrite(LED_AZUL, LOW);
DisplayOLED.setCursor(0, 34);
DisplayOLED.println(F("Conectando Wifi ..."));
DisplayOLED.drawRect(0, 48, DisplayOLED.width(), 10, SH110X_WHITE);
DisplayOLED.display();
Wifi_STA();
digitalWrite(LED_BUILTIN, HIGH);
//digitalWrite(LED_AZUL, HIGH);
}
Serial.println("\n\n");
}
uint64_t messageTimestamp;
void loop() {
onListenerReset();
onListenerOpenRelay();
onListenerBluetooth();
if( _WifiMode == 2 ){
socketIO.loop();
uint64_t now = millis();
if( _startINI == 0 ) {
if((now - messageTimestamp) > 12000) {
messageTimestamp = now;
Serial.println("ESP32 - Success !!");
onEventSocketIO_START();
digitalWrite(LED_BUILTIN, HIGH);
//digitalWrite(LED_AZUL, HIGH);
_startINI = 1;
}
}
}
if( bluetoothActivado ) {
/*if( serialBT.available() ) {
// Leer los datos entrantes desde el puerto Bluetooth
String serialData = serialBT.readStringUntil('\n');
// Crear un objeto JSON a partir de la cadena recibida
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, serialData);
if( error ) {
Serial.println("Error al analizar JSON");
return;
}
// Procesar el JSON recibido
bool valor1 = doc["valor1"];
String valor2 = doc["valor2"];
Serial.print("Valor1: ");
Serial.println(valor1);
Serial.print("Valor2: ");
Serial.println(valor2);
// Enviar una respuesta de vuelta al dispositivo remoto (si es necesario)
// serialBT.println("Respuesta al dispositivo remoto");
}*/
}
}