Measure system

Dependencies:   EthernetNetIf mbed RF12B

Revision:
1:b26ab2467b1a
Parent:
0:8d62137f7ff4
Child:
2:afe5826411e3
--- a/MeasureSystem.cpp	Thu Mar 03 08:45:49 2011 +0000
+++ b/MeasureSystem.cpp	Thu Mar 10 19:56:45 2011 +0000
@@ -1,6 +1,10 @@
 #define MEASURE_C
 
 
+#define WRITEFILE       1
+#define APPENDFILE      2
+#define READFILE        0
+
 #include "EthernetNetIf.h"
 #include "HTTPServer.h"
 #include "SDFileSystem.h"
@@ -10,6 +14,7 @@
 #include "NTPClient.h"
 #include "WatchDog.h"
 #include "HTTPClient.h"
+#include "AvailableMemory.h"
 
 //--------------Objects and vars------------------
 EthernetNetIf *eth;
@@ -28,7 +33,9 @@
 watchdog wdog(15);              // WDT 15 seconds
 
 const int MAX_PROBES = 2;
-#define        LOGGER_FILE        "/sd/syslog/log.txt"
+#define        LOGS_FOLDER        "/sd/log"
+#define        DATA_FOLDER        "/sd/data"
+#define        LOGGER_FILE        "/sd/data/log.txt"
 #define        STATUS_FILE        "/local/status.dat"
 #define        CONFIG_FILE        "/local/config.txt"
 #define        SOURCE_FILE        "/sd/index.htm"
@@ -38,18 +45,23 @@
 
 //------status flags-----------------
 int devices_found=0;
-static string wanIP;
-static string localIP;
-int logging;
-int fileindex;
+static char wanIP[18];
+static char localIP[18];
+int fileindex =0;
+char logfile[50] ;
 bool getIPfromDHCP;
 int interval;
+Timer timerMeasure;
 int ipConfig[4];
 int maskConfig[4];
 int gatewayConfig[4];
 int dnsConfig[4];
+int handlerCounter =0;
 //---------------------MAIN-----------------------
 int main() {
+    measureCommand = 0;
+    char buf[40];
+    string tempstring = ("");
     pc.baud(921600);
     HandlerActive = false;
     //-----------------LCD test-------------------
@@ -62,20 +74,20 @@
     //----------------SD.card test----------------
     printf("<SD card init>\r\n");
     lcd.printf("SDcard Init....");
-    mkdir("/sd/syslog", 0777);
+    mkdir(LOGS_FOLDER, 0777);
+    mkdir(DATA_FOLDER, 0777);
     FILE *fp = fopen(LOGGER_FILE, "a+");
     if (fp == NULL) {
         error("Could not open file for write\r\n");
-    }
-    else
-    {
-    fprintf(fp, "<-------------------->\r\n");
-    fclose(fp);
-    tempstring ="SYSTEM STARTUP";LogWrite(tempstring);
+    } else {
+        fprintf(fp, "<-------------------->\r\n");
+        fclose(fp);
+        tempstring ="SYSTEM STARTUP";
+        LogWrite(tempstring);
     }
     lcd.printf("Done\n");
-    
-    
+
+
     wdog.feed();
     //----------------DS1820 init-----------------
     printf("<DS1820 init>\r\n");
@@ -115,8 +127,7 @@
 
     sprintf(buf,"%d.%d.%d.%d",
             eth->getIp()[0], eth->getIp()[1], eth->getIp()[2], eth->getIp()[3]);
-    localIP = string(buf);
-
+    sprintf(localIP,"%s",buf);
     printf("Setup OK\r\n");
     lcd.printf("Done\n");
     wdog.feed();
@@ -130,7 +141,7 @@
     GetMyIP();
     if (wanIP!="none") {
         lcd.printf("Done\n");
-        printf("OK: %s\r\n",wanIP.c_str());
+        printf("OK: %s\r\n",wanIP);
 
     } else {
         lcd.printf("Fail\n");
@@ -158,13 +169,17 @@
     lcd.printf("Loading config.");
     LoadStatus();
     IndexInit();
+    if (logging == 1)
+    {
+    timerMeasure.start();
+    }
     lcd.printf("Done\n");
     wdog.feed();
     //-----------------Welcome message------------------
     wait(2);
     lcd.cls();
     lcd.printf("Welcome to mbed. \nMeasure system.\n");
-    lcd.printf("IP: %s\n",localIP.c_str());
+    lcd.printf("IP: %s\n",localIP);
     //--------------HTTP SERVER-------------------------
 
     FSHandler::mount("/local", "/"); //Mount /wwww path on web root path
@@ -175,12 +190,14 @@
     svr.bind(80);
 
     printf("<INIT DONE... Server running>\r\n");
-            ctTime = time(NULL);
-        ctTime += (clockoffset*3600);
-strftime(buf,sizeof(buf), "%Y/%m/%d %H:%M:%S", localtime(&ctTime));
+    ctTime = time(NULL);
+    ctTime += (clockoffset*3600);
+    strftime(buf,sizeof(buf), "%Y/%m/%d %H:%M:%S", localtime(&ctTime));
     tempstring ="";
-    tempstring += buf;LogWrite(tempstring);
-    tempstring ="SYSTEM READY";LogWrite(tempstring);
+    tempstring += buf;
+    LogWrite(tempstring);
+    tempstring ="SYSTEM READY";
+    LogWrite(tempstring);
     Timer tm;
     tm.start();
     //Listen indefinitely
@@ -194,14 +211,11 @@
             counter = (counter++)%3600;  //Timer counter loop
 
             led1=!led1; //Show that we are alive 1 sec timed
-            if (logging==1)
-           { 
-             led4 =!led1;
-             }
-             else
-             {
-             led4 = 0;
-             }
+            if (logging==1) {
+                led4 =!led1;
+            } else {
+                led4 = 0;
+            }
             UpdateLCD(counter);  //Refress LCD
 
             if (wanIP=="none" & (counter%30)==0) {      //If no network detected aat startup then try to connect every 30 sec
@@ -212,8 +226,26 @@
                 }
             }
 
+            //DEADLOCK PREVENTER
+            if (HandlerActive) {
+                handlerCounter++;
+            } else {
+                handlerCounter = 0;
+            }
+            if (handlerCounter>60) {
+                handlerCounter = 0;
+                HandlerActive = false;
+            }
+
+            if (logging == 1 & !HandlerActive) {
+                MeasureLogger();
+            }
+
+
             wdog.feed();
             tm.start();
+            
+            printf("Available memory (exact bytes) : %d\r\n", AvailableMemory(1));
         }
 
     }
@@ -259,9 +291,9 @@
     HTTPText txt;
     HTTPResult r = http.get("http://www.whatismyip.com/automation/n09230945NL.asp", &txt);
     if (r==HTTP_OK) {
-        wanIP =  txt.gets();
+        sprintf(wanIP,"%s", txt.gets());
     } else {
-        wanIP="none";
+        sprintf(wanIP,"none");
     }
 }
 
@@ -313,13 +345,7 @@
         }
 
         if (j==12) { //Change to find string element search by char.
-            if (wanIP!="none") {
-
-                temp = wanIP;
-            } else {
-                temp =localIP;
-            }
-            fprintf(fs_tgt,"      <param name=\"ServerAddress\" value=\"%s\">",temp.c_str());
+            fprintf(fs_tgt,"      <param name=\"ServerAddress\" value=\"%s\">",myUrl.c_str());
         } else {
             fprintf(fs_tgt,"%s",temp.c_str());
         }
@@ -336,14 +362,24 @@
 //------------Update lcd------------------------------
 bool IPshowflag = false;
 void UpdateLCD(int counter) {
+    char buf[40];
+
+    if (counter%1==0) { //Every sec
+        lcd.locate(0,1);
+        if (logging) {
+            lcd.printf("Logging with: %d ",interval);
+        } else {
+            lcd.printf("Not logging...      ");
+        }
+    }
+
     if (counter%4==0) {
         lcd.locate(0,2);
-        lcd.locate(0,2);
         if (wanIP!="none") {
             if (IPshowflag) {
-                lcd.printf("IP: %s        ", localIP.c_str());
+                lcd.printf("IP: %s        ", localIP);
             } else {
-                lcd.printf("IP: %s        ", wanIP.c_str());
+                lcd.printf("IP: %s        ", wanIP);
             }
             IPshowflag = !IPshowflag;
         } else {
@@ -372,6 +408,25 @@
     ctTime += (clockoffset*3600); //set jst time
 }
 
+//-------------Get Date short---------------------
+void GetFile(int index, char *st) {
+    string stringt = ("");
+    char buff[50];
+    ctTime = time(NULL);
+    ctTime += (clockoffset*3600);
+    strftime(buff,sizeof(buff), "%Y/%m/%d %H:%M:%S", localtime(&ctTime));
+    stringt += buff[2];
+    stringt += buff[3];
+    stringt += buff[5];
+    stringt += buff[6];
+    stringt += buff[8];
+    stringt += buff[9];
+    sprintf(buff,"%02d",index);
+    stringt += buff;
+    stringt += ".txt";
+    strcpy(st, stringt.c_str());
+}
+
 //---------------Load config----------------------
 void LoadConfig() {
     FILE    *fs_src;
@@ -404,6 +459,9 @@
             case 15:
                 sscanf(buffer,"%d",&clockoffset);
                 break;
+            case 18:
+                myUrl = buffer;
+                break;
         }
 
     }
@@ -412,8 +470,7 @@
 }
 
 //---------------Load status--------------------------
-void LoadStatus()
-{
+void LoadStatus() {
     FILE    *fs_src;
     char    buffer[ 100 ];
     int linecounter = 0;
@@ -426,23 +483,156 @@
                 sscanf(buffer,"%d",&logging);
                 break;
             case 2:
-                sscanf(buffer,"%d",&fileindex);
+                sscanf(buffer,"%s",logfile);
                 break;
         }
 
     }
 
     fclose( fs_src );
-
 }
 
-    //---------------Log writer-----------------------------
-void LogWrite(string stringin)
-{
+//-----------------Save status-------------------------
+void SaveStatus() {
+    printf("Saving status\r\n");
+    FILE    *fs_dest;
+    fs_dest    = fopen( STATUS_FILE, "w" );
+    fprintf(fs_dest,"%d\r\n%s\r\n",logging,logfile);
+    fclose( fs_dest );
+    printf("Status saved\r\n");
+}
+
+//---------------Log writer-----------------------------
+void LogWrite(string stringin) {
     FILE *fp = fopen(LOGGER_FILE, "a");
     if (fp == NULL) {
         error("Could not open file for write\r\n");
     }
-     fprintf(fp,"%s\r\n",stringin.c_str());
+    fprintf(fp,"%s\r\n",stringin.c_str());
     fclose(fp);
 }
+
+//---------------Measurement start/ stop --------------
+
+void MeasureStart() {
+    
+    char file[20];
+    char *st;
+    st = new char[50];
+    
+    if (logging ==0) {
+
+
+        logging = 1;
+        timerMeasure.start();
+        do {
+            GetFile(fileindex++,st);
+            strcpy(file,st);
+
+            sprintf(logfile,"%s%s%s",DATA_FOLDER,"/",file);
+            printf("Available memory (exact bytes) : %d\r\n", AvailableMemory(1));
+        } while  (exists(DATA_FOLDER,file));  // while  (sdcardIsFileExist (filepath.c_str())=='t');
+        
+        printf ("Saving log file name : %s\r\n",logfile);
+
+
+        SaveStatus();
+
+        printf ("Printing header into log file: %s\r\n",logfile);
+        
+        sdcardWriteFile (logfile,WRITEFILE,"Measure Start\r\n");
+    }
+}
+
+void MeasureStop() {
+    if (logging == 1) {
+        printf ("Stopping measure.");
+        logging = 0;
+        SaveStatus();
+        timerMeasure.stop();
+        printf ("Measure stopped.");
+    }
+
+}
+
+/** ----------------------------------------------------------------------
+*    sdcardWriteFile
+*    Ecrit une trame dans le fichier specifie
+*    In     : nom du fichier, mode d'ecriture, donnees a ecrire
+*    Out    : true/false
+* ---------------------------------------------------------------------*/
+char sdcardWriteFile(const char *fileName, char mode, char *data) {
+
+    FILE *fp2;
+    switch (mode) {
+        case WRITEFILE :
+            fp2 = fopen(fileName, "w+");
+            break;
+        case APPENDFILE :
+            fp2 = fopen(fileName, "a+");
+            break;
+        default:
+            fp2 = fopen(fileName, "r");
+    }
+
+    if (!fp2) {
+        return (false);
+    } else {
+        fprintf(fp2,data);
+        fclose(fp2);
+    }
+
+    return (true);
+}
+
+
+//---------- Logger method------------------------------------------------
+
+void MeasureLogger() {
+
+    if (timerMeasure.read() > interval) {
+    led2 = 1;
+        char buf[50];
+        ctTime = time(NULL);
+        ctTime += (clockoffset*3600);
+        strftime(buf,sizeof(buf), "%Y.%m.%d / %H:%M:%S", localtime(&ctTime));
+
+        char resp[100] = "";
+        strcat(resp,buf);
+        char temp[32] ;
+        probe[0]->convert_temperature(DS1820::all_devices);
+        for (int i=0; i<devices_found; i++) {
+            sprintf(temp," / %3.1f",(probe[i]->temperature('c')));
+            strcat(resp,temp);
+        }
+        sprintf( temp , "\r\n");
+        strcat(resp,temp);
+        sdcardWriteFile (logfile,APPENDFILE,resp);
+
+led2 = 0;
+        timerMeasure.reset();
+
+    }
+
+}
+
+bool exists(char * root, char *filename) {
+    DIR *d = opendir(root);
+    struct dirent *p;
+    //printf("\nList of files in the directory %s:\r\n", root);
+    bool found = false;
+    if ( d != NULL ) {
+        while ( !found && (p = readdir(d)) != NULL ) {
+            //printf(" - %s\r\n", p->d_name);
+            if ( strcmp(p->d_name, filename) == 0 ) {
+                found = true;
+                printf("File exist\r\n");
+            }
+        }
+    }
+    if (!found) {
+        printf("File not found\r\n");
+    }
+    closedir(d);
+    return found;
+}
\ No newline at end of file