cndavy

导航

统计
 
141 #include <ESP8266WiFi.h>          //ESP8266 Core WiFi Library (you most likely already have this in your sketch)
142 #include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
143 #include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
144 #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
145 #include <PubSubClient.h>         //MQTT
146 #include <ESP8266mDNS.h>
147 #include <ESP8266HTTPUpdateServer.h>
148  
149 ////**********START CUSTOM PARAMS******************//
150  
151 //Define parameters for the http firmware update
152 const char* host = "GarageESP";
153 const char* update_path = "/WebFirmwareUpgrade";
154 const char* update_username = "admin";
155 const char* update_password = "YourPassWordHere";
156  
157 //Define the pins
158 #define RELAY_PIN 5
159 #define DOOR_PIN 4
160  
161 //Define MQTT Params. If you don't need to 
162 #define mqtt_server "MQTT Broker IP Address"
163 #define door_topic "garage/door"
164 #define button_topic "garage/button"
165 const char* mqtt_user = "mqtt_user"; 
166 const char* mqtt_pass = "mqtt_pass";
167  
168 //************END CUSTOM PARAMS********************//
169 //This can be used to output the date the code was compiled
170 const char compile_date[] = __DATE__ " " __TIME__;
171  
172 //Setup the web server for http OTA updates. 
173 ESP8266WebServer httpServer(80);
174 ESP8266HTTPUpdateServer httpUpdater;
175  
176 WiFiClient espClient;
177  
178 //Initialize MQTT
179 PubSubClient client(espClient);
180  
181 //Setup Variables
182 String switch1;
183 String strTopic;
184 String strPayload;
185 char* door_state = "UNDEFINED";
186 char* last_state = "";
187  
188 //Wifi Manager will try to connect to the saved AP. If that fails, it will start up as an AP
189 //which you can connect to and setup the wifi
190 WiFiManager wifiManager;
191 long lastMsg = 0;
192  
193 void setup() {
194   //Set Relay(output) and Door(input) pins
195   pinMode(RELAY_PIN, OUTPUT);
196   pinMode(RELAY_PIN, LOW);
197   pinMode(DOOR_PIN, INPUT);
198  
199   Serial.begin(115200);
200  
201   //Set the wifi config portal to only show for 3 minutes, then continue.
202   wifiManager.setConfigPortalTimeout(180);
203   wifiManager.autoConnect(host);
204  
205   //sets up the mqtt server, and sets callback() as the function that gets called
206   //when a subscribed topic has data
207   client.setServer(mqtt_server, 1883);
208   client.setCallback(callback); //callback is the function that gets called for a topic sub
209  
210   //setup http firmware update page.
211   MDNS.begin(host);
212   httpUpdater.setup(&httpServer, update_path, update_username, update_password);
213   httpServer.begin();
214   MDNS.addService("http", "tcp", 80);
215   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);
216 }
217  
218 void loop() {
219   //If MQTT client can't connect to broker, then reconnect
220   if (!client.connected()) {
221     reconnect();
222   }
223   checkDoorState();
224   client.loop(); //the mqtt function that processes MQTT messages
225   httpServer.handleClient(); //handles requests for the firmware update page
226 }
227  
228 void callback(char* topic, byte* payload, unsigned int length) {
229   //if the 'garage/button' topic has a payload "OPEN", then 'click' the relay
230   payload[length] = '\0';
231   strTopic = String((char*)topic);
232   if (strTopic == button_topic)
233   {
234     switch1 = String((char*)payload);
235     if (switch1 == "OPEN")
236     {
237       //'click' the relay
238       Serial.println("ON");
239       pinMode(RELAY_PIN, HIGH);
240       delay(600);
241       pinMode(RELAY_PIN, LOW);
242     }
243   }
244 }
245  
246 void checkDoorState() {
247   //Checks if the door state has changed, and MQTT pub the change
248   last_state = door_state; //get previous state of door
249   if (digitalRead(DOOR_PIN) == 0) // get new state of door
250     door_state = "OPENED";
251   else if (digitalRead(DOOR_PIN) == 1)
252     door_state = "CLOSED"; 
253  
254   if (last_state != door_state) { // if the state has changed then publish the change
255     client.publish(door_topic, door_state);
256     Serial.println(door_state);
257   }
258   //pub every minute, regardless of a change.
259   long now = millis();
260   if (now - lastMsg > 60000) {
261     lastMsg = now;
262     client.publish(door_topic, door_state);
263   }
264 }
265  
266 void reconnect() {
267   //Reconnect to Wifi and to MQTT. If Wifi is already connected, then autoconnect doesn't do anything.
268   wifiManager.autoConnect(host);
269   Serial.print("Attempting MQTT connection...");
270   if (client.connect(host, mqtt_user, mqtt_pass)) {
271     Serial.println("connected");
272     client.subscribe("garage/#");
273   } else {
274     Serial.print("failed, rc=");
275     Serial.print(client.state());
276     Serial.println(" try again in 5 seconds");
277     // Wait 5 seconds before retrying
278     delay(5000);
279   }
280 }

 

posted on 2018-03-26 21:57 cndavy 阅读(...) 评论(...) 编辑 收藏