PowerTGS440

DarkNet Weather v0.1 by Tomasz Majcher

Apr 15th, 2021 (edited)
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 39.53 KB | None | 0 0
  1. // ------------------------------------------------------------------------------------------------------------ //
  2. // ---    D a r k N e t   S e r v e r   &   M e s h   &   B T     B Y   T O M A S Z   M A J C H E R   --------- //
  3. // ------------------------------------------------------------------------------------------------------------ //
  4. //
  5. //    Zaawansowany parser danych pogodowych z serwera : api.weatherapi.com
  6. //    dla prawidłowego działania należy założyć darmowe konto na serwerze api.weatherapi.com
  7. //    i w miejsca xxxxxxxxxxxxxxxxxx wpisac swoj token i swoja miejsowosc
  8. //
  9. // ------------------------------------------------------------------------------------------------------------ //
  10. // --- DOŁĄCZONE NAGŁÓWKI BIBLIOTEK --------------------------------------------------------------------------- //
  11. // ------------------------------------------------------------------------------------------------------------ //
  12.  
  13. #include <Arduino.h>
  14. #include <painlessMesh.h>
  15. #include <PubSubClient.h>
  16. #include <WiFiClient.h>
  17. #include <NTPClient.h>                                           // NTP klient (czas)
  18. #include <TimeLib.h>                                             // parser
  19. #include <WiFiUdp.h>                                             // UDP Wi-Fi
  20. #include <HTTPClient.h>                                                            
  21. #include <WiFiClient.h>
  22. #include <Arduino_JSON.h>
  23. #include <ArduinoJson.h>
  24. #include <ESP32Time.h>                                           // zegar RTC ESP32
  25. #include "tools.h"                                               // dołącz moje narzędzia
  26.  
  27.  
  28. // ------------------------------------------------------------------------------------------------------------ //
  29. // --- D E F I N I C J E -------------------------------------------------------------------------------------- //
  30. // ------------------------------------------------------------------------------------------------------------ //
  31.  
  32. #define   MESH_PREFIX         "ESP_Root"                  // nazwa sieci MESH
  33. #define   MESH_PASSWORD       "ESP_Root"                  // hasło sieci MESH
  34. #define   MESH_PORT           5555                        // port  sieci MESH
  35.  
  36. #define   STATION_SSID        "DIABLO"                    // nazwa sieci Wi-Fi (router podłączony do sieci)
  37. #define   STATION_PASSWORD    "haslo_sieci"               // hasło sieci Wi-Fi (router podłączony do sieci)
  38.  
  39. #define   HOSTNAME            "DarkNet"                   // nazwa hosta (bridge) most sieci MESH i INTERNET
  40.  
  41. #define   SERIAL              1                           // włącz terminal SERIAL.MONITOR
  42. #define   SPEED               115200                      // prędkość terminala SERIAL
  43. #define   THREAD_INFO         0
  44. #define   CORE0_TASK1         1
  45.  
  46.  
  47. // ------------------------------------------------------------------------------------------------------------ //
  48. // --- P R O T O T Y P Y -------------------------------------------------------------------------------------- //
  49. // ------------------------------------------------------------------------------------------------------------ //
  50.  
  51. void receivedCallback( const uint32_t &from, const String &msg );
  52. void mqttCallback(char* topic, byte* payload, unsigned int length);                                            
  53.  
  54. // ------------------------------------------------------------------------------------------------------------ //
  55. // --- O B I E K T Y ------------------------------------------------------------------------------------------ //
  56. // ------------------------------------------------------------------------------------------------------------ //
  57.  
  58. WiFiUDP ntpUDP;                                                     // dla NTP (pobieranie czasu z internetu)
  59. NTPClient timeClient(ntpUDP, "pool.ntp.org", 7200);                 // dla NTP (pobieranie czasu z internetu)
  60. IPAddress getlocalIP();                                             // pobierz adres lokalny IP
  61. IPAddress myIP(0,0,0,0);                                            // mój adres IP
  62. IPAddress mqttBroker(192, 168, 1, 1);                               // mój adres IP
  63. painlessMesh  mesh;                                                 // obiekt mesh                                                                
  64. WiFiClient wifiClient;                                              // obiekt WiFi
  65. HTTPClient http;                                                    // obiekt HTTP
  66. PubSubClient mqttClient(mqttBroker, 1883, mqttCallback, wifiClient);
  67. ESP32Time rtc;
  68.  
  69. JSONVar JSON_Astronomy;                                             // obiekt Astronomia
  70. JSONVar JSON_Weather;                                               // obiekt Pogoda    
  71. JSONVar JSON_Forecast;                                              // obiekt Forecast
  72. JSONVar JSON_Air;                                                   // obiekt Powietrze
  73.  
  74. void Core0_Task1( void * pvParameters );                            // funkcja Task1 dla rdzenia nr. 0 CPU        
  75. void Core0_Task2( void * pvParameters );                            // funkcja Task2 dla rdzenia nr. 0 CPU        
  76.  
  77. void Core1_Task1( void * pvParameters );                            // funkcja Task1 dla rdzenia nr. 1 CPU        
  78. void Core1_Task2( void * pvParameters );                            // funkcja Tasl2 dla rdzenia nr. 1 CPU    
  79.  
  80. TaskHandle_t CPU_Core_0;                                            // rdzeń nr. 0 CPU - ESP32
  81. TaskHandle_t CPU_Core_1;                                            // rdzeń nr. 1 CPU - ESP32
  82.  
  83. // ------------------------------------------------------------------------------------------------------------ //
  84. // --- Z M I E N N E   G L O B A L N E ------------------------------------------------------------------------ //
  85. // ------------------------------------------------------------------------------------------------------------ //
  86.  
  87. struct NTP_TIME
  88. {
  89.     String    SformatowanaData;
  90.     int       DzienTygodnia;
  91.     int       DzienMiesiaca;
  92.     int       Miesiac;
  93.     int       Rok;
  94.     String    SformatowanyCzas;
  95.     int       Godzina;
  96.     int       Minuta;
  97.     int       Sekunda;
  98. }
  99. zegar;
  100.  
  101. struct ASTRONOMY
  102. {
  103.     String    miejscowosc               = "";
  104.     String    kraj                      = "";
  105.     double    szerokosc_geograficzna    = 0;
  106.     double    dlugosc_geograficzna      = 0;    
  107.     long      czas_epoch                = 0;    
  108.     String    czas_lokalny              = "";
  109.     String    wschod_slonca             = "";
  110.     String    zachod_slonca             = "";
  111.     String    wschod_ksiezyca           = "";
  112.     String    zachod_ksiezyca           = "";
  113.     String    faza_ksiezyca             = "";
  114.     String    oswietlenie_ksiezyca      = "";      
  115. }
  116. astronomia;
  117.  
  118. struct Weather
  119. {
  120.     String    miejscowosc               = "";
  121.     String    kraj                      = "";
  122.     double    szerokosc_geograficzna    = 0;
  123.     double    dlugosc_geograficzna      = 0;    
  124.     String    id                        = "";
  125.     long      czas_epoch                = 0;    
  126.     String    czas_lokalny              = "";
  127.     String    ostatnia_aktualizacja     = "";
  128.     double    temperatura_C             = 0;
  129.     double    temperatura_C_odczuwalna  = 0;
  130.     String    kondycja                  = "";
  131.     double    predkosc_wiatru_kph       = 0;
  132.     double    podmuchy_wiatru           = 0;
  133.     int       kierunek_wiatru_stopnie   = 0;
  134.     String    kierunek_wiatru_kompas    = "";
  135.     int       cisnienie                 = 0;
  136.     double    opady                     = 0;
  137.     int       wilgotnosc                = 0;
  138.     int       zachmurzenie              = 0;
  139.     int       widzialnosc               = 0;
  140.     int       index_uv                  = 0;
  141. }
  142. pogoda;
  143.  
  144. struct Air
  145. {
  146.     double  co    = 0;                     // Carbon Monoxide (μg/m3)    -   Tlenek węgla (μg / m3)
  147.     double  o3    = 0;                     // Ozone (μg/m3)              -   Ozon (μg / m3)
  148.     double  no2   = 0;                     // Nitrogen dioxide (μg/m3)   -   Dwutlenek azotu (μg / m3)
  149.     double  so2   = 0;                     // Sulphur dioxide (μg/m3)    -   Dwutlenek siarki (μg / m3)
  150.     double  pm25  = 0;                     // PM2.5 (μg/m3)              -   aerozole atmosferyczne o średnicy nie większej niż 2,5 μm
  151.     double  pm10  = 0;                     // PM10 (μg/m3)               -   mieszanina zawieszonych w powietrzu cząsteczek o średnicy nie większej niż 10 μm
  152.     int     Defra = 0;                     // Air Quality Index          -   index jakości powietrza    
  153. }
  154. powietrze;
  155.  
  156.  
  157.  
  158.  
  159. bool F_Astronomia = false;
  160. bool F_Pogoda     = false;
  161. bool F_Prognoza   = false;
  162. bool F_Powietrze  = false;
  163. bool F_Zegar      = false;
  164.  
  165. // -- T A S K   M I L L I S   O L D   S C H O O L  -   B Y   T L G
  166.  
  167. unsigned long timeZERO = 0;  
  168. unsigned long task01m = 0;
  169. unsigned long task05m = 0;
  170. unsigned long task10m = 0;
  171. unsigned long task15m = 0;
  172. unsigned long timeout_task01m = 0;
  173. unsigned long timeout_task05m = 0;
  174. unsigned long timeout_task10m = 0;
  175. unsigned long timeout_task15m = 0;
  176.  
  177.  
  178. // ------------------------------------------------------------------------------------------------------------ //
  179. // --- o d b i o r n i k   b r o a d c a s t ------------------------------------------------------------------ //
  180. // ------------------------------------------------------------------------------------------------------------ //
  181.  
  182. void receivedCallback( const uint32_t &from, const String &msg )
  183. {
  184.     Serial.printf("\nESP Bridge: Odebralem wiadomosc od wezla: %u o tresci: %s\n", from, msg.c_str());  
  185.    
  186.     //mesh.sendSingle(from, ntp.SformatowanyNTP.c_str());          // wysyłam do nadawcy (tylko do nadawcy) !!!      
  187.  
  188.     #if SERIAL
  189.         //Serial.printf("\n *** wysłałem do nadawcy - aktualny czas i datę ***\n");
  190.     #endif
  191. }
  192.  
  193. // ------------------------------------------------------------------------------------------------------------ //
  194. // --- m q t t   C a l l b a c k  ----------------------------------------------------------------------------- //
  195. // ------------------------------------------------------------------------------------------------------------ //
  196.  
  197. void mqttCallback(char* topic, uint8_t* payload, unsigned int length)
  198. {
  199.     char* cleanPayload = (char*)malloc(length+1);
  200.     memcpy(cleanPayload, payload, length);
  201.     cleanPayload[length] = '\0';
  202.     String msg = String(cleanPayload);
  203.     free(cleanPayload);
  204.  
  205.     String targetStr = String(topic).substring(16);
  206.  
  207.     if(targetStr == "gateway")
  208.     {
  209.         if(msg == "getNodes")
  210.         {
  211.             auto nodes = mesh.getNodeList(true);
  212.             String str;
  213.             for (auto &&id : nodes)
  214.                 str += String(id) + String(" ");
  215.                 mqttClient.publish("painlessMesh/from/gateway", str.c_str());
  216.         }
  217.     }
  218.     else
  219.     if(targetStr == "broadcast")
  220.     {
  221.         mesh.sendBroadcast(msg);
  222.     }
  223.     else
  224.     {
  225.         uint32_t target = strtoul(targetStr.c_str(), NULL, 10);
  226.         if(mesh.isConnected(target))
  227.         {
  228.           mesh.sendSingle(target, msg);
  229.         }
  230.         else
  231.         {
  232.           mqttClient.publish("painlessMesh/from/gateway", "Klient nie podłaczony!");
  233.         }
  234.     }
  235. }
  236. //
  237. // ------------------------------------------------------------------------------------------------------------ //
  238. // ---                              M U L T I - C O R E   T A S K                                           --- //
  239. // ------------------------------------------------------------------------------------------------------------ //
  240. //
  241. //
  242. //
  243. //
  244. // ------------------------------------------------------------------------------------------------------------ //
  245. // ---        CORE0 TASK1     POBIERANIE CZASU i DATY Z SERWERA NTP i AKTUALIZACJA ZEGARA ESP32 RTC         --- //
  246. // ------------------------------------------------------------------------------------------------------------ //
  247. //
  248. void Core0_Task1( void * pvParameters )                          
  249. {                                                                
  250.     for(;;)                                                        
  251.     {                                                            
  252.         #if THREAD_INFO
  253.             PrintLine(60);
  254.             PrintMSG("ESP32","CORE", "Wykonuje watek TASK1 na CORE0");
  255.         #endif      
  256.  
  257.         timeClient.update();
  258.        
  259.         unsigned long epochTime = timeClient.getEpochTime();                                              
  260.         struct tm *ptm = gmtime ((time_t *)&epochTime);      
  261.                                                                                    
  262.         zegar.Godzina           =   timeClient.getHours();                  
  263.         zegar.Minuta            =   timeClient.getMinutes();                
  264.         zegar.Sekunda           =   timeClient.getSeconds();                
  265.         zegar.SformatowanyCzas  =   timeClient.getFormattedTime();                                
  266.         zegar.DzienTygodnia     =   timeClient.getDay();                                          
  267.         zegar.DzienMiesiaca     =   ptm->tm_mday;                                                
  268.         zegar.Miesiac           =   ptm->tm_mon+1;                                                
  269.         zegar.Rok               =   ptm->tm_year+1900;
  270.  
  271.         if (zegar.Rok !=1970)
  272.         {
  273.             if(zegar.DzienMiesiaca < 10)
  274.             {
  275.                 zegar.SformatowanaData = "0" + String(zegar.DzienMiesiaca) + ".";
  276.             }
  277.             else  zegar.SformatowanaData = String(zegar.DzienMiesiaca) + ".";
  278.  
  279.             if(zegar.Miesiac < 10)
  280.             {
  281.                 zegar.SformatowanaData += "0" + String(zegar.Miesiac) + ".";
  282.             }
  283.             else  zegar.SformatowanaData += String(zegar.Miesiac) + ".";
  284.  
  285.             zegar.SformatowanaData  += String(zegar.Rok);
  286.  
  287.             rtc.setTime(zegar.Sekunda, zegar.Minuta, zegar.Godzina, zegar.DzienMiesiaca, zegar.Miesiac, zegar.Rok);
  288.  
  289.        
  290.             #if CORE0_TASK1            
  291.                 PrintLine(60);
  292.                 PrintMSG("CORE0_TASK1", "NTP Time", zegar.SformatowanyCzas.c_str());          
  293.                 PrintMSG("CORE0_TASK1", "NTP Date", zegar.SformatowanaData.c_str());
  294.                 Serial.printf("\n[CORE0_TASK1] [RTC Time] ");  
  295.                 Serial.print(rtc.getTime());
  296.                 Serial.printf("\n[CORE0_TASK1] [RTC Date] ");  
  297.                 Serial.print(rtc.getDate());
  298.                 Serial.printf("\n[CORE0_TASK1] [FREE RAM] ");
  299.                 Serial.print(ESP.getFreeHeap());
  300.                 PrintLine(60);
  301.                 PrintEND();      
  302.             #endif
  303.                
  304.             F_Zegar = true;   // dane OK, flaga na true
  305.         }
  306.         else F_Zegar = false; // dane złe, flaga na false
  307.        
  308.         vTaskDelay(60000 / portTICK_PERIOD_MS);                 // wykonuj 1 minutę
  309.     }                                                            
  310. }      
  311. //
  312. // ------------------------------------------------------------------------------------------------------------ //
  313. // ---        CORE0 TASK2     POBIERANIE ASTRONOMII                                                         --- //
  314. // ------------------------------------------------------------------------------------------------------------ //
  315. //
  316. void Core0_Task2( void * pvParameters )                           // Rdzeń 0 Zadanie 1                  
  317. {                                                                 // początek                          
  318.     for(;;)                                                       // nieskończona pętla                
  319.     {                                                             // początek FOR                      
  320.         delay(900000);                                            // sprawdzaj co 15 minut
  321.     }                                                            
  322. }  
  323. //
  324. // ------------------------------------------------------------------------------------------------------------ //
  325. // ---        CORE1 TASK    
  326. // ------------------------------------------------------------------------------------------------------------ //
  327.  
  328. void Core1_Task1( void * pvParameters )                           // Rdzeń 0 Zadanie 1                  
  329. {                                                                 // początek                          
  330.     for(;;)                                                       // nieskończona pętla                
  331.     {                                                             // początek FOR                      
  332.         #if SERIAL
  333.             PrintLine(60);
  334.             PrintMSG("ESP32","CORE", "Wykonuje watek Task1 na CORE-1");
  335.         #endif      
  336.        
  337.         vTaskDelay(905000 / portTICK_PERIOD_MS);                 // wykonuj 15 min                    
  338.     }                                                            
  339. }      
  340.  
  341. void Core1_Task2( void * pvParameters )                           // Rdzeń 0 Zadanie 1                  
  342. {                                                                 // początek                          
  343.     for(;;)                                                       // nieskończona pętla                
  344.     {                                                             // początek FOR                      
  345.         #if SERIAL
  346.             PrintLine(60);
  347.             PrintMSG("ESP32","CORE", "Wykonuje watek Task2 na CORE-1");
  348.         #endif      
  349.        
  350.         vTaskDelay(905000 / portTICK_PERIOD_MS);                 // wykonuj 15 min                    
  351.     }                                                            
  352. }      
  353.      
  354. // ------------------------------------------------------------------------------------------------------------ //
  355. // --- p o b i e r z   a d r e s   I P  ----------------------------------------------------------------------- //
  356. // ------------------------------------------------------------------------------------------------------------ //
  357.  
  358. IPAddress getlocalIP()
  359. {
  360.     return IPAddress(mesh.getStationIP());
  361. }
  362.  
  363. // ------------------------------------------------------------------------------------------------------------ //
  364. // --- Aktualizacja Pogody z Serwera  ------------------------------------------------------------------------- //
  365. // ------------------------------------------------------------------------------------------------------------ //
  366. //
  367. String httpGETRequest(const char* serverName)                                                        
  368. {                                                                                                    
  369.     HTTPClient http;                                                                                  
  370.     http.begin(serverName);                                                                          
  371.     int httpResponseCode = http.GET();                                                                
  372.     String bufor = "{}";                                                                              
  373.                                                                                                      
  374.     if ( httpResponseCode > 0 )                                                                      
  375.     {                                                                                                
  376.         #if SERIAL
  377.             //Serial.print("\nHTTP Response code: ");                                                  
  378.             //Serial.print(httpResponseCode);                                                      
  379.         #endif          
  380.                                                                                      
  381.         bufor = http.getString();                                                                    
  382.     }                                                                                                
  383.     else                                                                                              
  384.     {                                                                                                
  385.         #if SERIAL                                                                                  
  386.             //Serial.print("Error code: ");                                                          
  387.             //Serial.println(httpResponseCode);                                                      
  388.         #endif                                                                                        
  389.     }                                                                                                
  390.     http.end();                                                                            
  391.     return bufor;                                                                                    
  392. }
  393. //
  394. // ------------------------------------------------------------------------------------------------------------ //
  395. // ---        A K T U A L I Z A C J A   P O G O D Y                                                         --- //    
  396. // ------------------------------------------------------------------------------------------------------------ //
  397. //
  398. void PogodaAktualizuj()
  399. {
  400.     PrintLine(60);
  401.     PrintMSG("ESP32","MyTask", "Aktualizję pogodę z serwera : api.weatherapi.com");
  402.    
  403.     String path = "http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=Lubin";
  404.     String jsonBuffer = httpGETRequest(path.c_str());    
  405.        
  406.     JSON_Weather = JSON.parse(jsonBuffer);                    
  407.  
  408.     if (JSON.typeof(JSON_Weather) == "undefined")                                                
  409.     {                                                                                        
  410.         PrintLine(60);
  411.         PrintMSG("DarkNet", "POGODA PARSER", "BŁĄD, BRAK DANYCH" );                                                                  
  412.     }      
  413.  
  414.     pogoda.miejscowosc                =   JSON_Weather["location"]["name"];
  415.     pogoda.kraj                       =   JSON_Weather["location"]["country"];
  416.     pogoda.szerokosc_geograficzna     =   JSON_Weather["location"]["lat"];
  417.     pogoda.dlugosc_geograficzna       =   JSON_Weather["location"]["lon"];
  418.     pogoda.id                         =   JSON_Weather["location"]["tz_id"];
  419.     pogoda.czas_epoch                 =   JSON_Weather["location"]["localtime_epoch"];
  420.     pogoda.czas_lokalny               =   JSON_Weather["location"]["localtime"];
  421.     pogoda.ostatnia_aktualizacja      =   JSON_Weather["current"]["last_updated"];
  422.     pogoda.temperatura_C              =   JSON_Weather["current"]["temp_c"];
  423.     pogoda.temperatura_C_odczuwalna   =   JSON_Weather["current"]["feelslike_c"];
  424.     pogoda.kondycja                   =   JSON_Weather["current"]["condition"]["text"];
  425.     pogoda.predkosc_wiatru_kph        =   JSON_Weather["current"]["wind_kph"];
  426.     pogoda.kierunek_wiatru_stopnie    =   JSON_Weather["current"]["wind_degree"];
  427.     pogoda.kierunek_wiatru_kompas     =   JSON_Weather["current"]["wind_dir"];
  428.     pogoda.podmuchy_wiatru            =   JSON_Weather["current"]["gust_kph"];
  429.     pogoda.cisnienie                  =   JSON_Weather["current"]["pressure_mb"];
  430.     pogoda.opady                      =   JSON_Weather["current"]["precip_mm"];
  431.     pogoda.wilgotnosc                 =   JSON_Weather["current"]["humidity"];
  432.     pogoda.zachmurzenie               =   JSON_Weather["current"]["cloud"];
  433.     pogoda.widzialnosc                =   JSON_Weather["current"]["vis_km"];
  434.     pogoda.index_uv                   =   JSON_Weather["current"]["uv"];
  435.  
  436.     if(pogoda.miejscowosc == "Lubin")
  437.     {
  438.         PrintLine(60);
  439.         Serial.printf("\n[DarkNet] [Pogoda] Miejscowość \t\t: ");
  440.         Serial.print(pogoda.miejscowosc);
  441.         Serial.printf("\n[DarkNet] [Pogoda] Kraj \t\t: ");
  442.         Serial.print(pogoda.kraj);
  443.         Serial.printf("\n[DarkNet] [Pogoda] Szer.Geograficzna \t: %2.2f",pogoda.szerokosc_geograficzna);
  444.         Serial.printf("\n[DarkNet] [Pogoda] Dług.Geograficzna \t: %2.2f",pogoda.dlugosc_geograficzna);            
  445.         Serial.printf("\n[DarkNet] [Pogoda] Czas Epoch \t\t: %u",pogoda.czas_epoch );            
  446.         Serial.printf("\n[DarkNet] [Pogoda] Serwer ID \t\t: ");
  447.         Serial.print( pogoda.id );    
  448.         Serial.printf("\n[DarkNet] [Pogoda] Czas Epoch \t\t: %u",pogoda.czas_epoch );            
  449.         Serial.printf("\n[DarkNet] [Pogoda] Czas Lokalny \t: ");      
  450.         Serial.print( pogoda.czas_lokalny );        
  451.         Serial.printf("\n[DarkNet] [Pogoda] Aktualizacja \t: ");      
  452.         Serial.print( pogoda.ostatnia_aktualizacja );      
  453.         Serial.printf("\n[DarkNet] [Pogoda] Temperatura \t\t: %2.2f",pogoda.temperatura_C);
  454.         Serial.printf("\n[DarkNet] [Pogoda] Temp.Odczuwalna \t: %2.2f",pogoda.temperatura_C_odczuwalna);  
  455.         Serial.printf("\n[DarkNet] [Pogoda] Opis pogody \t\t: ");
  456.         Serial.print(pogoda.kondycja);  
  457.         Serial.printf("\n[DarkNet] [Pogoda] Predkosc wiatru \t: %2.2f",pogoda.predkosc_wiatru_kph);
  458.         Serial.printf("\n[DarkNet] [Pogoda] Podmuchy wiatru \t: %2.2f",pogoda.podmuchy_wiatru);  
  459.         Serial.printf("\n[DarkNet] [Pogoda] Kierunek wiatru \t: %2.2f",pogoda.kierunek_wiatru_stopnie);  
  460.         Serial.printf("\n[DarkNet] [Pogoda] Kierunek wiatru \t: ");
  461.         Serial.print(pogoda.kierunek_wiatru_kompas);  
  462.         Serial.printf("\n[DarkNet] [Pogoda] Cisnienie \t\t: %d",pogoda.cisnienie);  
  463.         Serial.printf("\n[DarkNet] [Pogoda] Opady deszczu \t: %2.2f",pogoda.opady);  
  464.         Serial.printf("\n[DarkNet] [Pogoda] Wilgotnosc \t\t: %d",pogoda.wilgotnosc);  
  465.         Serial.printf("\n[DarkNet] [Pogoda] Zachmurzenie \t: %d",pogoda.zachmurzenie);  
  466.         Serial.printf("\n[DarkNet] [Pogoda] Widzialnosc \t\t: %d",pogoda.widzialnosc);  
  467.         Serial.printf("\n[DarkNet] [Pogoda] Index UV \t\t: %d",pogoda.index_uv);  
  468.              
  469.         PrintLine(60);
  470.         PrintEND();      
  471.        
  472.         F_Pogoda = true;      // dane OK, ustaw flagę na true
  473.     }
  474.     else  F_Pogoda = false;   // dane ZŁE, ustaw flagę na false
  475.  
  476. }
  477. //
  478. // ------------------------------------------------------------------------------------------------------------ //
  479. // ---        A K T U A L I Z A C J A   A S T R O N O M I I                                                 --- //    
  480. // ------------------------------------------------------------------------------------------------------------ //
  481. //
  482. void AstronomiaAktualizuj()
  483. {
  484.     PrintLine(60);
  485.     PrintMSG("ESP32","MyTask", "Aktualizję astronomię z serwera : api.weatherapi.com");    
  486.  
  487.     // pobierz dane astronomiczne z serwera dla miasta LUBIN
  488.        
  489.     String path = "http://api.weatherapi.com/v1/astronomy.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=Lubin";
  490.     String jsonBuffer = httpGETRequest(path.c_str());    
  491.        
  492.     JSON_Astronomy = JSON.parse(jsonBuffer);                
  493.  
  494.     if (JSON.typeof(JSON_Astronomy) == "undefined")                                                
  495.     {                                                                                        
  496.         PrintLine(60);
  497.         PrintMSG("DarkNet", "ASTRONOMIA PARSER", "BŁĄD, BRAK DANYCH" );                                                                              
  498.     }      
  499.      
  500.     astronomia.miejscowosc              =   JSON_Astronomy["location"]["name"];
  501.     astronomia.kraj                     =   JSON_Astronomy["location"]["country"];
  502.     astronomia.szerokosc_geograficzna   =   JSON_Astronomy["location"]["lat"];
  503.     astronomia.dlugosc_geograficzna     =   JSON_Astronomy["location"]["lon"];        
  504.     astronomia.czas_epoch               =   JSON_Astronomy["location"]["localtime_epoch"];        
  505.     astronomia.czas_lokalny             =   JSON_Astronomy["location"]["localtime"];
  506.     astronomia.wschod_slonca            =   JSON_Astronomy["astronomy"]["astro"]["sunrise"];
  507.     astronomia.zachod_slonca            =   JSON_Astronomy["astronomy"]["astro"]["sunset"];
  508.     astronomia.wschod_ksiezyca          =   JSON_Astronomy["astronomy"]["astro"]["moonrise"];            
  509.     astronomia.zachod_ksiezyca          =   JSON_Astronomy["astronomy"]["astro"]["moonset"];
  510.     astronomia.faza_ksiezyca            =   JSON_Astronomy["astronomy"]["astro"]["moon_phase"];
  511.     astronomia.oswietlenie_ksiezyca     =   JSON_Astronomy["astronomy"]["astro"]["moon_illumination"];      
  512.  
  513.     if(astronomia.miejscowosc == "Lubin")
  514.     {
  515.        PrintLine(60);
  516.        Serial.printf("\n[DarkNet] [Astronomia] Miejscowość \t\t: ");
  517.        Serial.print(astronomia.miejscowosc);
  518.        Serial.printf("\n[DarkNet] [Astronomia] Kraj \t\t\t: ");
  519.        Serial.print(astronomia.kraj);
  520.        Serial.printf("\n[DarkNet] [Astronomia] Szer.Geograficzna \t: %2.2f",astronomia.szerokosc_geograficzna);
  521.        Serial.printf("\n[DarkNet] [Astronomia] Dług.Geograficzna \t: %2.2f",astronomia.dlugosc_geograficzna);            
  522.        Serial.printf("\n[DarkNet] [Astronomia] Czas Epoch \t\t: %u",astronomia.czas_epoch );            
  523.        Serial.printf("\n[DarkNet] [Astronomia] Czas Lokalny \t\t: ");
  524.        Serial.print( astronomia.czas_lokalny );            
  525.        Serial.printf("\n[DarkNet] [Astronomia] Wschód Słońca \t\t: ");
  526.        Serial.print(astronomia.wschod_slonca );
  527.        Serial.printf("\n[DarkNet] [Astronomia] Zachód Słońca \t\t: ");
  528.        Serial.print(astronomia.zachod_slonca );
  529.        Serial.printf("\n[DarkNet] [Astronomia] Wschód Księżyca \t\t: ");
  530.        Serial.print(astronomia.wschod_ksiezyca );
  531.        Serial.printf("\n[DarkNet] [Astronomia] Zachód Księżyca \t\t: ");
  532.        Serial.print(astronomia.zachod_ksiezyca );
  533.        Serial.printf("\n[DarkNet] [Astronomia] Faza Księżyca \t\t: ");
  534.        Serial.print(astronomia.faza_ksiezyca);
  535.        Serial.printf("\n[DarkNet] [Astronomia] Oświetlenie Księżyca \t: ");
  536.        Serial.print(astronomia.oswietlenie_ksiezyca );            
  537.        PrintLine(60);
  538.        PrintEND();
  539.        F_Astronomia = true;      // dane OK, ustaw flagę na true
  540.     }
  541.     else  F_Astronomia = false;   // dane ZŁE, ustaw flagę na false
  542. }
  543. //
  544. // ------------------------------------------------------------------------------------------------------------ //
  545. // ---        A K T U A L I Z A C J A   J A K O Ś C I   P O W I E T R Z A                                   --- //    
  546. // ------------------------------------------------------------------------------------------------------------ //
  547. //
  548. void PowietrzeAktualizuj()
  549. {
  550.     PrintLine(60);
  551.     PrintMSG("ESP32","MyTask", "Aktualizję jakość powietrza z serwera : api.weatherapi.com");    
  552.  
  553.     // pobierz dane jakości powietrza z serwera dla miasta LUBIN
  554.        
  555.     String path = "http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=Lubin&aqi=yes";
  556.     String jsonBuffer = httpGETRequest(path.c_str());      
  557.        
  558.     JSON_Air = JSON.parse(jsonBuffer);                
  559.  
  560.     if (JSON.typeof(JSON_Air) == "undefined")                                                
  561.     {                                                                                        
  562.         PrintLine(60);
  563.         PrintMSG("DarkNet", "AIR PARSER", "BŁĄD, BRAK DANYCH" );                                                                              
  564.     }        
  565.  
  566.     powietrze.co     = JSON_Air["current"]["air_quality"]["co"];
  567.     powietrze.o3     = JSON_Air["current"]["air_quality"]["o3"];
  568.     powietrze.no2    = JSON_Air["current"]["air_quality"]["no2"];
  569.     powietrze.so2    = JSON_Air["current"]["air_quality"]["so2"];
  570.     powietrze.pm25   = JSON_Air["current"]["air_quality"]["pm2_5"];
  571.     powietrze.pm10   = JSON_Air["current"]["air_quality"]["pm10"];
  572.     powietrze.Defra  = JSON_Air["current"]["air_quality"]["gb-defra-index"];
  573.  
  574.     if (powietrze.co != 0)
  575.     {
  576.         PrintLine(60);
  577.         Serial.printf("\n[DarkNet] [Jakość Powietrza] Tlenek węgla \t\t: %2.8f [μg/ m3]", powietrze.co);
  578.         Serial.printf("\n[DarkNet] [Jakość Powietrza] Dwutlenek azotu \t\t: %2.8f [μg/ m3]", powietrze.no2);
  579.         Serial.printf("\n[DarkNet] [Jakość Powietrza] Ozon \t\t\t: %2.8f [μg/m3]", powietrze.o3);
  580.         Serial.printf("\n[DarkNet] [Jakość Powietrza] Pyły i aerozole PM2.5 \t: %2.8f [μm]", powietrze.pm25);
  581.         Serial.printf("\n[DarkNet] [Jakość Powietrza] Pyły i aerozole PM10 \t: %2.8f [μm]", powietrze.pm10);
  582.         Serial.printf("\n[DarkNet] [Jakość Powietrza] Index jakości \t\t: %d IND", powietrze.Defra);
  583.         PrintLine(60);
  584.         PrintEND();
  585.    
  586.         F_Powietrze  = true;  
  587.     }
  588.     else F_Powietrze  = false;
  589. }
  590. //
  591. // ------------------------------------------------------------------------------------------------------------ //
  592. // ---        A K T U A L I Z A C J A   P R O G N O Z Ę                                                     --- //    
  593. // ------------------------------------------------------------------------------------------------------------ //
  594. //
  595. void PrognozaAktualizuj()
  596. {
  597.     PrintLine(60);
  598.     PrintMSG("ESP32","MyTask", "Aktualizję prognozę z serwera : api.weatherapi.com");    
  599.  
  600.     // wkrótce :-)
  601. }
  602. //
  603. // ------------------------------------------------------------------------------------------------------------ //
  604. // --- MyTask ------------------------------------------------------------------------------------------------- //
  605. // ------------------------------------------------------------------------------------------------------------ //
  606. //
  607. void MyTask()
  608. {
  609.     timeZERO = millis();                                    // zapisz czas 0
  610.     task01m = timeZERO - timeout_task01m;                   // wyznacz nowy
  611.     task05m = timeZERO - timeout_task05m;                   // wyznacz nowy
  612.     task10m = timeZERO - timeout_task10m;                   // wyznacz nowy
  613.     task15m = timeZERO - timeout_task15m;                   // wyznacz nowy
  614.  
  615.     // --- ZADANIE co 1 minutę ------------------------------------------------------------------------------- //
  616.  
  617.     if(task01m >= 60000UL)                                  // wykonuj co 1 minutę
  618.     {
  619.         if (!F_Astronomia)  AstronomiaAktualizuj();         // jeśli BRAK DANYCH wykonuj co minutę
  620.         if (!F_Pogoda)      PogodaAktualizuj();             // jeśli BRAK DANYCH wykonuj co minutę
  621.         if (!F_Powietrze)   PowietrzeAktualizuj();          // jeśli BRAK DANYCH wykonuj co minutę
  622.         if (!F_Prognoza)    PrognozaAktualizuj();           // jeśli BRAK DANYCH wykonuj co minutę
  623.        
  624.         timeout_task01m = timeZERO;  
  625.     }
  626.  
  627.     // --- ZADANIE co 5 minut -------------------------------------------------------------------------------- //
  628.  
  629.     if(task05m >= 300000UL)                                 // wykonuj co 5 minut
  630.     {
  631.         timeout_task05m = timeZERO;  
  632.     }
  633.  
  634.     // --- ZADANIE co 10 minut ------------------------------------------------------------------------------- //
  635.  
  636.     if(task10m >= 600000UL)                                 // wykonuj co 10 minut
  637.     {
  638.         timeout_task10m = timeZERO;    
  639.     }
  640.  
  641.     // --- ZADANIE co 15 minut ------------------------------------------------------------------------------- //
  642.  
  643.     if(task15m >= 900000UL)                                 // wykonuj co 15 minut
  644.     {
  645.         if (F_Astronomia)  AstronomiaAktualizuj();          // jeśli DANE OK co 15 minut
  646.         if (F_Pogoda)      PogodaAktualizuj();              // jeśli DANE OK co 15 minut
  647.         if (F_Powietrze)   PowietrzeAktualizuj();           // jeśli DANE OK co 15 minut
  648.         if (F_Prognoza)    PrognozaAktualizuj();            // jeśli BRAK DANYCH wykonuj co minutę
  649.        
  650.         timeout_task15m = timeZERO;  
  651.     }
  652.  
  653. }
  654. //
  655. // ------------------------------------------------------------------------------------------------------------ //
  656. // --- S E T U P ---------------------------------------------------------------------------------------------- //
  657. // ------------------------------------------------------------------------------------------------------------ //
  658. //
  659. void setup()
  660. {
  661.    #if SERIAL
  662.         Serial.begin(SPEED);                // ustaw prędkość terminala SERIAL
  663.     #endif
  664.          
  665.     mesh.setDebugMsgTypes( ERROR | STARTUP | CONNECTION );  // ustaw przed init (), abyś mógł zobaczyć komunikaty startowe
  666.  
  667.     mesh.init( MESH_PREFIX, MESH_PASSWORD, MESH_PORT, WIFI_AP_STA, 6 );
  668.     mesh.onReceive(&receivedCallback);
  669.     mesh.stationManual(STATION_SSID, STATION_PASSWORD);
  670.     mesh.setHostname(HOSTNAME);
  671.  
  672.     mesh.setRoot(true);                           // sieć MESH na tym urządzeniu jako ROOT  
  673.     mesh.setContainsRoot(true);                   // sieć MESH na tym urządzeniu jako ROOT
  674.  
  675.     timeClient.begin();                           // włącz klienta NTP (pobieranie czasu z internetu)
  676.  
  677.     // --- CPU_Core_0 ----------------------------------------------------------------------------------
  678.                                                                                                        
  679.     xTaskCreatePinnedToCore(Core0_Task1, "CPU_Core_0", 5000, NULL, 1, &CPU_Core_0, 0);                
  680.     vTaskDelay(500 / portTICK_PERIOD_MS);                                                              
  681.                                                                                                        
  682.     xTaskCreatePinnedToCore(Core0_Task2, "CPU_Core_0", 5000, NULL, 1, &CPU_Core_0, 0);                
  683.     vTaskDelay(500 / portTICK_PERIOD_MS);  
  684.    
  685.     // --- CPU_Core_1 ----------------------------------------------------------------------------------
  686.                                                                                                          
  687.     xTaskCreatePinnedToCore(Core1_Task1, "CPU_Core_1", 5000, NULL, 1, &CPU_Core_1, 1);                
  688.     vTaskDelay(500 / portTICK_PERIOD_MS);                                                                
  689.                                                                                                          
  690.     xTaskCreatePinnedToCore(Core1_Task2, "CPU_Core_1", 5000, NULL, 1, &CPU_Core_1, 1);                
  691.     vTaskDelay(500 / portTICK_PERIOD_MS);
  692. }
  693.  
  694. // ------------------------------------------------------------------------------------------------------------ //
  695. // --- L O O P ------------------------------------------------------------------------------------------------ //
  696. // ------------------------------------------------------------------------------------------------------------ //
  697. //
  698. void loop()
  699. {
  700.     mesh.update();                                                                // aktulizuj MESH
  701.     mqttClient.loop();                                                            // pętla dla klienta mqtt
  702.  
  703.     if(myIP != getlocalIP())                                                      // jeśli moje IP różne od lokalnego IP
  704.     {                                                                          
  705.         myIP = getlocalIP();                                                      // zapisz lokalne IP
  706.  
  707.         #if SERIAL
  708.             Serial.println("Adres lokalny IP: " + myIP.toString());
  709.         #endif
  710.  
  711.         if (mqttClient.connect("painlessMeshClient"))                             // jeśli client
  712.         {
  713.             mqttClient.publish("painlessMesh/from/gateway","Gotowe!");
  714.             mqttClient.subscribe("painlessMesh/to/#");
  715.         }
  716.     }        
  717.  
  718.     MyTask();
  719. }
  720. //
  721. // ------------------------------------------------------------------------------------------------------------ //
  722. // --- E N D  ------------------------------------------------------------------------------------------------- //
  723. // ------------------------------------------------------------------------------------------------------------ //
Add Comment
Please, Sign In to add comment