Advertisement
Guest User

Untitled

a guest
Jan 8th, 2019
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. // Update these with values suitable for your network.
  5. const char* ssid = "MySpectrumWifi4c-2G";
  6. const char* password = "funnybread359";
  7. const char* mqtt_server = "192.168.1.223";
  8.  
  9. WiFiClient espClient;
  10. PubSubClient client(espClient);
  11. int SwitchedPin = 12;
  12. String switch1;
  13. String strTopic;
  14. String strPayload;
  15.  
  16. void setup_wifi() {
  17.  Serial.begin(115200);
  18.   delay(100);
  19.  
  20.   // We start by connecting to a WiFi network
  21.  
  22.   Serial.println();
  23.   Serial.println();
  24.   Serial.print("Connecting to ");
  25.   Serial.println(ssid);
  26.  
  27.   WiFi.begin(ssid, password);
  28.  
  29.   while (WiFi.status() != WL_CONNECTED) {
  30.     delay(500);
  31.     Serial.print(".");
  32.   }
  33.  
  34.   Serial.println("");
  35.   Serial.println("WiFi connected");  
  36.   Serial.println("IP address: ");
  37.   Serial.println(WiFi.localIP());
  38. }
  39.  
  40. void callback(char* topic, byte* payload, unsigned int length) {
  41.   payload[length] = '\0';
  42.   strTopic = String((char*)topic);
  43.   if(strTopic == "ha/led")
  44.     {
  45.     switch1 = String((char*)payload);
  46.     if(switch1 == "ON")
  47.       {
  48.         Serial.println("ON");
  49.         digitalWrite(SwitchedPin, HIGH);
  50.       }
  51.     else
  52.       {
  53.         Serial.println("OFF");
  54.         digitalWrite(SwitchedPin, LOW);
  55.       }
  56.     }
  57. }
  58.  
  59.  
  60. void reconnect() {
  61.   // Loop until we're reconnected
  62.   while (!client.connected()) {
  63.     Serial.print("Attempting MQTT connection...");
  64.     // Attempt to connect
  65.     if (client.connect("arduinoClient")) {
  66.       Serial.println("connected");
  67.       // Once connected, publish an announcement...
  68.       client.subscribe("ha/#");
  69.     } else {
  70.       Serial.print("failed, rc=");
  71.       Serial.print(client.state());
  72.       Serial.println(" try again in 5 seconds");
  73.       // Wait 5 seconds before retrying
  74.       delay(5000);
  75.     }
  76.   }
  77. }
  78.  
  79. void setup()
  80. {
  81.   setup_wifi();
  82.   client.setServer(mqtt_server, 1883);
  83.   client.setCallback(callback);
  84.  
  85.   pinMode(SwitchedPin, OUTPUT);
  86.   digitalWrite(SwitchedPin, LOW);
  87. }
  88.  
  89. void loop()
  90. {
  91.   if (!client.connected()) {
  92.     reconnect();
  93.   }
  94.   client.loop();
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement