this camera C328 http sdcard file server example is for academy

Dependencies:   CameraC328 SDFileSystem WIZnetInterface mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "EthernetInterface.h"
00003 #include "SDFileSystem.h"
00004 #include "CameraC328.h"
00005 
00006 #define EnDebugMSG  false //true-> print debug message to PC USB terminal, false->not print
00007 #include "filelib.h"
00008 
00009 /*
00010  * Set IP
00011  */
00012 #define IP      "192.168.240.100"
00013 #define MASK    "255.255.255.0"
00014 #define GATEWAY "192.168.240.1"
00015 #define PORT     80
00016 
00017 Serial pc (USBTX,USBRX);    // tx, rx
00018 SDFileSystem sd(PB_3, PB_2, PB_1, PB_0, "wfs"); // the pinout on the mbed
00019 CameraC328 camera(PA_13, PA_14, CameraC328::Baud115200); // camera pin set
00020 
00021 char sMethod[7];
00022 char sURL[250];
00023 char sProtocol[8];
00024 
00025 /* 
00026  * Camera C328 define
00027  */
00028 #define USE_JPEG_HIGH_RESOLUTION  1
00029 
00030 int take_picture = 0;
00031 
00032 /*
00033  * Camera C328 Variables.
00034  */
00035 static const int CAPTURE_FRAMES = 2;
00036 static FILE *fp_jpeg;
00037 
00038 /**
00039  * A callback function for jpeg images.
00040  * You can block this function until saving the image datas.
00041  *
00042  * @param buf A pointer to the image buffer.
00043  * @param siz A size of the image buffer.
00044  */
00045 void jpeg_callback(char *buf, size_t siz) {
00046     for (int i = 0; i < (int)siz; i++) {
00047         fprintf(fp_jpeg, "%c", buf[i]);
00048     }
00049 }
00050 
00051 /**
00052  * Camera C328 Synchronizing.
00053  */
00054 void sync(void) {
00055     CameraC328::ErrorNumber err = CameraC328::NoError;
00056 
00057     err = camera.sync();
00058     if (CameraC328::NoError == err) {
00059         printf("[Camera Initializing..]\r\n");
00060         printf("[ OK ] : CameraC328::sync\r\n");
00061     } else {
00062         printf("[Camera Initializing..]\r\n");
00063         printf("[FAIL] : CameraC328::sync (Error=%02X)\r\n", (int)err);
00064     }
00065 }
00066 
00067 /**
00068  * Camera C328 function for jpeg snapshot picture.
00069  */
00070 void test_jpeg_snapshot_picture(void) {
00071     CameraC328::ErrorNumber err = CameraC328::NoError;
00072 
00073 #if USE_JPEG_HIGH_RESOLUTION
00074     err = camera.init(CameraC328::Jpeg, CameraC328::RawResolution80x60, CameraC328::JpegResolution640x480);
00075 #else
00076     err = camera.init(CameraC328::Jpeg, CameraC328::RawResolution80x60, CameraC328::JpegResolution320x240);
00077 #endif
00078     if (CameraC328::NoError == err) {
00079         printf("[ OK ] : CameraC328::init\r\n");
00080         printf("\r\n[Start taking a picture]\r\n");
00081     } else {
00082         printf("[FAIL] : CameraC328::init (Error=%02X)\r\n", (int)err);
00083     }    
00084     for (int i = 0; i < CAPTURE_FRAMES; i++) {
00085         char fname[64];
00086         snprintf(fname, sizeof(fname), "/wfs/jpegSnapshot%02d.jpg",i);
00087         fp_jpeg = fopen(fname, "w");
00088 
00089         err = camera.getJpegSnapshotPicture(jpeg_callback);     // call the snapshot function
00090         
00091         if (CameraC328::NoError == err) {
00092             printf("[ OK ] : CameraC328::getJpegSnapshotPicture[%d]\r\n",i);
00093         } else {
00094             printf("[FAIL] : CameraC328::getJpegSnapshotPicture[%d] (Error=%02X)\r\n",i, (int)err);
00095         }       
00096         fclose(fp_jpeg);
00097     }
00098 }
00099 
00100 
00101 EthernetInterface eth;
00102 
00103 TCPSocketServer svr;
00104 bool serverIsListened = false;
00105 
00106 TCPSocketConnection client;
00107 bool clientIsConnected = false;
00108 
00109 char sentBuffer[1608] = {}; // 2*536=1072, 3*536=1608, 4*536=2144   !1500
00110 char line_response[256]= {0};
00111 char file_path[256] = {0};
00112 
00113 DigitalOut led1(LED1); //server listning status
00114 DigitalOut led2(LED2); //socket connecting status
00115 
00116 Ticker ledTick;
00117 
00118 void ledTickfunc()
00119 {
00120     if(serverIsListened)  {
00121         led1 = !led1;
00122     } else {
00123         led1 = false;
00124     }
00125 }
00126 
00127 void send_HTTP_header(char* protocol, int code, char* title, char* mime_type, long long lengthBody)
00128 {
00129     snprintf(line_response, sizeof(line_response),"%s %d %s\r\n", protocol, code, title );
00130     snprintf(sentBuffer, sizeof(sentBuffer),"%s",line_response);
00131 
00132     if ( mime_type != NULL ) {
00133         snprintf(line_response, sizeof(line_response), "Content-Type: %s\r\n", mime_type );
00134         snprintf(sentBuffer, sizeof(sentBuffer), "%s%s",sentBuffer,line_response);    //append to sentBuffer
00135     }
00136     if ( lengthBody >= 0 ) {
00137         snprintf(line_response, sizeof(line_response), "Content-Length: %lld\r\n", lengthBody );
00138         snprintf(sentBuffer, sizeof(sentBuffer), "%s%s",sentBuffer,line_response);    //append to sentBuffer
00139     }
00140     snprintf(line_response, sizeof(line_response), "Connection: close\r\n" );
00141     snprintf(sentBuffer, sizeof(sentBuffer),"%s%s\r\n",sentBuffer,line_response);    //append to sentBuffer
00142 
00143     if (EnDebugMSG)
00144         printf("\r\n-->sent Header--\r\n");
00145 
00146     client.send_all(sentBuffer,strlen(sentBuffer));
00147     if (EnDebugMSG) {
00148         printf(sentBuffer);
00149         printf("\r\n--end Header-- bytes:%d",strlen(sentBuffer));
00150     }
00151     wait(0.2);  //200ms important for browser!
00152 }
00153 
00154 void send_HTML_line(char* line, unsigned int length_line)
00155 {
00156     client.send_all(line,length_line);
00157     if (EnDebugMSG)
00158         printf("\r\n-->send HTML line:\r\n%s ...Ok!",line);
00159     wait(0.01);
00160 }
00161 
00162 void send_HTML_error( int status_code, char* title, char* body_text)
00163 {
00164     send_HTTP_header("HTTP/1.1", status_code, title, "text/html", -1);
00165     if (EnDebugMSG)
00166         printf("\r\n-->send_error...\r\n");
00167     sentBuffer[0]=NULL; //clear buffer
00168     sprintf(line_response, "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n<title>%d %s</title>\r\n</head>\r\n", status_code, title);
00169     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00170     sprintf(line_response, "<body><center><h2><center>%d %s</center></h2>\r\n",status_code, title );
00171     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00172     sprintf(line_response, "%s\r\n", body_text );
00173     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00174     sprintf(line_response, "<p>mbed HTTP File Server</p>\r\n</center></body></html>\r\n");
00175     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00176     send_HTML_line(sentBuffer, strlen(sentBuffer));
00177 }
00178 
00179 int send_file(char *path_file)
00180 {
00181     char *mime_type = {0};
00182     unsigned int bytes_for_send=0;
00183     long long filesize, all_send_bytes = 0;
00184 
00185     mime_type =  get_mime_type( path_file );
00186     snprintf(file_path, sizeof(file_path),"/wfs/%s",path_file);
00187     
00188     if (strcmp(file_path,"/wfs//take_a_picture.jpg") == 0){
00189         take_picture = 1;
00190     }
00191     else take_picture = 0;
00192     
00193     if (EnDebugMSG) {
00194         printf("\r\n-->from send_file:%s",file_path);
00195         printf("\r\n-->from send_file mime type:%s",mime_type);
00196     }
00197 
00198     if (Mystat(path_file, &myStatBuf)) { //fault with file
00199         send_HTML_error( 403, "Forbidden", "403 - File access forbidden.");
00200         return 403;
00201     }
00202     FILE* fp = NULL;
00203     fp = fopen(file_path,"r");
00204     if (fp==NULL ) {
00205         send_HTML_error( 403, "Forbidden", "403 - File access forbidden.");
00206         return 403;
00207     }
00208 
00209     filesize = myStatBuf.st_size;
00210     send_HTTP_header("HTTP/1.1", 200, "Ok", mime_type, myStatBuf.st_size);
00211     //binary send
00212     all_send_bytes=0;
00213     while(filesize)  {  //check for EOF !feof(fp)
00214         bytes_for_send = filesize;
00215         if (bytes_for_send > sizeof(sentBuffer)) {
00216             bytes_for_send = sizeof(sentBuffer);
00217         }
00218         fread (sentBuffer,1,bytes_for_send,fp);
00219         filesize -= bytes_for_send;
00220         if (EnDebugMSG)
00221             printf("\r\n---bytes_for_send...%d",bytes_for_send);
00222         client.send_all(sentBuffer,bytes_for_send);
00223         //Thread::wait(10);
00224         all_send_bytes += bytes_for_send;
00225     }
00226     if (EnDebugMSG)
00227         printf("\r\n---buffer fill end - all ...%lld", all_send_bytes);
00228     //binary send
00229 
00230     sprintf(line_response, "\r\n");
00231     client.send_all(line_response,strlen(line_response));
00232     if ( fp != NULL )
00233         fclose(fp);
00234     //Thread::wait(10);
00235     return 0;
00236 }
00237 
00238 int send_directory(char *path)
00239 {
00240     char process_name[64]= {0};
00241 
00242     char posOfLastSlash;
00243     char *pLS;
00244 
00245     struct dirent *p;
00246     struct sMystat sb;
00247     struct tm *timeinfo;
00248     char timeBuf[40];
00249 
00250     if (EnDebugMSG)
00251         printf("\r\n-->from send_directory:%s",path);
00252     snprintf(file_path,sizeof(file_path),"/wfs%s",path);
00253     DIR *d = opendir(file_path);
00254     if (EnDebugMSG && d!=NULL)
00255         printf("\r\n-->from send_directory:%s ...open OK",file_path);
00256     if (d==NULL) {   //error open dir
00257         send_HTML_error( 403, "Forbidden", "403 - Directory access forbidden.");
00258         return -1;
00259     }
00260     send_HTTP_header("HTTP/1.1", 200, "Ok",NULL, -1);
00261     sentBuffer[0]=NULL;
00262     sprintf(line_response,"<!DOCTYPE html>\r\n<html>\n<head><title>Index of %s</title>\n",path);
00263     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00264     
00265     sprintf(line_response,"<meta content=\"text/html; charset=iso-8859-1\" http-equiv=\"Content-Type\"></head>\n");
00266     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00267     
00268     
00269     sprintf(line_response,"<body><center>\n<h3>Index of %s</h3>\n", path);
00270     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00271     send_HTML_line(sentBuffer, strlen(sentBuffer));
00272 //begin table
00273     sentBuffer[0]=NULL; //clear buffer
00274     sprintf(line_response,"<table border=\"0\">\n");
00275     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00276     sprintf(line_response,"<tr><th align=\"left\" width=\"200\">Name</th><th align=\"right\" width=\"100\">Size(bytes)</th><th align=\"right\" width=\"200\">Date/Time</th></tr>\n");
00277     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00278 //begin table
00279 
00280     pLS=strrchr(path,'/');
00281     posOfLastSlash=pLS-path+1;
00282     if (EnDebugMSG)
00283         printf("\r\n>>posOfLastSlash=%d",posOfLastSlash);
00284     snprintf(process_name,posOfLastSlash+1,"%s",path);
00285     if (EnDebugMSG)
00286         printf("\r\n>>process_name=%s",process_name);
00287     sprintf(line_response,"<tr><td align=\"left\"><a href=\"%s\">../reflash</a></td></tr>\n",process_name);
00288     snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00289     while((p = readdir(d)) != NULL) {
00290         if (EnDebugMSG)
00291             printf("\r\n   :%s",p->d_name);
00292         sprintf(file_path,"%s/%s",path,p->d_name);
00293         Mystat( file_path, &sb );
00294         if (get_dirInfo(file_path)==0 ) { //this is directory path
00295             if (EnDebugMSG)
00296                 printf("\r\nDIR");
00297             sprintf(line_response, "<tr><td align=\"left\"><a href=\"%s\">%s</a><br></td></tr>\n",file_path,p->d_name);
00298             if (strlen(line_response)>(sizeof(sentBuffer)-strlen(sentBuffer))) { //buffer must be sent
00299                 send_HTML_line(sentBuffer, strlen(sentBuffer));
00300                 sentBuffer[0]=NULL; //clear buffer
00301             }
00302             snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00303 
00304         } else {    //this is file
00305             if (EnDebugMSG)
00306                 printf("\r\nFILE");
00307             timeinfo = localtime (&sb.st_mtime);
00308             //strftime(timeBuf,40, "%I:%M:%S %p (%Y/%m/%d)\r\n", localtime(&sb.st_mtime));
00309             strftime(timeBuf, 40, "%c", timeinfo);
00310             sprintf(line_response, "<tr><td align=\"left\"><a href=\"%s\">%s</a></td><td align=\"right\">%lld</td><td align=\"right\">%s</td></tr>\n", file_path, p->d_name,(long long) sb.st_size,timeBuf);    // asctime(timeinfo) );
00311 
00312             if (strlen(line_response)>(sizeof(sentBuffer)-strlen(sentBuffer))) { //buffer must be sent
00313                 send_HTML_line(sentBuffer, strlen(sentBuffer));
00314                 sentBuffer[0]=NULL; //clear buffer
00315             }
00316             snprintf(&(sentBuffer[strlen(sentBuffer)]),sizeof(sentBuffer),"%s",line_response); //append to buffer
00317         }
00318     }
00319     send_HTML_line(sentBuffer, strlen(sentBuffer));
00320     closedir(d);
00321 
00322     sprintf(line_response, "</table>\n<br><h4>mbed HTTP File Server</h4>\n</center></body></html>\n");
00323     send_HTML_line(line_response, strlen(line_response));
00324 
00325     return 0;
00326 }
00327 
00328 void parseHTTPRequest(char* buffer)
00329 {
00330     char spacePos;
00331     char *tmpBuffer;
00332     spacePos = strcspn(buffer, " ") + 1;   //position of first space character
00333     snprintf(sMethod, spacePos,"%s", buffer);
00334 
00335     //get Protocol
00336     tmpBuffer=&(buffer[spacePos]);   //move pointer to buffer (delete Method)
00337     spacePos = strcspn(tmpBuffer, "\r\n") + 1;
00338     tmpBuffer[spacePos]='\0';    //set end of string ...cut
00339     sprintf(sProtocol, "%s", strrchr(tmpBuffer,' '));  //get string after last (space )
00340     printf("\r\nsProtocol:%s", tmpBuffer);
00341     buffer = &(sProtocol[1]);  //cut first character (space)
00342     sprintf(sProtocol, "%s", buffer);
00343 
00344     //get URL
00345     snprintf(sURL,strlen(tmpBuffer)-strlen(sProtocol),"%s\r\n", tmpBuffer);   //URL is between Method and Protocol
00346 
00347     printf("\r\nParse Method:%s",sMethod);
00348     printf("\r\nParse URL:%s",sURL);
00349     printf("\r\nParse PROTOCOL:%s",sProtocol);
00350     printf("\n\r\n");
00351 }
00352 
00353 int processHTTP(char* sMethod, char* sURL, char* sProtocol)
00354 {
00355     int gdi, gfi;   //status of get_dir_info(xxx), and get_file_info(xxx)
00356 
00357     if (strcmp(sMethod,"GET")!=0) {
00358         send_HTML_error( 501, "501 Not Implemented", "501 - The server either does not recognize the request method");
00359         return 501;
00360     }
00361     if (sURL[0]!= '/') {
00362         send_HTML_error( 400, "Bad Request", "400 - The request cannot be fulfilled due to bad syntax.");
00363         return 400;
00364     }
00365     if (sURL[strlen(sURL)-1]=='/') {
00366         sURL[strlen(sURL)-1]=sURL[strlen(sURL)];  //delete last symbol
00367         if (EnDebugMSG)
00368             printf("\r\n delete last:%s",sURL);
00369     }
00370     gdi= get_dirInfo(sURL);
00371     gfi= get_fileInfo(sURL);
00372     if (gfi!=0) {   //!=0 file not found
00373         if (gdi==0) { //0-ok this is directory
00374             return send_directory(sURL);
00375         }
00376         if (EnDebugMSG)
00377             printf("\r\n404-br File not found or...(Fresult is:%d)",gfi);
00378         send_HTML_error( 404, "Not Found","404 - The requested resource could not be found.");
00379         return 404;
00380     } else {    //==0  found
00381         if (gdi==0)  //0-ok this is directory
00382             return send_directory(sURL);
00383         else
00384             return send_file(sURL);
00385     }
00386 }
00387 
00388 int main()
00389 {   
00390     *(volatile uint32_t *)(0x41001014) = 0x0060100; //clock setting 48MHz
00391     uint8_t MAC_Addr[6] = {0x00, 0x08, 0xDC, 0x00, 0x01, 0x02}; 
00392     ledTick.attach(&ledTickfunc,0.5);
00393     //ledTick.detach();
00394     //setup ethernet interface
00395     //eth.init(); //Use DHCP
00396     eth.init(MAC_Addr,IP,MASK,GATEWAY);  //MAC,IP,mask,Gateway
00397     eth.connect();
00398     printf("IP Address is %s\n\r", eth.getIPAddress());
00399 
00400     //setup tcp socket
00401     if(svr.bind(PORT)< 0) {
00402         printf("tcp server bind failed.\n\r");
00403         return -1;
00404     } else {
00405         printf("tcp server bind successed.\n\r");
00406         serverIsListened = true;
00407     }
00408 
00409     if(svr.listen(1) < 0) {
00410         printf("tcp server listen failed.\n\r");
00411         return -1;
00412     } else {
00413         printf("tcp server is listening...\n\r");
00414     }
00415 
00416     //listening for http GET request
00417     while (serverIsListened) {
00418         //blocking mode(never timeout)
00419         if(svr.accept(client)<0) {
00420             printf("failed to accept connection.\n\r");
00421         }
00422         else {
00423             //client.set_blocking(false,5000);    //5000=5sec
00424             printf("connection success!\n\rIP: %s\n\r",client.get_address());
00425             clientIsConnected = true;
00426             led2 = true;
00427             while(clientIsConnected) {
00428                 char buffer[1024] = {};
00429                 switch(client.receive(buffer, 1023)) {
00430                     case 0:
00431                         printf("recieved buffer is empty.\n\r");
00432                         clientIsConnected = false;
00433                         break;
00434                     case -1:
00435                         printf("failed to read data from client.\n\r");
00436                         clientIsConnected = false;
00437                         break;
00438                     default:
00439                         printf("Recieved Data: %d\n\r\n\r%.*s\n\r",strlen(buffer),strlen(buffer),buffer);
00440                         parseHTTPRequest(buffer);
00441                         //if(buffer[0] == 'G' && buffer[1] == 'E' && buffer[2] == 'T' ) {
00442                         if (strcmp(sMethod, "GET" ) == 0 ) {
00443                             printf("GET request incomming.\n\r");
00444                             processHTTP(sMethod, sURL, sProtocol);
00445                             clientIsConnected = false;
00446                         }//if get
00447                         break;
00448                 }   //switch
00449                 //ledTick.attach(&ledTickfunc,0.5);
00450             }//while
00451             printf("close connection.\n\rHTTP server is listening...\n\r\n");
00452             client.close();
00453             wait(0.05); 
00454             
00455             // take a picture function
00456             if (take_picture) {
00457             
00458                 sync();
00459                 test_jpeg_snapshot_picture();   
00460                     
00461                 take_picture = 0;
00462             }
00463             led2 = false;
00464         }
00465     }
00466 
00467 }
00468