Advertisement
TolentinoCotesta

MQTT & Telegram

Apr 13th, 2021 (edited)
1,501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.76 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <AsyncTelegram2.h>
  3. #include <PubSubClient.h>
  4.  
  5. // Timezone definition
  6. #define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"
  7. #include <time.h>
  8.  
  9. // Client "secure" passed to Telegram library
  10. BearSSL::WiFiClientSecure tg_client;
  11. BearSSL::Session   session;
  12. BearSSL::X509List  certificate(telegram_cert);
  13. AsyncTelegram2 myBot(tg_client);
  14.  
  15. // Client "unsecure" passed to MQTT library
  16. WiFiClient espClient;
  17. PubSubClient mqtt_client(espClient);
  18.  
  19. const char* ssid  =  "xxxxxxxx";     // SSID WiFi network
  20. const char* pass  =  "xxxxxxxx";     // Password  WiFi network
  21. const char* token =  "xxxxxxxxx:AAFLd-B-xxxxxxxxxxxxxxxxxxxxxxxxxx";
  22. const char* mqtt_server = "broker.mqtt-dashboard.com";
  23.  
  24. #define MSG_BUFFER_SIZE (50)
  25. char msg[MSG_BUFFER_SIZE];
  26. int value = 0;
  27.  
  28. void callback(char* topic, byte* payload, unsigned int length) {
  29.   Serial.print("Message arrived [");
  30.   Serial.print(topic);
  31.   Serial.print("] ");
  32.   for (int i = 0; i < length; i++) {
  33.     Serial.print((char)payload[i]);
  34.   }
  35.   Serial.println();
  36. }
  37.  
  38.  
  39. void reconnect() {
  40.   // Loop until we're reconnected
  41.   while (!mqtt_client.connected()) {
  42.     Serial.print("Attempting MQTT connection...");
  43.     // Create a random client ID
  44.     String clientId = "ESP8266Client-";
  45.     clientId += String(random(0xffff), HEX);
  46.     // Attempt to connect
  47.     if (mqtt_client.connect(clientId.c_str())) {
  48.       Serial.println("connected");
  49.       // Once connected, publish an announcement...
  50.       mqtt_client.publish("outTopic", "hello world");
  51.       // ... and resubscribe
  52.       mqtt_client.subscribe("inTopic");
  53.     } else {
  54.       Serial.print("failed, rc=");
  55.       Serial.print(mqtt_client.state());
  56.       Serial.println(" try again in 5 seconds");
  57.       // Wait 5 seconds before retrying
  58.       delay(5000);
  59.     }
  60.   }
  61. }
  62.  
  63. void setup() {
  64.   pinMode(LED_BUILTIN, OUTPUT);
  65.   Serial.begin(115200);
  66.  
  67.   // connects to the access point
  68.   WiFi.mode(WIFI_STA);
  69.   WiFi.begin(ssid, pass);
  70.   delay(500);
  71.   while (WiFi.status() != WL_CONNECTED) {
  72.     Serial.print('.');
  73.     delay(500);
  74.   }
  75.  
  76.   // Sync time with NTP, to check properly Telegram certificate
  77.   configTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
  78.   //Set certficate, session and some other base client properies
  79.   tg_client.setSession(&session);
  80.   tg_client.setTrustAnchors(&certificate);
  81.   tg_client.setBufferSizes(TCP_MSS, TCP_MSS);
  82.  
  83.   // Set the Telegram bot properties
  84.   myBot.setUpdateTime(2000);
  85.   myBot.setTelegramToken(token);
  86.  
  87.   // Check if all things are ok
  88.   Serial.print("\nTest Telegram connection... ");
  89.   myBot.begin() ? Serial.println("OK") : Serial.println("NOK");
  90.   Serial.print("Bot name: @");
  91.   Serial.println(myBot.getBotName());
  92.  
  93.   randomSeed(micros());
  94.   mqtt_client.setServer(mqtt_server, 1883);
  95.   mqtt_client.setCallback(callback);
  96. }
  97.  
  98.  
  99. void loop() {
  100.   if (!mqtt_client.connected()) {
  101.     reconnect();
  102.   }
  103.   mqtt_client.loop();
  104.  
  105.   static unsigned long lastMsg = 0;
  106.   if ( millis() - lastMsg > 10000) {
  107.     lastMsg = millis();
  108.     ++value;
  109.     snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
  110.     Serial.print("Publish message: ");
  111.     Serial.println(msg);
  112.     mqtt_client.publish("outTopic", msg);
  113.   }
  114.  
  115.   // LED blink
  116.   static uint32_t ledTime = millis();
  117.   if (millis() - ledTime > 200) {
  118.     ledTime = millis();
  119.     digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  120.   }
  121.  
  122.   // local variable to store telegram message data
  123.   TBMessage msg;
  124.  
  125.   // if there is an incoming message...
  126.   if (myBot.getNewMessage(msg)) {    
  127.     char message[256];
  128.     snprintf(message, 256, "Message from @%s:\n%s", myBot.getBotName(), msg.text.c_str());
  129.     Serial.println(message);
  130.  
  131.     // echo the received message to the user
  132.     myBot.sendMessage(msg, msg.text);
  133.   }
  134. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement