Projekt Hausklima - Gigi's Hobby

HIFI
Distribution
Direkt zum Seiteninhalt

Projekt Hausklima

Arduino > Pojects
						/// ESP32 WiFi Libraries
						#include <Arduino.h>
						#include <stdint.h>
						#include <WiFi.h>               // Core
						#include "ESPAsyncWebServer.h"  // 
						#include "SPIFFS.h"
						#include <Adafruit_ILI9341.h>
						// Output Time Status Line 
						#include "StatusBar4Time.h"     // my Own Component
						#include <time.h>
						#include "ESPAsyncWebServer.h"
						#include "NTPProcedure.h"       // my Own Component
						// Font For Output
						
						#include "Fonts/comic8pt.c"
						#include <ArduinoOTA.h>
						#include "soc/timer_group_struct.h"
						#include "soc/timer_group_reg.h"
						#include "GridOutput_Ver2.h"  // my Own Component
						#include <dht.h>
						#include <DHT_U.h>
						#include <thread>
						#include <chrono>
						#include <FirebaseESP32.h>    // For Firebase Google Database
						#include "WiFi_config.inc"
						
						/// Script Credentials
						const auto one_sec = std::chrono::minutes
						{
						    1
						};
						
						WiFiUDP Udp;
						DHT_Unified dht(DHTPIN, DHTTYPE);
						Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
						FirebaseData firebaseData;
						FirebaseJsonArray ArrayHumidity;
						FirebaseJsonArray ArrayTemperature;
						FirebaseJsonArray ArrayTimeStamp;
						
						/*********************************************************************************
						* @param  Init
						*********************************************************************************/
						void InitDHTSensors();
						GridOutputClass GridOutput;
						StatusBar4TimeClass StatusBar;
						AsyncWebServer server(80);
						
						
						/*********************************************************************************
						* @param  prototypes
						*********************************************************************************/
						void LoopSetKlimaValue();
						void AddData(rKlimaServer Value);
						String HTML_Processor(const String& var);
						void InitOTA();
						void InitILI9341();
						void feedTheDog();
						void InitGridOutPut();
						///-------------
						void SetupNTP();
						void InitTimer0();
						void InitTimer1();
						void IRAM_ATTR ontimer0();
						void IRAM_ATTR ontimer1();
						void connectToWiFi(const char * ssid, const char * pwd);
						void WiFiEvent(system_event_id_t event);
						void PrintText(uint16_t X, uint16_t Y, const char* Text, uint16_t Color, uint16_t EraseColor);
						void SendFireBaseData( rKlimaServer Value);
						
						void Send_UDP_Beacon2Client1(const char Msg[]);
						void Send_UDP_Beacon2Client2(const char Msg[]);
						void CheckWhatSender(String IPAdr,String Value);
						
						
						
						/*********************************************************************************
						* @brief   counter_loop()  Just a Test if this works
						* @param  none
						* @return none
						*********************************************************************************/
						void counter_loop() 
						{
						    uint32_t counter = 0;
						    while(true) {
						        Serial.print("counter_loop: ");
						        Serial.println(counter);
						        std::this_thread::sleep_for(one_sec);
						        counter++;
						    }
						}
						
						/*********************************************************************************
						* @brief  blinker_loop()  Just a Test if this works
						* @param  none
						* @return none
						*********************************************************************************/
						void blinker_loop() 
						{
						    uint32_t counter = 0;
						    while(true) {
						        digitalWrite(LED_BUILTIN, HIGH);
						        Serial.print("blinker_loop (HIGH) counter: ");
						        Serial.println(counter);
						        std::this_thread::sleep_for(one_sec);
						        
						        digitalWrite(LED_BUILTIN, LOW);
								
						        Serial.print("blinker_loop (LOW) counter: ");
						        Serial.println(counter);
						        std::this_thread::sleep_for(one_sec);
						         
						        counter++;
						    }
						}
						
						 std::thread counter_loop_thread(counter_loop);
						 std::thread blinker_loop_thread(blinker_loop);
						
						/*********************************************************************************
						* @brief  setup()
						* @param  none
						* @return none
						*********************************************************************************/
						void setup()
						{
							Serial.begin(115200);
							InitILI9341();
						   InitGridOutPut();
							tft.setFont(&_comic8pt_);
							connectToWiFi(sBufferSSID, sBufferPASS);
						
							// Give it 500 tries to connect
						uint32_t Versuch = 0;
						while ((bWiFiConnected == false) & (Versuch++ < 500))
						{
							Serial.printf(". %d", Versuch);
							delay(50);
						}
						
						InitDHTSensors();
						  pinMode(LED_BUILTIN, OUTPUT);
						   SetupNTP();
						   InitOTA();
						
						// Initialize SPIFFS
						  if(!SPIFFS.begin(true)){
						    Serial.println("An Error has occurred while mounting SPIFFS");
						    return;
						  }
						
						  dht.begin();
						
						  // Route for root / web page
						  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
						    request->send(SPIFFS, "/index.html", String(), false, HTML_Processor);
						  });
						  
						  // Route to load style.css file
						  server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
						    request->send(SPIFFS, "/style.css", "text/css");
						  });
						
						  // Route to set GPIO to HIGH
						  
						  server.on("/on", HTTP_GET, [](AsyncWebServerRequest *request){
						    digitalWrite(ledPin, HIGH);    
						    request->send(SPIFFS, "/index.html", String(), false, HTML_Processor);
						  });
						
						   Udp.begin(UDP_PORT_Send_Receive);
						
						  StatusBar.init(&tft,ILI9341_AQUAMARINE, ILI9341_RED, ILI9341_RED,FullAll);  
						  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
						  Firebase.reconnectWiFi(true);
						
						  InitTimer0(); // Init Timer0	
						  InitTimer1(); // Init Timer1	
						 ArrayHumidity.clear();
						 ArrayTemperature.clear();
						 ArrayTimeStamp.clear();
						  server.begin();
						}
						
						/*********************************************************************************
						* @brief  loop()
						* @param  none
						* @return none
						*********************************************************************************/ 
						void loop()
						{
						    feedTheDog();
						if (bWiFiConnected)
						{	 
							ArduinoOTA.handle();
						  int packetSize = Udp.parsePacket();
						
						    if (packetSize)
						{
						    Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
						    int len = Udp.read(Buffer, 40); // Importend if the Size is bigger than the Buffer the Stack reboots the MCU
						    if (len > 0)
						     {
						        Buffer[len] = '\0';
						       CheckWhatSender(Udp.remoteIP().toString() , Buffer);
						        Serial.printf("UDP packet contents: %s\n", Buffer);
						    
						     }}
						
						if (bKlimaGetClient1 & bKlimaGetClient2)
						  {
						      bKlimaGetClient1 =  false;
						      bKlimaGetClient2 = false;
						      LoopSetKlimaValue();
						}
							if (bKlimaTrigger)
							{
						    Serial.print("Klima Trigger -->   ");
						   Send_UDP_Beacon2Client1("#Deck#");
						   Send_UDP_Beacon2Client2("#Garten#");
						   
							bKlimaTrigger = false;
							}
								
						    if (bSecondTrigger)
						 {
							
							tft.setFont(&_comic8pt_);	
						    StatusBar.SetTime(NewTime, OldTime);
						    bSecondTrigger = false;		
						 }
						
						   if (bTriggerNTP)
						   {	
						Serial.println("Trigger NTP !!");
						while ( getNTPtime(10, NewTime) == false)
						{
						delay(100);
						Serial.println("-get NTP Zeit-");
						}
						
						 bTriggerNTP = false;
						     }     
							 
						if (bGotNTPData)
						{
						//PrintText(10,50,"Got NTP Data",ILI9341_LIGHTSALMON, ILI9341_DARKGREEN);
						bGotNTPData = false;
						}}
						 delay(10);
						}
						
						
						/*********************************************************************************
						* @brief  InitDHTSensors()
						* @param  none
						* @return none
						*********************************************************************************/
						void InitDHTSensors()
						{
						  dht.begin();
						  sensor_t sensor;
						  
						  dht.temperature().getSensor(&sensor);
						  Serial.println("------------------------------------");
						  Serial.println("Temperature");
						  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
						  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
						  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
						  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" *C");
						  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" *C");
						  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" *C");  
						  Serial.println("------------------------------------");
						  // Print humidity sensor details.
						  dht.humidity().getSensor(&sensor);
						  Serial.println("------------------------------------");
						  Serial.println("Humidity");
						  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
						  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
						  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
						  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println("%");
						  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println("%");
						  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println("%");  
						  Serial.println("------------------------------------");
						}
						
						/*********************************************************************************
						* @brief  uint64ToString because standard function just work with uint32_t integer
						* @param  uint64_t input
						* @return uint64_t as Text
						*********************************************************************************/
						String uint64ToString(uint64_t input) 
						{
						  String result = "";
						  uint8_t base = 10;
						
						  do {
						    char c = input % base;
						    input /= base;
						
						    if (c < 10)
						      c +='0';
						    else
						      c += 'A' - 10;
						    result = c + result;
						  } while (input);
						  return result;
						}
						
						/*********************************************************************************
						* @brief  LoopGetKlimaValue()
						* @param  none
						* @return Kima Values
						*********************************************************************************/
						rKlimaServer LoopGetKlimaValue()
						{
						
						tm ZNeu;
						vKlimaServer.Counter++ ;
						Serial.print("KC---> "); Serial.print(vKlimaServer.Counter);
						vKlimaServer.Zeit = NewTime;
						 sensors_event_t event;  
						  dht.temperature().getEvent(&event);
						  if (isnan(event.temperature)) {
						    Serial.println("Error reading temperature!");
						  } else
						  vKlimaServer.Temperature1 =  event.temperature;
						dht.humidity().getEvent(&event);
						  if (isnan(event.relative_humidity)) {
						    Serial.println("Error reading Humidity!");
						  } else
						  vKlimaServer.Humidity1 =  event.relative_humidity;
						  localtime_r(&NewTime, &ZNeu);
							ZNeu.tm_year += 1900;
							ZNeu.tm_mon -= 1;
							localtime_r(&OldTime, &ZNeu);
							ZNeu.tm_year += 1900;
							
						  itoa(ZNeu.tm_year,Buffer,10);
						   sYear =  Buffer;
						  
						   sMonth = strcpy(Buffer,  caMonth[ZNeu.tm_mon]);
						   sMonth = Buffer;
						
						return (vKlimaServer);
						}
						
						/*********************************************************************************
						* @brief  LoopGetKlimaValue()
						* @param  none
						* @return none
						*********************************************************************************/
						void LoopSetKlimaValue()
						{
						  vKlimaServer = LoopGetKlimaValue();
						    
						 GridOutput.ColTextOut(Col2, Row2, vKlimaServer.Temperature1 ,'°','C'); 
						 GridOutput.ColTextOut(Col3, Row2, vKlimaServer.Humidity1 ,' ','%'); 
						
						 GridOutput.ColTextOut(Col2, Row3, vKlimaServer.Temperature2 ,'°','C'); 
						 GridOutput.ColTextOut(Col3, Row3, vKlimaServer.Humidity2 ,' ','%'); 
						
						 GridOutput.ColTextOut(Col2, Row4, vKlimaServer.Temperature3 ,'°','C'); 
						 GridOutput.ColTextOut(Col3, Row4, vKlimaServer.Humidity3 ,' ','%'); 
						  AddData(vKlimaServer);
						}
						
						void AjustArray()
						{
						  for (int k = 0; k<KlimaCounter; k++)
						  aKlimaServer[k] = aKlimaServer[k+ 1];
						}
						
						
						/*********************************************************************************
						* @brief  AddData(rKlimaServer Value)
						* @param  rKlimaServer Record
						* @return none
						*********************************************************************************/
						void AddData(rKlimaServer Value)
						{
						
						#ifdef DebugInfo
						sprintf(Buffer, "[%d , %3.2f , %3.2f ], \n", Value.Counter, Value.Temperature, Value.Humidity);
						Serial.print("++++++++++++++++++++++++++++++++++++++\n");
						Serial.println(Buffer);
						Serial.print("++++++++++++++++++++++++++++++++++++++\n");
						#endif
						
						if (KlimaCounter > MaxData)  AjustArray();
						
						aKlimaServer[KlimaCounter] = Value;
						
						#ifdef DebugInfo
						sprintf(Buffer, "[%d , %3.2f , %3.2f ], \n", aKlimaServer[99].Zeit, aKlimaServer[99].Temperature, aKlimaServer[99].Humidity);
						Serial.print("#######################################\n");
						Serial.println(Buffer);
						Serial.print("########################################\n");
						#endif
						
						if (KlimaCounter < MaxData ) KlimaCounter++;
						
						
						sData.clear();
						for (int i  = 0; i < KlimaCounter; i++)
						{
						
						uint64_t Time =  aKlimaServer[i].Zeit;
						Time = Time * 1000;
						String TimeDummy = uint64ToString(Time);
						sprintf(Buffer, "[new Date(%s) , %3.2f , %3.2f , %3.2f, %3.2f, %3.2f, %3.2f], \n", TimeDummy.c_str() , aKlimaServer[i].Temperature1, \
						aKlimaServer[i].Humidity1, aKlimaServer[i].Temperature2, aKlimaServer[i].Humidity2, aKlimaServer[i].Temperature3, aKlimaServer[i].Humidity3 );
						sData = sData + Buffer;
						///Serial.println(sData); - // For Debugging purpose
						}
						#ifdef DebugInfo
						Serial.print("***************************************\n");
						Serial.println(sData);
						Serial.print("---------------------------------------\n");
						#endif
						SendFireBaseData( Value ); 
						}
						
						/*********************************************************************************
						* @brief  HTML_Processor(const String& var) For the HTML Webpage Values
						* @param  rKlimaServer Record
						* @return String
						*********************************************************************************/
						String HTML_Processor(const String& var)
						{
						String Status;
						float fStatus = 0.00;
						bool bFloat = false;
						  Serial.print("------> "); Serial.println(var);
						  if(var == "data"){
						        Status = sData;
						    }
						    else
						    if(var == "MONTH"){
						     Status = sMonth;
						     
						    }
						    else
						    if(var == "YEAR"){
						     Status = sYear;
						     
						    }
						    else
						    if(var == "TEMPERATURE1"){
						     fStatus = vKlimaServer.Temperature1;
						     bFloat = true;
						    }
						    else
						    if(var == "HUMIDITY1"){
						    fStatus = vKlimaServer.Humidity1;
						    bFloat = true;
						    }
						    else
						    if(var == "TEMPERATURE2"){
						     fStatus = vKlimaServer.Temperature2;
						     bFloat = true;
						    }
						    else
						    if(var == "HUMIDITY2"){
						      fStatus = vKlimaServer.Humidity2;    
						      bFloat = true;
						    }
						     else
						    if(var == "TEMPERATURE3"){
						     fStatus = vKlimaServer.Temperature3;
						     bFloat = true;
						    }
						    else
						    if(var == "HUMIDITY3"){
						     fStatus = vKlimaServer.Humidity3;
						     bFloat = true;
						    }
						  if (bFloat){
						  dtostrf(fStatus, 3, 2, Buffer);
						   Status = Buffer;
						  }
						    return Status;
						  }
						
						/*********************************************************************************
						* @brief  InitOTA()
						* @param  none
						* @return none
						*********************************************************************************/
						void InitOTA()
						{
						// OTA Configuration *************************************************
						/* create a connection at port 3232 */
							ArduinoOTA.setPort(3232);
							/* we use mDNS instead of IP of ESP32 directly */
							ArduinoOTA.setHostname("ESP32-Power-Consumption");
						
							/* we set password for updating */
							ArduinoOTA.setPassword(OTA_PASS);
							Serial.print(OTA_PASS);
						
							/* this callback function will be invoked when updating start */
							ArduinoOTA.onStart([]() {
								Serial.println("Start updating");
							});
							/* this callback function will be invoked when updating end */
							ArduinoOTA.onEnd([]() {
								Serial.println("\nEnd updating");
							});
							/* this callback function will be invoked when a number of chunks of software was flashed
							so we can use it to calculate the progress of flashing */
							ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
								Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
							});
						
							ArduinoOTA.onError([](ota_error_t error) {
								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");
							});
							/* start updating */
							ArduinoOTA.begin();
						  Serial.println("****************************** Arduino Ota Start ***********************************");
						}
						
						/*********************************************************************************
						* @brief  InitILI9341() Init ILI9341 Graphic 
						* @param  none
						* @return none
						*********************************************************************************/
						void InitILI9341()
						{
							Serial.print("****** TFT Mode  ******");
							tft.begin();
						
							// read diagnostics (optional but can help debug problems)
							tft.begin();
						
							pinMode(TFT_LED, OUTPUT);
							digitalWrite(TFT_LED, HIGH);
						
							// read diagnostics (optional but can help debug problems)
							uint8_t x = tft.readcommand8(ILI9341_RDMODE);
							Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
							x = tft.readcommand8(ILI9341_RDMADCTL);
							Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
							x = tft.readcommand8(ILI9341_RDPIXFMT);
							Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
							x = tft.readcommand8(ILI9341_RDIMGFMT);
							Serial.print("Image Format: 0x"); Serial.println(x, HEX);
							x = tft.readcommand8(ILI9341_RDSELFDIAG);
							Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);
							tft.setRotation(1); // Set ILI9341 to Landscape
							tft.fillScreen(ILI9341_NAVY);
						 	tft.setTextWrap(false);
							tft.setRotation(1); // horizontal display - in this App it's a "MUST"
						
						}
						
						/*********************************************************************************
						* @brief InitGridOutPut()
						* @param  none
						* @return none
						*********************************************************************************/
						void InitGridOutPut()
						{
						  Serial.print("------------ InitGridOutPut --------------");
						  GridOutput.init(&tft, ILI9341_GOLD, ILI9341_NAVY, ILI9341_SALMON) ;
						  	strcpy(Buffer, "Location");
							GridOutput.ColTextOut(Col1, Row1, Buffer,0,0 );
							strcpy(Buffer, "Temperatur");
							GridOutput.ColTextOut(Col2, Row1, Buffer,0,0);
							strcpy(Buffer, "Humidity");
							GridOutput.ColTextOut(Col3, Row1, Buffer,0,0);
							strcpy(Buffer, "Home");
							GridOutput.ColTextOut(Col1, Row2, Buffer,0,0);
							strcpy(Buffer, "Deck");
							GridOutput.ColTextOut(Col1, Row3, Buffer,0,0);	
							strcpy(Buffer, "Garden");
							GridOutput.ColTextOut(Col1, Row4, Buffer,0,0);
						
						}
						
						/*********************************************************************************
						* @brief feedTheDog() Prevent a Brown out Reset
						* @param  none
						* @return none
						*********************************************************************************/
						void feedTheDog()
						{
						  // feed dog 0
						  TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE; // write enable
						  TIMERG0.wdt_feed=1;                       // feed dog
						  TIMERG0.wdt_wprotect=0;                   // write protect
						  // feed dog 1
						  TIMERG1.wdt_wprotect=TIMG_WDT_WKEY_VALUE; // write enable
						  TIMERG1.wdt_feed=1;                       // feed dog
						  TIMERG1.wdt_wprotect=0;                   // write protect
						}
						
						/*********************************************************************************
						* @brief InitTimer1() 
						* @param  none
						* @return none
						*********************************************************************************/
						void InitTimer1()
						{
							// Inalize Timer
							timer1 = timerBegin(1, 80, true);
							Serial.println("Timer 1******");
							// Attach onTimer function to our timer
							timerAttachInterrupt(timer1, &ontimer1, true);
							// Set alarm to call onTimer function every second 1 tick is 1us
							// => 1 second is 1000000us
							// Repeat the alarm (third parameter)
							timerAlarmWrite(timer1, 1000000, true);
						  timerAlarmEnable(timer1);
						}
						
						/*********************************************************************************
						* @brief InitTimer0() 
						* @param  none
						* @return none
						*********************************************************************************/
						void InitTimer0()
						{
							// Inalize Timer
							timer0 = timerBegin(0, 80, true);
							Serial.println("Timer 0******");
							// Attach onTimer function to our timer
							timerAttachInterrupt(timer0, &ontimer0, true);
							// Set alarm to call onTimer function every second 1 tick is 1us
							// => 1 second is 1000000us
							// Repeat the alarm (third parameter)
							timerAlarmWrite(timer0, 1000000, true);
						  timerAlarmEnable(timer0);
						}
						
						/*********************************************************************************
						* @brief void IRAM_ATTR ontimer1()
						* @param  none
						* @return none
						*********************************************************************************/
						void IRAM_ATTR ontimer1()
						{
						  OldTime = NewTime;
						  NewTime++;
						  bSecondTrigger = true;
						
						//Every 15 Minutes send Values to HTML and FirebaseServer
						if (TriggerKlimaCounter++ > /* 10 * */ 20) //
						{
						  TriggerKlimaCounter = 0;
						  bKlimaTrigger = true;
						}}
						
						/*********************************************************************************
						* @brief void IRAM_ATTR ontimer0()
						* @param  none
						* @return none
						*********************************************************************************/
						void IRAM_ATTR ontimer0()
						{
						  if (TriggerNTPCounter++ > 60 * 10) // every 10 Minutes Get NTP Datas
							{
								TriggerNTPCounter = 0;
								bTriggerNTP = true;
							}	
						}
						
						/*********************************************************************************
						* @brief SetupNTP()
						* @param  none
						* @return none
						*********************************************************************************/
						void SetupNTP()
						{
						SetNTP_SERVER();
						 if (getNTPtime(10,NewTime))
						 {
						 bGotNTPData = true;
						  }
						else
						bGotNTPData = false;
						
						}
						
						/*********************************************************************************
						* @brief connectToWiFi
						* @param  none
						* @return none
						*********************************************************************************/
						void connectToWiFi(const char * ssid, const char * pwd)
						{
						  	Serial.printf(Buffer, "Connecting to WiFi network : %s", ssid);
						
						  // delete old config
						  WiFi.disconnect(true);
						
						  //register event handler
						  WiFi.onEvent(WiFiEvent);
						  //Initiate connection
						  WiFi.begin(ssid, pwd);
						  WiFi.setHostname("ESP32_NTP_Klima");
						   }
						
						/*********************************************************************************
						* @brief WiFiEvent(system_event_id_t event)
						* @param  WiFi Event
						* @return none
						*********************************************************************************/
						void WiFiEvent(system_event_id_t event)
						{
							Serial.print("event ");
						Serial.print(event);
						
						switch (event)
						{
						case     SYSTEM_EVENT_WIFI_READY:
						 Serial.print("Wifi Ready");
							break;
						case     SYSTEM_EVENT_STA_START:
						 Serial.print("Wifi Event Start");
							break;
						case     SYSTEM_EVENT_STA_STOP:
						 Serial.print("Wifi Event Stop");
							break;
						case     SYSTEM_EVENT_STA_CONNECTED:
						{
							bWiFiConnected = true;
						strcpy(Buffer, "WiFi Connected");
						 //GridOutput.RowTextOut(Row4, Buffer, '\0', '\0'); 
						}
							break;
						case     SYSTEM_EVENT_STA_DISCONNECTED:
						{
						bWiFiConnected = false;
						strcpy(Buffer, "WiFi Disconnected");
						 //GridOutput.RowTextOut(Row4, Buffer, '\0', '\0'); 
						}
						
						   break;
						case     SYSTEM_EVENT_STA_GOT_IP:
						 Serial.println(WiFi.localIP());
						 //udp.begin(WiFi.localIP(),UDP_PORT);
						 strcpy(Buffer, "Got IP Address");
						 //GridOutput.RowTextOut(Row4, Buffer, '\0', '\0'); 
						 bWiFiConnected = true;
						
							break;
						case     SYSTEM_EVENT_STA_LOST_IP:
						strcpy(Buffer, "Wifi lost IP");
						 //GridOutput.RowTextOut(Row4, Buffer, '\0', '\0'); 
						 Serial.print("Wifi lost IP");
						 bWiFiConnected = false;
							break;
						 default:
						 Serial.print("Not recognized Wifi Event ");
						}}
						
						/*********************************************************************************
						* @brief PrintText(uint16_t X, uint16_t Y, const char* Text, uint16_t Color, uint16_t EraseColor)
						* @param  To Print a Text on the LCD screen
						* @return none
						*********************************************************************************/
						void PrintText(uint16_t X, uint16_t Y, const char* Text, uint16_t Color, uint16_t EraseColor)
						{
							tft.fillRect(X-10, Y-12, 200, 16, EraseColor);
							tft.setTextColor(Color);
							tft.setCursor(X, Y);
						    tft.print(Text);
						}
						
						/*********************************************************************************
						* @brief SendFireBaseData(void)
						* @param  none
						* @return none
						*********************************************************************************/
						void SendFireBaseData(rKlimaServer Value)
						{
							String S;
							String SItem;
							String Folder = "Error";
							/////////////// Temperature ////////////////////////////////
						   sprintf(Buffer, "Item%d", Value.Counter);
						   String Item = Buffer;
						          
						if (Firebase.setDouble(firebaseData,Folder + "/Temperature/" + Item, Value.Temperature1))
						  {
						    Serial.println("PASSED");
						    Serial.println("PATH: " + firebaseData.dataPath());
						    Serial.print("PUSH NAME: ");
						    Serial.println(firebaseData.pushName());
						}
						else 
						{
						  Serial.println("Array Failed");
						}
						/////////////// Humidity ////////////////////////////////
						if (Firebase.setDouble(firebaseData,Folder + "/Humidity/" + Item, Value.Humidity1))
						  {
						    Serial.println("PASSED");
						    Serial.println("PATH: " + firebaseData.dataPath());
						    Serial.print("PUSH NAME: ");
						    Serial.println(firebaseData.pushName());
						}
						else 
						{
						  Serial.println("Array Failed");
						}
						
						if (Firebase.setInt(firebaseData,Folder +"/Timestamp/" + Item, Value.Zeit))
						  {
						    Serial.println("PASSED");
						    Serial.println("PATH: " + firebaseData.dataPath());
						    Serial.print("PUSH NAME: ");
						    Serial.println(firebaseData.pushName());
						}
						else 
						{
						  Serial.println("Array Failed");
						}}
						
						/*********************************************************************************
						 @brief Receiver Float from my two Satallites 
						 @param  Text Float Data a "C" String
						 @return none
						*********************************************************************************/
						 rKlimaLocation GetFloatValues(char Text[])
						{
						rKlimaLocation Result;
						int  a = -1;
						char sFloat1[30] = {0};
						int c = -1;
						char sFloat2[30] = {0};
						bool b = false;
						int l = strlen(Text);
						int i;
						
						for (i = 0; i < l; i++)
						{
						if (Text[i] == '<') {   
						b = false;
						break;
						}
						if (Text[i] == '>')
						b = true;
						if (b) 
						sFloat1[a++] = Text[i];
						}
						
						int Merker = i;
						
						Merker++;
						
						for (i = Merker; i < l; i++)
						{
						if (Text[i] == '<') {   
						b = false;
						break;
						}
						if (Text[i] == '>')
						b = true;
						if (b) 
						sFloat2[c++] = Text[i];
						}
						
						Result.Temperature = atof(sFloat1);
						Result.Humidity = atof(sFloat2);
						Serial.printf ("\nATOF %f - %f end atof\n\n", Result.Temperature, Result.Humidity );
						return (Result);
						 }
						
						/*********************************************************************************
						 @brief SendUDPPackets
						 @param  IP Address
						 @param  Port
						 @param  Value  Text to send
						 @return none
						*********************************************************************************/
						void SendUDPPackets(const IPAddress Adr, uint16_t Port,const  String Value )
						{ 
						    Udp.beginPacket(Adr, Port );
						    Udp.print(Value);
						    Udp.endPacket(); 
						    Serial.print("~");
						}
						
						/*********************************************************************************
						 @brief Send_UDP_Beacon2Client1(const char Msg[]) Handshake to Client 1
						 @param  Msg Message to client Not neccecary we use IP Address for recocnition
						 @return none
						*********************************************************************************/
						void Send_UDP_Beacon2Client1(const char Msg[])
						{
						 SendUDPPackets(IPAddress((192), (168), (1), (50)   ), 1234, "Ola");
						 Serial.println("Send Client 1");
						}
						
						/*********************************************************************************
						 @brief Send_UDP_Beacon2Client2(const char Msg[]) Handshake to Client 2
						 @param  Msg Message to client Not neccecary we use IP Address for recocnition
						 @return none
						*********************************************************************************/
						void Send_UDP_Beacon2Client2(const char Msg[])
						{
						  SendUDPPackets(IPAddress((192), (168), (1), (51)   ), 1234, "Hallo");
						    Serial.println("Send Client 2");
						}
						
						/*********************************************************************************
						 @brief CheckWhatSender(String IPAdr,String Value) Dispatch received Values
						 @param  IPAdr IP Address
						 @param  Value coded like ->76.65<-->24.87<-
						 @return none
						*********************************************************************************/
						void CheckWhatSender(String IPAdr,String Value)
						{
						rKlimaLocation Result;
						if (IPAdr == "192.168.1.50")
						{
						  strcpy(Buffer,Value.c_str());
						Result = GetFloatValues(Buffer);
						vKlimaServer.Temperature2 = Result.Temperature;
						vKlimaServer.Humidity2 =  Result.Humidity;
						bKlimaGetClient1 = true;
						}
						
						if (IPAdr == "192.168.1.51")
						{
						  strcpy(Buffer,Value.c_str());
						Result = GetFloatValues(Buffer);
						vKlimaServer.Temperature3 = Result.Temperature;
						vKlimaServer.Humidity3 =  Result.Humidity;
						bKlimaGetClient2 = true;
						}
						Serial.printf("Klienten > %d - %d", bKlimaGetClient1 , bKlimaGetClient2 );
						}
						
						
						
						
Hello, for Download the Projekt Files check out my Github  Publication


© 2020 MMK

Created With WebSite X5

Zurück zum Seiteninhalt