· 6 years ago · Nov 04, 2019, 07:02 AM
1/*
2 Rui Santos
3 Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files.
7
8 The above copyright notice and this permission notice shall be included in all
9 copies or substantial portions of the Software.
10
11 Inital Code provided by Rui Sanotos et al.
12
13 Code further developed by Vikram Nayak and Jayanth Varma @ Katalyst D&E
14
15 +91 9110457911
16
17 katalystautomotive@gmail.com
18
19 Ver: 1.3
20
21 29/10/2019
22
23 */
24
25#include <WiFiClient.h>
26#include <WebServer.h>
27#include <ESPmDNS.h>
28#include <Update.h>
29
30const char* host = "esp32";
31const char* ssid = "Katalyst_Wifi";
32const char* password = "cmipl1234";
33
34WebServer server(80);
35
36/*
37 * Login page
38 */
39
40const char* loginIndex =
41 "<form name='loginForm'>"
42 "<table width='20%' bgcolor='E7D62A' align='center'>"
43 "<tr>"
44 "<td colspan=2>"
45 "<center><font size=4><b>FLip UPDATER</b></font></center>"
46 "<br>"
47 "</td>"
48 "<br>"
49 "<br>"
50 "</tr>"
51 "<td>Username:</td>"
52 "<td><input type='text' size=25 name='userid'><br></td>"
53 "</tr>"
54 "<br>"
55 "<br>"
56 "<tr>"
57 "<td>Password:</td>"
58 "<td><input type='Password' size=25 name='pwd'><br></td>"
59 "<br>"
60 "<br>"
61 "</tr>"
62 "<tr>"
63 "<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
64 "</tr>"
65 "</table>"
66"</form>"
67"<script>"
68 "function check(form)"
69 "{"
70 "if(form.userid.value=='katalyst' && form.pwd.value=='cmipl1234')"
71 "{"
72 "window.open('/serverIndex')"
73 "}"
74 "else"
75 "{"
76 " alert('Error Password or Username')/*displays error message*/"
77 "}"
78 "}"
79"</script>";
80
81/*
82 * Server Index Page
83 */
84
85const char* serverIndex =
86"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
87"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
88 "<input type='file' name='update'>"
89 "<input type='submit' value='Update'>"
90 "</form>"
91 "<div id='prg'>progress: 0%</div>"
92 "<script>"
93 "$('form').submit(function(e){"
94 "e.preventDefault();"
95 "var form = $('#upload_form')[0];"
96 "var data = new FormData(form);"
97 " $.ajax({"
98 "url: '/update',"
99 "type: 'POST',"
100 "data: data,"
101 "contentType: false,"
102 "processData:false,"
103 "xhr: function() {"
104 "var xhr = new window.XMLHttpRequest();"
105 "xhr.upload.addEventListener('progress', function(evt) {"
106 "if (evt.lengthComputable) {"
107 "var per = evt.loaded / evt.total;"
108 "$('#prg').html('progress: ' + Math.round(per*100) + '%');"
109 "}"
110 "}, false);"
111 "return xhr;"
112 "},"
113 "success:function(d, s) {"
114 "console.log('success!')"
115 "},"
116 "error: function (a, b, c) {"
117 "}"
118 "});"
119 "});"
120 "</script>";
121
122 #include <WiFi.h>
123 #include <HTTPClient.h>
124/* #else
125 #include <ESP8266WiFi.h>
126 #include <ESP8266HTTPClient.h>
127 #include <WiFiClient.h>
128#endif
129
130#include <Wire.h> */
131
132
133// Replace with your network credentials
134
135const char* serverName = "http://katalystpower.com/post-esp-data.php";
136
137// Keep this API Key value to be compatible with the PHP code provided in the project page.
138// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key
139String apiKeyValue = "tPmAT5Ab3j7F9";
140
141//String sensorName = "razmaan";
142//String sensorLocation = "fuckyou";
143
144
145int analog_value = 0 ;
146int ledPin = 2 ;
147unsigned long previousMillis = 0;
148const long interval = 5000;
149unsigned long currentMillis = 0 ;
150
151unsigned long previousMillis1 = 0;
152unsigned long currentMillis1 = 0;
153int interval1 = 500;
154
155int counter = 0;
156int ledState = LOW;
157
158
159
160void setup() {
161
162
163 pinMode(5,OUTPUT);
164 digitalWrite(5,HIGH);
165 pinMode(2,OUTPUT);
166 Serial.begin(115200);
167
168 WiFi.begin(ssid, password);
169 Serial.println("Connecting");
170 while(WiFi.status() != WL_CONNECTED) {
171
172
173
174 Serial.print(".");
175 digitalWrite(ledPin,HIGH);
176 delay(150);
177 digitalWrite(ledPin,LOW);
178
179 }
180
181 Serial.println("");
182 Serial.print("Connected to WiFi network with IP Address: ");
183 Serial.println(WiFi.localIP());
184
185 if (!MDNS.begin(host)) { //http://esp32.local
186 Serial.println("Error setting up MDNS responder!");
187 while (1) {
188 delay(1000);
189 }
190 }
191 Serial.println("mDNS responder started");
192 /*return index page which is stored in serverIndex */
193 server.on("/", HTTP_GET, []() {
194 server.sendHeader("Connection", "close");
195 server.send(200, "text/html", loginIndex);
196 });
197 server.on("/serverIndex", HTTP_GET, []() {
198 server.sendHeader("Connection", "close");
199 server.send(200, "text/html", serverIndex);
200 });
201 /*handling uploading firmware file */
202 server.on("/update", HTTP_POST, []() {
203 server.sendHeader("Connection", "close");
204 server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
205 ESP.restart();
206 }, []() {
207 HTTPUpload& upload = server.upload();
208 if (upload.status == UPLOAD_FILE_START) {
209 Serial.printf("Update: %s\n", upload.filename.c_str());
210 if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
211 Update.printError(Serial);
212 }
213 } else if (upload.status == UPLOAD_FILE_WRITE) {
214 /* flashing firmware to ESP*/
215 if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
216 Update.printError(Serial);
217 }
218 } else if (upload.status == UPLOAD_FILE_END) {
219 if (Update.end(true)) { //true to set the size to the current progress
220 Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
221 } else {
222 Update.printError(Serial);
223 }
224 }
225 });
226 server.begin();
227
228
229
230}
231
232void loop() {
233
234server.handleClient();
235delay(1);
236if(counter >= 50)
237{
238 counter = 0 ;
239 Serial.println("ESP Restart sequence");
240 delay(2000);
241 ESP.restart();
242}
243currentMillis = millis();
244
245 if (currentMillis - previousMillis >= interval) {
246 // save the last time you blinked the LED
247
248 previousMillis = currentMillis;
249 post();
250 // if the LED is off turn it on and vice-versa:
251
252 }
253
254currentMillis1 = millis();
255
256 if (currentMillis1 - previousMillis1 >= interval1) {
257 // save the last time you blinked the LED
258
259 previousMillis1 = currentMillis1;
260 if (ledState == LOW) {
261 ledState = HIGH;
262 } else {
263 ledState = LOW;
264 }
265 // if the LED is off turn it on and vice-versa:
266
267 }
268
269
270 digitalWrite(ledPin, ledState);
271}
272
273void post()
274{
275 //Check WiFi connection status
276 analog_value = analogRead(34);
277 Serial.println(analog_value);
278
279 if(WiFi.status()== WL_CONNECTED){
280
281 long rssi = WiFi.RSSI();
282 Serial.print("RSSI:");
283 Serial.println(rssi);
284 interval1 = 1000 ;
285
286
287 HTTPClient http;
288
289 // Your Domain name with URL path or IP address with path
290 http.begin(serverName);
291
292 // Specify content-type header
293 http.addHeader("Content-Type", "application/x-www-form-urlencoded");
294
295 // Prepare your HTTP POST request data
296 String httpRequestData = "api_key=" + apiKeyValue + "&b1wt=" + String(random(150, 360))
297 + "&b1px=" + String(random(15, 100)) + "&b2wt=" + String(random(15, 45))
298 + "&b2px=" + String(random(15, 100)) + "&b3wt=" + String(random(15, 45))
299 + "&b3px=" + String(random(15, 100)) + "&b4wt=" + String(random(15, 45))
300 + "&b4px=" + String(random(15, 100)) + "&b3wt=" + String(random(15, 45))
301 + "";
302 Serial.print("httpRequestData: ");
303 Serial.println(httpRequestData);
304
305
306 // You can comment the httpRequestData variable above
307 // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
308 //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";
309
310 // Send HTTP POST request
311 int httpResponseCode = http.POST(httpRequestData);
312 if(httpResponseCode != 200)
313 {
314 interval1 = 0 ;
315 }
316
317 // If you need an HTTP request with a content type: text/plain
318 //http.addHeader("Content-Type", "text/plain");
319 //int httpResponseCode = http.POST("Hello, World!");
320
321 // If you need an HTTP request with a content type: application/json, use the following:
322 //http.addHeader("Content-Type", "application/json");
323 //int httpResponseCode = http.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
324
325 if (httpResponseCode>0) {
326 Serial.print("HTTP Response code: ");
327 Serial.println(httpResponseCode);
328 }
329 else {
330 Serial.print("Error code: ");
331 Serial.println(httpResponseCode);
332 Serial.println("Restart on Error code");
333 delay(2000);
334 ESP.restart();
335
336 }
337 // Free resources
338 http.end();
339 }
340 else {
341 Serial.println("WiFi Disconnected");
342 interval1 = 150 ;
343 WiFi.begin(ssid, password);
344 }
345 counter = counter + 1 ;
346}