Bueno, pues esta noche no ha reseteado.
No había pensado en lo de telegram, pero, como veréis en el código, solo mira si hay mensajes cada 30 segundos. No creo que sea eso, pero puedo implementar algo para evitar que lea entre las 03:10 y las 03:13 en las próximas pruebas.
Os paso el código.
// ESP32-WRRoOM-DA module
#ifndef ARDUINO_ARCH_ESP32
#error No es ESP32
#endif
bool MENSA_EN_USO=false;
String MENSA;
void loop2(void *parameter);
void envio(void);
String mi_IP(void);
void VER_MENSA(void);
String showTime(bool largo);
void HAY_LUZ(void);
bool hay_luz=true;
unsigned long LED_CON=4000UL; //tiempo apagada
#define LED_flash 30 //tiempo encendida
unsigned long flash=0; // medida del tiempo del flash led
bool ENCEN=false;
#define ENCENDER LOW // como se enciende el led? LOW/HIGH
#define LED_BUILTIN 23 // led
#define CENTRAL 34 // pin conectado a la central divisor 10k/10k + bd139 + pull-up 1K
#define LUZ 33 // detectar si hay luz a 3.3v / divisor de 330+/1k-
#define TELEGRAM 30000 // tiempo entre llamadas a telegram
String errors,IP_PUBLICA_ACTUAL;
bool ANTES=true, test=true;
unsigned long t_wifi=0; // tiempo inicial -TELEGRAM para que entre la primera vez
bool wifi_ok=false;
bool init_time=false;
#include "time.h"
#include "esp_sntp.h"
#include <WiFi.h>
#include <HTTPClient.h>
String ssid = ""; // REPLACE mySSID WITH YOUR WIFI SSID
String pass = ""; // REPLACE myPassword YOUR WIFI PASSWORD, IF ANY
String TOKEN = ""; // REPLACE myToken WITH YOUR TELEGRAM BOT TOKEN
#include "CTBot.h"
CTBot myBot;
TBMessage msg;
TaskHandle_t Task2;
void setup(){
Serial.begin(115200);
pinMode(CENTRAL,INPUT); //sirena
pinMode(LUZ,INPUT);
pinMode(LED_BUILTIN,OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
flash=millis(); // iniciar flash con 300ms
LED_CON=300UL;
myBot.setMaxConnectionRetries(20); // 20 * 500 milis = 10 seg
// connect to the desired access point
myBot.wifiConnect(ssid, pass);
// set the telegram bot token
myBot.setTelegramToken(TOKEN);
// check if all things are ok
if (myBot.testConnection())
Serial.println("\ntestConnection OK");
else
Serial.println("\ntestConnection NOK");
t_wifi=0-TELEGRAM;
// iniciar NTP
sntp_set_time_sync_notification_cb(timeavailable);
const char *TZstr ="CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00";
configTzTime(TZstr,"es.pool.ntp.org","pool.ntp.org", "time.nist.gov");
showTime(false); // primera cridada
delay(1000);
xTaskCreatePinnedToCore( loop2, "Task_2", 20480, NULL, 0, &Task2, 0);
delay(2500);
if(!init_time){ // ver si time esta ja good?
do{
Serial.print(".");
delay(20);
}while(!init_time);
Serial.println();
}
mi_IP(); // ller IP publica: se usa pa saber si hay internet
MENSA="ESP32D ha arrancado";
MENSA+="\r\nIP: "+IP_PUBLICA_ACTUAL;
envio();
Serial.println("en marcha");
}
//#define PROBA_RESET
void loop() {
int resul;
test=digitalRead(CENTRAL);
if(test!=ANTES){ //de inicio ANTES=true test=true
// si no es pulso de setup, cambiar a pulso pin activo
if(!test){
if(LED_CON!=300) LED_CON=2500UL;
VER_MENSA(); //mirar si mensa esta ocupado
MENSA+=showTime(false);
MENSA+="La alarma se ha conectado";
MENSA_EN_USO=false;
// envio(); se envia desde loop2
}
ANTES=test;
} // hay señal en sirena
HAY_LUZ();
wifi_flash();
vTaskDelay( pdMS_TO_TICKS( 10 ) );
}
void wifi_flash()
{
if(!LED_CON) return; // no led
if(ENCEN)
if(millis() - flash >LED_flash){
digitalWrite(LED_BUILTIN, ENCENDER);
flash=millis();
ENCEN=false;
}
if(!ENCEN)
if(millis() - flash >LED_CON){
digitalWrite(LED_BUILTIN, !ENCENDER);
flash=millis();
ENCEN=true;
}
}
// espera a que se termine de usar MENSA
void VER_MENSA(void){
while(MENSA_EN_USO) delay(10);
MENSA_EN_USO=true;
}
void envio(void)
{
int32_t res=1;
String TEMP="";
if(MENSA=="" && errors=="") return;
if(MENSA!=""){
VER_MENSA();
TEMP=MENSA;
MENSA="";
MENSA_EN_USO=false;
TEMP.trim();
if(TEMP=="" && errors=="") return;
}
vTaskDelay( pdMS_TO_TICKS( 30 ) );
if(TEMP!=""){
Serial.print("envio() running on core: ");
Serial.println(xPortGetCoreID());
Serial.println("TEMP ["+TEMP+"]");
res=myBot.sendMessage(msg.sender.id,TEMP); // enviar
}
if(res<1){ // error de envio telegram
if(LED_CON!=300) LED_CON=900UL; // de setup no cambia
if(errors.length()) errors+="\r\n";
errors+"["+String(res)+"]";
errors+="<"+showTime(true)+">";
errors+=TEMP;
Serial.println("errores ["+errors+"]");
}
else{
if(LED_CON!=300) LED_CON=5000UL; // de setup no cambia
if(errors.length()){
res=myBot.sendMessage(msg.sender.id,errors); // enviar?
if(res>0){
Serial.print("envio() running on core: ");
Serial.println(xPortGetCoreID());
Serial.println("Errores ["+errors+"]");
errors=""; // sin error? borrar
}
}
}
TEMP="";
vTaskDelay( pdMS_TO_TICKS( 30 ) );
}
// largo false=normal: true=largo
String showTime(bool largo)
{
struct tm timeinfo;
time_t nowSecs=time(nullptr);
char time_output[60];
if (!getLocalTime(&timeinfo)) return "";
strftime(time_output, 56,"%d-%m-%y a las %T" , localtime(&nowSecs));
return (String)time_output;
}
// Callback function (gets called when time adjusts via NTP)
void timeavailable(struct timeval *t) {
Serial.println("Got time adjustment from NTP!");
init_time=true;
}
String mi_IP()
{
// ######## LEER IP PUBLICA ######## //
WiFiClient client;
HTTPClient http;
String new_ip="";
http.begin(client, "http://ifconfig.me/ip");
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) new_ip=http.getString();
else new_ip="";
http.end();
new_ip.trim();
IP_PUBLICA_ACTUAL=new_ip;
return new_ip;
}
// core 1
void loop2(void *parameter){
for(;;){
envio(); // mirar si hay mensajes que enviar
if( millis () - t_wifi >= TELEGRAM ){ // revisar si hay mensajes de entrada
vTaskDelay( pdMS_TO_TICKS( 10 ) );
while(myBot.getNewMessage(msg,true)==true){ // repetir mentres nian datos
Serial.println("TEXT= "+msg.text);
LED_CON=5000UL; // flash normal
if(msg.text.indexOf("start")!=-1){
mi_IP();
VER_MENSA();
MENSA+="[ESP32D start] esperando\r\n";
MENSA+="\r\nIP: "+IP_PUBLICA_ACTUAL;
MENSA+="\r\n"+showTime(true);
MENSA+="\r\n";
MENSA+= hay_luz==true ? "SI" : "NO";
MENSA+=" hay luz";
MENSA_EN_USO=false;
envio();
}
}
t_wifi = millis(); // tiempo nuevo
}
vTaskDelay( pdMS_TO_TICKS( 50 ) );
}
} // loop2
void HAY_LUZ(void){
int luz=digitalRead(LUZ); // hay luz?
if(hay_luz && luz) return; // SI
if(!luz && hay_luz){// se ha ido
hay_luz=false;
VER_MENSA();
MENSA+="Se ha ido la luz";
MENSA_EN_USO=false;
//envio(); //desde loop2
}
if(!hay_luz && luz){ //ya hay luz
VER_MENSA();
MENSA +="Ya hay luz";
MENSA_EN_USO=false;
//envio();
}
}
En cuanto a lo último de gabgold, si te soy sincero, no he entendido nada. Por eso te ruego que le des un vistazo al código en cuanto al watchdog se refiere.
Gracias a los 2. Ahora iré restituyendo el código poco a poco a ver si "aguanta". Serán muchos días de pruebas.
Saludos