Advertisement
Guest User

Garage Sketch

a guest
Dec 18th, 2017
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.74 KB | None | 0 0
  1. #include <ESP8266WiFi.h>          //ESP8266 Core WiFi Library (you most likely already have this in your sketch)
  2. #include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
  3. #include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
  4. #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
  5. #include <PubSubClient.h>         //MQTT
  6. #include <ESP8266mDNS.h>
  7. #include <ESP8266HTTPUpdateServer.h>
  8.  
  9. ////**********START CUSTOM PARAMS******************//
  10.  
  11. //Define parameters for the http firmware update
  12. const char* host = "GarageESP";
  13. const char* update_path = "/WebFirmwareUpgrade";
  14. const char* update_username = "[redacted]";
  15. const char* update_password = "[redacted]";
  16.  
  17. //Define the pins
  18. #define RELAY_PIN 5
  19. #define DOOR_PIN 4
  20.  
  21. //Define MQTT Params. If you don't need to
  22. #define mqtt_server "[redacted]"
  23. #define door_topic "garage/door"
  24. #define button_topic "garage/button"
  25. const char* mqtt_user = "[redacted]";
  26. const char* mqtt_pass = "[redacted]";
  27.  
  28. //************END CUSTOM PARAMS********************//
  29. //This can be used to output the date the code was compiled
  30. const char compile_date[] = __DATE__ " " __TIME__;
  31.  
  32. //Setup the web server for http OTA updates.
  33. ESP8266WebServer httpServer(80);
  34. ESP8266HTTPUpdateServer httpUpdater;
  35.  
  36. WiFiClient espClient;
  37.  
  38. //Initialize MQTT
  39. PubSubClient client(espClient);
  40.  
  41. //Setup Variables
  42. String switch1;
  43. String strTopic;
  44. String strPayload;
  45. char* door_state = "UNDEFINED";
  46. char* last_state = "";
  47.  
  48. //Wifi Manager will try to connect to the saved AP. If that fails, it will start up as an AP
  49. //which you can connect to and setup the wifi
  50. WiFiManager wifiManager;
  51. long lastMsg = 0;
  52.  
  53.  
  54. void reconnect() {
  55.   //Reconnect to Wifi and to MQTT. If Wifi is already connected, then autoconnect doesn't do anything.
  56.   wifiManager.autoConnect(host);
  57.   Serial.print("Attempting MQTT connection...");
  58.   if (client.connect(host, mqtt_user, mqtt_pass)) {
  59.     Serial.println("connected");
  60.     client.subscribe("garage/#");
  61.   } else {
  62.     Serial.print("failed, rc=");
  63.     Serial.print(client.state());
  64.     Serial.println(" try again in 5 seconds");
  65.     // Wait 5 seconds before retrying
  66.     delay(5000);
  67.   }
  68. }
  69.  
  70.  
  71.  
  72. void checkDoorState() {
  73.   //Checks if the door state has changed, and MQTT pub the change
  74.   last_state = door_state; //get previous state of door
  75.   if (digitalRead(DOOR_PIN) == 0) // get new state of door
  76.     door_state = "OPENED";
  77.   else if (digitalRead(DOOR_PIN) == 1)
  78.     door_state = "CLOSED";
  79.  
  80.   if (last_state != door_state) { // if the state has changed then publish the change
  81.     client.publish(door_topic, door_state);
  82.     Serial.println(door_state);
  83.   }
  84.   //pub every minute, regardless of a change.
  85.   long now = millis();
  86.   if (now - lastMsg > 60000) {
  87.     lastMsg = now;
  88.     client.publish(door_topic, door_state);
  89.   }
  90. }
  91.  
  92.  
  93. void loop() {
  94.   //If MQTT client can't connect to broker, then reconnect
  95.   if (!client.connected()) {
  96.     reconnect();
  97.   }
  98.   checkDoorState();
  99.   client.loop(); //the mqtt function that processes MQTT messages
  100.   httpServer.handleClient(); //handles requests for the firmware update page
  101. }
  102.  
  103. void callback(char* topic, byte* payload, unsigned int length) {
  104.   //if the 'garage/button' topic has a payload "OPEN", then 'click' the relay
  105.   payload[length] = '\0';
  106.   strTopic = String((char*)topic);
  107.   if (strTopic == button_topic)
  108.   {
  109.     switch1 = String((char*)payload);
  110.     if (switch1 == "OPEN")
  111.     {
  112.       //'click' the relay
  113.       Serial.println("ON");
  114.       digitalWrite(RELAY_PIN, HIGH);
  115.       delay(600);
  116.       digitalWrite(RELAY_PIN, LOW);
  117.     }
  118.   }
  119. }
  120.  
  121.  
  122.  
  123. void setup() {
  124.   //Set Relay(output) and Door(input) pins
  125.   pinMode(RELAY_PIN, OUTPUT);
  126.   pinMode(RELAY_PIN, HIGH);
  127.   pinMode(DOOR_PIN, INPUT);
  128.  
  129.   Serial.begin(115200);
  130.  
  131.   //Set the wifi config portal to only show for 3 minutes, then continue.
  132.   wifiManager.setSTAStaticIPConfig(IPAddress(192,168,1,101), IPAddress(192,168,1,1), IPAddress(255,255,255,0));
  133.   wifiManager.setConfigPortalTimeout(180);
  134.   wifiManager.autoConnect(host);
  135.  
  136.   //sets up the mqtt server, and sets callback() as the function that gets called
  137.   //when a subscribed topic has data
  138.   client.setServer(mqtt_server, 1883);
  139.   client.setCallback(callback); //callback is the function that gets called for a topic sub
  140.  
  141.   //setup http firmware update page.
  142.   MDNS.begin(host);
  143.   httpUpdater.setup(&httpServer, update_path, update_username, update_password);
  144.   httpServer.begin();
  145.   MDNS.addService("http", "tcp", 80);
  146.   Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with username '%s' and your password\n", host, update_path, update_username);
  147. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement