-->
Page 1 of 1

Problems with esp8266 Wifi

PostPosted: Wed Jun 22, 2022 1:08 am
by rvinaso
Hi friends!! I have been working in a code, that basically extracts the credentials of a wifi network that I previously have stored in Flash Memory of my ESP8266. The problem is that when I use Wifi.begin() fuction it doesn't connect to the network because there are wrong characters in the credentials.I added the code with some comments of where I detected the problem.Thanks a lot!
~~~~~~~~~~~~~~~~~~~~~~~~~

#include <splash.h>

/*
This sketch trys to Connect to the best AP based on a given list

*/
#include "FS.h"
#include <ArduinoJson.hpp>
#include <ArduinoJson.h>
bool spiffsActive = false;
String json;
int Pin1 = 1;// is connected TX azul
int Pin4 = 3;// is connected RX amarillo
#include <ESP8266WiFi.h>
#include <SPI.h> // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <WiFiManager.h>
#include <WiFiUdp.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
#include <Wire.h>
#include "SSD1306.h"





bool activateWifiManager = false;
int contador;
int listoparaenviar = 0;
const char* ssidjson;
const char* passwordjson;
const char *ssidwifi ;
const char * passwordwifi;
const char* ssidSmartCentral="SmartCentral";
const char* incomingSsidwifi ;
const char* incomingPasswordwifi ;
unsigned int localPort = 8888;
String routerSSID;
String routerKey;
int salvarConfig = 0;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
//int D0;
int activar = 0;
int salvarSSID = 0;
int salvarPASSWORD = 0;
String state2;
WiFiManager wm;
WiFiUDP Udp;
DHT dht(DHTPIN, DHTTYPE);
SSD1306 display(0x3c, 4, 3); // revisar los pines de comunicacion a lo mejor lo q chiva el json son los pines q se usan para otra cosa
#define flipDisplay true


uint8_t MAC_array[6];
char MAC_char[18];

IPAddress server;
String ipadd;
String paquete = "esperando";

void writeDisplay(String mostrar,int espera)
{display.clear();
display.setFont(ArialMT_Plain_16);
display.drawString(0, 0, mostrar);
display.display();
delay(espera);

}





void SerializeObject(String wifi_ssid, String pass_wifi)
{

StaticJsonDocument<300> doc;
doc["SSID"] = wifi_ssid;
doc["PASSWORD"] = pass_wifi;

serializeJson(doc, json);
Serial.println(json);
}

void DeserializeObject(String desjson)
{

StaticJsonDocument<300> doc;
DeserializationError err = deserializeJson(doc, desjson);
if (err) {writeDisplay("NO JSON",5000);
return;
}
ssidjson = doc["SSID"];
passwordjson = doc["PASSWORD"];


}


/**
escribe contenido en un archivo
string state - contenido a escribir en el archivo
string path - archivo que se va a escribir
*/

void writeFile(String state, String path) {


File rFile = SPIFFS.open(path, "w+");
if (!rFile) {
Serial.println("Error abriendo!");
} else {
rFile.println(state);

Serial.println(state);
}
rFile.close();
}

void appendFile(String state, String path) {


File rFile = SPIFFS.open(path, "a+");
if (!rFile) {
Serial.println("Error!");
} else {
rFile.println(state);

Serial.println(state);
}
rFile.close();
}

/**
el contenido de un archivo
param cadena path - archivo que se va a leer
return string - contenido leído del archivo
*/

String readFile(String path) {
File rFile = SPIFFS.open(path, "r");
if (!rFile) {
Serial.println("Error !");
}
String content = rFile.readStringUntil('\r');
Serial.print("reading state: ");
Serial.println(content);
rFile.close();
return content;
}

/* *
@desc inicializa el sistema de archivos
*/

void openFS(void) {

if (!SPIFFS.begin()) {
Serial.println("\nError abriendo archivo spiffs");
} else {
Serial.println("\nSuccess iniciando Spiffs!");
}
}









void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
display.init();
if (flipDisplay) display.flipScreenVertically();
writeDisplay("STARTING",3000);
Udp.begin(localPort);
WiFi.mode(WIFI_STA);

delay(1000);





// Start filing subsystem
if (SPIFFS.begin()) {
Serial.println("SPIFFS Active");
// Serial.println();
spiffsActive = true;
} else {
//Serial.println("Unable to activate SPIFFS");
}
delay(2000);

openFS();



state2 = readFile("/config.txt");
DeserializeObject(state2);
delay(1000);
ssidwifi=ssidjson;
passwordwifi=passwordjson;
Serial.println(ssidwifi);////here everything is ok
Serial.println(passwordwifi);
WiFi.begin(ssidwifi, passwordwifi); //

Serial.println(ssidwifi);//////here credentials have wrong characters
Serial.println(passwordwifi);

writeDisplay(ssidwifi,3000);
writeDisplay(passwordwifi,3000);
writeDisplay("Searching",3000);




////////////////////////////////////////////////////levantar el hotspot si no se conecta
while (WiFi.status() != WL_CONNECTED)
{
// Serial.println("WiFi not connected!");
writeDisplay("waiting wifi",100);
contador++;


if (contador == 1800) ///se cumple el minuto sin conectarse a la central
{ writeDisplay("No central",5000);
activateWifiManager = true;
//break;
}
}

if (activateWifiManager == true) ///activo el hotspot propio
{ bool res;
writeDisplay("Starting AP",3000);
res = wm.autoConnect("SmartSensor", "12345678");

routerSSID = WiFi.SSID().c_str(); //cojo clave y
routerKey = WiFi.psk().c_str(); //password del router
ssidwifi = routerSSID.c_str();
passwordwifi = routerKey.c_str();
SerializeObject(ssidwifi, passwordwifi);

writeFile(json, "/config.txt"); //los guardo
}
else ///////// se conecta a la central directamente
{
writeDisplay("central found",3000);

IPAddress broad = WiFi.localIP();
broad[3] = 255;
Udp.beginPacket(broad, 8888);
Udp.write("credentials");
Udp.endPacket();
//////////////esperar las credenciales para conectarse a la red&//////
while(salvarSSID == 0)
{
writeDisplay("Waiting credentials",100);
int packetSize = Udp.parsePacket();
if (packetSize)
{
IPAddress remote = Udp.remoteIP();

Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);

//Serial.print("Contents: ");
String mensaje = packetBuffer;
Serial.println(mensaje);
if (mensaje.substring(0, 4) == "net:")
{String credentials = String (mensaje.substring(4));
DeserializeObject(credentials);
salvarSSID = 1;
writeDisplay("serializing",3000);
SerializeObject(incomingSsidwifi, incomingPasswordwifi);
delay(2000);
writeFile(json, "/config.txt");

ssidwifi=incomingSsidwifi ;
passwordwifi=incomingPasswordwifi;



}
memset(packetBuffer, 0, sizeof(packetBuffer));
}
}
writeDisplay("displaying cred",3000);





writeDisplay(ssidwifi,3000);
writeDisplay(passwordwifi,3000);

delay(2000);
WiFi.begin(ssidwifi, passwordwifi);
delay(3000);
if(WiFi.status() == WL_CONNECTED)
{writeDisplay("Wifi ok",5000);
writeDisplay(ssidwifi,3000);
writeDisplay(passwordwifi,3000);
}

}

//////////////////aqui ya el se conecto al router/////////////////////////////////
IPAddress broad = WiFi.localIP();
broad[3] = 255;
String dir_Mac = WiFi.macAddress(); //cojo la direccion mac
Serial.print("Direccion MAC");
Serial.println(dir_Mac);
WiFi.macAddress(MAC_array);
for (int i = 0; i < sizeof(MAC_array); i++)
{ sprintf(MAC_char, "%s%02x", MAC_char, MAC_array[i]);
}
Serial.print("MAC CON ARRAY: ");
Serial.println(MAC_char);
writeDisplay("Sending",3000);
Udp.beginPacket(broad, 8888); //direccion de broadcast
//envia un paquete a todos los elementos de la red
// el servidor debe almacenar esta direccion

Udp.write("sentemp:");
Udp.write(MAC_char);
Udp.endPacket();
delay(10);
while (paquete == "esperando")
{ writeDisplay("Waiting",3000);
int packetSize = Udp.parsePacket();
if (packetSize)
{
// read the packet into packetBufffer
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
paquete = packetBuffer;
if (paquete == "sincronizado")
server = Udp.remoteIP();
listoparaenviar = 1;
}
if (paquete == "esperando")
{
Udp.beginPacket(broad, 8888);
Udp.write("sentemp:");
Udp.write(MAC_char);
Udp.endPacket();
delay(10);
}
}
writeDisplay("Sincronized",3000);

}


void loop() {

if(listoparaenviar==1)
{char* buffn="";

char buffer[1024]=" ";
//
float humedad = dht.readHumidity();
// Read temperature as Celsius
float temp = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(humedad) || isnan(temp) ) {

return;
}
dtostrf(temp,3,2,buffn);
sprintf(buffer,buffn);
Udp.beginPacket(server, 8888);
Udp.write(buffer);
Udp.endPacket();


display.clear();
display.setFont(ArialMT_Plain_24);
display.drawString(0, 0, buffer);

display.display();
delay(10000);


}


if (WiFi.status() != WL_CONNECTED) ///se cayo la conexion por alguna razon
{
writeDisplay("LOST CONN",1000);
listoparaenviar=0;
}
else
{listoparaenviar=1;
}






}
~~~~~~~~~~~~~~~~~~~
And it is what returns from the Serial Monitor:

~~~~~~~~~~~~~~~~~~~~~~~
Success iniciando Spiffs!
reading state: {"SSID":"SmartCentral","PASSWORD":"12345678"}
SmartCentral
12345678

@⸮⸮⸮?
~~~~~~~~~~~~~~~~~~~~~~~~~