Thanawat Phattaraworamet / Mbed 2 deprecated ESP8266-WEB-Mbed-Controller

Dependencies:   DS18B20_1wire mbed

Fork of ESP8266-WEB-Mbed-Controller by Paul Staron

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 // ESP8266 Static page WEB server to control Mbed
00002 
00003 #include "mbed.h"
00004 #include "DS18B20.h"
00005 
00006 Serial pc(USBTX, USBRX);
00007 Serial esp(PTE0, PTE1); // tx, rx
00008 
00009 DS18B20 thermom(A0, DS18B20::RES_12_BIT);
00010 
00011 // Standard Mbed LED definitions
00012 DigitalOut  led1(LED_RED);      // (PTB18)
00013 DigitalOut  led2(LED_GREEN);    // (PTB19)
00014 DigitalOut  led3(LED_BLUE);     // (PTD1)
00015 
00016 // Digital Out and In pins, can be configured to any suitable pin depending on Platform
00017 DigitalOut  Out1(D7);
00018 DigitalOut  Out2(D8);
00019 DigitalOut  Out3(D4);
00020 
00021 DigitalIn  In1(A2);
00022 DigitalIn  In2(A3);
00023 DigitalIn  In3(A4);
00024 
00025 PwmOut speaker(D5);
00026 AnalogIn   BATin(A1);
00027 
00028 Timer t1;
00029 Timer t2;
00030 
00031 struct tm t;
00032 
00033 int bufflen, DataRX, count, getcount, replycount, servreq, timeout;
00034 int bufl, ipdLen, linkID, weberror, webcounter;
00035 float temperature, AdcIn, Ht; 
00036 float R1=100000, R2=10000; // resistor values to give a 10:1 reduction of measured AnalogIn voltage
00037 char Vcc[10];
00038 char Temp[10];
00039 char temp[10];
00040 char webcount[8];
00041 char lasthit[30];
00042 char timebuf[30];
00043 char type[16];
00044 char type1[16];
00045 char channel[2];
00046 char cmdbuff[32];
00047 char replybuff[512];
00048 char webdata[1024]; // This may need to be bigger depending on WEB browser used
00049 char webbuff[4096];     // Currently using 1986 characters, Increase this if more web page data added
00050 
00051 void SendCMD(),getreply(),ReadWebData(),startserver(),sendpage(),SendWEB(),sendcheck();
00052 void gettime(),gettemp(),getbattery(),setRTC(),beep();
00053 
00054 // manual set RTC values
00055 int minute      =20;    // 0-59
00056 int hour        =9;    // 2-23
00057 int dayofmonth  =20;    // 1-31
00058 int month       =2;     // 1-12
00059 int year        =15;    // last 2 digits
00060 
00061 int port        =8266;  // set server port
00062 int SERVtimeout =5;    // set server timeout in seconds incase link breaks.
00063  
00064 // Serial Interrupt read ESP data
00065 void callback() {    
00066     while (esp.readable()) {webbuff[count] = esp.getc();count++;}
00067     if(strlen(webbuff)>bufflen){DataRX=1;}  
00068 }
00069 
00070 int main() {
00071     led1=1,led2=1,led3=1;
00072     pc.baud(115200);
00073     esp.baud(115200);   // ESP8266 baudrate. Maximum on KLxx' is 115200, 230400 works on K20 and K22F
00074     if (time(NULL) < 1420070400) {setRTC();}    
00075     beep();
00076     startserver();
00077       
00078     while(1){     
00079         if(DataRX==1){
00080             ReadWebData();
00081             beep();
00082             if (servreq == 1 && weberror == 0){sendpage();}
00083             esp.attach(&callback);     
00084             pc.printf(" IPD Data:\r\n\n Link ID = %d,\r\n IPD Header Length = %d \r\n IPD Type = %s\r\n", linkID, ipdLen, type);        
00085             pc.printf("\n\n  HTTP Packet: \n\n%s\n", webdata); 
00086             pc.printf("  Web Characters sent : %d\n\n", bufl);
00087             pc.printf("  -------------------------------------\n\n");
00088             strcpy(lasthit, timebuf);
00089             servreq=0;               
00090         }                             
00091     }
00092 }    
00093 // Static WEB page    
00094 void sendpage()
00095 {          
00096     gettemp();
00097     getbattery();gettime();  
00098         
00099 // WEB page data     
00100     strcpy(webbuff, "<!DOCTYPE html>");
00101     strcat(webbuff, "<html><head><title>ESP8266 Mbed</title></head>");
00102     strcat(webbuff, "<body>");    
00103     strcat(webbuff, "<div style=\"text-align:center; background-color:#F4F4F4; color:#00AEDB;\"><h1>ESP8266 Mbed Web Controller</h1>");   
00104     strcat(webbuff, "Hit Count - ");
00105     strcat(webbuff, webcount);
00106     strcat(webbuff, "<br>Last Hit - ");
00107     strcat(webbuff, lasthit);                     
00108     strcat(webbuff, "</div><br /><hr>");
00109     strcat(webbuff, "<h3>Mbed RTC Time -&nbsp&nbsp");             
00110     strcat(webbuff, timebuf);
00111     strcat(webbuff, "</h3>\r\n");
00112     strcat(webbuff, "<p><form method=\"POST\"><strong> Temperature:&nbsp&nbsp<input type=\"text\" size=6 value=\"");
00113     strcat(webbuff, Temp);
00114     strcat(webbuff, "\"> <sup>O</sup>C <form method=\"POST\"> <strong> &nbsp&nbspBattery:&nbsp&nbsp<input type=\"text\" size=4 value=\"");
00115     strcat(webbuff, Vcc);
00116     strcat(webbuff, "\"> </sup>V");    
00117     if(led1==1){strcat(webbuff, "<p><input type=\"radio\" name=\"led1\" value=\"0\" checked>  Red LED off");
00118                 strcat(webbuff, "<br><input type=\"radio\" name=\"led1\" value=\"1\" >  Red LED on");} 
00119         else{strcat(webbuff, "<p><input type=\"radio\" name=\"led1\" value=\"0\" >  Red LED off");
00120                 strcat(webbuff, "<br><input type=\"radio\" name=\"led1\" value=\"1\" checked>  Red LED on");}   
00121     if(Out1==0){strcat(webbuff, "<p><input type=\"radio\" name=\"Out1\" value=\"0\" checked>  Digital Out 1  off");
00122                 strcat(webbuff, "<br><input type=\"radio\" name=\"Out1\" value=\"1\" >  Digital Out 1 on");}
00123         else{strcat(webbuff, "<p><input type=\"radio\" name=\"Out1\" value=\"0\" >  Digital Out 1 off");
00124                 strcat(webbuff, "<br><input type=\"radio\" name=\"Out1\" value=\"1\" checked>  Digital Out 1 on");}   
00125     if(Out2==0){strcat(webbuff, "<p><input type=\"radio\" name=\"Out2\" value=\"0\" checked>  Digital Out 2 off");
00126                 strcat(webbuff, "<br><input type=\"radio\" name=\"Out2\" value=\"1\" >  Digital Out 2 on");}
00127         else{strcat(webbuff, "<p><input type=\"radio\" name=\"Out2\" value=\"0\" >  Digital Out 2 off");
00128                 strcat(webbuff, "<br><input type=\"radio\" name=\"Out2\" value=\"1\" checked>  Digital Out 2 on");}           
00129     if(Out3==0){strcat(webbuff, "<p><input type=\"radio\" name=\"Out3\" value=\"0\" checked>  Digital Out 3 off");
00130                 strcat(webbuff, "<br><input type=\"radio\" name=\"Out3\" value=\"1\" >  Digital Out 3 on");}
00131         else{strcat(webbuff, "<p><input type=\"radio\" name=\"Out3\" value=\"0\" >  Digital Out 3 off");
00132                 strcat(webbuff, "<br><input type=\"radio\" name=\"Out3\" value=\"1\" checked>  Digital Out 3 on");}    
00133     if(In1==0){strcat(webbuff, "<p><input type=\"radio\" name=\"In1\" value=\"0\" >  Digital In 1");}
00134         else{strcat(webbuff, "<p><input type=\"radio\" name=\"In1\" value=\"1\" checked>  Digital In 1");}   
00135     if(In2==0){strcat(webbuff, "<br><input type=\"radio\" name=\"In2\" value=\"0\" >  Digital In 2");}
00136         else{strcat(webbuff, "<br><input type=\"radio\" name=\"In2\" value=\"1\" checked>  Digital In 2");}           
00137     if(In3==0){strcat(webbuff, "<br><input type=\"radio\" name=\"In3\" value=\"0\" >  Digital In 3");}
00138         else{strcat(webbuff, "<br><input type=\"radio\" name=\"In3\" value=\"1\" checked>  Digital In 3");}                  
00139     strcat(webbuff, "</strong><p><input type=\"submit\" value=\"send-refresh\" style=\"background: #3498db;");    
00140     strcat(webbuff, "background-image:-webkit-linear-gradient(top, #3498db, #2980b9);");    
00141     strcat(webbuff, "background-image:linear-gradient(to bottom, #3498db, #2980b9);");
00142     strcat(webbuff, "-webkit-border-radius:12;border-radius: 12px;font-family: Arial;color:#ffffff;font-size:20px;padding:");
00143     strcat(webbuff, "10px 20px 10px 20px; border:solid #103c57 3px;text-decoration: none;"); 
00144     strcat(webbuff, "background: #3cb0fd;");
00145     strcat(webbuff, "background-image:-webkit-linear-gradient(top,#3cb0fd,#1a5f8a);"); 
00146     strcat(webbuff, "background-image:linear-gradient(to bottom,#3cb0fd,#1a5f8a);");
00147     strcat(webbuff, "text-decoration:none;\"></form></span>");
00148     strcat(webbuff, "<p/><h2>How to use:</h2><ul>");
00149     strcat(webbuff, "<li>Select the Radio buttons to control the digital out pins.</li>");
00150     strcat(webbuff, "<li>Click 'Send-Refresh' to send.</li>");      
00151     strcat(webbuff, "<li>Use the 'Send-Refresh' button to refresh the data.</li>"); 
00152     strcat(webbuff, "</ul>");
00153     strcat(webbuff, "</body></html>");    
00154 // end of WEB page data       
00155     bufl = strlen(webbuff); // get total page buffer length            
00156     sprintf(cmdbuff,"AT+CIPSEND=%d,%d\r\n", linkID, bufl); // send IPD link channel and buffer character length.
00157     timeout=200;getcount=7;
00158     SendCMD();
00159     getreply();                                                               
00160     SendWEB();  // send web page
00161     memset(webbuff, '\0', sizeof(webbuff));
00162     sendcheck();              
00163 }
00164 
00165 //  wait for ESP "SEND OK" reply, then close IP to load web page
00166 void sendcheck()
00167 {
00168      weberror=1;timeout=500;getcount=24;
00169     t2.reset();t2.start();
00170     while(weberror==1 && t2.read() <5){        
00171         getreply();
00172         if (strstr(replybuff, "SEND OK") != NULL) {weberror=0;}  // wait for valid SEND OK 
00173         }
00174     if(weberror==1){ // restart connection
00175         strcpy(cmdbuff, "AT+CIPMUX=1\r\n"); 
00176         timeout=500;getcount=10;
00177         SendCMD();getreply(); 
00178         sprintf(cmdbuff,"AT+CIPSERVER=1,%d\r\n", port);
00179         timeout=500;getcount=10;
00180         SendCMD();getreply();
00181         }
00182         else{
00183             sprintf(cmdbuff, "AT+CIPCLOSE=%s\r\n",channel); // close current connection
00184             SendCMD();}       
00185     t2.reset();      
00186 }    
00187 
00188 // Reads and processes GET and POST web data 
00189 void ReadWebData()
00190  {
00191     wait_ms(200);        
00192     esp.attach(NULL);
00193     count=0;DataRX=0;weberror=0;
00194     memset(webdata, '\0', sizeof(webdata));    
00195     int x = strcspn (webbuff,"+");
00196     if(x){
00197         strcpy(webdata, webbuff + x);weberror=0;                                   
00198         int numMatched = sscanf(webdata,"+IPD,%d,%d:%s", &linkID, &ipdLen, type);    
00199         if( strstr(webdata, "led1=1") != NULL ) {led1=0;}
00200         if( strstr(webdata, "led1=0") != NULL ) {led1=1;}
00201         if( strstr(webdata, "Out1=1") != NULL ) {Out1=1;}
00202         if( strstr(webdata, "Out1=0") != NULL ) {Out1=0;}
00203         if( strstr(webdata, "Out2=1") != NULL ) {Out2=1;}
00204         if( strstr(webdata, "Out2=0") != NULL ) {Out2=0;}
00205         if( strstr(webdata, "Out3=1") != NULL ) {Out3=1;}
00206         if( strstr(webdata, "Out3=0") != NULL ) {Out3=0;}
00207         sprintf(channel, "%d",linkID);        
00208         if (strstr(webdata, "GET") != NULL) {servreq=1;}
00209         if (strstr(webdata, "POST") != NULL) {servreq=1;}
00210         webcounter++;
00211         sprintf(webcount, "%d",webcounter);
00212         }
00213             else {
00214                 memset(webbuff, '\0', sizeof(webbuff));
00215                 esp.attach(&callback);weberror=1;
00216                 }         
00217 }
00218 // Starts and restarts webserver if errors detected.
00219 void startserver()
00220 {
00221     gettemp();gettime();
00222     pc.printf("\n\n RTC time   %s\r\n\n",timebuf);
00223     pc.printf("++++++++++ Resetting ESP ++++++++++\r\n");  
00224     strcpy(cmdbuff,"AT+RST\r\n");
00225     timeout=2000;getcount=600;
00226     SendCMD();
00227     getreply();
00228     pc.printf(replybuff);
00229     pc.printf("%d",count);
00230     if (strstr(replybuff, "OK") != NULL) {
00231         pc.printf("\n++++++++++ Starting Server ++++++++++\r\n");
00232         strcpy(cmdbuff, "AT+CIPMUX=1\r\n");  // set multiple connections. 
00233         timeout=500;getcount=10;
00234         SendCMD();
00235         getreply();
00236         sprintf(cmdbuff,"AT+CIPSERVER=1,%d\r\n", port);
00237         timeout=500;getcount=10;
00238         SendCMD();
00239         getreply();
00240         sprintf(cmdbuff,"AT+CIPSTO=%d\r\n",SERVtimeout);
00241         timeout=500;getcount=50;
00242         SendCMD();
00243         getreply();
00244         pc.printf("\n Getting Server IP \r\n"); 
00245         strcpy(cmdbuff, "AT+CIFSR\r\n");
00246         timeout=1000;getcount=50;
00247         while(weberror==0){
00248             SendCMD();getreply();
00249             if (strstr(replybuff, "0.0.0.0") == NULL) {weberror=1;}  // wait for valid IP
00250             }
00251         pc.printf("\n Enter WEB address in your browser \r\n\n");
00252         replybuff[strlen(replybuff) - 8] = '\0';                
00253         char* IP = replybuff + 5;
00254         sprintf(webdata,"   http://%s:%d", IP, port);
00255         pc.printf(webdata);       
00256         led2=0;wait(2);led2=1;
00257         bufflen=200;count=0;
00258         pc.printf("\n\n++++++++++ Ready ++++++++++\r\n\n");
00259         esp.attach(&callback);
00260         }
00261         else{
00262             pc.printf("\n++++++++++ ESP8266 error, check power/connections ++++++++++\r\n");
00263             while(1){}
00264             }
00265         t2.reset();t2.start();beep();      
00266 }    
00267 // ESP Command data send
00268 void SendCMD()
00269 {
00270     esp.printf("%s", cmdbuff);      
00271 }    
00272 // Large WEB buffer data send
00273 void SendWEB()
00274 {    
00275     int i=0;
00276     if(esp.writeable()) {
00277         while(webbuff[i]!='\0') {esp.putc(webbuff[i]);i++;}
00278         }     
00279 } 
00280 // Get Cammand and ESP status replies
00281 void getreply()
00282 {    
00283     memset(replybuff, '\0', sizeof(replybuff));
00284     t1.reset(); t1.start();replycount=0;
00285     while(t1.read_ms()< timeout && replycount < getcount) {
00286         if(esp.readable()) {
00287             replybuff[replycount] = esp.getc();replycount++;
00288             }
00289         }
00290     t1.stop();      
00291 }
00292 // Analog in example
00293 void getbattery()
00294 {
00295     AdcIn=BATin.read(); 
00296     Ht = (AdcIn*3.328f*(R1+R2)/R2); // set the numeric to the exact MCU analog reference voltage for greater accuracy
00297     sprintf(Vcc,"%2.3f",Ht);    
00298 }
00299 // Temperature example
00300 void gettemp()
00301 {   
00302     temperature=thermom.GetTemperature();   // comment this out if no sensor connected
00303     //temperature = 21.357;                 // include for dummy value
00304     sprintf(Temp,"%3.3f",temperature);             
00305 }
00306 // Get RTC time        
00307 void gettime()
00308 {
00309     time_t seconds = time(NULL);
00310     strftime(timebuf,50,"%H:%M:%S %a %d %b %y", localtime(&seconds));               
00311 }
00312 
00313 void beep()
00314 {   
00315     speaker.period(1.0/2000); // 2000hz period
00316     speaker = 0.5; //50% duty cycle - max volume
00317     wait_ms(60);
00318     speaker=0.0; // turn off audio
00319 }
00320 
00321 void setRTC()
00322 {
00323             t.tm_sec = (0);             // 0-59
00324             t.tm_min = (minute);        // 0-59
00325             t.tm_hour = (hour);         // 0-23
00326             t.tm_mday = (dayofmonth);   // 1-31
00327             t.tm_mon = (month-1);       // 0-11  "0" = Jan, -1 added for Mbed RCT clock format
00328             t.tm_year = ((year)+100);   // year since 1900,  current DCF year + 100 + 1900 = correct year
00329             set_time(mktime(&t));       // set RTC clock                
00330 }