Monil
Dependencies: mbed RA8875 mbed-rtos SDFileSystem Keypad
main.cpp
- Committer:
- mchheta
- Date:
- 2021-01-11
- Revision:
- 15:a557a4c85e54
- Parent:
- 14:d71b1aa3c8bf
File content as of revision 15:a557a4c85e54:
#include "mbed.h" #include <math.h> #include <string.h> #include "SDFileSystem.h" #include <iostream> #include <string> #include "rtos.h" # define FileName "/sd/Backup.txt" using namespace std; SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd"); //SD card Serial pc(USBTX, USBRX ); //Serial Communication Serial esp(PTC17, PTC16); // tx, rx (Wifi) AnalogIn Port[]={PTB2,PTB3,PTB10, PTB11, PTC11, PTC10, PTC2, PTC0,PTC9, PTC8}; //Define sensor pins float PortVal[10], timeout, Port_Multiplier[11]; char buf[1024], snd[1024], text[1024], cpyStr[1024], Port_Description[11][100]; //char Board_specs[10][50];// Board_specs[1]= Board-id, Board_specs[2]=WIFI ssid, Board_specs[3]=Wifi-Password,Board_specs[4]=Database TableName. char Board_specs[10][50]; //= {"IAC_Board3", "ENGR-IOT", "engr-iot", "sensor_readings"}; int rTime,bufcnt,lineCnt,prtCnt,ended,Multiplier,Port_SensorID[11], brdspCnt=0, count = 0; char port[10][10] = {"Port_1","Port_2","Port_3","Port_4","Port_5","Port_6","Port_7","Port_8","Port_9","Port_10"}; Timer t; int port_number; float port_value; //char ssid[32] = "iPhone"; // enter WiFi router ssid inside the quotes //char pwd [32] = "sl197197"; //char ssid[32] = "ENGR-IOT"; // enter WiFi router ssid inside the quotes //char pwd [32] = "engr-iot"; //char ssid[32] = "BatCave"; // enter WiFi router ssid inside the quotes //char pwd [32] = "bringyourownbeer232"; char ssid[32] ; // enter WiFi router ssid inside the quotes char pwd [32] ; char wifiIP[32]; void SendCMD(),getreply(), TCP_Boardspecs(), TCP_IPSend(), TCP_DataSend(), SDcrdRead(), Backup(char*),SendBackupData(); char readConfigText(); float UnitConversion(int Sens_ID); char *SensorName(int Sens_ID); FILE * fp; FILE * fp2; DigitalOut Relay1(PTD2), Relay2(PTD0), Relay3(PTC4), Relay4(PTC12); time_t seconds = time(NULL); /*This function parses the SD Card Config File*/ void SDcrdRead(void){ //FILE * fp; printf("\r\nReading from SD card...\r\n\n\n"); fp = fopen("/sd/IAC_Config_File.txt", "rb"); if (fp != NULL) { readConfigText(); fclose(fp); printf(" \r\n\r\n\r\nRead Successfully!\r\n\r\n\r\n"); printf(" \r\n\r\n\r\n ---- Config File ---- \r\n\r\n\r\n"); printf("%s\n", text); printf(" \r\n\r\n\r\n ---- End of Config File ---- \r\n\r\n\r\n"); } else { printf("\nReading Failed!\r\n"); } } /*This function is used to rename a file in SD Card.*/ int file_rename(const char *oldfname, const char *newfname) { int retval = 0; int ch; FILE *fpold = fopen(oldfname, "r"); // src file FILE *fpnew = fopen(newfname, "w"); // dest file while (1) { // Copy src to dest ch = fgetc(fpold); // until src EOF read. if (ch == EOF) break; fputc(ch, fpnew); } fclose(fpnew); fclose(fpold); fpnew = fopen(newfname, "r"); // Reopen dest to insure if(fpnew == NULL) { // that it was created. retval = (-1); // Return Error. } else { fclose(fpnew); remove(oldfname); // Remove original file. retval = (0); // Return Success. } return (retval); } /*This function is used to copy contents of one file in SD card to another file in SD card*/ int file_copy (const char *src, const char *dst) { int retval,co = 0; int ch; FILE *fpsrc = fopen(src, "r"); // src file FILE *fpdst = fopen(dst, "w"); // dest file while (1) { // Copy src to dest ch = fgetc(fpsrc); // until src EOF read. if (ch == EOF) break; if(co==1)co++; else fputc(ch, fpdst); } fclose(fpsrc); fclose(fpdst); fpdst = fopen(dst, "r"); // Reopen dest to insure if(fpdst == NULL) { // that it was created. retval = (-1); // Return error. } else { fclose(fpdst); retval = (0); // Return success. } return (retval); } /* This function extracts essential information from SD Card Config file */ char readConfigText() { memset(buf, '\0', sizeof(buf)); t.start(); ended=0; bufcnt=0; lineCnt=0; prtCnt =0; while(true) { char C = fgetc(fp); //if(t.read() <= timeout) { buf[bufcnt] = C; bufcnt++; //printf(buf); if(feof(fp)){ break; } if(C == '\n'){ //buf[bufcnt] = '\0'; lineCnt++; strcpy(snd,buf); strcat(text,snd); if(buf[0]=='B'){ const char s[2] = ":"; char *token; /* get the first token */ token = strtok(buf, s); /* get the other tokens there*/ while( token != NULL ) { brdspCnt++; strcpy(Board_specs[brdspCnt],token); printf( " Boardspec[%d] = %s\r\n\n",brdspCnt, Board_specs[brdspCnt] ); token = strtok(NULL, s); } } else if(buf[0]=='P'){ prtCnt++; if (prtCnt<10){ Port_SensorID[prtCnt]=int(buf[9]-'0'); Port_Multiplier[prtCnt]= UnitConversion(Port_SensorID[prtCnt]); char *senStr = SensorName(Port_SensorID[prtCnt]); strcpy(Port_Description[prtCnt],senStr); printf("%d %0.2f %s\r\n",Port_SensorID[prtCnt],Port_Multiplier[prtCnt],Port_Description[prtCnt]); } else{ Port_SensorID[prtCnt]=int(buf[10]-'0'); Port_Multiplier[prtCnt]= UnitConversion(Port_SensorID[prtCnt]); char *senStr = SensorName(Port_SensorID[prtCnt]); strcpy(Port_Description[prtCnt],senStr); printf("%d %0.2f %s\r\n",Port_SensorID[prtCnt],Port_Multiplier[prtCnt],Port_Description[prtCnt]); } } //printf(text); memset(buf, '\0', sizeof(buf)); bufcnt = 0; } } printf("\r\n End of text file \r\n"); printf("\r\nLine Count %d\r\n",lineCnt); } /*This function returns the multiplying factor for sensor. It helps converting raw value to standard units. Sensor ID is available in SD Card */ float UnitConversion(int Sens_ID){ switch (Sens_ID){ case 0 : Multiplier = 0.0; break; case 1 : Multiplier = 2000.0; break; case 2 : Multiplier = 140; break; case 3 : Multiplier = 27.85; break; case 4 : Multiplier = 50.0; break; case 5 : Multiplier = 50.0; break; case 6 : Multiplier = 240.0; break; case 7 : Multiplier = 100.0; break; case 8 : Multiplier = 100; break; } return Multiplier; } /* This function returns name of the sensor based on Sensor ID */ char *SensorName(int Sens_ID){ static char *strng ; //memset(strng, '\0', sizeof(strng)); switch (Sens_ID){ case 0 : strng = "Null"; break; case 1 : strng = "Carbondioxide(ppm)"; break; case 2 : strng = "Current(0-100)Amps"; break; case 3 : strng = "Current(0-20)Amps"; break; case 4 : strng = "Temperature(0-50)Degree-Celsius"; break; case 5 : strng = "Temperature(0-50)Degree-Celsius"; break; case 6 : strng = "Pressure(PSIG)"; break; case 7 : strng = "Humidity(Percentage)"; break; case 8 : strng = "Compressed-Airflow(Percentage)"; break; } return strng; } /*This function is used to send command to Wi-Fi module. */ void SendCMD() { esp.printf("%s", snd); } /*This function is used to receieve response from the Wi-Fi module */ void getreply() { memset(buf, '\0', sizeof(buf)); t.start(); ended=0; count=0; while(!ended) { if(esp.readable()) { buf[count] = esp.getc(); count++; } if(t.read() > timeout) { ended = 1; t.stop(); t.reset(); } } } /* This function is used to configure Wi-Fi module. It also connects to the internet */ void ESPconfig() { wait(1); strcpy(snd,"AT\r\n"); SendCMD(); wait(1); strcpy(snd,"AT\r\n"); SendCMD(); wait(1); strcpy(snd,"AT\r\n"); SendCMD(); timeout=1; getreply(); wait(1); pc.printf("\f---------- Starting ESP Config ----------\r\n\n"); pc.printf("---------- Reset & get Firmware ----------\r\n"); strcpy(snd,"AT+RST\r\n"); SendCMD(); timeout=5; getreply(); pc.printf(buf); wait(1); pc.printf("\n---------- Get Version ----------\r\n"); strcpy(snd,"AT+GMR\r\n"); SendCMD(); timeout=4; getreply(); pc.printf(buf); wait(1); // set CWMODE to 1=Station,2=AP,3=BOTH, default mode 1 (Station) pc.printf("\n---------- Setting Mode ----------\r\n"); strcpy(snd, "AT+CWMODE=1\r\n"); SendCMD(); timeout=4; getreply(); //getEspReply(); pc.printf(buf); wait(2); // set CIPMUX to 0=Single,1=Multi pc.printf("\n---------- Setting Connection Mode ----------\r\n"); strcpy(snd, "AT+CIPMUX=1\r\n"); SendCMD(); timeout=4; getreply(); //getEspReply(); pc.printf(buf); wait(2); /*pc.printf("\n---------- Listing Access Points ----------\r\n"); strcpy(snd, "AT+CWLAP\r\n"); SendCMD(); timeout=15; getreply(); pc.printf(buf); wait(2);*/ pc.printf("\n---------- Connecting to AP ----------\r\n"); pc.printf("ssid = %s pwd = %s\r\n",Board_specs[2],Board_specs[3]);//,ssid,pwd); strcpy(snd, "AT+CWJAP=\""); strcat(snd, Board_specs[2]); strcat(snd, "\",\"");/* Here (\") denotes inverted commas in strings */ strcat(snd, Board_specs[3]); strcat(snd, "\"\r\n"); pc.printf(snd); SendCMD(); timeout=10; getreply(); //getEspReply(); pc.printf(buf); wait(5); pc.printf("\n---------- Get IP's ----------\r\n"); strcpy(snd, "AT+CIFSR\r\n"); SendCMD(); timeout=3; getreply(); pc.printf(buf); memset(text, '\0', sizeof(text)); strcpy(text,buf); //const char s[2] = ","; char *token2; /* get the first token */ token2 = strtok(text, "\""); token2 = strtok(NULL, "\""); strcpy(wifiIP,token2); //token2 = strtok(NULL, "\""); pc.printf("\n\n%s\n\n",wifiIP); //const char* ipData = string(buf); //const char* msg="Hello World!"; //pc.printf(ipData); wait(1); pc.printf("\n---------- Get Connection Status ----------\r\n"); strcpy(snd, "AT+CIPSTATUS\r\n"); SendCMD(); timeout=5; //getEspReply(); getreply(); pc.printf(buf); pc.printf("\n\n\n If you get a valid (non zero) IP, ESP8266 has been set up.\r\n"); pc.printf(" Run this if you want to reconfig the ESP8266 at any time.\r\n"); pc.printf(" It saves the SSID and password settings internally\r\n"); wait(1); TCP_Boardspecs(); } void reconnect() { pc.printf("\n---------- Connecting to AP ----------\r\n"); pc.printf("ssid = %s pwd = %s\r\n",Board_specs[2],Board_specs[3]);//,ssid,pwd); strcpy(snd, "AT+CWJAP=\""); strcat(snd, Board_specs[2]); strcat(snd, "\",\"");/* Here (\") denotes inverted commas in strings */ strcat(snd, Board_specs[3]); strcat(snd, "\"\r\n"); pc.printf(snd); SendCMD(); timeout=1; getreply(); //getEspReply(); pc.printf(buf); } /* This function sends information to the server. The information consits of which sensor is connected to each port, board_id and Boot time */ void TCP_Boardspecs(){ pc.printf("\n---------- Start TCP_IP Connection with WAMP ----------\r\n"); strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"134.68.70.220\",80\r\n"); //strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"192.168.1.2\",8181\r\n"); SendCMD(); timeout=0.5; getreply(); pc.printf(buf); //wait(); pc.printf("\n---------- Set TCP Data frame ----------\r\n"); memset(text, '\0', sizeof(text)); sprintf(text, "GET /IAC_BoardSpecs_DataLoad.php?boardId=IAC_%s&wifiIP=%s&Port1Sensor=%s&Port2Sensor=%s&Port3Sensor=%s&Port4Sensor=%s&Port5Sensor=%s&Port6Sensor=%s&Port7Sensor=%s&Port8Sensor=%s&Port9Sensor=%s&Port10Sensor=%s\r\n",Board_specs[1],wifiIP,Port_Description[1],Port_Description[2],Port_Description[3],Port_Description[4],Port_Description[5],Port_Description[6],Port_Description[7],Port_Description[8],Port_Description[9],Port_Description[10]); int sz = strlen(text); pc.printf("\n\n%d\r\n",sz); sprintf(snd, "AT+CIPSEND=4,%d\r\n",sz); //strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"184.106.153.149\",80\r\n") SendCMD(); timeout=0.5; getreply(); pc.printf(buf); //wait(0.5); pc.printf("\n---------- Send Data frame ----------\r\n"); strcpy(snd,text); pc.printf(snd); SendCMD(); timeout=0.5; getreply(); pc.printf(buf); //wait(1); pc.printf("\n---------- Close TCP/IP Connection ----------\r\n"); strcpy(snd, "AT+CIPCLOSE=5\r\n"); SendCMD(); timeout=0.1; getreply(); pc.printf(buf); //wait(2); } /*This function sends sensor data to the server. Once the sensor data is read, this function is used to send the data to the server */ void TCP_DataSend(){ char buffer[32]; pc.printf("\n---------- Start TCP_IP Connection with WAMP ----------\r\n"); strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"134.68.70.220\",80\r\n"); SendCMD(); timeout=0.1; getreply(); pc.printf(buf); pc.printf("\n---------- Set TCP Data frame ----------\r\n"); memset(text, '\0', sizeof(text)); sprintf(text, "GET /Sensor_readings.php?Board_ID=IAC_%s&Port_ID=%s&Value=%0.2f&MCTime=%u\r\n", Board_specs[1], port[port_number], port_value,(unsigned int)seconds); int sz1 = strlen(text); pc.printf("\n\n%d\r\n",sz1); sprintf(snd, "AT+CIPSEND=4,%d\r\n",sz1); SendCMD(); pc.printf("\r \n\nGetting Reply\n\r\n"); timeout=0.1; getreply(); pc.printf(buf); pc.printf("\n---------- Send Data frame ----------\r\n"); strcpy(snd,text); pc.printf(snd); pc.printf("\n\n Getting Reply\n\r\n"); SendCMD(); timeout=0.2; getreply(); pc.printf(buf); /*If the response from wi-fi module is an error, the sensor data is stored as backup data in SD card. It also attempts to reconnect to the server */ if(strstr(buf,"ERROR")!=0 ||strstr(buf,"busy")!=0 || strstr(buf,"404 Not Found")!=0) { Backup(snd); //ESPconfig(); reconnect(); } /*Based on the server response, actuation of relay is done here */ if(strstr(buf,"Relay 1=on")!=0) Relay1=1; else if(strstr(buf,"Relay 1=off")!=0) Relay1=0; if(strstr(buf,"Relay 2=on")!=0) Relay2=1; else if(strstr(buf,"Relay 2=off")!=0) Relay2=0; if(strstr(buf,"Relay 3=on")!=0) Relay3=1; else if(strstr(buf,"Relay 3=off")!=0) Relay3=0; if(strstr(buf,"Relay 4=on")!=0) Relay4=1; else if(strstr(buf,"Relay 4=off")!=0) Relay4=0; /* get the first token */ //wait(1); pc.printf("\n---------- Close TCP/IP Connection ----------\r\n"); strcpy(snd, "AT+CIPCLOSE=5\r\n"); SendCMD(); timeout=0.1; //getreply(); pc.printf(buf); /*If the response from the server is as expected, the command attempts to send backup data from the SD Card */ if(strstr(buf,"Relay")!=0) { //for(int i=0;i<10;i++) //{ SendBackupData(); //} } } /*This function is used to extract particular information from string. For example, information enclosed between < and > symbol will be extracted into a string */ std::string extract(const std::string& str, char beg, char end) { std::size_t begPos ; if ( (begPos = str.find(beg)) != std::string::npos ) { std::size_t endPos ; if ( (endPos = str.find(end, begPos)) != std::string::npos && endPos != begPos+1 ) return str.substr(begPos+1, endPos-begPos-1) ; } return std::string() ; } /*This function is used to retrieve current time from the web */ int retriveTime() { pc.printf("\n---------- Start TCP_IP Connection with WAMP ----------\r\n"); strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"134.68.70.220\",80\r\n"); SendCMD(); timeout=0.5; getreply(); pc.printf(buf); //wait(); pc.printf("\n---------- Set TCP Data frame ----------\r\n"); memset(text, '\0', sizeof(text)); //sprintf(text, "GET /test1.php?\r\n"); sprintf(text, "GET /TimeQuery.php?\r\n"); int sz = strlen(text); pc.printf("\n\n%d\r\n",sz); sprintf(snd, "AT+CIPSEND=4,%d\r\n",sz); //strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"184.106.153.149\",80\r\n") SendCMD(); timeout=0.5; getreply(); pc.printf(buf); pc.printf("\n---------- Send Data frame ----------\r\n"); strcpy(snd,text); pc.printf(snd); SendCMD(); timeout=0.5; getreply(); pc.printf("Start"); pc.printf(buf); pc.printf("End"); string time = extract(buf,'>','<'); int rTime = atoi(time.c_str()); //int rtime = stoi(time); pc.printf("Time = %d",rTime); pc.printf("\n---------- Close TCP/IP Connection ----------\r\n"); strcpy(snd, "AT+CIPCLOSE=5\r\n"); SendCMD(); timeout=0.5; getreply(); pc.printf(buf); return rTime; } /*This function is responsible to open TCP/IP connection and send the backup data to server */ void Senddta(char bckp[]) { if(strlen(bckp)>1){ pc.printf("\n---------- Start TCP_IP Connection with WAMP ----------\r\n"); strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"134.68.70.220\",80\r\n"); //strcpy(snd, "AT+CIPSTART=4,\"TCP\",\"149.165.231.70\",8660\r\n"); SendCMD(); timeout=0.1; getreply(); pc.printf(buf); pc.printf("\n---------- Set TCP Data frame ----------\r\n"); memset(text, '\0', sizeof(text)); char buffer[32]; //strftime(buffer, 32,"%Y%m%d%H%M%S\n", localtime(&seconds)); //strftime(buffer, 32,"%s\n", localtime(&seconds)); //printf("Time as a custom formatted string = %s", buffer); sprintf(text, bckp); int sz1 = strlen(text); pc.printf("\n\n%d\r\n",sz1); sprintf(snd, "AT+CIPSEND=4,%d\r\n",sz1); SendCMD(); pc.printf("\r \n\nGetting Reply\n\r\n"); timeout=0.2; getreply(); pc.printf(buf); pc.printf("\n---------- Send Backup Data frame ----------\r\n"); strcpy(snd,bckp); pc.printf(snd); pc.printf("\n\n Getting Reply\n\r\n"); SendCMD(); timeout=0.1; getreply(); pc.printf(buf); } //else //wait(0.15); } /*In case the firmware is unable to send data to the server, this function stores data into SD Card */ void Backup(char text[]) { fclose(fp); pc.printf("Appending data to data file \r\n"); //fp = fopen("/sd/Backup.txt", "a"); if((fp=fopen("/sd/Backup.txt","a")) == NULL){ pc.printf("Could not open file"); fclose(fp); fp=fopen("/sd/Backup.txt","w"); fclose(fp); } fclose(fp); fp = fopen("/sd/Backup.txt", "a"); fprintf(fp, "%s", text); pc.printf("\n\n%s\n\n", text); //fputc('\n', fp); fclose(fp); wait(0.5); } /*This function extracts data from backup file in SD Card. It passes data Senddta function which opens TCP/IP connection and sends data to server. Once data is sent to the server, that particular sent data is deleted from Backup file. */ void SendBackupData() { char bckp[1024]; fp = fopen("/sd/Backup.txt","r"); //fp2 = fopen("/sd/temp.txt","w"); if(strlen(fgets(bckp, sizeof(bckp), fp)) < 10){ pc.printf("No Backup Data"); fclose(fp); wait(1.5); //remove("/sd/Backup.txt"); } //fclose(fp); else { fclose(fp); fp = fopen("/sd/Backup.txt","r"); //for(int i=0;i<5;i++){ fgets(bckp, sizeof(bckp), fp); pc.printf("%s", bckp); fclose(fp); //wait(2); Senddta(bckp); //} fclose(fp); int ctr = 0; memset(bckp, '\0', sizeof(bckp)); //char c = fgetc(fp); char copy[100]; //wait(3); fp=fopen("/sd/Backup.txt","r"); fp2 = fopen("/sd/temp.txt","w"); while ((fgets(copy,sizeof(copy),fp))!=NULL) { ctr++; if(ctr==1) pc.printf("Skip first line\r\n"); else fputs(copy,fp2); } //sprintf(copy,"\0"); //sprintf(bckp,"\0"); //wait(2); fclose(fp); fclose(fp2); remove("/sd/Backup.txt"); file_rename("/sd/temp.txt", "/sd/Backup.txt"); memset(copy, '\0', sizeof(copy)); } } int main() { pc.baud(115200); esp.baud(115200); SDcrdRead(); pc.printf("Board_specs[2] = %s and Board_specs[3]= %s \r\n", Board_specs[2], Board_specs[3]); wait(2); ESPconfig(); set_time(retriveTime()); while (true) { seconds = time(NULL); //wait(1); /*Loop to read and send data to server */ for(int i = 0; i <10; i++){ if(Port_Multiplier[i+1]==0) //If no sensor attached, don't read data { } else{ //seconds = time(NULL); port_value=Port[i].read()*Port_Multiplier[i+1]; //Read data and convert raw value to standard units port_number=i; TCP_DataSend(); //Send data to the server pc.printf(" %f",port_value); } } //wait(4); //fp = fopen("/sd/Backup.txt","r"); pc.printf("\n"); } }