PitCnD

PitCnD, dopo PitAlarmBot - Pit Check aNd Do.

 

Partendo da PitAlarmBot, PitCnD PitAlarm è un sistema integrato di controllo (Check) e in funzione di determinati eventi di azione (Do). In pratica sitentizza in un unico codice personalizzabile attraverso la programmazione condizionale alcuni precedenti software.

Check Do Funzione
Orario e presenza h2o messaggio e chiusura contatto (rele) PitOrto - irrigazione orto sul balcone
presenza sensore di PIR messaggio PitAlarm - messaggio allarme presenza
Sensore Reed messaggio PitAlarm - allarme apertura/chiusura (apertura porta/livello h2o/ecc)
livello rilevazione sensore messaggio PitMqSensor - allarme soglia superata (fuga di gas)
distanza messaggio PitDist - messaggio di distanza soglia superata (oggetto troppo vicino/lontano)

ozio_gallery_jgallery

Codice sorgente:


Zappoco        - PitCnD21_01_1D 31/01/2021 -- taratura sensore serie MQ - prova con MQ04 - metano
Zappoco        - PitCnD21_01_1C 30/01/2021 -- prima integrazione PitOrto - funzionamento giornaliero
Zappoco        - PitCnD20_08_1B 29/08/2020 -- integrazione sensore ultrasuoni
Zappoco        - PitCnD20_08_1A 28/08/2020 -- integrazione sensore PIR
Zappoco        - PitCnD20_08_19 21/08/2020 -- integrazione sensore di fumo o simile
  PitCnD --> Stazione di controllo Check and Do del PIT
  www.zappoco.altervista.org
  Evoluzione di PitAlarm e integrazione di PitPump
   Check                 Do            Tag             Pin Scheda
---------------------------------------------------------------
  Orario           --> Pompaggio --> OnPitPump     -->   D1 D2
  Dist             --> Allarme   --> OnPitDist     -->   not jet implemented
  Pir              --> Allarme   --> OnPitPir      -->   D5
  Reed             --> Allarme   --> OnPitReed     -->   D1
  Sensore (soglia) --> Allarme   --> OnPitMQSensor -->   A0
---------------------------------------------
---------------------------------------------
    	Pinout per WEMOS D1 mini	
---------------------------------------------
	Pin Sheda        Pin IDE 
				           (GPIONN)
	  D4  ------------  2
	  D3  ------------  0
	  D2  ------------  4
	  D1  ------------  5
	  D0  ------------ 16
	  D5  ------------ 14
	  D6  ------------ 12
	  D7  ------------ 13
	  D8  ------------ 15
	  RX  ------------ 03
	  TX  ------------ 01
---------------------------------------------
*/
#define PitProgramVersion "PitCnD_V21_01_1D - by Zappoco"
//----------------------------------------------------------------------------------------
// Weblogger
//----------------------------------------------------------------------------------------
  #define TE_ST_01                            //Profilo TEST completo          -- PitCnD_V21_01_1D - by Zappoco
//----------------------------------------------------------------------------------------
//  Fine settaggio
//----------------------------------------------------------------------------------------
//Profilo di test
#ifdef TE_ST_01
  #define PitLocation_DEF "MRGB"   //nome della location
  #define PitStation_DEF  "AL01"   //nome della stazione
  #define PitSubject_DEF  " --> stazione di TEST inizializzata correttamente";
  //----------------------------------------------------------------------------------------
  //Impostazioni PitPir
  //----------------------------------------------------------------------------------------
  //#define OnPitPir               //2021030 --> ok verificato
  #ifdef OnPitPir
    #define PitPirBody_DEF " allarme sensore PIR"
  #endif 
  //----------------------------------------------------------------------------------------
  //Impostazioni PitReed
  //----------------------------------------------------------------------------------------
  #define OnPitReed              //2021030 --> ok verificato
  #ifdef OnPitReed
    //#define OnPitReedOpen        // invia l'allarme se aperto anzichè se chiuso
    #ifdef OnPitReedOpen
      #define PitReedBody_DEF " allarme apertura contatto reed"
    #else
      #define PitReedBody_DEF " allarme chiusura contatto reed"
    #endif
  #endif
  //----------------------------------------------------------------------------------------
  //Impostazioni PitPump
  //----------------------------------------------------------------------------------------
  //#define OnPitPump              //2021030 --> ok verificato
  #ifdef OnPitPump
    #define pumpOrario 20        // Ora in cui viene accesa la pompa
    #define pumpDurata 30000     // durata del pompaggio
    #define PitPumpBody_DEF " pompaggio completato correttamente"
    #define PitPumpBody_DNO " livello H2O insufficiente"
  #endif
  //----------------------------------------------------------------------------------------
  //Impostazioni PitMQSensor
  //----------------------------------------------------------------------------------------
  //#define OnPitMQSensor           //2021030 --> ok verificato
  #ifdef OnPitMQSensor
    #define MQsensorLevel 450      // livello di allarme
    //#define MQsensorLE             // minore o uguale
    #define MQsensorGE           // maggiore o uguale
    #define PitMQSensorBody_DEF " MQ04 - Allarme Metano Soggiorno"
  #endif
  #define OnReset                     // Attiva il reset
  #define Router
  #define OnWebLogger
  #define OnTelegramBotSend
  #define TimeNTP
  #define OnSerial                    // stampa sulla seriale
  #define OnDebug                     // accorcia i tempi
  //#define OnPiuDebug                  // stampa maggiori dettagli sulla seriale
#endif
#ifdef OnWebLogger
  #include "Arduino.h"           //HTTP
#endif
#include "ESP8266WiFi.h"
#ifdef OnWebLogger
  #include "ESP8266WiFiMulti.h"
  #include "ESP8266HTTPClient.h"
  #include "WiFiClient.h"
  ESP8266WiFiMulti WiFiMulti;
#endif
#ifdef OnTelegramBotSend
  #include "WiFiClientSecure.h"
  // ----------------------------
  // Additional Libraries - each one of these will need to be installed.
  // ----------------------------
  #include "UniversalTelegramBot.h"
  #include "ArduinoJson.h"
  // Search for "Arduino Json" in the Arduino Library manager
  // https://github.com/bblanchon/ArduinoJson
#endif
#define PitAlarmMyHostUrl_DEF      "http://www.fdt.altervista.org"
#ifdef Router
  #define MySsid     "MySsid"
  #define MyPassword "MyPassword"
#endif
// Initialize Wifi connection to the router
char ssid[]     = MySsid;                     // your network SSID (name)
char password[] = MyPassword;                 // your network key
#ifdef OnTelegramBotSend
  // Use @myidbot to find out the chat ID of an individual or a group
  // Also note that you need to click "start" on a bot before it can
  // message you
  #define CHAT_ID "12345678"
  // Initialize Telegram BOT
  #define BOTtoken "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  // your Bot Token (Get from Botfather)
  WiFiClientSecure BOTclient;
  UniversalTelegramBot bot(BOTtoken, BOTclient);
#endif
#ifdef TimeNTP
  #include "TimeLib.h"
  #include "WiFiUdp.h"
  // NTP Servers:
  // IPAddress timeServer(193, 204, 114, 232); // ntp1.inrim.it -->  www.inrim.it (istituto nazionale di ricerca e meteorologia)
  // IPAddress timeServer(193, 204, 114, 233); // ntp2.inrim.it -->  www.inrim.it (istituto nazionale di ricerca e meteorologia)
  IPAddress timeServer(193, 204, 114, 105); // time.inrim.it -->  www.inrim.it (istituto nazionale di ricerca e meteorologia)
  //
  // era definita const int
  //
  int timeZone = 1;     // Central European Time - con ora solare
  unsigned int localPort = 8888;  // local port to listen for UDP packets
  time_t prevDisplay = 0; // when the digital clock was displayed
  WiFiUDP Udp;
  time_t getNtpTime();
  // unsigned int localPort = 8888;  // local port to listen for UDP packets
#endif
//----------------------------------------------------------------------------------------
//  Fine impostazioni
//----------------------------------------------------------------------------------------
#ifdef OnDebug     
  #define intTime  20000     // setta a 1 minuto (60000 millisecondi) l'intervallo tra gli allarmi (timedelay)
  #define intReset 5         // setta a 5 le volte per il ritardo reset
#else
  #define intTime  300000    // setta a 5 minuti (300000 millisecondi) l'intervallo tra gli allarmi (timedelay)
  #define intReset 72        // setta a 72 le volte per il ritardo reset  --> 6 ore 
#endif
#if defined(PitAlarmMyHostUrl_DEF)
  String PitAlarmMyHost  =  PitAlarmMyHostUrl_DEF;
#endif
#if defined(PitLocation_DEF)
  String PitAlarmSub  = PitLocation_DEF;
#else
  String PitAlarmSub  = "dati";
#endif
#if defined(PitStation_DEF)
  String PitSt  = PitStation_DEF;
#else
  String PitSt  = "";
#endif
String PitAlarmDir = "/Z_PitAlarm/";
String Subject = PitProgramVersion;
#ifdef OnPitPir
  String BodyPir = PitAlarmSub + " " + PitSt + ": " + PitPirBody_DEF;
#endif
#ifdef OnPitReed
  String BodyReed = PitAlarmSub + " " + PitSt + ": " + PitReedBody_DEF;
#endif
#ifdef OnPitPump
  String BodyOrto  = PitAlarmSub + " " + PitSt + ": " + PitPumpBody_DEF;
  String BodyOrNO  = PitAlarmSub + " " + PitSt + ": " + PitPumpBody_DNO;
#endif
#ifdef OnPitMQSensor
  String BodyMQSensor = PitAlarmSub + " " + PitSt + ": " + PitMQSensorBody_DEF;
#endif
//----------------------------------------------------------------------------------------
// Variabili controllo allarmi
//----------------------------------------------------------------------------------------
boolean FlagSended      = false;  // Flag di allarme inviato
boolean FlagAllarmeReed = false;  // Flag di allarme rilevato
boolean FlagAllarmePir  = false;  // Flag di allarme rilevato
//----------------------------------------------------------------------------------------
// Variabili temporali
//----------------------------------------------------------------------------------------
unsigned long TimeDelay = intTime;
unsigned long TimeReset = intReset * intTime;
unsigned long TimeStart = 0;             // tempo di partenza 
unsigned long TimeUltima = 0;            // tempo ultima lettura
unsigned long TimeAdesso = 0;            // tempo della lettura
long TimeDelta  = 0;                     // differenza
unsigned long tempo;
// ---------------------------------------------------
// Variabili controllo PitPir su D1 Mini - Pin D5 --> GPIO 14 
// ---------------------------------------------------
#ifdef OnPitPir
  int pirPin = 14;
  int pirVal ;
#endif
// ---------------------------------------------------
// Variabili controllo PitReed su D1 Mini - Pin D1 --> GPIO 5
// ---------------------------------------------------
#ifdef OnPitReed
  int reedPin = 5;
  int reedVal ;
#endif
// ---------------------------------------------------
// Variabili controllo PitPump su D1 Mini
// Pin D2 --> GPIO 4 --> sensore H2O
// Pin D1 --> GPIO 5 --> relais
// ---------------------------------------------------
#ifdef OnPitPump
  const int h2oSensorPin = 4;              //pin collegamento livello H2O D2 - GPIO4
  int liquidSensorVal;
  int pumpPin = 5;                         //pin collegamento pompa D1 - GPIO5
  int pumpHour = pumpOrario;               //ora in cui viene accesa la pompa
  unsigned long pumpDelay = pumpDurata;    //durata del pompaggio
  boolean pumpFlag = false;                //Flag pompaggio
#endif
  unsigned long Counter = 0;               // contatore delle letture
// ---------------------------------------------------
// Variabili controllo PitMQSensor
// ---------------------------------------------------
#ifdef OnPitMQSensor
  int smokeA0 = A0;
  // Your threshold value
  int sensorThres = MQsensorLevel;
  boolean analogSensorFlag;
#endif
void setup() {
  #ifdef OnSerial
    Serial.begin(9600);
  #endif
 #ifdef OnSerial     
    // Serial.println(Arduino);
    Serial.println("");
    Serial.println("");
    Serial.println(PitProgramVersion);
    Serial.println("---------------------------");    
    #ifdef OnPiuDebug
      Serial.print  (" OnPitPir        is ");
      #ifdef OnPitPir
        Serial.println("on");
      #else
        Serial.println("off");
      #endif
      Serial.print  (" OnPitReed       is ");
      #ifdef OnPitReed
        Serial.println("on");
      #else
        Serial.println("off");
      #endif
      Serial.print  (" OnPitReedOpen   is ");
      #ifdef OnPitReedOpen
        Serial.println("on");
      #else
        Serial.println("off");
      #endif
      Serial.print  (" OnPitPump       is ");
      #ifdef OnPitPump
        Serial.println("on");
      #else
        Serial.println("off");
      #endif
      Serial.print  (" OnPitMQSensor      is ");  
      #ifdef OnPitMQSensor
        Serial.println("on");
        Serial.print  (" MQsensorLevel      is "); Serial.print  (sensorThres);
        #ifdef MQsensorLE
          Serial.println(" LE --> minore o uguale");  
        #endif
        #ifdef MQsensorGE
          Serial.println(" GE --> maggiore o uguale");  
        #endif
      #else
        Serial.println("off");
      #endif
      Serial.print  (" OnDebug            is ");
      #ifdef OnDebug
        Serial.println("on");
      #else
        Serial.println("off");
      #endif
      Serial.print  (" OnPiuDebug         is ");
      #ifdef OnPiuDebug
        Serial.println("on");
      #else
        Serial.println("off");
      #endif
      #ifdef TimeNTP
        Serial.println(" TimeNTP            is on");
        Serial.print  (" TimeZone           is "); Serial.println(timeZone);
      #endif
      Serial.println("---------------------------");
    #endif
  #endif 
  Subject = Subject + " - " + PitAlarmSub + " " + PitSt + PitSubject_DEF ;
  #ifdef OnTelegramBotSend
    // This is the simplest way of getting this working
    // if you are passing sensitive information, or controlling
    // something important, please either use certStore or at
    // least client.setFingerPrint
    BOTclient.setInsecure();
  #endif
  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  #ifdef OnSerial
    // Attempt to connect to Wifi network:
    Serial.print("Connecting Wifi: ");
    Serial.println(ssid);
  #endif
  WiFi.begin(ssid, password);    // commentato per linea HTTP
  while (WiFi.status() != WL_CONNECTED) {
    #ifdef OnSerial
      Serial.print(".");
    #endif
    delay(500);
  }
  #ifdef OnSerial
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  #endif
  #ifdef TimeNTP
    // NTP Time
    Udp.begin(localPort);
    #ifdef OnPiDebug
      #ifdef ESP8266
        Serial.print(" local port: ");
        Serial.print(Udp.localPort());
      #endif
      Serial.println(" NTP waiting for sync ... ");
    #endif
    setSyncProvider(getNtpTime);
    setSyncInterval(300);
    time_t prevDisplay = 0; // when the digital clock was displayed
    //
    // verifica se deve scattare ora legale o ora solare
    //
    // legaltime estrapolata da  http://www.mauroalfieri.it/elettronica/orto-idroponico-verticale-con-arduino-quinta-parte.html
    //
    // attenzione nella routine di Mauro Alfieri la domenica è 0 mentre nella routine arduino la domenica è 1
    //
          byte cFlag = 0;
    const byte iDayW = weekday();
    const byte iDay  = day() -1;  // attenzione nella routine di mauro alfieri la domenica è 0 mentre nella routine arduino la domenica è 1
    const byte iMonth= month();
    const byte iHour = hour();
    // ottobre
    if (iMonth == 10) {
      if (iDayW == 0) {
          if (((iDay + 7) > 31) && (iHour >= 3)) { cFlag = 0; }
      } else {
        if ((iDay + (7 - iDayW))> 31) { cFlag = 0; }
        else { cFlag = 1; }
      }
    }
    // marzo
    if (iMonth == 3) {
      if (iDayW == 0) {
        if (((iDay + 7) > 31) && (iHour >= 2)) { cFlag = 1; }
      } else {
        if((iDay + (7 - iDayW))> 31) { cFlag = 1; } else { cFlag = 0; }
      }
    }
    if(iMonth >= 4 && iMonth <= 9) { cFlag = 1; }
    if((iMonth >= 1 && iMonth <= 2) || (iMonth >= 11 && iMonth <= 12)) { cFlag = 0; }
    // cFlag= 1; // solo per test
    if (cFlag != 0){
      timeZone += cFlag;
      setSyncProvider(getNtpTime);
      prevDisplay = now();
    }
    #ifdef OnPiuDebug
      Serial.println(".......................................................");
      Serial.println("passaggio automatico ora legale / solare");
      Serial.println(".......................................................");
      Serial.print("day      : "); Serial.println(day());
      Serial.print("month    : "); Serial.println(month());
      Serial.print("year     : "); Serial.println(year());
      // Day of the week (1-7), Sunday (domenica) is day 1  --> http://playground.arduino.cc/Code/Time
      Serial.print("weekday  : "); Serial.println(weekday()); 
      Serial.print("hour     : "); Serial.println(hour());
      Serial.print("minute   : "); Serial.println(minute());
      Serial.print("second   : "); Serial.println(second());
      Serial.println(".......................................................");
      Serial.print("cFlag    : "); Serial.println(cFlag);
      Serial.println(".......................................................");
      Serial.print("timeZone : "); Serial.println(timeZone);
      Serial.println(".......................................................");
    #endif
  #endif // --> #ifdef TimeNTP
  PrintAlarmData (Subject);
  FlagSended = false;
  PrintAlarmData (PitAlarmSub + " " + PitSt + ": PitCnD --> Stazione di controllo Check and Do del PIT");
  FlagSended = false;
  // ---------------------------------------------------
  // Inizializzazione PIN
  // ---------------------------------------------------
  #ifdef OnPitPir
    PrintAlarmData (PitAlarmSub + " " + PitSt + ": se il sensore Pir rileva presenza (Check) invia (Do) un messaggio di allarme"); 
    pinMode (pirPin, INPUT);
    FlagSended = false;
  #endif
  #ifdef OnPitReed
    #ifdef OnPitReedOpen
      PrintAlarmData (PitAlarmSub + " " + PitSt + ": se il sensore Reed è aperto (Check) invia (Do) un messaggio di allarme"); 
    #else
      PrintAlarmData (PitAlarmSub + " " + PitSt + ": se il sensore Reed è chiuso (Check) invia (Do) un messaggio di allarme"); 
    #endif
    pinMode (reedPin, INPUT);
    FlagSended = false;
  #endif
  #ifdef OnPitPump
    //sprintf(str, "%06d", Counter)
    PrintAlarmData (PitAlarmSub + " " + PitSt + ": se sono le ore " + String (pumpHour) + " e c'è acqua nel serbatoio (Check) aziona l'irrigazione (Do) per " + String(pumpDelay/1000) + " secondi"); 
    pinMode(h2oSensorPin, INPUT);
    pinMode (pumpPin, OUTPUT);
    digitalWrite (pumpPin, LOW);
    FlagSended = false;
  #endif
  #ifdef OnPitMQSensor
    pinMode(smokeA0, INPUT);  
    #ifdef MQsensorLE
      PrintAlarmData (PitAlarmSub + " " + PitSt + ": se il valore rilevato è minore di " +  String(MQsensorLevel) + " (Check) invia (Do) un messaggio di allarme"); 
    #endif
    #ifdef MQsensorGE
      PrintAlarmData (PitAlarmSub + " " + PitSt + ": se il valore rilevato è maggiore di " +  String(MQsensorLevel) + " (Check) invia (Do) un messaggio di allarme"); 
    #endif
    FlagSended = false;
  #endif
  FlagSended = false;
  TimeStart  = millis();
  TimeAdesso = TimeStart;
  TimeUltima = TimeStart;
}
void loop() {
  // --------------------------------------------------------
  // PitPirCode - START
  // --------------------------------------------------------
    #ifdef OnPitPir
      pirVal = digitalRead(pirPin);
      if (pirVal == HIGH) {
        FlagAllarmePir = true;
      } else {
        FlagAllarmePir = false;
      }
      if (FlagAllarmePir){
        PrintAlarmData (BodyPir);
      }
    #endif
  // --------------------------------------------------------
  // PitPirCode - END
  // --------------------------------------------------------
  // --------------------------------------------------------
  // PitReedCode - START
  // --------------------------------------------------------
    #ifdef OnPitReed
      #ifdef OnPitReedOpen  
        reedVal = !digitalRead(reedPin);
      #else
        reedVal = digitalRead(reedPin);
      #endif
      if (reedVal == HIGH) {
        FlagAllarmeReed = true;
      } else {
        FlagAllarmeReed = false;
      }
      if (FlagAllarmeReed){
        PrintAlarmData (BodyReed);
      }
    #endif
  // --------------------------------------------------------
  // PitReedCode - END
  // --------------------------------------------------------
  // --------------------------------------------------------
  // PitPumpCode - START
  // --------------------------------------------------------
    #ifdef OnPitPump
      TimeAdesso = millis();
      TimeDelta = TimeAdesso - TimeUltima - TimeDelay;
      #ifdef OnPiuDebug
        Serial.print("TimeAdesso:") ;Serial.println(TimeAdesso);
        Serial.print("TimeUltima:") ;Serial.println(TimeUltima);
        Serial.print("TimeDelta :") ;Serial.println(TimeDelta);
      #endif
      if (TimeDelta >= 0) {  
        TimeUltima = millis();
        Counter++;
        #ifdef TimeNTP
          if  (hour() == pumpHour){
            #ifdef OnSerial
              PrintDateTime();
              Serial.print  (" pumpHour = ");
              Serial.print  (pumpHour);
              Serial.println(" -->  OK  e' l'ora giusta");
            #endif
            if  (pumpFlag == false) {
              #ifdef OnSerial
                Serial.println("  controllo livelli per pompaggio ");
              #endif
              liquidSensorVal = digitalRead (h2oSensorPin);
              // se non presente sensore 
              //liquidSensorVal = !digitalRead (h2oSensorPin);
              #ifdef OnSerial
                #ifdef OnPiuDebug
                  Serial.print  ("liquidSensorVal :");
                  Serial.println(liquidSensorVal);
                #endif              
              #endif              
              if (liquidSensorVal == HIGH) {
                #ifdef OnSerial
                  Serial.print  ("  Livello H2O OK ");
                #endif
                digitalWrite (pumpPin, HIGH);
                pumpFlag = true;
                delay(pumpDelay);
                digitalWrite (pumpPin, LOW);
                #ifdef OnSerial
                  Serial.println("--> Pompaggio completato correttamente");
                #endif
                PrintAlarmData (BodyOrto);
              } else {
                pumpFlag = true;
                #ifdef OnSerial
                  Serial.println("  Livello H2O basso: pump OFF");
                #endif
                PrintAlarmData (BodyOrNO);
              }
              digitalWrite (pumpPin, LOW);
            } else {
              #ifdef OnSerial
                Serial.println("  pompaggio gia' eseguito");
              #endif
            }          
          } else {
            #ifdef OnSerial
              PrintDateTime();
              Serial.print  (" pumpHour = ");
              Serial.print  (pumpHour);
              Serial.println(" --> Non e' l'ora giusta");
            #endif
          }
        #endif      
      }
    #endif
  // --------------------------------------------------------
  // PitPumpCode - END
  // --------------------------------------------------------
  // --------------------------------------------------------
  // PitMQSensor - START
  // --------------------------------------------------------
    #ifdef OnPitMQSensor
      TimeAdesso = millis();
      TimeDelta = TimeAdesso - TimeUltima - TimeDelay;
      #ifdef OnPiuDebug
        Serial.print("TimeAdesso:") ;Serial.println(TimeAdesso);
        Serial.print("TimeUltima:") ;Serial.println(TimeUltima);
        Serial.print("TimeDelta :") ;Serial.println(TimeDelta);
      #endif
      if (TimeDelta >= 0) {  
        TimeUltima = millis();
        Counter++;
        int analogSensor = analogRead(smokeA0);
        #ifdef OnSerial
          Serial.print("Pin A0: "); Serial.print(analogSensor);
        #endif
        // Checks if it has reached the threshold value
        #ifdef MQsensorLE           // minore o uguale
          analogSensorFlag = analogSensor <= sensorThres;
        #endif
        #ifdef MQsensorGE           // maggiore o uguale
          analogSensorFlag = analogSensor >= sensorThres;
        #endif
        if (analogSensorFlag)
        {
          #ifdef OnSerial
            Serial.println(" --> ALARM OK");
          #endif
          PrintAlarmData (BodyMQSensor);
        }
        else
        {
          #ifdef OnSerial
            Serial.println(" --> ALARM NO");
          #endif
        }
        #ifdef TimeNTP
        #endif      
      }
    #endif
  // --------------------------------------------------------
  // PitMQSensor - END
  // --------------------------------------------------------
  #ifdef OnReset
    TimeAdesso = millis();
    TimeDelta = TimeAdesso - TimeStart - TimeReset;
    if (TimeDelta >= 0) {
      ESP.reset();
      #ifdef OnSerial     
        Serial.println("Reset del sistema");
      #endif 
    }
  #endif
}
//--------------------------------------------------------------------------------------------------------------
// Questa funzione stampa i dati
// 
// -->  seriale
// -->  WEB
// -->  TelegramBOT
//--------------------------------------------------------------------------------------------------------------
void PrintAlarmData ( String PitAlarmString_S) {
  TimeAdesso = millis();
  TimeDelta = TimeAdesso - TimeUltima - TimeDelay;
  if (TimeDelta >= 0) {  
    FlagSended = false;  
  }
  String PitAlarmString_W = PitAlarmString_S;
  PitAlarmString_W.replace(" ", "_");
  #ifdef TimeNTP
    // NTP Time
    prevDisplay = now();
    #ifdef OnSerial
      PrintDateTime();      
    #endif
  #endif
  #ifdef OnSerial     
    Serial.print (PitAlarmString_S);
  #endif
  #ifdef OnTelegramBotSend
    if (!FlagSended ){
      #ifdef OnSerial     
        Serial.print(" : [TBOT] send ok");
      #endif 
      bot.sendMessage(CHAT_ID, PitAlarmString_S, "");
      PitAlarmString_W = PitAlarmString_W + "_[TBOT]_send_ok" ;
      FlagSended = true;  
      TimeUltima = millis();
    } else{
      #ifdef OnSerial     
        Serial.print(" : [TBOT] send no");
      #endif 
    }
  #endif
  String PitAlarmUrl = PitAlarmMyHost + PitAlarmDir + "PIT_write_logs.php?P1=" + PitAlarmSub + "/" + PitSt  + "&dato=" + PitAlarmString_W;
  #ifdef OnSerial     
    #ifdef OnPiuDebug
      Serial.print   ("url: ");
      Serial.println (PitAlarmUrl);
    #endif
  #endif
  #ifdef OnWebLogger
    // wait for WiFi connection
    if ((WiFiMulti.run() == WL_CONNECTED)) {
      WiFiClient httpClient;
      HTTPClient httpServer;
      #ifdef OnSerial
        Serial.print(" : [HTTP] send ");
      #endif
      //if (httpServer.begin(httpClient, "http://www.fdt.altervista.org/Z_PitAlarm/PIT_write_logs.php?P1=RVFL/FL01&dato=FL01_inizializzato_correttamente")) {  // HTTP
      if (httpServer.begin(httpClient, PitAlarmUrl)) {  // HTTP
        #ifdef OnSerial
          Serial.println("ok");
        #endif
        #ifdef OnPiuDebug
          Serial.print("[HTTP] GET...\n");
        #endif
        // start connection and send HTTP header
        int httpCode = httpServer.GET();
        // httpCode will be negative on error
        if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          #ifdef OnPiuDebug
            Serial.printf("[HTTP] GET... code: %d\n", httpCode);
          #endif
          // file found at server
          if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            String payload = httpServer.getString();
            #ifdef OnPiuDebug
              Serial.println(payload);
            #endif
          }
        } else {
          Serial.printf("[HTTP] GET... failed, error: %s\n", httpServer.errorToString(httpCode).c_str());
        }
        httpServer.end();
      } else {
        Serial.printf("[HTTP} Unable to connect\n");
      }
    }
  #endif  
}
#ifdef TimeNTP
  #ifdef OnSerial
    void PrintDateTime() {
      // digital clock display of the time
      if (day() < 10)
        Serial.print('0');
      Serial.print(day());
      Serial.print("/");
      if (month() < 10)
        Serial.print('0');
      Serial.print(month());
      Serial.print("/");
      Serial.print(year());
      Serial.print(",");
      if (hour() < 10)
        Serial.print('0');
      Serial.print(hour());
      printDigits(minute());
      printDigits(second());
      Serial.print(",");
    }
    void printDigits(int digits) {
      // utility for digital clock display: prints preceding colon and leading 0
      Serial.print(":");
      if (digits < 10)
        Serial.print('0');
      Serial.print(digits);
    }
  #endif
#endif
#ifdef TimeNTP
  /*-------- NTP code ----------*/
  const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
  byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
  time_t getNtpTime()
  {
    while (Udp.parsePacket() > 0) ; // discard any previously received packets
    #ifdef OnPiuDebug
      Serial.print(" Transmit NTP Request ... ");
    #endif
    sendNTPpacket(timeServer);
    uint32_t beginWait = millis();
    while (millis() - beginWait < 1500) {
      int size = Udp.parsePacket();
      if (size >= NTP_PACKET_SIZE) {
        #ifdef OnPiuDebug
          Serial.println("Receive NTP Response ok");
        #endif
        Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
        unsigned long secsSince1900;
        // convert four bytes starting at location 40 to a long integer
        secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
        secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
        secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
        secsSince1900 |= (unsigned long)packetBuffer[43];
        /*
        #ifdef OnPiuDebug
          //
          // Ivano - calcolo del giorno della settimana - per ora legale
          //
          Serial.print("Seconds since Jan 1 1900 = ");
          Serial.println(secsSince1900);
          // now convert NTP time into everyday time:
          Serial.print("Unix time = ");
          // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
          const unsigned long seventyYears = 2208988800UL;
          // subtract seventy years:
          unsigned long epoch = secsSince1900 - seventyYears;
          // print Unix time:
          Serial.println(epoch);
          // https://forum.arduino.cc/index.php?topic=120325.0
          // https://stackoverflow.com/questions/36389130/how-to-calculate-the-day-of-the-week-based-on-unix-time
          //        
          int day_of_the_week = ((epoch / 86400L) + 4) % 7;
          Serial.print("Day of week = ");
          Serial.println(day_of_the_week);
        #endif
        */
        return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
      }
    }
    #ifdef OnPiuDebug
      Serial.println("No NTP Response :-(");
    #endif
    return 0; // return 0 if unable to get the time
  }
  // send an NTP request to the time server at the given address
  void sendNTPpacket(IPAddress &address)
  {
    // set all bytes in the buffer to 0
    memset(packetBuffer, 0, NTP_PACKET_SIZE);
    // Initialize values needed to form NTP request
    // (see URL above for details on the packets)
    packetBuffer[0] = 0b11100011;   // LI, Version, Mode
    packetBuffer[1] = 0;     // Stratum, or type of clock
    packetBuffer[2] = 6;     // Polling Interval
    packetBuffer[3] = 0xEC;  // Peer Clock Precision
    // 8 bytes of zero for Root Delay & Root Dispersion
    packetBuffer[12]  = 49;
    packetBuffer[13]  = 0x4E;
    packetBuffer[14]  = 49;
    packetBuffer[15]  = 52;
    // all NTP fields have been given values, now
    // you can send a packet requesting a timestamp:
    Udp.beginPacket(address, 123); //NTP requests are to port 123
    Udp.write(packetBuffer, NTP_PACKET_SIZE);
    Udp.endPacket();
  }
#endif

Codice sorgente sul sito:


";
echo "dato  : " . $_GET["dato"] . "
"; echo "-----------------" . "
"; $pitSta = $_GET["P1"]; echo "pitSta : " . $pitSta . "
"; $pitDat = date("Ymd"); echo "pitDat : " . $pitDat . "
"; $pitTim = date("H:i:s"); echo "pitTim : " . $pitTim . "
"; $pitExt = substr ($_GET["P1"] , $pos3 ); $dto = $_GET["dato"]; echo "dto : " . $dto . "
"; if ($debug) { // // dummy file for debug // //$fdmm = str_replace(".txt", ".tmp" , $_GET["P1"]); $fdmm = "tmp/" . $pitSta . $pitDat . ".tmp"; $myfdmm = fopen($fdmm , 'a'); $txt = "-----------------------" . "\r\n"; $txt .= "Parametri passati" . "\r\n"; $txt .= date("d/m/Y") . "," . date("H:i:s") . "\r\n"; $txt .= "-----------------------" . "\r\n\r\n"; $txt .= "P1 = " . $_GET["P1"] . "\r\n"; $txt .= "dato = " . $_GET["dato"] . "\r\n"; $txt .= "Time = " . $_GET["Time"] . "\r\n\r\n"; $txt .= "-----------------------" . "\r\n\r\n"; fwrite($myfdmm, $txt); } // // analisi di dato // /* $dto = $_GET["dato"]; $posCTR = strpos($dto, " "); echo "posCTR : " . $posCTR . "
"; if ($posCTR !== false){ $pitTip = substr ($dto , 0, $posCTR); $dto = substr ($dto , $posCTR+1); } else { $pitTip = "dati"; } echo "pitTip : " . $pitTip . "
"; echo "dto : " . $dto . "
"; */ // if ($debug) { $txt = "P1 = " . $_GET["P1"] . "\r\npos1 = " . $pos1 . "\r\npos2 = " . $pos2 . "\r\npitDir = " . $pitDir . "\r\npitSta = " . $pitSta . "\r\npitDat = " . $pitDat . "\r\npitExt = " . $pitExt . "\r\n"; $txt .= "dato = " . $_GET["dato"] . "\r\ntipodato = " . $pitTip . "\r\npos = " . $pos . "\r\nfdato1 = " . $dato1 . "\r\nfdato2 = " . $dato2 . "\r\nfdato3 = " . $dato3 . "\r\n\r\n"; fwrite($myfdmm, $txt); } // // creazione del file csv // $fgch = $pitSta . "_" . $pitDat . ".csv"; $fgcp = $pitSta . ".txt"; // echo "csv : " . $fgch . "
"; echo "txt : " . $fgcp . "
"; echo "-----------------" . "
"; $myfile = fopen($fgch, 'a'); // $txt = date("d/m/Y") . "," . $pitTim . "," . $dto . "\r" ; // \n"; fwrite($myfile, $txt); fclose($myfile); copy($fgch,$fgcp); ?>

Cosa serve:

  • ESp8266 - ESP-12d1 mini
  • Sensore reed di livello H2O
  • Sensore contatto reed
  • Sensore presenza di h2o senza contatto
  • Sensore MQ
  • RELE
  • Resistenza da 10kOhm
  • cavetti

Scarica tutto quello che serve: