Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ------------------------------------------------------------------------------------------------------------ //
- // --- 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 ---------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- //
- // MESH-SERVER Wi-Fi BRIDGE v0.02 dla ESP8266
- //
- //
- // ------------------------------------------------------------------------------------------------------------ //
- // --- DOŁĄCZONE NAGŁÓWKI BIBLIOTEK --------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- #include <Arduino.h>
- #include <painlessMesh.h>
- #include <PubSubClient.h>
- #include <WiFiClient.h>
- #include <NTPClient.h> // NTP klient (czas)
- #include <TimeLib.h> // parser
- #include <WiFiUdp.h> // UDP Wi-Fi
- #include <ESP8266HTTPClient.h>
- #include <WiFiClient.h>
- #include <Arduino_JSON.h>
- // ------------------------------------------------------------------------------------------------------------ //
- // --- D E F I N I C J E -------------------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- #define MESH_PREFIX "ESP_Root" // nazwa sieci MESH
- #define MESH_PASSWORD "ESP_Root" // hasło sieci MESH
- #define MESH_PORT 5555 // port sieci MESH
- #define STATION_SSID "DIABLO" // nazwa sieci Wi-Fi (router podłączony do sieci)
- #define STATION_PASSWORD "XXXXXXXXXXX" // hasło sieci Wi-Fi (router podłączony do sieci)
- #define HOSTNAME "ESP_Bridge" // nazwa hosta (bridge) most sieci MESH i INTERNET
- const String s_geo = "51.40"; // szerokosc geograficzna Twojego Miasta
- const String d_geo = "16.20"; // dlugosc geograficzna Twojego Miasta
- String serverPath = "http://fcc-weather-api.glitch.me/api/current"; // darmowy serwer pogody
- #define TRUE true
- #define FALSE false
- #define SERIAL TRUE // włącz terminal
- #define SPEED 115200 // prędkość terminala
- // ------------------------------------------------------------------------------------------------------------ //
- // --- P R O T O T Y P Y -------------------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- void receivedCallback( const uint32_t &from, const String &msg );
- void mqttCallback(char* topic, byte* payload, unsigned int length);
- void TimeDateUpdate(); // aktualizuj czas z Serwera NTP
- void WeatherUpdate(); // aktualizuj pogodę z Serwera FCC
- // ------------------------------------------------------------------------------------------------------------ //
- // --- O B I E K T Y ------------------------------------------------------------------------------------------ //
- // ------------------------------------------------------------------------------------------------------------ //
- WiFiUDP ntpUDP; // dla NTP (pobieranie czasu z internetu)
- NTPClient timeClient(ntpUDP, "pool.ntp.org", 3600); // dla NTP (pobieranie czasu z internetu)
- IPAddress getlocalIP(); // pobierz adres lokalny IP
- IPAddress myIP(0,0,0,0); // mój adres IP
- IPAddress mqttBroker(192, 168, 1, 1); // mój adres IP
- painlessMesh mesh; // obiekt mesh
- WiFiClient wifiClient; // obiekt WiFi
- HTTPClient http; // obiket HTTP
- PubSubClient mqttClient(mqttBroker, 1883, mqttCallback, wifiClient);
- // ------------------------------------------------------------------------------------------------------------ //
- // --- Z M I E N N E G L O B A L N E ------------------------------------------------------------------------ //
- // ------------------------------------------------------------------------------------------------------------ //
- struct NTP
- {
- int8_t Godzina;
- int8_t Minuta;
- int8_t Sekunda;
- int8_t Dzien;
- int8_t Miesiac;
- int16_t Rok;
- String SformatowanyCzas;
- String SformatowanaData;
- String SformatowanyNTP;
- } ntp;
- unsigned long time_ZERO = 0;
- unsigned long time_01S = 0;
- unsigned long time_60S = 0;
- unsigned long time_out_01S = 0;
- unsigned long time_out_60S = 0;
- // ------------------------------------------------------------------------------------------------------------ //
- // --- o d b i o r n i k b r o a d c a s t ------------------------------------------------------------------ //
- // ------------------------------------------------------------------------------------------------------------ //
- void receivedCallback( const uint32_t &from, const String &msg )
- {
- Serial.printf("ESP Bridge: Odebralem wiadomosc od wezla: %u o tresci: %s\n", from, msg.c_str());
- mesh.sendSingle(from, ntp.SformatowanyNTP.c_str()); // wysyłam do nadawcy (tylko do nadawcy) !!!
- #if SERIAL
- Serial.printf("\n *** wysłałem do nadawcy - aktualny czas i datę ***\n");
- #endif
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- m q t t C a l l b a c k ----------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- void mqttCallback(char* topic, uint8_t* payload, unsigned int length)
- {
- char* cleanPayload = (char*)malloc(length+1);
- memcpy(cleanPayload, payload, length);
- cleanPayload[length] = '\0';
- String msg = String(cleanPayload);
- free(cleanPayload);
- String targetStr = String(topic).substring(16);
- if(targetStr == "gateway")
- {
- if(msg == "getNodes")
- {
- auto nodes = mesh.getNodeList(true);
- String str;
- for (auto &&id : nodes)
- str += String(id) + String(" ");
- mqttClient.publish("painlessMesh/from/gateway", str.c_str());
- }
- }
- else
- if(targetStr == "broadcast")
- {
- mesh.sendBroadcast(msg);
- }
- else
- {
- uint32_t target = strtoul(targetStr.c_str(), NULL, 10);
- if(mesh.isConnected(target))
- {
- mesh.sendSingle(target, msg);
- }
- else
- {
- mqttClient.publish("painlessMesh/from/gateway", "Klient nie podłaczony!");
- }
- }
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- p o b i e r z a d r e s I P ----------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- IPAddress getlocalIP()
- {
- return IPAddress(mesh.getStationIP());
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- Aktualizacja Czasu i Daty ----------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- void TimeDateUpdate()
- {
- timeClient.update(); // pobierz aktualny czas i datę z serwera NTP
- unsigned long epochTime = timeClient.getEpochTime(); // zapisz EpochTime
- struct tm *ptm = gmtime ((time_t *)&epochTime); // struktura daty EpochTime
- ntp.Godzina = timeClient.getHours(); // zapisz godzinę z serwera NTP do struktury
- ntp.Minuta = timeClient.getMinutes(); // zapisz minutę z serwera NTP do struktury
- ntp.Sekunda = timeClient.getSeconds(); // zapisz sekundę z serwera NTP do stuktury
- ntp.Dzien = ptm->tm_mday; // dzień miesiąca
- ntp.Miesiac = ptm->tm_mon+1; // aktualny miesiąc (musimy dodać +1)
- ntp.Rok = ptm->tm_year+1900; // aktualny rok (musimy dodać +1900)
- ntp.SformatowanyCzas = timeClient.getFormattedTime();
- ntp.SformatowanaData = String(ntp.Dzien) + "." + String(ntp.Miesiac) + "." + String(ntp.Rok);
- ntp.SformatowanyNTP = ntp.SformatowanaData + " " + ntp.SformatowanyCzas;
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- Aktualizacja Pogody z Serwera ------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- void WeatherUpdate()
- {
- String path = serverPath + "?lat=" + s_geo + "&lon=" + d_geo; // ścieżka do serwera pogody
- String jsonBuffer = httpGETRequest(path.c_str());
- #if SERIAL
- Serial.println(jsonBuffer);
- #endif
- Serial.println(path);
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- Aktualizacja Pogody z Serwera ------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- String httpGETRequest(const char* serverName)
- {
- HTTPClient http;
- http.begin(serverName);
- int httpResponseCode = http.GET();
- String bufor = "{}";
- if ( httpResponseCode > 0 )
- {
- #if SERIAL
- //Serial.print("\nHTTP Response code: ");
- //Serial.print(httpResponseCode);
- #endif
- bufor = http.getString();
- }
- else
- {
- #if SERIAL
- //Serial.print("Error code: ");
- //Serial.println(httpResponseCode);
- #endif
- }
- http.end();
- return bufor;
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- MY TASK ------------------------------------------------------------------------------------------------ //
- // ------------------------------------------------------------------------------------------------------------ //
- void my_task()
- {
- time_ZERO = millis();
- time_01S = time_ZERO - time_out_01S;
- time_60S = time_ZERO - time_out_60S;
- if(time_01S >= 1000UL)
- {
- TimeDateUpdate();
- time_out_01S = time_ZERO;
- }
- if(time_60S >= 60000UL)
- {
- WeatherUpdate();
- time_out_60S = time_ZERO;
- }
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- S E T U P ---------------------------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
- void setup()
- {
- #if SERIAL
- Serial.begin(SPEED); // ustaw prędkość terminala SERIAL
- #endif
- mesh.setDebugMsgTypes( ERROR | STARTUP | CONNECTION ); // ustaw przed init (), abyś mógł zobaczyć komunikaty startowe
- mesh.init( MESH_PREFIX, MESH_PASSWORD, MESH_PORT, WIFI_AP_STA, 6 );
- mesh.onReceive(&receivedCallback);
- mesh.stationManual(STATION_SSID, STATION_PASSWORD);
- mesh.setHostname(HOSTNAME);
- mesh.setRoot(true); // sieć MESH na tym urządzeniu jako ROOT
- mesh.setContainsRoot(true); // sieć MESH na tym urządzeniu jako ROOT
- timeClient.begin(); // włącz klienta NTP (pobieranie czasu z internetu)
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- L O O P ------------------------------------------------------------------------------------------------ //
- // ------------------------------------------------------------------------------------------------------------ //
- void loop()
- {
- mesh.update(); // aktulizuj MESH
- mqttClient.loop(); // pętla dla klienta mqtt
- if(myIP != getlocalIP()) // jeśli moje IP różne od lokalnego IP
- {
- myIP = getlocalIP(); // zapisz lokalne IP
- #if SERIAL
- Serial.println("Adres lokalny IP: " + myIP.toString());
- #endif
- if (mqttClient.connect("painlessMeshClient")) // jeśli client
- {
- mqttClient.publish("painlessMesh/from/gateway","Gotowe!");
- mqttClient.subscribe("painlessMesh/to/#");
- }
- }
- my_task();
- }
- // ------------------------------------------------------------------------------------------------------------ //
- // --- E N D ------------------------------------------------------------------------------------------------- //
- // ------------------------------------------------------------------------------------------------------------ //
Advertisement
Add Comment
Please, Sign In to add comment