Facebook
From Arti, 3 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 127
  1. #include <Arduino.h>
  2. #include <ESP8266WiFi.h>
  3. #include <PubSubClient.h>
  4.  
  5. #define RELAY 0 // relay connected to  GPIO0
  6.  
  7. const char* ssid = "NAZWA_SIECI";
  8. const char* password =  "HASLO_SIECI";
  9.  
  10. const char* mqttServer = "10.0.0.138"; //IP SERVERA MQTT
  11. const int mqttPort = 1883;                      //PORT SERVERA MQTT
  12. const char* mqttUser = "USER";          //LOGIN SERVERA MQTT
  13. const char* mqttPassword = "PASSWORD";  //HASLO SERVERA MQTT
  14.  
  15. const char* device_name = "Test Switch";
  16.  
  17. //TOPICS
  18. const char* main_topic = "switches/bench/main";
  19. const char* temp_topic = "sensors/bench/temperature";
  20.  
  21. void callback(char* topic, byte* payload, unsigned int length);
  22.  
  23. uint counter = 0;
  24.  
  25. WiFiClient espClient;
  26. PubSubClient client(espClient);
  27.  
  28. void setup()
  29. {
  30.   pinMode(RELAY, OUTPUT);
  31.   Serial.begin(9600);
  32.   WiFi.begin(ssid, password);
  33.   while (WiFi.status() != WL_CONNECTED) {
  34.     WiFi.hostname(device_name);
  35.    // Serial.println("Connected");
  36.     delay(500);
  37.   }
  38.  
  39.     client.setServer(mqttServer, mqttPort);
  40.     client.setCallback(callback);
  41.  
  42.   while (!client.connected())
  43.   {
  44.       if (client.connect(device_name , mqttUser, mqttPassword))
  45.       {
  46.  
  47.       }
  48.       else
  49.       {
  50.         delay(2000);
  51.       }
  52.   }
  53.  
  54.   client.publish(main_topic, "0");
  55.   client.publish(temp_topic, "40");
  56.   client.subscribe(main_topic);
  57. }
  58.  
  59. void loop()
  60. {
  61.   if(client.connected())
  62.   {
  63.     client.loop();
  64.  
  65.       //simulate temperatures
  66.       counter++;
  67.       if(counter >= 1000000)
  68.       {
  69.         int temp = (rand() % 40 + 1);
  70.  
  71.         client.publish(temp_topic, String(temp).c_str(), true);
  72.         Serial.println(temp);
  73.         counter = 0;
  74.       }
  75.   }
  76.   else
  77.   {
  78.     client.connect(device_name , mqttUser, mqttPassword);
  79.   }
  80. }
  81.  
  82. void callback(char* topic, byte* payload, unsigned int length)
  83. {
  84.     String message = "";
  85.     for (uint i = 0; i < length; i++) {
  86.       message += (char)payload[i];
  87.     }
  88.     Serial.println(message);
  89.     if(message == "1")
  90.     {
  91.       digitalWrite(RELAY, HIGH);
  92.     }
  93.     else
  94.     {
  95.       digitalWrite(RELAY, LOW);
  96.     }
  97. }