Advertisement
Seelenkind

ESP_Connect

Sep 27th, 2023
1,250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 6.89 KB | Source Code | 0 0
  1. #pragma GCC optimize("-Ofast")
  2. //#define USE_FIREBASE  // FBWrite(path, data); String txt = FBRead(path);
  3. #define USE_MQTT      // MQTTsend(topic, data); String txt = MQTTget(topic);
  4. #define USE_TELNET    // TELNETsend(data); String txt=TELNETget();
  5.  
  6. #include <Arduino.h>
  7. #include <WiFiClient.h>
  8. #if defined(ESP32)
  9. #include <WiFi.h>
  10. #elif defined(ESP8266)
  11. #include <ESP8266WiFi.h>
  12. #endif
  13. #include <NTPClient.h>
  14. #include <WiFiUdp.h>
  15. WiFiUDP ntpUDP;
  16. NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 7200, 60000);
  17.  
  18. #define WIFI_SSID "WIFI_SSID"
  19. #define WIFI_PASSWORD "WIFI_PASSWORD"
  20.  
  21. #ifdef USE_FIREBASE
  22. #include <Firebase_ESP_Client.h>
  23. #include <addons/TokenHelper.h>
  24. #include <addons/RTDBHelper.h>
  25. #include <ArduinoJson.h>
  26. #define API_KEY "API_KEY"
  27. #define DATABASE_URL "DATABASE_URL"
  28. #define USER_EMAIL "USER_EMAIL"
  29. #define USER_PASSWORD "USER_PASSWORD"
  30. FirebaseData fbdo;
  31. FirebaseAuth auth;
  32. FirebaseConfig config;
  33.  
  34. String FBRead(String path) {
  35.   String r;
  36.   byte x = 0;
  37.   do {
  38.     Firebase.RTDB.getString(&fbdo, path);
  39.     r = fbdo.to<const char*>();
  40.     x++;
  41.     if (x > 10) break;
  42.   } while (r == "");
  43.   return r;
  44. }
  45.  
  46. void FBWrite(String path, String data) {
  47.   Firebase.RTDB.setString(&fbdo, path, data);
  48. }
  49. #endif
  50.  
  51. #ifdef USE_MQTT
  52. #include <PubSubClient.h>
  53. #define mqtt_server "broker.emqx.io"
  54. #define mqtt_port 1883
  55. //mqtt_use_credentials
  56. #ifdef mqtt_use_credentials
  57. #define mqtt_user "mqtt_user"
  58. #define mqtt_password "mqtt_password"
  59. #endif
  60. #define sub_topic1 "/zz/testinput1"
  61. #define sub_topic2 "/zz/testinput2"
  62. #define sub_topic3 "/zz/testinput3"
  63. #define sub_topic4 "/zz/testinput4"
  64. String pyld[4 + 1] = {}, xtopic;
  65. byte tp;
  66.  
  67. WiFiClient espClient;
  68. PubSubClient mqttClient(espClient);
  69.  
  70. void mqttReconnect() {
  71.   while (!mqttClient.connected()) {
  72.     Serial.print("Attempting MQTT connection...");
  73.     String clientId = "ESPClient-";
  74.     clientId += String(random(0xffff), HEX);
  75. #ifdef mqtt_use_credentials
  76.     if (mqttClient.connect("ESPClient", mqtt_user, mqtt_password))
  77. #else
  78.     if (mqttClient.connect(clientId.c_str()))
  79. #endif
  80.     {
  81.       Serial.println("connected");
  82.       mqttClient.subscribe(sub_topic1);
  83.       mqttClient.subscribe(sub_topic2);
  84.       mqttClient.subscribe(sub_topic3);
  85.       mqttClient.subscribe(sub_topic4);
  86.     } else {
  87.       Serial.print("failed, rc=");
  88.       Serial.print(mqttClient.state());
  89.       Serial.println(" try again in 5 seconds");
  90.       delay(5000);
  91.     }
  92.   }
  93. }
  94. void MQTT_LOOP() {
  95.   if (!mqttClient.connected()) {
  96.     mqttReconnect();
  97.   }
  98.   mqttClient.loop();
  99. }
  100.  
  101. void callback(char* topic, byte* payload, unsigned int length) {
  102.   xtopic = topic;
  103.   if (String(topic) == String(sub_topic1)) tp = 1;
  104.   if (String(topic) == String(sub_topic2)) tp = 2;
  105.   if (String(topic) == String(sub_topic3)) tp = 3;
  106.   if (String(topic) == String(sub_topic4)) tp = 4;
  107.   for (unsigned int i = 0; i < length; i++) {
  108.     pyld[tp] += String(char(payload[i]));
  109.   }
  110. }
  111. void MQTTsend(const char* tpc, String msg) {
  112.   mqttClient.publish(tpc, msg.c_str());
  113. }
  114. #endif
  115.  
  116. #ifdef USE_TELNET
  117. uint8_t i;
  118. bool ConnectionEstablished;
  119. #define MAX_TELNET_CLIENTS 2
  120. WiFiServer TelnetServer(23);
  121. WiFiClient TelnetClient[MAX_TELNET_CLIENTS];
  122.  
  123. void TELNETsend(String text) {
  124.   for (i = 0; i < MAX_TELNET_CLIENTS; i++) {
  125.     if (TelnetClient[i] || TelnetClient[i].connected()) {
  126.       TelnetClient[i].println(text);
  127.     }
  128.   }
  129.   delay(10);
  130. }
  131.  
  132. String TELNETget() {
  133.   String readTelnet = "";
  134.   for (i = 0; i < MAX_TELNET_CLIENTS; i++) {
  135.     if (TelnetClient[i] && !TelnetClient[i].connected()) {
  136.       Serial.print("Client disconnected ... terminate session ");
  137.       Serial.println(i + 1);
  138.       TelnetClient[i].stop();
  139.     }
  140.   }
  141.   if (TelnetServer.hasClient()) {
  142.     ConnectionEstablished = false;  // Set to false
  143.     for (i = 0; i < MAX_TELNET_CLIENTS; i++) {
  144.       if (!TelnetClient[i]) {
  145.         TelnetClient[i] = TelnetServer.available();
  146.  
  147.         Serial.print("New Telnet client connected to session ");
  148.         Serial.println(i + 1);
  149.  
  150.         TelnetClient[i].flush();  // clear input buffer, else you get strange characters
  151.         TelnetClient[i].println("Welcome!");
  152.         TELNETsend("Connected with ip:" + WiFi.localIP().toString());
  153.         ConnectionEstablished = true;
  154.         break;
  155.       } else {
  156.       }
  157.     }
  158.     if (ConnectionEstablished == false) {
  159.       Serial.println("No free sessions ... drop connection");
  160.       TelnetServer.available().stop();
  161.     }
  162.   }
  163.   for (i = 0; i < MAX_TELNET_CLIENTS; i++) {
  164.     if (TelnetClient[i] && TelnetClient[i].connected()) {
  165.       if (TelnetClient[i].available()) {
  166.         while (TelnetClient[i].available()) {
  167.           readTelnet = TelnetClient[i].readString();
  168.         }
  169.       }
  170.     }
  171.   }
  172.   return readTelnet;
  173. }
  174. #endif
  175.  
  176. String getserial() {
  177.   String txt = "";
  178.   while (Serial.available()) {
  179.     txt = Serial.readString();
  180.     txt.trim();
  181.   }
  182.   return txt;
  183. }
  184.  
  185. void Test() {
  186.   timeClient.update();
  187.   String rnd = timeClient.getFormattedTime();
  188.   String senddata = getserial();
  189.  
  190. #ifdef USE_MQTT
  191.   if (senddata != "") MQTTsend("/zz/testoutput", rnd + " : " + senddata);
  192.   if (pyld[tp] != "") {
  193.     Serial.println("Topic: " + String(xtopic) + " payload: " + pyld[tp]);
  194.     pyld[tp] = "";
  195.   }
  196. #endif
  197.  
  198. #ifdef USE_FIREBASE
  199.   if (senddata != "") {
  200.     FBWrite("ESP_Basic/test", rnd + " : " + senddata);
  201.     String txt = FBRead("ESP_Basic/test");
  202.     Serial.println("Firebase Data: " + txt);
  203.   }
  204. #endif
  205.  
  206. #ifdef USE_TELNET
  207.   if (senddata != "") TELNETsend(rnd + " : " + senddata);
  208.   String telnetmsg = TELNETget();
  209.   if (telnetmsg != "") Serial.println("Telnet message: " + telnetmsg);
  210. #endif
  211. }
  212.  
  213. void setup() {
  214.   delay(3000);
  215.   Serial.begin(115200);
  216.   Serial.println("Connecting to: " + String(WIFI_SSID));
  217.   WiFi.mode(WIFI_STA);  // Setup ESP in client mode
  218.   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  219.   while (WiFi.status() != WL_CONNECTED) {
  220.     Serial.print(".");
  221.     delay(300);
  222.   }
  223.   Serial.println();
  224.   Serial.print("Connected with IP: ");
  225.   Serial.println(WiFi.localIP());
  226.  
  227. #ifdef USE_FIREBASE
  228.   Serial.printf("\n\rFirebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
  229.   config.api_key = API_KEY;
  230.   auth.user.email = USER_EMAIL;
  231.   auth.user.password = USER_PASSWORD;
  232.   config.database_url = DATABASE_URL;
  233.   config.token_status_callback = tokenStatusCallback;
  234.   Firebase.reconnectNetwork(true);
  235.   fbdo.setBSSLBufferSize(4096 /* Rx buffer size in bytes from 512 - 16384 */, 1024 /* Tx buffer size in bytes from 512 - 16384 */);
  236.   fbdo.setResponseSize(2048);
  237.   Firebase.begin(&config, &auth);
  238.   Firebase.setDoubleDigits(5);
  239.   config.timeout.serverResponse = 10 * 1000;
  240. #endif
  241.  
  242. #ifdef USE_MQTT
  243.   mqttClient.setServer(mqtt_server, mqtt_port);
  244.   mqttClient.setCallback(callback);
  245. #endif
  246.  
  247. #ifdef USE_TELNET
  248.   TelnetServer.begin();
  249.   TelnetServer.setNoDelay(true);
  250. #endif
  251.   timeClient.begin();
  252. }
  253.  
  254. void loop() {
  255.   MQTT_LOOP();
  256.   Test();
  257.   yield();
  258. }
  259.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement