Freeze of the unit (esp8266) while using widget led. Help PLz

Hello to all again :slight_smile:

My unit ESP8266 is getting freeze while I hit the buttom and also is running that code:

Since IPHONE notification wont work with local server I use this code:
void notificacionPushbullet(String titulo, String mensaje) {

  WiFiClientSecure client;
  //Serial.print("connecting to ");
  //Serial.println(host);
  if (!client.connect(host, httpsPort)) {
    //Serial.println("connection failed");
    return;
  }

  if (client.verify(fingerprint, host)) {
    //Serial.println("certificate matches");
  } else {
    //Serial.println("certificate doesn't match");
  }
  String url = "/v2/pushes";
  
  String messagebody = "{\"channel_tag\": \"CHANNELNAME\",\"type\": \"note\", \"title\": \"" + titulo + "\", \"body\": \"" + mensaje + "\"}\r\n"; // EN PRUEBAS
  //Serial.print("requesting URL: ");
  //Serial.println(url);

  client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Authorization: Bearer " + PushBulletAPIKEY + "\r\n" +
               "Content-Type: application/json\r\n" +
               "Content-Length: " +
               String(messagebody.length()) + "\r\n\r\n");
  client.print(messagebody);



  Serial.println("request sent");
  

  //print the response

  while (client.available() == 0);

  while (client.available()) {
    String line = client.readStringUntil('\n');
   // Serial.println(line);
  }
}

And the buttom I hit on the app connect to this code
BLYNK_WRITE(V1) {
if (param.asInt() == 1) {
armed = true;
led3.on();
led2.off();

  } else {
    armed = false;
    led3.off();
    led2.on();
  }

}

I am trying to make the alarm stress test I mean make a lot of request so I could check.

Well when my alarm is running pushbullet notification and I hit the virtual pin1 buttom If I hit several times the ESP8266 freeze and no more response.

I am thinking in a way that make this to not happen .

RESUME:
If a notification with pushbullet is running and the buttom is pressed several times in litle time the unit freeze .

I need to be able to hit the buttom and the unit not freeze but some lag is ok.

I tried to run also LCD RTC and Simpletimer but the unit keep connecting disconnecting from wifi.

The only method that need to run yes or yes inside loop is :
timer.setInterval(1000L, comprobarAlarmas);

or

comprobarAlarmas(); <— Check alarm sensors. This methods only read pin status there are no delays inside only if detect alarm run pushbullet method.

QUESTION:

Someone tested to run in webmos d1 r2 :

  • Do this on wifi
  • Read three pins status -> launch notification to pushbullet in case of pin change .
  • Run lcd
  • Run RTC
  • Run Timer for check pin status and update lcd
  • Press buttom fast on blink that connect to two leds

ÂżAnd get the Esp8266 alive after do that test ?

My code works but it freeze when i hit several times and it disconnect reconnect if I add rtc lcd and timer . withouth touch a buttom.

Maybe the thing I want to do is not for webmos d1 r2 maybe I need a more powerfull unit .

What do you think?

The D1 is just a bigger form of the Mini and that should be capable of doing what you want.

If you provide a basic sketch with all the Blynk stuff we can run it through our Mini’s. We don’t use Apple products or local servers so the test would be for Android and the cloud server.

I undo what I did but I could do again and post here , give me some time.

@Costas Here is the scketch.
In order to test you may modify this :
pushbullet api key
blynk id api key
wifi ssid
password of wifi
Push bullet channel name
Blynk.begin must be adapted to your server.

Widgets in use:
1 Buttom
2 leds
1 RTC
1 LCD

Since you dont have the sensors connected (floating pin) you will get random launch of pushbullet notifications .
If you keep that and press the buttom located in V1 pin several times atleast I am able to freeze the webmos d1.

I admit It could be my code probably need optimization to lower variables and use timer or rtc to make few things more friendly.

I use two sensors an infrared and a door sensor , door sensor has double check because got fake launch less than 1 second due to external noise .

My idea for use RTC was make an auto arm of the alarm based on day of the week and hour.

If you need I could modify and make it more simple I think you dont need to add pushbullet api key or channel name unless you want to receive message in your phone, so I think easy to test, I am still able to freeze that way no pushbullet api key.

UPDATE 1:
Since I make the code again I saw If I remove pushbulletnotification method the Webmos wont freeze even on long press … so I am lost not sure what to do now because notification should be nearly real time . I am pretty sure the notification with push bullet is taking a lot of resources.

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <SPI.h>
#include <TimeLib.h>
#include <WidgetRTC.h>
SimpleTimer timer;
WidgetRTC rtc;
BLYNK_ATTACH_WIDGET(rtc, V5);




/**
   Variables envio  Pushbullet

 * */

const char* host = "api.pushbullet.com";
const int httpsPort = 443;
const char* PushBulletAPIKEY = "PUSHBULLET API KEY HERE"; //get it from your pushbullet account

// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char* fingerprint = "2C BC 06 10 0A E0 6E B0 9E 60 E5 96 BA 72 C5 63 93 23 54 B3"; //got it using https://www.grc.com/fingerprints.htm
//- See more at: http://www.esp8266.com/viewtopic.php?f=29&t=7116#sthash.ZqJBCrMz.dpuf
/***********************************************************************************************************/



/**
   Variables  Blynk*/
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).

char auth[] = "BLYNK ID HERE";// pruebas
WidgetLED led3(3);
WidgetLED led2(2);
WidgetLCD lcd(V20);

/******************************************************************************************/

/**
   Variables Bocina y armado alarma
*/

boolean armed = true; // Alarma activada o no ...
boolean bocina = false; // Si la bocina salta ...
int relePin = 13; // Pin para activar/desactivar rele.

/*********************************************************/


/**
   Variables WIFI
*/
const char* ssid = "SSID HERE";//repetidor inv.
const char* password = "PASSWORD HERE";
WiFiClient client;

/*********************************************************/




/**
   ConfiguraciĂłn y ajustes de alarma.
*/
int valuePausa = 1000;// tiempo de espera entre el primer salto y el segundo que hará saltar el mensaje.
int pirPin = 12;// pir
int puertaPin = 4; //sensorpuerta
int tamperPin = 14; // Rele control sabotaje unidad IR.

boolean estadoPuerta = false;// Abierta true , cerrada False.
boolean primerIntento = true; // Corrección de falsa alarma en el primer intento  no saltará .
long lastMensajePir = 0;
long lastMensajePuerta = 0;
long ahora = 0;
long puertaPausa = millis();

/**************************************************************/

/**
   Control sonidos bocina
   This should contain  some pause  to avoid  burn power sourde
*/

//Siren code here.


/**
   Metodo para envio de notificaciĂłn simplicado y posible reutilizaciĂłn del cĂłdigo.
*/
void notificacionPushbullet(String titulo, String mensaje) {

  WiFiClientSecure client;
  //Serial.print("connecting to ");
  //Serial.println(host);
  if (!client.connect(host, httpsPort)) {
    //Serial.println("connection failed");
    return;
  }

  if (client.verify(fingerprint, host)) {
    //Serial.println("certificate matches");
  } else {
    //Serial.println("certificate doesn't match");
  }
  String url = "/v2/pushes";
  String messagebody = "{\"channel_tag\": \"CHANNEL NAME HERE\",\"type\": \"note\", \"title\": \"" + titulo + "\", \"body\": \"" + mensaje + "\"}\r\n"; // EN PRUEBAS
  //Serial.print("requesting URL: ");
  //Serial.println(url);

  client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Authorization: Bearer " + PushBulletAPIKEY + "\r\n" +
               "Content-Type: application/json\r\n" +
               "Content-Length: " +
               String(messagebody.length()) + "\r\n\r\n");
  client.print(messagebody);



  Serial.println("request sent");


  //print the response

  while (client.available() == 0);

  while (client.available()) {
    String line = client.readStringUntil('\n');
    // Serial.println(line);
  }
}
void setup() {
  Serial.begin(115200);
  Blynk.begin(auth, ssid, password, "192.168.1.128");
  delay(5000); // Al enchufar la  placa a la corriente tenemos que dar un margen para que la gente pueda salir y no se dispare.
  rtc.begin();//Comienza el reloj en tiempo real.
  Serial.print("Connecting to ");
  Serial.println(ssid);
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  pinMode(pirPin, INPUT);// INFRARED SENSOR DG-85dw
  pinMode(puertaPin, INPUT); // DOOR SENSOR NORMALLY CLOSE.
  pinMode(tamperPin, INPUT);//TAMPER SENSOR DG-85dw
  pinMode(relePin, OUTPUT); //PIN THAT CONTROLS A RELAY  WITH A SIREN
  digitalWrite(relePin, LOW); // BE SURE ON POWER LOSS  SIREN DONT GO ON.


  notificacionPushbullet("Perdida corriente. Sistema re-iniciado y listo.", "Almacén torillos");// NOTIFY POWER WAS LOST THIS UNIT SHOULD NOT BE POWERED OFF

}



/**
 * BLYNK APP BUTTOM THAT CONTROL  TWO LEDS  ONE RED AND ONE GREEN.
 * GREEN ON MEANS  ALARM IS ARMED
 * RED ON MEANS ALARM IS NOT ARMED
 */
BLYNK_WRITE(V1) {
  if (param.asInt() == 1) {
    armed = true;
    led3.on();
    led2.off();

  } else {
    armed = false;
    led3.off();
    led2.on();
  }

}

void pintarLCD() {
    int hora=hour();
  int minuto= minute();
  lcd.print(0, 0, hora + minuto);
  //lcd.print(0, 1, "Alar:ON SIRE:OFF");// NOT NEEDED IF THERE SOME LAG.
}
void  comprobarAlarmas()
{
  /**
     Chequeamos el pir que sin estar alarmado  el circuito está abierto
  */
  if (digitalRead(pirPin) == LOW && armed == true ) { // La luz del sensor de movimiento se ha encendido y ha abierto el circuito.

    if ( millis() - ahora > 2000) {
      if (millis() - lastMensajePir  >= 5000) {
        bocina = true; // Ponemos la variable de la bocina a true para que si está conectada salte.

        notificacionPushbullet("Alarma almacen", "Detectado movimiento");
        lastMensajePir = millis();
      }
      //saltar alarma y mensajes aplicacion blynk.


    }
  } else if (digitalRead(pirPin) == HIGH) {
    ahora = millis();
  }


  /*************************************INICIO CORRECION FALSAS ALARMAS PUERTA***************************************/
  /* Debido a los falsos positivos antes de saltar la puerta medimos el primer tiempo de salto no mandando mensaje ,
      una vez que  ha pasado el lapso de tiempo (valuePausa) en esa ocasión seguirá saltando hasta que la puerta sea cerrada.
  */
  if (digitalRead(puertaPin) == LOW && armed == true && primerIntento == true )
  {
    puertaPausa = millis() + valuePausa;// Establecemos el valor  a partir del cual si la puerta sigue abierta  debe saltar si millis es mayor .
    primerIntento = false; // Al ajustar  por primera vez la puerta ya no es el primer intento.

  }  else if (digitalRead(puertaPin) == HIGH) {
    primerIntento = true; // La puerta solo recibe el primer intento nuevamente si ha sido cerrada .
  }
  /*************************************FIN CORRECION FALSAS ALARMAS PUERTA***************************************/



  if (digitalRead(puertaPin) == LOW && armed == true && primerIntento == false && millis() >= puertaPausa) {

    estadoPuerta = true;

    if (millis() - lastMensajePuerta >= 5000) {

      // Saltar alarma de apertura
      notificacionPushbullet("Alarma almacen", "Puerta ABIERTA");
      lastMensajePuerta = millis();

    }


  } else  if (digitalRead(puertaPin) == HIGH && armed == true) {

    if (estadoPuerta) {
      //saltar alarma de cierre de puerta.
      notificacionPushbullet("Alarma almacen", "Puerta CERRADA");
      estadoPuerta = false;
    }


  }
  if (digitalRead(relePin) == LOW) {
    // Serial.println("low");
  } else
  {
    // Serial.println("high");
  }
}
void loop() {


  //pintarLCD();
  comprobarAlarmas();

  Blynk.run();
  timer.run();
  timer.setInterval(11111L, pintarLCD);
  //  timer.setInterval(1000L, comprobarAlarmas);//MUST CHECK WHATS BETTER  RUN DIRECTLY OR USE TIMER.

  //Pendiente poner codigo para el TAMPER
}

@kranick you can’t have timer.setInterval(11111L, pintarLCD) in the main loop it belongs in setup().

comprobarAlarmas() is probably not suitable for the main loop either and needs to be called with SimpleTimer, at intervals. I haven’t looked through the comprobarAlarmas() as Google translate isn’t helping very much.

If you feel comprobarAlarmas() NEEDS to be in the main loop please explain what it does and why it can’t be called from SimpleTimer.

1 Like

@Costas You are right with the timer no need to set it on each iteration.

comprobarAlarmas() is for check two pins and in case infrared sensor fire or door sensor fire launch notificationpushbullet() with a message. Also I added some things like do not send more than 1 msg every 5 sec.

For example when infrared sensor fire (true alarm) keeps the relay 5 second open so the pin is low. I should check during atleast 2 second the pin is still LOW to fire this alarm. Fake alarm take less than 2 seconds.

Door sensor was easy until noise comes so I must check 1 second later the door is still opened to avoid problems. Withouth that I was receiving pin change.

The reasons I put in Loop comprobaralarmas was basically I just started working with Timer and I am looking to move it out of the loop and check how it works.

I just wonder how Timer works because was happen when you put 1second delay between task and the task take more than 1 second because is sending pushbullet msg.

I cant run infrared sensor method every two seconds because could loose 2 seconds of fire alarm.

I calculated if the thief open the door the webmos need atleast 4 seconds for send the msg.

Of course the code works but need optimization Timer integrations to reduce variables and make it more easy to read.

I don’t really mean to be rude, but you may want to consider translating everything to English. It makes it much more easy for us to help you out with things like that because we would probably understand the code better as to what it is supposed to do.

Why use a separate message service anyway? I don’t think that is very handy since Blynk has pretty much everything on board to do that.