Advertisement
lllClusterlll

Basic MQTT with ESP32

Oct 3rd, 2022 (edited)
954
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | Software | 0 0
  1. /*
  2.  * เชื่อมต่อไปยัง MQTT Broker ผ่าน WiFi
  3.  * แสดงผลการทำงาน (Debug Message) ผ่าน Serial Port
  4.  * Subscribe ไปยัง Topic ที่ต้องการและแสดงผลลัพธ์ผ่าน Serial Port
  5.  * Publish ข้อมูล 1 ครั้งเมื่อเชื่อมต่อสำเร็จ
  6.  */
  7.  
  8.  
  9. #include "EspMQTTClient.h"
  10.  
  11.  
  12. EspMQTTClient client
  13. (
  14.   "",   // SSID, ชื่อ WiFi ที่ต้องการเชื่อมต่อ
  15.   "",   // WiFi Password
  16.   "",   // MQTT Broker Address
  17.   "",   // MQTT Username
  18.   "",   // MQRR Password
  19.   "",   // MQTT Device ID
  20.   1883  // MQTT Port
  21. );
  22.  
  23.  
  24. void setup()
  25. {
  26.  
  27.   // ใช้งาน Serial Port
  28.   Serial.begin(115200);
  29.  
  30.   Serial.println("\r\nSTART ...");
  31.  
  32.   // แสดงผลการทำงาน (Debug Message) ผ่าน Serial Port
  33.   client.enableDebuggingMessages();
  34.  
  35. }
  36.  
  37.  
  38. // Function นี้ทำงานเมื่อ WiFi และ MQTT เชื่อมต่อไปยัง MQTT Broker สำเร็จ
  39. void onConnectionEstablished()
  40. {
  41.  
  42.   // Subscribe
  43.   client.subscribe("fibo/log", [](const String & payload)
  44.   {
  45.  
  46.     // แสดงข้อความ (Message) เมื่อมีการส่งข้อมูลไปยัง Topic ที่ทำการ Subscribe ไว้
  47.     Serial.println(payload);
  48.    
  49.   });
  50.  
  51.   // Publish
  52.   client.publish("fibo/init", "My IoT Device Connected.");
  53.  
  54. }
  55.  
  56.  
  57. void loop()
  58. {
  59.  
  60.   // MQTT Library Core Function.
  61.   client.loop();
  62.  
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement