From f1070e030c19f18c5f7f44bfd7b11ed6e1c9db5e Mon Sep 17 00:00:00 2001 From: Gerardo Date: Thu, 26 Sep 2024 09:59:48 +0200 Subject: [PATCH] Version inicial --- .gitignore | 1 + DomoEspSensor/.theia/launch.json | 8 + DomoEspSensor/DomoEspConfig.h | 40 +++++ DomoEspSensor/DomoEspSensor.ino | 11 ++ DomoEspSensor/DomoEspSensorManager.cpp | 155 +++++++++++++++++ DomoEspSensor/DomoEspSensorManager.h | 51 ++++++ DomoEspSensor/MecanismoPulso.h | 120 +++++++++++++ DomoEspSensor/SensorAin.h | 57 +++++++ DomoEspSensor/SensorDHT.h | 66 +++++++ DomoEspSensor/SensorDin.h | 47 +++++ DomoEspSensor/SensorDout.h | 78 +++++++++ DomoEspSensor/SensorPulsante.h | 51 ++++++ DomoEspSensor/SensorRF.h | 41 +++++ DomoEspSensor/SensorVD.h | 64 +++++++ DomoEspSensor/Utiles.cpp | 227 +++++++++++++++++++++++++ DomoEspSensor/Utiles.h | 66 +++++++ DomoEspSensor/configuracionActual.h | 175 +++++++++++++++++++ DomoEspSensor/defines.h | 94 ++++++++++ 18 files changed, 1352 insertions(+) create mode 100644 .gitignore create mode 100644 DomoEspSensor/.theia/launch.json create mode 100644 DomoEspSensor/DomoEspConfig.h create mode 100644 DomoEspSensor/DomoEspSensor.ino create mode 100644 DomoEspSensor/DomoEspSensorManager.cpp create mode 100644 DomoEspSensor/DomoEspSensorManager.h create mode 100644 DomoEspSensor/MecanismoPulso.h create mode 100644 DomoEspSensor/SensorAin.h create mode 100644 DomoEspSensor/SensorDHT.h create mode 100644 DomoEspSensor/SensorDin.h create mode 100644 DomoEspSensor/SensorDout.h create mode 100644 DomoEspSensor/SensorPulsante.h create mode 100644 DomoEspSensor/SensorRF.h create mode 100644 DomoEspSensor/SensorVD.h create mode 100644 DomoEspSensor/Utiles.cpp create mode 100644 DomoEspSensor/Utiles.h create mode 100644 DomoEspSensor/configuracionActual.h create mode 100644 DomoEspSensor/defines.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d5edf36 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.vs/* diff --git a/DomoEspSensor/.theia/launch.json b/DomoEspSensor/.theia/launch.json new file mode 100644 index 0000000..9a49ac9 --- /dev/null +++ b/DomoEspSensor/.theia/launch.json @@ -0,0 +1,8 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + "version": "0.2.0", + "configurations": [ + + ] +} diff --git a/DomoEspSensor/DomoEspConfig.h b/DomoEspSensor/DomoEspConfig.h new file mode 100644 index 0000000..2bd7313 --- /dev/null +++ b/DomoEspSensor/DomoEspConfig.h @@ -0,0 +1,40 @@ +#ifndef DomoEspConfigDef +#define DomoEspConfigDef 1 +#include +#include "defines.h" +class DomoEspConfig +{ + + public: + char ssidWifi[24];//nombre wifi al que conectar + char keyWifi[32];//key wifi a conectar + char ideEsp[32];//identificador unico por esp + char hostMQTT[16]; + int portMQTT; + + int velocidadPortSerie; + int refresTimeVars;//tiempo de refresco en segundos de las variables + + int refresTimeSens;//tiempo de refresco en segundos de los sensores + + DomoEspConfig() + { + velocidadPortSerie=115200; + strcpy(ssidWifi,"Idhun");//nombre wifi + strcpy(keyWifi,"Ardileorca1234.");//key wifi + strcpy(ideEsp,"Esp8266_noName");//idenitificador del esp (sera único) + strcpy(hostMQTT,"192.168.2.50");//servidor mqttBroker + portMQTT=1883;//puerto del servidor mqtt Broker + refresTimeVars=30;//tiempo de refresco en segundos de las variables + refresTimeSens=5;//tiempo de refresco en segundos de los sensores + } + + virtual void inicia(ISensorManager* man) + { + + } +}; + +#endif + + diff --git a/DomoEspSensor/DomoEspSensor.ino b/DomoEspSensor/DomoEspSensor.ino new file mode 100644 index 0000000..a2869c8 --- /dev/null +++ b/DomoEspSensor/DomoEspSensor.ino @@ -0,0 +1,11 @@ +#include "DomoEspSensorManager.h" +#include "configuracionActual.h" +DomoEspManager manager; + +void setup() { + manager.inicia(&ConfiguracionActual); +} + +void loop() { + manager.loop(); +} diff --git a/DomoEspSensor/DomoEspSensorManager.cpp b/DomoEspSensor/DomoEspSensorManager.cpp new file mode 100644 index 0000000..4425c20 --- /dev/null +++ b/DomoEspSensor/DomoEspSensorManager.cpp @@ -0,0 +1,155 @@ + +#include "DomoEspConfig.h" +#include "DomoEspSensorManager.h" + + +DomoEspManager::DomoEspManager() +{ + clienteMqtt.setClient(espClient); + n=0; + tiempo=0; + suscrito=false; + tiempo_sens=0; + SetTimeRefres(15); +} +void DomoEspManager::SetTimeRefres(int seg) +{ + incre_tsens=seg*1000; +} +void DomoEspManager::inicia(DomoEspConfig* cnf) +{ + conf=cnf; + #ifdef DEBUG_PS + Serial.begin(conf->velocidadPortSerie); + delay(100); + Serial.println(""); + Serial.println("Iniciando"); + #endif + #ifdef DEBUG_PS + Serial.println("Inicia Wifi"); + #endif + wifi.inicia(&espClient, conf->ssidWifi, conf->keyWifi, conf->ideEsp); + #ifdef DEBUG_PS + Serial.println("Inicia Mqtt"); + #endif + mqtt.inicia(&clienteMqtt,conf->ideEsp, conf->hostMQTT, conf->portMQTT, this); + + #ifdef DEBUG_PS + Serial.println("Configura Sensores"); + #endif + conf->inicia(this); + + + //pasar funcion de configuracion de añadir sensores + for(int i=0; iinicia(); + } +} + +void DomoEspManager::loop() +{ + if(!wifi.loop()) + { + suscrito=false; + return; + } + + if(!mqtt.loop()) + { + suscrito=false; + return; + } + + if(!suscrito) + { + for(int i=0; iSubscribeMqtt(this); + } + suscrito=true; + } + int tiempoAux=0; + if(MqttUtiles::pasa_incre(&tiempo_sens, incre_tsens)) + { + + tiempo=(tiempo+1)%2; + tiempoAux=tiempo+1; + #ifdef DEBUG_PS + Serial.print("Procesa Tiempo: "); + Serial.print(tiempoAux); + Serial.println("------------ "); + #endif + } + + for(int i=0; iprocesa(this, tiempoAux); + } + #ifdef DEBUG_PS + if(tiempoAux>0) + Serial.println("----------------------------- "); + #endif +} + +void DomoEspManager::OnMqtt(char* topic, char* payload) +{ + char buf[MAXTOPICVAR]; + strcpy(buf, topic); + int nt=strlen(buf); + if(nt<4) + { + #ifdef DEBUG_PS + Serial.print("se descarta por topic corto:"); + Serial.println(buf); + #endif + return; + } + int tipo=Topic::NO_RECONOCIDO; + if(!strcmp("/get", &buf[nt-4])) + tipo=Topic::GET; + else if(!strcmp("/set", &buf[nt-4])) + tipo=Topic::SET; + else if(!strcmp("/pul", &buf[nt-4])) + tipo=Topic::PUL; + + if(tipo!=Topic::NO_RECONOCIDO) + buf[nt-4]=0; + #ifdef DEBUG_PS + Serial.print("OnMqtt "); + Serial.print(topic); + Serial.print(" -> "); + Serial.println(payload); + #endif + for(int i=0; iOnMqtt(this, buf, payload, tipo); + } + +} + +void DomoEspManager::SubscribeMqtt(PubSubClient *client_mqtt) +{ + for(int i=0; iSubscribeMqtt(this); + } +} + +void DomoEspManager::MqttSend(char* topic, char* payload) +{ + clienteMqtt.publish(topic, payload); +} +void DomoEspManager::MqttSubs(char* topic) +{ + clienteMqtt.subscribe(topic); +} + +void DomoEspManager::Add(DomoEspSensorReceiver* sensor) +{ + if(n +#include +#include "utiles.h" +class DomoEspConfig; +class IDomoEspLisener +{ + public: + void inicia(); + void loop(); + virtual void OnMqtt(char* topic, char* payload); + virtual bool SubscribeMqtt(char *topic); + +}; + +class DomoEspManager: public MqttReceiver, public IMqttManager, public ISensorManager +{ + WifiManager wifi; + DomoEspConfig* conf; + WiFiClient espClient; + PubSubClient clienteMqtt; + MqttManager mqtt; + + DomoEspSensorReceiver* sensores[MAXSENS]; + int n; + int tiempo; + bool suscrito; + unsigned long tiempo_sens; + unsigned long incre_tsens; + + public: + + DomoEspManager(); + //funcion inicial + void SetTimeRefres(int seg); + void inicia(DomoEspConfig* cnf); + void loop(); + +//funciones auxiliares + virtual void OnMqtt(char* topic, char* payload); + virtual void SubscribeMqtt(PubSubClient *client_mqtt); + + virtual void MqttSend(char* topic, char* payload); + virtual void MqttSubs(char* topic); + + virtual void Add(DomoEspSensorReceiver* sensor); +}; + + +#endif \ No newline at end of file diff --git a/DomoEspSensor/MecanismoPulso.h b/DomoEspSensor/MecanismoPulso.h new file mode 100644 index 0000000..da3dc46 --- /dev/null +++ b/DomoEspSensor/MecanismoPulso.h @@ -0,0 +1,120 @@ +#ifndef MecanismoPulsoDef +#define MecanismoPulsoDef 1 +#include "defines.h" +//sensor activador envia a topicOut el valor val_send si los activadores cumplen umbral +class Cactivador +{ + public: + Cactivador(){} + DomoEspSensorReceiver *sen; + float umbral; + char operacion;//< > = val oper umbral +}; +#define MAX_ACTIVADORES 5 + +class MecanismoPulso: public DomoEspSensorReceiver +{ + float val; + char topicOut[MAXTOPICVAR]; + char valSend[3]; + Cactivador activador[MAX_ACTIVADORES]; + + public: + char id[10]; + MecanismoPulso() + { + strcpy(id, "Meca"); + topic[0]=0; + for(int i=0; iMqttSubs(buffer_t); + sprintf(buffer_t, "%s/pul",topic); + man->MqttSubs(buffer_t); + } + virtual void OnMqtt(IMqttManager * man, char* _topic, char* payload, int tipo) + { + if(strcmp(_topic, topic)) + return; + if(tipo==Topic::GET) + { + float val_act=atof(payload); + if (val_act!=val) + { + val=val_act; + ejecuta(man); + } + } + else if(tipo==Topic::PUL) + { + ejecuta(man); + } + } + private: + void ejecuta(IMqttManager * man) + { + if(valida()) + { + #ifdef DEBUG_PS + Serial.print("Ejecuta id: "); + Serial.println(id); + + #endif + strcpy(buffer_p, valSend); + sprintf(buffer_t, "%s/set",topicOut); + man->MqttSend(buffer_t, buffer_p); + } + } + bool valida() + { + for(int i=0; i') + return activador[i].sen->getVal()>activador[i].umbral; + if(activador[i].operacion=='<') + return activador[i].sen->getVal()getVal()==activador[i].umbral; + return false; + } +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/SensorAin.h b/DomoEspSensor/SensorAin.h new file mode 100644 index 0000000..89a9285 --- /dev/null +++ b/DomoEspSensor/SensorAin.h @@ -0,0 +1,57 @@ +#ifndef SensorAinDef +#define SensorAinDef 1 +#include "utiles.h" + +class SensorAin: public DomoEspSensorReceiver +{ + float val; + bool negado; + uint8_t pin; + float dif; + unsigned long t; + unsigned long incre; + public: + virtual float getVal() + { + return val; + } + SensorAin(){} + void set(uint8_t _pin, char* topic_id, bool _negado, float _dif) + { + t=0; + incre=1000; + dif=_dif; + negado=_negado; + pin=_pin; + val=0; + strcpy(topic, topic_id); + } + virtual void procesa(IMqttManager * man, int tiempo) + { + //mirar para configurar por interrupcion + if((dif!=0 && MqttUtiles::pasa_incre(&t, incre)) || tiempo==2) + { + float val_act; + if(negado) + val_act =100.*((float)(1024- analogRead(pin)))/1024; + else + val_act =100.*((float)(analogRead(pin)))/1024; + if(dif<=abs(val_act-val) || tiempo==2) + { + val=val_act; + #ifdef DEBUG_PS + Serial.print("Sensor Analog log "); + Serial.println(val); + #endif + //loguea------------ + + dtostrf(val,3, 2, buffer_p); + sprintf(buffer_t, "%s/get",topic); + man->MqttSend(buffer_t, buffer_p); + } + } + + } +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/SensorDHT.h b/DomoEspSensor/SensorDHT.h new file mode 100644 index 0000000..f127655 --- /dev/null +++ b/DomoEspSensor/SensorDHT.h @@ -0,0 +1,66 @@ +#ifndef SensorDHTDef +#define SensorDHTDef 1 +#include "defines.h" +#include + +class SensorDHT: public DomoEspSensorReceiver +{ + SimpleDHT22 dht; + uint8_t pin; + float t,h; + + public: + virtual float getVal() + { + return t; + } + SensorDHT() + { + pin=0; + t=h=0; + topic[0]=0; + } + void set(uint8_t _pin, char* topic_id) + { + pin=_pin; + t=h=0; + strcpy(topic, topic_id); + } + virtual void procesa(IMqttManager * man, int tiempo) + { + if(tiempo==0) + return; + #ifdef DEBUG_PS + Serial.println("ProcesaDHT"); + #endif + for(int i=0; i<4; i++) + { + if (dht.read2(pin, &t, &h, NULL) != SimpleDHTErrSuccess) + { + delay(20); + continue; + } + break; + } + if(tiempo==2) + { + #ifdef DEBUG_PS + Serial.println("LogDHT"); + #endif + //loguea------------ + //char buffer_t[MAXTOPICVAR]; + //char buffer_p[MAXTOPICVAR]; + //temperatura----------------- + dtostrf(t,3, 2, buffer_p); + sprintf(buffer_t, "%s/t/get",topic); + man->MqttSend(buffer_t, buffer_p); + //humedad----------------- + dtostrf(h,3, 2, buffer_p); + sprintf(buffer_t, "%s/h/get",topic); + man->MqttSend(buffer_t, buffer_p); + } + } + +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/SensorDin.h b/DomoEspSensor/SensorDin.h new file mode 100644 index 0000000..4b98d6f --- /dev/null +++ b/DomoEspSensor/SensorDin.h @@ -0,0 +1,47 @@ +#ifndef SensorDinDef +#define SensorDinDef 1 +#include "defines.h" + +class SensorDin: public DomoEspSensorReceiver +{ + bool val; + uint8_t pin; + + public: + + virtual float getVal() + { + return (float)val; + } + SensorDin(){} + void set(uint8_t _pin, char* topic_id) + { + pin=_pin; + val=0; + strcpy(topic, topic_id); + } + virtual void procesa(IMqttManager * man, int tiempo) + { + //mirar para configurar por interrupcion + int val_ac=digitalRead(pin); + + if(tiempo==2 || val_ac!=val) + { + val=val_ac; + //loguea------------ + //char buffer_t[MAXTOPICVAR]; + //char buffer_p[MAXTOPICVAR]; + sprintf(buffer_p, "%d", (int)val); + sprintf(buffer_t, "%s/get",topic); + man->MqttSend(buffer_t, buffer_p); + } + } + + virtual void inicia() + { + pinMode(pin, INPUT); + val=digitalRead(pin); + } +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/SensorDout.h b/DomoEspSensor/SensorDout.h new file mode 100644 index 0000000..1b0b572 --- /dev/null +++ b/DomoEspSensor/SensorDout.h @@ -0,0 +1,78 @@ +#ifndef SensorDoutDef +#define SensorDoutDef 1 +#include "defines.h" + +class SensorDout: public DomoEspSensorReceiver +{ + bool val; + uint8_t pin; + + public: + virtual float getVal() + { + return (float)val; + } + SensorDout() + { + pin=0; + val=0; + topic[0]=0; + } + void set(uint8_t _pin, char* topic_id, bool valdef) + { + pin=_pin; + val=valdef; + strcpy(topic, topic_id); + } + virtual void procesa(IMqttManager * man, int tiempo) + { + if(tiempo==2) + { + #ifdef DEBUG_PS + Serial.print("LogDout "); + Serial.println(val); + #endif + //loguea------------ + //char buffer_t[MAXTOPICVAR]; + //char buffer_p[MAXTOPICVAR]; + sprintf(buffer_p, "%d", (int)val); + sprintf(buffer_t, "%s/get",topic); + man->MqttSend(buffer_t, buffer_p); + } + } + + virtual void inicia() + { + pinMode(pin, OUTPUT); + digitalWrite(pin, val); + } + virtual void SubscribeMqtt(IMqttManager* man){ + //char buffer_t[MAXTOPICVAR]; + sprintf(buffer_t, "%s/set",topic); + man->MqttSubs(buffer_t); + } + virtual void OnMqtt(IMqttManager * man, char* _topic, char* payload, int tipo) + { + if(tipo!=Topic::SET) + return; + if(!strcmp(_topic, topic)) + { + if(payload[0]=='X') + val=!val; + else + val=(atoi(payload)==1); + //cambia estado relle + + digitalWrite(pin, val); + //loguea------------ + //char buffer_t[MAXTOPICVAR]; + //char buffer_p[MAXTOPICVAR]; + sprintf(buffer_p, "%d", (int)val); + sprintf(buffer_t, "%s/get",topic); + man->MqttSend(buffer_t, buffer_p); + } + + }; +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/SensorPulsante.h b/DomoEspSensor/SensorPulsante.h new file mode 100644 index 0000000..5bb9da1 --- /dev/null +++ b/DomoEspSensor/SensorPulsante.h @@ -0,0 +1,51 @@ +#ifndef SensorPulsanteDef +#define SensorPulsanteDef 1 +#include "defines.h" +//sensor que avisa del cambio cuando deja de ser el valor por defecto +class SensorPulsante: public DomoEspSensorReceiver +{ + bool val; + bool valDef; + uint8_t pin; + + public: + virtual float getVal() + { + return (float)val; + } + SensorPulsante() + {} + void set(uint8_t _pin, char* topic_id, bool _valDef) + { + pin=_pin; + valDef=_valDef; + val=valDef; + strcpy(topic, topic_id); + } + virtual void procesa(IMqttManager * man, int tiempo) + { + //mirar para configurar por interrupcion + int val_ac=digitalRead(pin); + + if(val_ac!=val && val_ac!=valDef) + { + #ifdef DEBUG_PS + Serial.println("SensorPulsante log "); + #endif + //loguea------------ + sprintf(buffer_p, "%d", (int)val_ac); + sprintf(buffer_t, "%s/pul",topic); + man->MqttSend(buffer_t, buffer_p); + delay(100); + } + val=val_ac; + } + + virtual void inicia() + { + pinMode(pin, INPUT); + val=digitalRead(pin); + } +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/SensorRF.h b/DomoEspSensor/SensorRF.h new file mode 100644 index 0000000..3a8178d --- /dev/null +++ b/DomoEspSensor/SensorRF.h @@ -0,0 +1,41 @@ +#ifndef SensorRFDef +#define SensorRFDef 1 +#include "defines.h" +//sensor Replica, sensor interno que se setea con get y no se publica +class SensorRF: public DomoEspSensorReceiver +{ + float val; + + public: + SensorRF() + { + val=0; + topic[0]=0; + } + void set(char* topic_id, float valdef) + { + val=valdef; + strcpy(topic, topic_id); + } + virtual float getVal() + { + return (float)val; + } + virtual void SubscribeMqtt(IMqttManager* man){ + //char buffer_t[MAXTOPICVAR]; + sprintf(buffer_t, "%s/get",topic); + man->MqttSubs(buffer_t); + } + virtual void OnMqtt(IMqttManager * man, char* _topic, char* payload, int tipo) + { + if(tipo!=Topic::GET) + return; + if(!strcmp(_topic, topic)) + { + val=atof(payload); + } + + } +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/SensorVD.h b/DomoEspSensor/SensorVD.h new file mode 100644 index 0000000..a8a6367 --- /dev/null +++ b/DomoEspSensor/SensorVD.h @@ -0,0 +1,64 @@ +#ifndef SensorVDDef +#define SensorVDDef 1 +#include "defines.h" +//sensor virtual +class SensorVD: public DomoEspSensorReceiver +{ + bool val; + + public: + SensorVD() + { + val=0; + topic[0]=0; + } + void set(char* topic_id, bool valdef) + { + val=valdef; + strcpy(topic, topic_id); + } + virtual float getVal() + { + return (float)val; + } + virtual void procesa(IMqttManager * man, int tiempo) + { + if(tiempo==2) + { + #ifdef DEBUG_PS + Serial.print("LogSV "); + Serial.println(val); + #endif + //loguea------------ + //char buffer_t[MAXTOPICVAR]; + //char buffer_p[MAXTOPICVAR]; + sprintf(buffer_p, "%d", (int)val); + sprintf(buffer_t, "%s/get",topic); + man->MqttSend(buffer_t, buffer_p); + } + } + + virtual void SubscribeMqtt(IMqttManager* man){ + //char buffer_t[MAXTOPICVAR]; + sprintf(buffer_t, "%s/set",topic); + man->MqttSubs(buffer_t); + } + virtual void OnMqtt(IMqttManager * man, char* _topic, char* payload, int tipo) + { + if(tipo!=Topic::SET) + return; + if(!strcmp(_topic, topic)) + { + if(payload[0]=='X') + val=!val; + else + val=(atoi(payload)==1); + sprintf(buffer_p, "%d", (int)val); + sprintf(buffer_t, "%s/get",topic); + man->MqttSend(buffer_t, buffer_p); + } + + } +}; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/Utiles.cpp b/DomoEspSensor/Utiles.cpp new file mode 100644 index 0000000..bb77d07 --- /dev/null +++ b/DomoEspSensor/Utiles.cpp @@ -0,0 +1,227 @@ +#include +#include +#include +#include +#include +#include +#include + + +#include "Utiles.h" +//************************************************************************************************************************************************** + + + +bool MqttUtiles::pasa_incre( unsigned long *tt, unsigned long incre) +{ + unsigned long t=millis(); + if(t<*tt) + { + *tt=t; + return true; + } + if((*tt+incre)>=t) + return false; + *tt=t; + return true; +} + +bool MqttUtiles::pasa_incre( volatile unsigned long *tt, unsigned long incre) +{ + unsigned long t=millis(); + if(t<*tt) + { + *tt=t; + return true; + } + if((*tt+incre)>=t) + return false; + *tt=t; + return true; +} +void MqttUtiles::resetFunc() +{ + ESP.wdtEnable(1); + while(1){}; +} +//************************************************************************************************************************************************** +WifiManager::WifiManager() +{ + +} + +void WifiManager::inicia( WiFiClient *espclient,char *ssid, char* key, char *idArdu) +{ + espClient= espclient; + strcpy(nred, ssid); + strcpy(pass, key); + strcpy(idArduino,idArdu); + conecta(); + + //return WiFi.status() == WL_CONNECTED; +} + +bool WifiManager::conecta() +{ + #ifdef DEBUG_PS + Serial.println("Conectando wifi"); + Serial.println(nred); + Serial.println(pass); + #endif + + WiFi.mode(WIFI_STA); + WiFi.begin(nred, pass); + + for(int i=0; i<100 && WiFi.status() != WL_CONNECTED; i++) + { + delay(500); + #ifdef DEBUG_PS + Serial.print("."); + #endif + } + #ifdef DEBUG_PS + Serial.println(""); + if(WiFi.status() == WL_CONNECTED) + Serial.println("Wifi Conectado"); + else + { + Serial.println("No se pudo conectar"); + + } + #endif + if(WiFi.status() != WL_CONNECTED) + return false; + + //ota---------------------------------- + // Port defaults to 8266 + // ArduinoOTA.setPort(8266); + + // Hostname defaults to esp8266-[ChipID] + ArduinoOTA.setHostname(idArduino); + + // No authentication by default + // ArduinoOTA.setPassword("admin"); + + // Password can be set with it's md5 value as well + // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 + // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); + + ArduinoOTA.onStart([]() { + String type; + if (ArduinoOTA.getCommand() == U_FLASH) { + type = "sketch"; + } else { // U_FS + type = "filesystem"; + } + #ifdef DEBUG_PS + // NOTE: if updating FS this would be the place to unmount FS using FS.end() + Serial.println("Start updating " + type); + #endif + }); + ArduinoOTA.onEnd([]() { + Serial.println("\nEnd"); + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + #ifdef DEBUG_PS + Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + #endif + }); + ArduinoOTA.onError([](ota_error_t error) { + #ifdef DEBUG_PS + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) { + Serial.println("Auth Failed"); + } else if (error == OTA_BEGIN_ERROR) { + Serial.println("Begin Failed"); + } else if (error == OTA_CONNECT_ERROR) { + Serial.println("Connect Failed"); + } else if (error == OTA_RECEIVE_ERROR) { + Serial.println("Receive Failed"); + } else if (error == OTA_END_ERROR) { + Serial.println("End Failed"); + } + #endif + }); + ArduinoOTA.begin(); + #ifdef DEBUG_PS + Serial.println("Ready"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + #endif + return true; +} +bool WifiManager::loop() +{ + if((WiFi.status() == WL_CONNECTED)) + { + ArduinoOTA.handle(); + return true; + } + #ifdef DEBUG_PS + Serial.println("Fallo de conexion, se reinicia arduino"); + #endif + ESP.reset(); + return false; +} +//************************************************************************************************************************************************** +MqttManager::MqttManager() +{ + +} + +void MqttManager::inicia(PubSubClient *mqttClient,char *ideEsp, char *host, int port, MqttReceiver* classReceiver) +{ + strcpy(idEsp,ideEsp); + Mqttlistener=classReceiver; + client_mqtt=mqttClient; + client_mqtt->setServer(host, port); + client_mqtt->setCallback(MqttManager::OnMqtt); +} + +bool MqttManager::loop() +{ + if(client_mqtt->loop()) + return true; + #ifdef DEBUG_PS + if(WiFi.status() == WL_CONNECTED) + Serial.println("Conectando a broker"); + #endif + if(client_mqtt->connect(idEsp)) + { + #ifdef DEBUG_PS + if(WiFi.status() == WL_CONNECTED) + Serial.println("Conectado a broker"); + #endif + subscribe_mqtt(); + return true; + + } + #ifdef DEBUG_PS + Serial.println("Fallo de conexion, se reinicia arduino"); + #endif + ESP.reset(); + return false; +} +void MqttManager::subscribe_mqtt() +{ + if(Mqttlistener==NULL) + return; + Mqttlistener->SubscribeMqtt(client_mqtt); +} +//auxiliar------------------ +void MqttManager::OnMqtt(char* topic, byte* payload, unsigned int length) +{ + if(Mqttlistener==NULL) + return; + int i; + char buf[MAXTOPICVAR]; + i= MAXTOPICVAR-1; + if(i>length) + i=length; + memcpy(buf, payload, i); + buf[i]=0; + Mqttlistener->OnMqtt(topic, buf); + +} + +//************************************************************************************************************************************************** diff --git a/DomoEspSensor/Utiles.h b/DomoEspSensor/Utiles.h new file mode 100644 index 0000000..8549bc9 --- /dev/null +++ b/DomoEspSensor/Utiles.h @@ -0,0 +1,66 @@ +#ifndef UtilesDef +#define UtilesDef 1 +#include "defines.h" +class PubSubClient; +class WiFiClient; + +class MqttUtiles +{ + public: + static bool pasa_incre( unsigned long *tt, unsigned long incre); + static bool pasa_incre( volatile unsigned long *tt, unsigned long incre); + static void resetFunc(); +}; + +class MqttOnVarChangeListenner +{ + public: + virtual void OnVarChange(int ivar)=0; +}; + +class WifiManager +{ + public: + + char nred[32]; + char pass[32]; + char idArduino[32]; + WiFiClient *espClient; + + WifiManager(); + bool conecta(); + void inicia( WiFiClient *espClient, char *ssid, char* key, char *idArduino); + bool loop(); + +}; + + + +static MqttReceiver* Mqttlistener; +class MqttManager +{ + public: + + private: + + char idEsp[32]; + public: + + PubSubClient *client_mqtt; + MqttReceiver *mqttlisener; + MqttManager(); + +/* + WiFiClient espClient;//conexion a wifi + PubSubClient client_qqtt(espClient);//para conexion con mqtt + */ + void inicia(PubSubClient *mqttClient,char *ideEsp, char *host, int port, MqttReceiver* classReceiver); + bool loop(); + + //void desconecta(); + + //auxiliar------------------ + static void OnMqtt(char* topic, uint8_t * payload, unsigned int length); + void subscribe_mqtt(); +}; +#endif \ No newline at end of file diff --git a/DomoEspSensor/configuracionActual.h b/DomoEspSensor/configuracionActual.h new file mode 100644 index 0000000..c37b2dd --- /dev/null +++ b/DomoEspSensor/configuracionActual.h @@ -0,0 +1,175 @@ + +#ifndef DomoConfActualDef +#define DomoConfActualDef 1 +#include "DomoEspConfig.h" +#include "SensorDout.h" +#include "SensorDHT.h" +#include "SensorDin.h" +#include "SensorPulsante.h" +#include "SensorAin.h" +#include "SensorVD.h" +#include "SensorRF.h" + + +#include "MecanismoPulso.h" +//---------------------------------------------------------------------------------------------------------------------------------------------- +class AutomatismoPulsador//automatismo para encender luz con interruptor o pulsador +{ + + MecanismoPulso pulsador;//cambia estado con pulsador + public: + AutomatismoPulsador(){} + void inicia(ISensorManager* man, DomoEspSensorReceiver* tp_pul, DomoEspSensorReceiver* tpOut, DomoEspSensorReceiver* bloqueo=NULL ) + { + inicia(man, tp_pul->topic, tpOut->topic, bloqueo); + } + void inicia(ISensorManager* man, char* tp_pul, char* tpOut, DomoEspSensorReceiver* bloqueo=NULL ) + { + pulsador.set(tp_pul, tpOut, 0); + pulsador.setValSend("X"); + if(bloqueo) + { + pulsador.AddActivador(bloqueo,'>',0); + } + man->Add(&pulsador); + } +}; +class AutomatismoPresencia//automatismo para encender luz con presencia +{ + + MecanismoPulso presenciaOn; + MecanismoPulso presenciaOff; + MecanismoPulso nivelLuzOff; + float fnivelLuz; + public: + AutomatismoPresencia() + { + fnivelLuz=50; + + + strcpy(presenciaOn.id, "PresOn"); + strcpy(presenciaOff.id, "PresOff"); + strcpy(nivelLuzOff.id, "luzOff"); + + } + + + void inicia(ISensorManager* man, DomoEspSensorReceiver* presencia, DomoEspSensorReceiver* nivelluz, DomoEspSensorReceiver* out, DomoEspSensorReceiver* bloqueo=NULL ) + { + + presenciaOn.set(presencia->topic, out->topic, 0); + presenciaOn.setValSend("1"); + presenciaOn.AddActivador(nivelluz,'<',fnivelLuz);//nivel de luz bajo + presenciaOn.AddActivador(out,'<',1);//out apagada + presenciaOn.AddActivador(presencia,'>',0);//presencia + if(bloqueo) + { + presenciaOn.AddActivador(bloqueo,'>',0); + } + presenciaOff.set(presencia->topic, out->topic, 0); + presenciaOff.setValSend("0"); + presenciaOff.AddActivador(out,'>',0);//out encendido + presenciaOff.AddActivador(presencia,'<',1);//no presencia + if(bloqueo) + { + presenciaOff.AddActivador(bloqueo,'>',0); + } + + nivelLuzOff.set(nivelluz->topic, out->topic, 0); + nivelLuzOff.setValSend("0"); + nivelLuzOff.AddActivador(out,'>',0);//out encendido + nivelLuzOff.AddActivador(nivelluz,'>',fnivelLuz);//no luz + if(bloqueo) + { + nivelLuzOff.AddActivador(bloqueo,'>',0); + } + + + man->Add(&presenciaOn); + man->Add(&nivelLuzOff); + man->Add(&presenciaOff); + + + } +}; +//configuraciones----------------------------------------------------- +class Automatismos: public DomoEspConfig +{ + SensorRF presencia; + SensorRF nivelLuz; + SensorRF out; + SensorVD bloqueo; + + //AutomatismoPulsador pulsadorSalon; + AutomatismoPresencia Apresen; + public: + Automatismos() + { + strcpy(ssidWifi,"IdhunAux");//nombre wifi + strcpy(ideEsp,"Esp8266_auto");//idenitificador del esp (sera único) + //pulsador sin activadores + presencia.set("casa/pruebas/inter",0); + nivelLuz.set("casa/pruebas/ana",0); + out.set("casa/pruebas/luz",0); + bloqueo.set("casa/pruebas/auto", true); + + } + + + + virtual void inicia(ISensorManager* man) + { + man->Add(&presencia); + man->Add(&nivelLuz); + man->Add(&out); + man->Add(&bloqueo); + Apresen.inicia(man,&presencia,&nivelLuz,&out,&bloqueo); + //pulsadorSalon.inicia(man,"casa/pruebas/pul", "casa/pruebas/luz"); + } + +}; + +class ConfActual: public DomoEspConfig +{ + + SensorDout luz; + SensorDHT dht; + SensorPulsante pul; + SensorDin interup; + SensorAin analog; + SensorVD sv; + + public: + ConfActual() + { + strcpy(ssidWifi,"IdhunAux");//nombre wifi + strcpy(ideEsp,"Esp8266_pruebas");//idenitificador del esp (sera único) + + luz.set(D1, "casa/pruebas/luz",0); + dht.set(D0, "casa/pruebas/dht"); + pul.set(D2,"casa/pruebas/pul",1); + interup.set(D3,"casa/pruebas/inter"); + analog.set(0,"casa/pruebas/ana",0, 1); + //analog.set(0,"casa/pruebas/ana",0, 0);*/ + + sv.set("casa/pruebas/vir",0); + + + } + virtual void inicia(ISensorManager* man) + { + man->Add(&luz); + man->Add(&dht); + man->Add(&pul); + man->Add(&interup); + man->Add(&analog); + man->Add(&sv); + + } + +}; + + +Automatismos ConfiguracionActual; + +#endif \ No newline at end of file diff --git a/DomoEspSensor/defines.h b/DomoEspSensor/defines.h new file mode 100644 index 0000000..6f90b06 --- /dev/null +++ b/DomoEspSensor/defines.h @@ -0,0 +1,94 @@ +#ifndef DefinesDef +#define DefinesDef 1 + +#define DEBUG_PS 1 +#define CON_WOL 0 +#define CON_LCD 0 + +#define MAXTOPICVAR 32//maximo de caracteres de los topic de las variables + +//vars-------------------- +#define MAXSTR 2024//maximo de caracteres para str + +//sens-------------------- +#define MAXSENS 16 +#define MAXINTERRUP 8 + + +#ifndef DO +#define D0 16 +#endif +#ifndef D1 +#define D1 5 +#endif +#ifndef D2 +#define D2 4 +#endif +#ifndef D3 +#define D3 0 +#endif +#ifndef D4 +#define D4 2 +#endif +#ifndef D5 +#define D5 14 +#endif +#ifndef D6 +#define D6 12 +#endif +#ifndef D7 +#define D7 13 +#endif +#ifndef D8 +#define D8 15 +#endif + +class Topic +{ + public: + enum TipoTopic//indica el tipo de sensor + { + NO_RECONOCIDO=0,//TIPO TOPIC NO RECONOCIDO + GET,//TIPO GET + SET,//TIPO SET + PUL//TIPO PULSANTE (HA SUCEDIDO ALGO) + }; +}; + +class PubSubClient; +//clases +class MqttReceiver +{ + public: + virtual void OnMqtt(char* topic, char* payload)=0; + virtual void SubscribeMqtt(PubSubClient *client_mqtt){} +}; + +class IMqttManager +{ + public: + virtual void MqttSend(char* topic, char* payload)=0; + virtual void MqttSubs(char* topic)=0; +}; + + static char buffer_t[MAXTOPICVAR]; + static char buffer_p[MAXTOPICVAR]; + +class DomoEspSensorReceiver +{ + public: + char topic[MAXTOPICVAR]; + + virtual void OnMqtt(IMqttManager * man, char* topic, char* payload, int tipo){}; + virtual void SubscribeMqtt(IMqttManager* man){}; + virtual void procesa(IMqttManager * man, int tiempo){}; + virtual void inicia(){}; + virtual float getVal()=0; +}; + +class ISensorManager +{ + public: + virtual void Add(DomoEspSensorReceiver* sensor)=0; +}; +#endif \ No newline at end of file