Advertisement
hendriawan

01-MQTT PUB AND SUB arduino

Sep 29th, 2020 (edited)
2,197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // contoh penggunaan di PC
  2. // matikan Lampu
  3. // hendri@MyLinux:~$ mosquitto_pub  -t room/lamp -m "off"
  4. // nyalakan lampu
  5. // hendri@MyLinux:~$ mosquitto_pub  -t room/lamp -m "on"
  6. // mosquitto_sub -d -t room/humidity
  7. // mosquitto_sub -d -t room/temperature
  8. #include <ESP8266WiFi.h>
  9. #include <PubSubClient.h>
  10.  
  11. // Change the credentials below, so your ESP8266 connects to your router
  12. const char* ssid = "MyWIFI";
  13. const char* password = "aremania";
  14.  
  15. // Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
  16. const char* mqtt_server = "192.168.1.6";
  17.  
  18. // Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system
  19. WiFiClient espClient;
  20. PubSubClient client(espClient);
  21.  
  22. // Timers auxiliar variables
  23. long now = millis();
  24. long lastMeasure = 0;
  25.  
  26. // Don't change the function below. This functions connects your ESP8266 to your router
  27. void setup_wifi() {
  28.   delay(10);
  29.   // We start by connecting to a WiFi network
  30.   Serial.println();
  31.   Serial.print("Connecting to ");
  32.   Serial.println(ssid);
  33.   WiFi.begin(ssid, password);
  34.   while (WiFi.status() != WL_CONNECTED) {
  35.     delay(500);
  36.     Serial.print(".");
  37.   }
  38.   Serial.println("");
  39.   Serial.print("WiFi connected - ESP IP address: ");
  40.   Serial.println(WiFi.localIP());
  41. }
  42.  
  43. // This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
  44. // Change the function below to add logic to your program, so when a device publishes a message to a topic that
  45. // your ESP8266 is subscribed you can actually do something
  46. void callback(String topic, byte* message, unsigned int length) {
  47.   Serial.print("Message arrived on topic: ");
  48.   Serial.print(topic);
  49.   Serial.print(". Message: ");
  50.   String messageTemp;
  51.  
  52.   for (int i = 0; i < length; i++) {
  53.     Serial.print((char)message[i]);
  54.     messageTemp += (char)message[i];
  55.   }
  56.   Serial.println();
  57.  
  58.   // Feel free to add more if statements to control more GPIOs with MQTT
  59.  
  60.   // If a message is received on the topic room/lamp, you check if the message is either on or off. Turns the lamp GPIO according to the message
  61.   if(topic=="room/lamp"){
  62.       Serial.print("Changing Room lamp to ");
  63.       if(messageTemp == "on"){
  64.         digitalWrite(LED_BUILTIN, LOW);
  65.         Serial.print("On");
  66.       }
  67.       else if(messageTemp == "off"){
  68.         digitalWrite(LED_BUILTIN, HIGH);
  69.         Serial.print("Off");
  70.       }
  71.   }
  72.   Serial.println();
  73. }
  74.  
  75. // This functions reconnects your ESP8266 to your MQTT broker
  76. // Change the function below if you want to subscribe to more topics with your ESP8266
  77. void reconnect() {
  78.   // Loop until we're reconnected
  79.   while (!client.connected()) {
  80.     Serial.print("Attempting MQTT connection...");
  81.     // Attempt to connect
  82.     /*
  83.      YOU MIGHT NEED TO CHANGE THIS LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
  84.      To change the ESP device ID, you will have to give a new name to the ESP8266.
  85.      Here's how it looks:
  86.        if (client.connect("ESP8266Client")) {
  87.      You can do it like this:
  88.        if (client.connect("ESP1_Office")) {
  89.      Then, for the other ESP:
  90.        if (client.connect("ESP2_Garage")) {
  91.       That should solve your MQTT multiple connections problem
  92.     */
  93.     if (client.connect("ESP8266Client")) {
  94.       Serial.println("connected");  
  95.       // Subscribe or resubscribe to a topic
  96.       // You can subscribe to more topics (to control more LEDs in this example)
  97.       client.subscribe("room/lamp");
  98.     } else {
  99.       Serial.print("failed, rc=");
  100.       Serial.print(client.state());
  101.       Serial.println(" try again in 5 seconds");
  102.       // Wait 5 seconds before retrying
  103.       delay(5000);
  104.     }
  105.   }
  106. }
  107.  
  108. // The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200
  109. // Sets your mqtt broker and sets the callback function
  110. // The callback function is what receives messages and actually controls the LEDs
  111. void setup() {
  112.   pinMode(LED_BUILTIN, OUTPUT);
  113.  
  114.   Serial.begin(115200);
  115.   setup_wifi();
  116.   client.setServer(mqtt_server, 1883);
  117.   client.setCallback(callback);
  118.  
  119. }
  120.  
  121. // For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker
  122. void loop() {
  123.  
  124.   if (!client.connected()) {
  125.     reconnect();
  126.   }
  127.   if(!client.loop())
  128.     client.connect("ESP8266Client");
  129.  
  130.   now = millis();
  131.   // Publishes new temperature and humidity every 30 seconds
  132.   if (now - lastMeasure > 30000) {
  133.     lastMeasure = now;
  134.  
  135.     // Publishes Temperature and Humidity values
  136.     client.publish("room/temperature", "27C");
  137.     client.publish("room/humidity", "10%");    
  138.   }
  139. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement