Simple HTTP Server with one page index.html stored inside MBED as char vector and javascript to update a table content
Fork of HTTP_SERVER by
Revision 14:f21da0acc9f6, committed 2018-05-10
- Comitter:
- mmdonatti
- Date:
- Thu May 10 20:24:03 2018 +0000
- Parent:
- 13:b6dd6ed0060b
- Commit message:
- Simple server GET and POST for one index.html page and javascript
Changed in this revision
diff -r b6dd6ed0060b -r f21da0acc9f6 HTTP_SERVER.cpp --- a/HTTP_SERVER.cpp Fri Mar 16 21:55:50 2018 +0000 +++ b/HTTP_SERVER.cpp Thu May 10 20:24:03 2018 +0000 @@ -1,9 +1,82 @@ #include "HTTP_SERVER.h" -#include "string" + #ifndef DEBUG //#define DEBUG #endif +//HTML file - with Javascript +const char *index_html = "<html><head><title>DCM Heaters Driver</title><link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"http://cnpem.br/wp-content/uploads/2018/01/LNLS_Sirius-02-293x300.png\" />\n\ +<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head>\n\ +<script language=\"javascript\" type=\"text/javascript\">\n\ +function loop(){\n\ +$.post(\"read_data\", function(data){\n\ +if(data.length >0)\n\ +{\n\ +var str = data;\n\ +var res = str.split(\" \");\n\ +if(res.length == 97){\n\ +var table = '<div id=\"data_table\">'+\n\ +'<table width=\"100%\" border=\"1\" cellpadding=\"3\" cellspacing=\"1\" bgcolor=\"#E3EBFB\">'+\n\ +'<tr align=\"center\" valign=\"middle\">'+\n\ +'<td width=\"50\" height=\"40\"><strong>Channel</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>Voltage (V)</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>Current (A)</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>Control (%)</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>Current Limit (A)</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>Failure</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>Overload</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>No Load</font></strong></td>'+\n\ +'<td width=\"96\" height=\"40\"><strong>Enable</font></strong></td></tr>';\n\ +for(var i=0;i<8;i++){\n\ +table = table + '<tr align=\"center\" valign=\"middle\">'+\n\ +'<td width=\"50\" height=\"31\"bgcolor=\"#FFFFFF\"><span style=\"font-weight:bold;\">'+(i+1)+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"#FFFFFF\"><span style=\"font-weight:bold;\">'+res[i*12]+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"#FFFFFF\"><span style=\"font-weight:bold;\">'+res[i*12+1]+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"#FFFFFF\"><span style=\"font-weight:bold;\">'+res[i*12+2]+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"#FFFFFF\"><span style=\"font-weight:bold;\">'+res[i*12+3]+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"'+res[i*12+4]+'\"><span style=\"font-weight:bold;\">'+res[i*12+5]+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"'+res[i*12+6]+'\"><span style=\"font-weight:bold;\">'+res[i*12+7]+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"'+res[i*12+8]+'\"><span style=\"font-weight:bold;\">'+res[i*12+9]+'</span></td>'+\n\ +'<td width=\"96\" height=\"28\"bgcolor=\"'+res[i*12+10]+'\"><span style=\"font-weight:bold;\">'+res[i*12+11]+'</span></td>'+\n\ +'</tr>';\n\ +}\n\ +table = table + '</table></div>';\n\ +document.getElementById(\"data_table\").innerHTML = table;\n\ +}}\n\ +});\n\ +setTimeout(function(){ loop() }, 2000);\n\ +}\n\ +</script>\n\ +<body onLoad=\"loop()\">\n\ +<table width=\"100%\"border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"font-weight:normal;\">\n\ +<tr>\n\ +<td width=\"25%\" height=\"142\" align=\"center\" valign=\"middle\" style=\"border-bottom: #000000 solid 1px;\">\n\ +<a href=\"http://www.lnls.cnpem.br/\"><img src=\"http://lnls.cnpem.br/wp-content/themes/lnls-v2/assets/images/logo-header.svg\" alt=\"LNLS\" width=\"305\" height=\"142\" /></a></td>\n\ +<td colspan=\"5\" height=\"142\" align=\"center\" scope=\"col\" style=\"border-bottom: #000000 solid 1px;\"><p><span class=\"style7\">DCM HEATERS DRIVER<br /><br/>\n\ +<strong>DIAGNOSTICS<br/></strong></span></p>\n\ +<p><span class=\"style7\"><strong><em> <a href=\"http://www.lnls.cnpem.br\">LNLS</a></em></strong></span></p></td>\n\ +<td width=\"25%\" height=\"142\" align=\"center\" style=\"border-bottom: #000000 solid 1px;\">\n\ +<a href=\"http://www.lnls.cnpem.br/grupos/gae/\"><img src=\"http://www.gae.agency/wp-content/uploads/2016/03/Logo_gae_hp_blue.png\" alt=\"GAE\" width=\"305\" height=\"99\" /></a></td>\n\ +</tr>\n\ +</table>\n<div id=\"data_table\"></div></body></html>\0"; + +//table colors vector +const char *color[] = {"#C8FFC8\0","#FF0000\0"}; + +int index_html_len; //index with html length + +char buffer[MAX_BUFFER_SIZE]; //receive and transmit buffer +char tmp_buffer[200]; //aux buffer +int status_code; //http status code +char reason_phrase[30]; //http reason phrase + +char httpmethod[20]; //http method +char filepath[20]; //file requested +char http_ver[20]; //http version + +int idx_buffer; //index buffer + +//Debug functions namespace HTTP_SERVER { void DEBUG_PRINT_LINE(const char* arg_line) @@ -37,181 +110,124 @@ HttpServer::HttpServer() { - keep_alive = (false); - listening_flag = (false); - req_buf[0] = '\0'; + buffer[0] = '\0'; //constructor } HttpServer::~HttpServer() { } - bool HttpServer::init() { - -// Ethernet Initialization - if(eth.init()) { - printf("(HTTP_SERVER) Error!@EthernetInterface::init()\r\n"); - return false; - } - // Ethernet Connecting setup - if(eth.connect()) { - printf("(HTTP_SERVER) Error!@EthernetInterface::connect()\r\n"); - return false; - } else { - printf("(HTTP_SERVER) IP Address is %s\r\n", eth.getIPAddress()); - } // TCP Socket setup // To open Server-side PORT if(tcpsvr.bind(TCP_PORT)< 0) { - printf("(HTTP_SERVER) Error!@TCPSocketServer::bind()\r\n"); return false; - } else { - printf("(HTTP_SERVER) TCP Server has bounden!\r\n"); - } + } + tcpsvr.set_blocking(true,1500); //set blocking socket + // Server start listening Request from a web browser. - if(tcpsvr.listen(1) < 0) { - printf("(HTTP_SERVER) tcp server listen failed.\r\n"); + + if(tcpsvr.listen(5) < 0) { return false; - } else { - listening_flag = true; - printf("(HTTP_SERVER) tcp server is listening...\r\n"); } + + index_html_len = strlen(index_html); //calculate string length return true; } -bool HttpServer::run() -{ - DigitalOut led1(LED1); - DigitalOut led2(LED1); - - while (listening_flag) { - led1 = true; - // blocking mode (never timeout) - // waiting client connection - printf("(HTTP_SERVER) waiting connection\r\n"); - if(tcpsvr.accept(tcpcon) < 0) { - printf("(HTTP_SERVER) failed to accept connection.\r\n"); - return -1; - } else { - printf("(HTTP_SERVER) connection success!\r\nIP: %s\r\n",tcpcon.get_address()); - led2 = true; +bool HttpServer::run(channel *CH) +{ + if(tcpsvr.accept(tcpcon) < 0) { + //printf("(HTTP_SERVER) failed to accept connection.\r\n"); + return -1; + } + // When conected + while(tcpcon.is_connected()) + { + tcpcon.set_blocking(false,100); + // + // Request Analysis + // + + DEBUG_PRINT_LINE("DEBUG MODE"); + switch(tcpcon.receive(buffer, 1023)) { + case 0: + //DEBUG_PRINT_LINE("received buffer is empty."); + status_code = 400; + sprintf(reason_phrase,"No Request\0"); + httpmethod[0] = '\0'; + filepath[0] = '\0'; + http_ver[0] = '\0'; + break; + case -1: + DEBUG_PRINT_LINE("failed to read data from client."); + status_code = 500; + sprintf(reason_phrase,"Internal Server Error\0"); + httpmethod[0] = '\0'; + filepath[0] = '\0'; + http_ver[0] = '\0'; + break; + default: + DEBUG_PRINT_LINE("Received Data: %d",strlen(buffer)); + DEBUG_PRINT_LINE("-->\r\n"); + DEBUG_PRINT_LINE("%.*s[End of Request]",strlen(buffer),buffer); + // get HTTP method, File path, HTTP version + sprintf(httpmethod,strtok(buffer," ")); + filepath[0] = '\0'; + sprintf(http_ver,"HTTP/1.1\0"); + DEBUG_PRINT_LINE("httpmethod: %s", httpmethod); + DEBUG_PRINT_LINE("file path: %s", filepath); + DEBUG_PRINT_LINE("http ver : %s", http_ver); + break; } - // When conected - while(tcpcon.is_connected()) { - printf("(HTTP_SERVER) connected\r\n"); - - char buffer[1024] = {0}; - char* httpmethod = NULL; - char* filepath = NULL; - char* http_ver = NULL; - char* header_field_name = NULL; - char* header_field_val = NULL; - - // - // Request Analysis - // - DEBUG_PRINT_LINE("DEBUG MODE"); - switch(tcpcon.receive(buffer, 1023)) { - case 0: - DEBUG_PRINT_LINE("recieved buffer is empty."); - msger.setStatusLine(400, "No Request"); - if(msger.setHeaderField("Connection", "Close"))DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - httpmethod = NULL; - filepath = NULL; - http_ver = NULL; - break; - case -1: - DEBUG_PRINT_LINE("failed to read data from client."); - msger.setStatusLine(500, "Internal Server Error"); - if(msger.setHeaderField("Connection", "Close"))DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - httpmethod = NULL; - filepath = NULL; - http_ver = NULL; - break; - default: - DEBUG_PRINT_LINE("Recieved Data: %d",strlen(buffer)); - DEBUG_PRINT_LINE("-->\r\n"); - DEBUG_PRINT_LINE("%.*s[End of Request]",strlen(buffer),buffer); - // get HTTP method, File path, HTTP version - httpmethod = strtok(buffer," "); - filepath = strtok(NULL, " "); - http_ver = strtok(NULL, "\r\n"); - DEBUG_PRINT_LINE("httpmethod: %s", httpmethod); - DEBUG_PRINT_LINE("file path: %s", filepath); - DEBUG_PRINT_LINE("http ver : %s", http_ver); - break; - } + + if (httpmethod[0] == '\0') { + buffer[MAX_BUFFER_SIZE - 1] = '\0'; + sprintf(buffer,"%s %d %s\r\nConnection: Close\r\n\r\n\0", http_ver, status_code, reason_phrase); + DEBUG_PRINT_LINE("echo back done."); + break; + } + + // Response + if (strcmp(httpmethod,"GET") == 0 ) //GET request - always index.html stoed in index_html + { + DEBUG_PRINT_LINE("GET request incomming."); + + buffer[MAX_BUFFER_SIZE-1] = '\0'; + status_code = 200; + sprintf(reason_phrase,"OK\0"); - // - // Response - // - if (strcmp(httpmethod,"GET") == 0 ) { - DEBUG_PRINT_LINE("GET request incomming."); + sprintf(buffer,"%s %d %s\r\nConnection: Close\r\nContent-Type: text/html\r\nKeep-Alive: timeout=15\r\n\r\n\0", http_ver, status_code, reason_phrase); + tcpcon.send_all(buffer,strlen(buffer)); + tcpcon.send_all((char*)index_html,index_html_len); + + break; + } + if (strcmp(httpmethod,"POST") == 0 ) //POST request - javascript request + { + DEBUG_PRINT_LINE("POST request incomming."); + status_code = 200; + sprintf(reason_phrase,"OK\0"); + + sprintf(buffer,"%s %d %s\r\nConnection: Close\r\n\r\n\0", http_ver, status_code, reason_phrase); - // file calibration - DEBUG_PRINT_LINE("file opening"); - fhandl.open(filepath,"rb"); - if(fhandl.arrival()) { - msger.setStatusLine(200, "OK"); - if(msger.setHeaderField("Content-Length", fhandl.getFileSize())) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - if(msger.setHeaderField("Connection", "keep-alive")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - } else { - if(msger.setStatusLine(404, "NOT FOUND")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - if(msger.setHeaderField("Connection", "Close")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - DEBUG_PRINT_LINE("NOT FOUND"); - } - if( !strcmp(fhandl.getSuffix(), "htm" ) || - !strcmp(fhandl.getSuffix(), "HTM" ) || - !strcmp(fhandl.getSuffix(), "html") || - !strcmp(fhandl.getSuffix(), "HTML")){ - if(msger.setHeaderField("Content-Type", "text/html")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - } else if( !strcmp(fhandl.getSuffix(), "js" )){ - if(msger.setHeaderField("Content-Type", "text/javascript")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - } else if ( !strcmp(fhandl.getSuffix(), "ico" )){ - if(msger.setHeaderField("Content-Type", "image/png")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - } else if ( !strcmp(fhandl.getSuffix(), "png" ) || - !strcmp(fhandl.getSuffix(), "PNG" )){ - if(msger.setHeaderField("Content-Type", "image/png")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - } else if ( !strcmp(fhandl.getSuffix(), "jpg" ) || - !strcmp(fhandl.getSuffix(), "JPG" )){ - if(msger.setHeaderField("Content-Type", "image/jpg")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - } else { - msger.setStatusLine(406, "not acceptable"); - } + for(idx_buffer=0;idx_buffer<=7;idx_buffer++) + { + sprintf(tmp_buffer,"%4.2f %3.2f %d %3.2f %s %d %s %d %s %d %s %d \0",CH[idx_buffer].voltage,CH[idx_buffer].current,CH[idx_buffer].control,CH[idx_buffer].limit,\ + color[CH[idx_buffer].failure>0],CH[idx_buffer].failure,\ + color[CH[idx_buffer].overload>ERROR_REP],CH[idx_buffer].overload>ERROR_REP,\ + color[CH[idx_buffer].noload>ERROR_REP],CH[idx_buffer].noload>ERROR_REP,\ + color[CH[idx_buffer].enable==0],CH[idx_buffer].enable); + strcat(buffer,tmp_buffer); - // Connection timeout field - if(msger.setHeaderField("Keep-Alive", "timeouit=15")) DEBUG_PRINT_LINE("buffer over flow @ ResponseMessenger"); - - // send response - msger.sendHTTPResponse(tcpcon, fhandl); + } + tcpcon.send_all(buffer,strlen(buffer)); + break; + - //file close - if( fhandl.close()== 0) - DEBUG_PRINT_LINE("file has closed"); - else if(EOF) - DEBUG_PRINT_LINE("failed to close the file"); - - msger.resetHeader(); - DEBUG_PRINT_LINE("echo back done."); - } - if (httpmethod == NULL) { - msger.sendHTTPResponse(tcpcon); - msger.resetHeader(); - DEBUG_PRINT_LINE("echo back done."); - } - printf("(HTTP_SERVER) Response to Request has done\r\n"); - // - // - // - } - printf("(HTTP_SERVER) close connection.\r\ntcp server is listening...\r\n"); - tcpcon.close(); - led2 = false; + } } - tcpsvr.close(); - listening_flag = false; - led1 = false; + tcpcon.close(); //always close the connection return 0; } \ No newline at end of file
diff -r b6dd6ed0060b -r f21da0acc9f6 HTTP_SERVER.h --- a/HTTP_SERVER.h Fri Mar 16 21:55:50 2018 +0000 +++ b/HTTP_SERVER.h Thu May 10 20:24:03 2018 +0000 @@ -1,12 +1,13 @@ //HTTP_SERVER.h #ifndef HTTP_SERVER_H #define HTTP_SERVER_H -#include "mbed.h" + #include "EthernetInterface.h" -#include "ResponseMessenger.h" -#include "FileHandler.h" +#include "definitions.h" #include "string.h" -#include <stdlib.h> + +#define MAX_BUFFER_SIZE 1024 + using namespace std; enum PortNum { @@ -35,19 +36,11 @@ * @retval TRUE at error end. * @retval FALSE at normal end. */ - bool run(); + bool run(channel *CH); -private: // Handlers - EthernetInterface eth; // Eternet TCPSocketServer tcpsvr; // TCP server TCPSocketConnection tcpcon; // TCP server connection clerk - ResponseMessenger msger; // Messenger for a client - FileHandler fhandl; // - // Param - bool keep_alive; - bool listening_flag; - char req_buf[1024]; }; #endif \ No newline at end of file
diff -r b6dd6ed0060b -r f21da0acc9f6 handlers/FileHandler.h --- a/handlers/FileHandler.h Fri Mar 16 21:55:50 2018 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,32 +0,0 @@ -/*FileHandler.h*/ -#ifndef FILE_HANDLER_H -#define FILE_HANDLER_H -#include "mbed.h" -#include "string.h" -#include <stdlib.h> - -using namespace std; -class FileHandler -{ -public: - FileHandler(); - ~FileHandler(); - FILE* open(const char*, const char*); - int close(); - virtual int getc(); - bool arrival(); - bool atEOF(); - bool hasError(); - char *getFullpath(); - char *getFilename(); - char *getSuffix(); - int getFileSize(); -private: - FILE *fp; - char *fullpath; - char *filename; - char *suffix; - char content_buffer[1024]; - int file_size; -}; -#endif \ No newline at end of file
diff -r b6dd6ed0060b -r f21da0acc9f6 handlers/Filehandler.cpp --- a/handlers/Filehandler.cpp Fri Mar 16 21:55:50 2018 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,137 +0,0 @@ -#include "FileHandler.h" -#ifndef DEBUG -//#define DEBUG -#endif -LocalFileSystem local("local"); - -FileHandler::FileHandler() -{ - fullpath = NULL; - filename = NULL; - suffix = NULL; - fp = NULL; - file_size = 0; -} -FileHandler::~FileHandler() -{ - if (fullpath != NULL) free(fullpath); - if (fp != NULL) fclose(fp); -} - -FILE* FileHandler::open -( const char* arg_filepath, - const char* arg_mode -) -{ - FILE *tmp; - - //////printf("\r\n" - // "fp: %d@FileHandler::open\r\n", fp); - if (fullpath != NULL) free(fullpath); - fullpath = (char*)malloc(sizeof(char) * (strlen("/local/") + strlen(arg_filepath) + strlen("index.htm") + 1)); - //////printf("fp: %d@FileHandler::open\r\n", fp); - - // Path formatting - if (arg_filepath[0] == '/') { - sprintf(fullpath, "/local/%s", arg_filepath + 1); - } else { - sprintf(fullpath, "/local/%s", arg_filepath); - } - // if the argument has no file name but directory, defalt settiing. - if (fullpath[strlen(fullpath) - 1] == '/') - strcat(fullpath, "index.htm"); - // store the file name part to a pointer - filename = strrchr(fullpath, '/'); - if(filename != NULL) filename++; // remove '/' and just get only the file name. - // store the suffix part to a pointer - suffix = strchr(filename, '.'); - if(suffix != NULL) suffix++; // remove '.' and just get only the suffix. -#ifdef DEBUG - //////printf("full path: %s\r\nfilename: %s\r\nsuffix: %s\r\n", getFullpath(), getFilename(), getSuffix()); -#endif - fp = fopen(fullpath, arg_mode); -#ifdef DEBUG - //////////printf("file opened@FileHandler::open\r\n"); -#endif - // mesure file size - file_size = 0; - tmp = fp; - if(tmp != NULL ) { - ////printf("\r\nfile content\r\n"); - int ctmp; - while(1) { - ctmp = fgetc(tmp); - if(ctmp != EOF) { - //////printf("%c", ctmp); - file_size++; - } else { - //////printf("[EOF]\r\n"); - break; - } - } - ////printf("file size: %d\r\n", file_size); - if(fseek(tmp, 0L, SEEK_SET) != 0) { - //////printf("fseek failed\r\n"); - } - } else { - file_size = 0; - } - - return fp; -} -int FileHandler::close() -{ - int tmp; - - if(fp != NULL) { - tmp = fclose(fp); - fp = NULL; - return tmp; - } else { - return 1; - } -} - -int FileHandler::getc() -{ - int tmp = fgetc(fp); -#ifdef DEBUG - if(0x20 < tmp && tmp < 0x7e) - printf("%c", tmp); - else if (tmp == '\r') - printf("\r"); - else if (tmp == '\n') - printf("\n"); - else - printf("@"); -#endif - return tmp; -} -bool FileHandler::arrival() -{ - return (bool)fp; -} -bool FileHandler::atEOF() -{ - return (bool)feof(fp); -} -bool FileHandler::hasError() -{ - return (bool)ferror(fp); -} -char *FileHandler::getFullpath() -{ - return fullpath; -} -char *FileHandler::getFilename() -{ - return filename; -} -char *FileHandler::getSuffix() -{ - return suffix; -} -int FileHandler::getFileSize() -{ - return file_size; -} \ No newline at end of file
diff -r b6dd6ed0060b -r f21da0acc9f6 handlers/ResponseMessenger.cpp --- a/handlers/ResponseMessenger.cpp Fri Mar 16 21:55:50 2018 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,204 +0,0 @@ -#include "ResponseMessenger.h" - -const char ResponseMessenger::http_ver[9] = "HTTP/1.1"; -ResponseMessenger::ResponseMessenger() -{ - // Status-Line - status_code = 0; - reason_phrase[0] = '\0'; - header_field_buffer[0]='\0'; - // Response Header -} -ResponseMessenger::~ResponseMessenger() -{ -} -int ResponseMessenger::resetHeader() -{ - // Status-Line - status_code = 0; - reason_phrase[0] = '\0'; - // Response Header - header_field_buffer[0]='\0'; - return 0; -} -int ResponseMessenger::setStatusLine( - int arg_status_code, - const char* arg_reason_phrase -) -{ - status_code = arg_status_code; - strcpy(reason_phrase, arg_reason_phrase); - - // To be safe on the sage side - reason_phrase[REASON_PHRASE_SIZE - 1] = '\0'; - // Send 0 if arg str size is too big, else -1. - if (strlen(arg_reason_phrase) < REASON_PHRASE_SIZE) - return 0; - else - return -1; -} - -int ResponseMessenger::setHeaderField( - const char* arg_field_name, const char* arg_field_val) -{ - const int nField = 7; - char registered_field_name[nField][32]= { - "Connection", - "Location", - "Keep-Alive", - "Content-Type", - "Upgrade", - "Sec-WebSocket-Accept", - "Access-Control-Allow-Origin" - }; - bool flag = false; - char header_field_line_buffer[128]; - int buffer_size = strlen(header_field_buffer); - - for (int i = 0; i < nField; i++) { - if(strcmp(arg_field_name, registered_field_name[i]) == 0) - flag = true; - } - if(flag) { - sprintf(header_field_line_buffer, "%s: %s\r\n", arg_field_name, arg_field_val); - strcat(header_field_buffer, header_field_line_buffer); - //printf("(RM) header field: \r\n%s\r\n", header_field_buffer); - } - // To be safe on the sage side - header_field_buffer[HEADER_FIELDS_SIZE - 1] = '\0'; - // Send 0 if arg str size is too big, else -1. - if (buffer_size + strlen(arg_field_name) + strlen(arg_field_val) < HEADER_FIELDS_SIZE + 1) - return 0; - else - return -1; -} - -int ResponseMessenger::setHeaderField( - const char* arg_field_name, int arg_field_val) -{ - const int nField = 1; - char registered_field_name[nField][32]= { - "Content-Length" - }; - bool flag = false; - char header_field_line_buffer[128]; - int buffer_size = strlen(header_field_buffer); - - for (int i = 0; i < nField; i++) { - if(strcmp(arg_field_name, registered_field_name[i]) == 0) - flag = true; - } - if(flag) { - sprintf(header_field_line_buffer, "%s: %d\r\n", arg_field_name, arg_field_val); - strcat(header_field_buffer, header_field_line_buffer); - //printf("(RM) header field: \r\n%s\r\n", header_field_buffer); - } - // To be safe on the sage side - header_field_buffer[HEADER_FIELDS_SIZE - 1] = '\0'; - // Send 0 if arg str size is too big, else -1. - if (buffer_size + strlen(arg_field_name) + 10 < HEADER_FIELDS_SIZE + 1) - return 0; - else - return -1; -} - -int ResponseMessenger::rmHeaderField( - const char* arg_field_name) -{ - char* removedLineHead; - char* removedLineEnd; - int buffer_size; - - // Look for the head of the line to want to remove - removedLineHead = strstr(header_field_buffer, arg_field_name); - if(removedLineHead == NULL) return -1; - // Look for the first "\r\n" which is the end of the line - removedLineEnd = strstr(removedLineHead, "\r\n"); - removedLineEnd += 3; //pointing next line head or '\0' if the line of the last one. - buffer_size = strlen(removedLineEnd); - - for(int i = 0; i < buffer_size + 1; i++) - removedLineHead[i] = removedLineEnd[i]; - - return 0; -} - -int ResponseMessenger::getStatusCode() -{ - return status_code; -} - -char ResponseMessenger::sendHTTPResponse( - TCPSocketConnection &arg_connection) -{ - int err_log = 0; - int err_code = 0; - enum { - MAX_BUFFER_SIZE = 1024 - }; - char buffer[MAX_BUFFER_SIZE] = "\0"; - - // - // Header - // - printf("(RM) [send]Header\r\n"); - // Status Line - sprintf(buffer, "%s %d %s\r\n", http_ver, status_code, reason_phrase); - buffer[MAX_BUFFER_SIZE - 1] = '\0'; - err_log = arg_connection.send_all(buffer, strlen(buffer)); - if(err_log < 0) err_code = ((err_code << 1) | 1); - // Response Header - err_log = arg_connection.send_all(header_field_buffer, strlen(header_field_buffer)); - if(err_log < 0) err_code = ((err_code << 1) | 1); - // Blank line - err_log = arg_connection.send_all("\r\n", strlen("\r\n")); - if(err_log < 0) err_code = ((err_code << 1) | 1); - printf("(RM) [Header has sent]\r\n"); - //return error code - return err_code << 2; - -} - -char ResponseMessenger::sendHTTPResponse( - TCPSocketConnection &arg_connection, - FileHandler &arg_file) -{ - int err_log = 0; - int err_code = 0; - enum { - MAX_BUFFER_SIZE = 1024 - }; - signed char buffer[MAX_BUFFER_SIZE]; - - // - // Header - // - err_code = sendHTTPResponse(arg_connection); - // - // Body - // - if (arg_file.arrival() && status_code == 200) { - printf("(RM) [send]Body\r\n"); - do { - int i = 0; - do { - buffer[i++] = arg_file.getc();//return a byte from file ponter, or -1 if EOF or ERROR - } while ((i < MAX_BUFFER_SIZE - 1) && (buffer[i - 1] != EOF)); - if(buffer[i - 1] == EOF)buffer[i - 1] = '\0'; - buffer[i] = '\0'; - if (!arg_file.hasError()) { - err_log = arg_connection.send_all((char*)buffer, i); - //printf("(RM) buffer log: %s", buffer); - } - if (arg_file.hasError()) printf("(RM)---[ERR]---\r\n"); - if (arg_file.atEOF()) printf("(RM)---[EOF]---\r\n"); - } while (!arg_file.atEOF() && !arg_file.hasError()); - printf("(RM) [Body has sent]\r\n"); - - if (err_log < 0) err_code = ((err_code) | 2); - if (!arg_file.hasError())err_code = ((err_code) | 1); - } else { - printf("(RM) [No Body]\r\n"); - } - return (char)err_code; -} \ No newline at end of file
diff -r b6dd6ed0060b -r f21da0acc9f6 handlers/ResponseMessenger.h --- a/handlers/ResponseMessenger.h Fri Mar 16 21:55:50 2018 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,51 +0,0 @@ -/* ResponseMessenger.h */ -#ifndef RESPONSE_MESSENGER_H -#define RESPONSE_MESSENGER_H -#include "mbed.h" -#include "string.h" -#include "EthernetInterface.h" -#include "FileHandler.h" -#include <stdlib.h> -using namespace std; - -class ResponseMessenger -{ - enum { - REASON_PHRASE_SIZE = 32, - HEADER_FIELDS_SIZE = 2048 - }; -public: - ResponseMessenger(); - ~ResponseMessenger(); - int resetHeader(); - int setStatusLine(int,const char*); - int setHeaderField(const char*, const char*); - int setHeaderField(const char*, int); - int rmHeaderField(const char*); - int getStatusCode(); - /** - * Function to send response messages. - * just header only - * @return char - * @retval error code - */ - char sendHTTPResponse(TCPSocketConnection&); - /** - * Function to send response messages. - * @return char - * @retval error code - */ - char sendHTTPResponse(TCPSocketConnection&, FileHandler&); -private: - // Status-Line - static const char http_ver[9]; - int status_code; - char reason_phrase[REASON_PHRASE_SIZE]; - // Header Field buffer - // - General Header - // - Response Header - // - Entity Header - char header_field_buffer[HEADER_FIELDS_SIZE]; -}; - -#endif \ No newline at end of file