PowerTGS440

ESP8266 Mesh Bridge

Apr 9th, 2021 (edited)
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.39 KB | None | 0 0
  1. // ------------------------------------------------------------------------------------------------------------ //
  2. // --- M E S H   B R I D G E   B Y   T O M A S Z   M A J C H E R ---------------------------------------------- //
  3. // ------------------------------------------------------------------------------------------------------------ //
  4. //
  5. // MESH-BRIDGE v0.01 dla ESP8266 - prosty most (BRIDGE) Wi-FI i węzeł ROOT sieci MESH
  6. // odsyła aktualną datę i czas (pobrany z serwera NTP do nadawcy)
  7. //
  8. // ------------------------------------------------------------------------------------------------------------ //
  9. // --- DOŁĄCZONE NAGŁÓWKI BIBLIOTEK --------------------------------------------------------------------------- //
  10. // ------------------------------------------------------------------------------------------------------------ //
  11.  
  12. #include <Arduino.h>
  13. #include <painlessMesh.h>
  14. #include <PubSubClient.h>
  15. #include <WiFiClient.h>
  16. #include <NTPClient.h>                                           // NTP klient (czas)
  17. #include <TimeLib.h>                                             // parser
  18. #include <WiFiUdp.h>                                             // UDP Wi-Fi
  19.  
  20. // ------------------------------------------------------------------------------------------------------------ //
  21. // --- D E F I N I C J E -------------------------------------------------------------------------------------- //
  22. // ------------------------------------------------------------------------------------------------------------ //
  23.  
  24. #define   MESH_PREFIX     "ESP_Root"                  // nazwa sieci MESH
  25. #define   MESH_PASSWORD   "ESP_Root"                  // hasło sieci MESH
  26. #define   MESH_PORT       5555                        // port  sieci MESH
  27.  
  28. #define   STATION_SSID     "DIABLO"                   // nazwa sieci Wi-Fi (router podłączony do sieci)
  29. #define   STATION_PASSWORD "******"                   // hasło sieci Wi-Fi (router podłączony do sieci)
  30.  
  31. #define   HOSTNAME "ESP_Bridge"                       // nazwa hosta (bridge) most sieci MESH i INTERNET
  32.  
  33. #define   TRUE      true
  34. #define   FALSE     false
  35.  
  36. #define   SERIAL  TRUE                                // włącz terminal
  37. #define   SPEED   115200                              // prędkość terminala
  38.  
  39. // ------------------------------------------------------------------------------------------------------------ //
  40. // --- P R O T O T Y P Y -------------------------------------------------------------------------------------- //
  41. // ------------------------------------------------------------------------------------------------------------ //
  42.  
  43. void receivedCallback( const uint32_t &from, const String &msg );
  44. void mqttCallback(char* topic, byte* payload, unsigned int length);
  45. void TimeDateUpdate();
  46.  
  47. // ------------------------------------------------------------------------------------------------------------ //
  48. // --- O B I E K T Y ------------------------------------------------------------------------------------------ //
  49. // ------------------------------------------------------------------------------------------------------------ //
  50.  
  51. WiFiUDP ntpUDP;                                                 // dla NTP (pobieranie czasu z internetu)
  52. NTPClient timeClient(ntpUDP, "pool.ntp.org", 3600);             // dla NTP (pobieranie czasu z internetu)
  53.  
  54. IPAddress getlocalIP();                                         // pobierz adres lokalny IP
  55. IPAddress myIP(0,0,0,0);                                        // mój adres IP
  56. IPAddress mqttBroker(192, 168, 1, 1);                           // mój adres IP
  57.  
  58. painlessMesh  mesh;                                             // obiekt mesh
  59.                                                                
  60. WiFiClient wifiClient;
  61. PubSubClient mqttClient(mqttBroker, 1883, mqttCallback, wifiClient);
  62.  
  63. // ------------------------------------------------------------------------------------------------------------ //
  64. // --- Z M I E N N E   G L O B A L N E ------------------------------------------------------------------------ //
  65. // ------------------------------------------------------------------------------------------------------------ //
  66.  
  67. struct NTP
  68. {
  69.     int8_t    Godzina;
  70.     int8_t    Minuta;
  71.     int8_t    Sekunda;
  72.     int8_t    Dzien;
  73.     int8_t    Miesiac;
  74.     int16_t   Rok;    
  75.     String    SformatowanyCzas;
  76.     String    SformatowanaData;
  77.     String    SformatowanyNTP;
  78. } ntp;
  79.  
  80. // ------------------------------------------------------------------------------------------------------------ //
  81. // --- S E T U P ---------------------------------------------------------------------------------------------- //
  82. // ------------------------------------------------------------------------------------------------------------ //
  83.  
  84. void setup()
  85. {
  86.     #if SERIAL
  87.         Serial.begin(SPEED);                // ustaw prędkość terminala SERIAL
  88.     #endif
  89.  
  90.     mesh.setDebugMsgTypes( ERROR | STARTUP | CONNECTION );  // ustaw przed init (), abyś mógł zobaczyć komunikaty startowe
  91.  
  92.     mesh.init( MESH_PREFIX, MESH_PASSWORD, MESH_PORT, WIFI_AP_STA, 6 );
  93.     mesh.onReceive(&receivedCallback);
  94.     mesh.stationManual(STATION_SSID, STATION_PASSWORD);
  95.     mesh.setHostname(HOSTNAME);
  96.  
  97.     mesh.setRoot(true);                           // sieć MESH na tym urządzeniu jako ROOT  
  98.     mesh.setContainsRoot(true);                   // sieć MESH na tym urządzeniu jako ROOT
  99.  
  100.     timeClient.begin();                           // włącz klienta NTP (pobieranie czasu z internetu)
  101.    
  102. }
  103.  
  104. // ------------------------------------------------------------------------------------------------------------ //
  105. // --- L O O P ------------------------------------------------------------------------------------------------ //
  106. // ------------------------------------------------------------------------------------------------------------ //
  107.  
  108. void loop()
  109. {
  110.     mesh.update();                                                                // aktulizuj MESH
  111.     mqttClient.loop();                                                            // pętla dla klienta mqtt
  112.  
  113.     if(myIP != getlocalIP())                                                      // jeśli moje IP różne od lokalnego IP
  114.     {                                                                          
  115.         myIP = getlocalIP();                                                      // zapisz lokalne IP
  116.  
  117.         #if SERIAL
  118.             Serial.println("Adres lokalny IP: " + myIP.toString());
  119.         #endif
  120.  
  121.         if (mqttClient.connect("painlessMeshClient"))                             // jeśli client
  122.         {
  123.             mqttClient.publish("painlessMesh/from/gateway","Gotowe!");
  124.             mqttClient.subscribe("painlessMesh/to/#");
  125.         }
  126.     }  
  127. }
  128.  
  129. // ------------------------------------------------------------------------------------------------------------ //
  130. // --- o d b i o r n i k   b r o a d c a s t ------------------------------------------------------------------ //
  131. // ------------------------------------------------------------------------------------------------------------ //
  132.  
  133. void receivedCallback( const uint32_t &from, const String &msg )
  134. {
  135.     Serial.printf("ESP Bridge: Odebralem wiadomosc od wezla: %u o tresci: %s\n", from, msg.c_str());
  136.    
  137.     TimeDateUpdate();    
  138.    
  139.     mesh.sendSingle(from, ntp.SformatowanyNTP.c_str());          // wysyłam do nadawcy (tylko do nadawcy) !!!      
  140.  
  141.     #if SERIAL
  142.         Serial.printf("\n *** wysłałem do nadawcy - aktualny czas i datę ***\n");
  143.     #endif
  144. }
  145.  
  146. // ------------------------------------------------------------------------------------------------------------ //
  147. // --- m q t t   C a l l b a c k  ----------------------------------------------------------------------------- //
  148. // ------------------------------------------------------------------------------------------------------------ //
  149.  
  150. void mqttCallback(char* topic, uint8_t* payload, unsigned int length)
  151. {
  152.     char* cleanPayload = (char*)malloc(length+1);
  153.     memcpy(cleanPayload, payload, length);
  154.     cleanPayload[length] = '\0';
  155.     String msg = String(cleanPayload);
  156.     free(cleanPayload);
  157.  
  158.     String targetStr = String(topic).substring(16);
  159.  
  160.     if(targetStr == "gateway")
  161.     {
  162.         if(msg == "getNodes")
  163.         {
  164.             auto nodes = mesh.getNodeList(true);
  165.             String str;
  166.             for (auto &&id : nodes)
  167.                 str += String(id) + String(" ");
  168.                 mqttClient.publish("painlessMesh/from/gateway", str.c_str());
  169.         }
  170.     }
  171.     else
  172.     if(targetStr == "broadcast")
  173.     {
  174.         mesh.sendBroadcast(msg);
  175.     }
  176.     else
  177.     {
  178.         uint32_t target = strtoul(targetStr.c_str(), NULL, 10);
  179.         if(mesh.isConnected(target))
  180.         {
  181.           mesh.sendSingle(target, msg);
  182.         }
  183.         else
  184.         {
  185.           mqttClient.publish("painlessMesh/from/gateway", "Klient nie podłaczony!");
  186.         }
  187.     }
  188. }
  189.  
  190. // ------------------------------------------------------------------------------------------------------------ //
  191. // --- p o b i e r z   a d r e s   I P  ----------------------------------------------------------------------- //
  192. // ------------------------------------------------------------------------------------------------------------ //
  193.  
  194. IPAddress getlocalIP()
  195. {
  196.     return IPAddress(mesh.getStationIP());
  197. }
  198.  
  199. // ------------------------------------------------------------------------------------------------------------ //
  200. // --- L O O P ------------------------------------------------------------------------------------------------ //
  201. // ------------------------------------------------------------------------------------------------------------ //
  202.  
  203. void TimeDateUpdate()                                                                  
  204. {                            
  205.      timeClient.update();                                    // pobierz aktualny czas i datę z serwera NTP
  206.  
  207.     unsigned long epochTime = timeClient.getEpochTime();    // zapisz EpochTime                                            
  208.     struct tm *ptm = gmtime ((time_t *)&epochTime);         // struktura daty EpochTime                        
  209.  
  210.     ntp.Godzina    =   timeClient.getHours();               // zapisz godzinę z serwera NTP do struktury
  211.     ntp.Minuta     =   timeClient.getMinutes();             // zapisz minutę z serwera NTP do struktury
  212.     ntp.Sekunda    =   timeClient.getSeconds();             // zapisz sekundę z serwera NTP do stuktury
  213.  
  214.     ntp.Dzien     =   ptm->tm_mday;                         // dzień miesiąca                                                  
  215.     ntp.Miesiac   =   ptm->tm_mon+1;                        // aktualny miesiąc (musimy dodać +1)                
  216.     ntp.Rok       =   ptm->tm_year+1900;                    // aktualny rok (musimy dodać +1900)
  217.  
  218.     ntp.SformatowanyCzas  =   timeClient.getFormattedTime();
  219.     ntp.SformatowanaData  =   String(ntp.Dzien) + "." + String(ntp.Miesiac) + "." + String(ntp.Rok);
  220.     ntp.SformatowanyNTP   =   ntp.SformatowanaData + " " + ntp.SformatowanyCzas;
  221.  
  222. }    
  223.  
  224. // ------------------------------------------------------------------------------------------------------------ //
  225. // --- K O N I E C -------------------------------------------------------------------------------------------- //
  226. // ------------------------------------------------------------------------------------------------------------ //
  227.  
Advertisement
Add Comment
Please, Sign In to add comment