![](/media/cache/profiles/100d5d9191f185eeb98d6e291756954a.50x50_q85.png)
Measure system
Dependencies: EthernetNetIf mbed RF12B
MeasureSystem.cpp
- Committer:
- benecsj
- Date:
- 2011-03-10
- Revision:
- 1:b26ab2467b1a
- Parent:
- 0:8d62137f7ff4
- Child:
- 2:afe5826411e3
File content as of revision 1:b26ab2467b1a:
#define MEASURE_C #define WRITEFILE 1 #define APPENDFILE 2 #define READFILE 0 #include "EthernetNetIf.h" #include "HTTPServer.h" #include "SDFileSystem.h" #include "TextLCD.h" #include "DS1820.h" #include "MeasureSystem.h" #include "NTPClient.h" #include "WatchDog.h" #include "HTTPClient.h" #include "AvailableMemory.h" //--------------Objects and vars------------------ EthernetNetIf *eth; HTTPServer svr; NTPClient ntp; Serial pc(USBTX, USBRX); // Serial debug usb port DigitalIn dhcpOn(p30); DigitalOut led1(LED1, "led1"); DigitalOut led2(LED2, "led2"); DigitalOut led3(LED3, "led3"); DigitalOut led4(LED4, "led4"); LocalFileSystem local("local"); //Internal flash SDFileSystem sd(p5, p6, p7, p8, "sd"); // the pinout on the mbed Cool Components workshop board TextLCD lcd(p21, p23, p24, p25, p26, p27, TextLCD::LCD20x4 ); //Char lcd watchdog wdog(15); // WDT 15 seconds const int MAX_PROBES = 2; #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" #define TARGET_FILE "/local/index.htm" #define COPY_BLOCK_SIZE 2048 DS1820* probe[MAX_PROBES]; //Temp sensors //------status flags----------------- int devices_found=0; 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------------------- printf("\r\n\r\n<----------------------------------------------->"); printf("\r\n<System Startup>\r\n"); lcd.cls(); lcd.printf("LCD Init.......Done\n"); wait(0.2); //----------------SD.card test---------------- printf("<SD card init>\r\n"); lcd.printf("SDcard Init...."); 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); } lcd.printf("Done\n"); wdog.feed(); //----------------DS1820 init----------------- printf("<DS1820 init>\r\n"); lcd.printf("Init sensors."); InitDS1820(); lcd.printf(".Done\n"); wdog.feed(); //--------------Read config.txt--------------- LoadConfig(); //---------------Network init----------------- lcd.printf("Network Init..."); printf("<Network Init>\r\n"); /* char mac[6]; mbed_mac_address(mac); for (int i=0; i<6;i++) { printf("%02X ", mac[i]); } printf("\n"); */ if (getIPfromDHCP) { eth = new EthernetNetIf(); } else { eth = new EthernetNetIf( IpAddr(ipConfig[0],ipConfig[1],ipConfig[2],ipConfig[3]), //IP Address IpAddr(maskConfig[0],maskConfig[1],maskConfig[2],maskConfig[3]), //Network Mask IpAddr(gatewayConfig[0],gatewayConfig[1],gatewayConfig[2],gatewayConfig[3]), //Gateway IpAddr(dnsConfig[0],dnsConfig[1],dnsConfig[2],dnsConfig[3]) //DNS ); } EthernetErr ethErr = eth->setup(10000); if (ethErr) { printf("Error %d in setup.\r\n", ethErr); lcd.printf("Error"); } sprintf(buf,"%d.%d.%d.%d", eth->getIp()[0], eth->getIp()[1], eth->getIp()[2], eth->getIp()[3]); sprintf(localIP,"%s",buf); printf("Setup OK\r\n"); lcd.printf("Done\n"); wdog.feed(); //-----------------WAN check--------------------------- wait(1); printf("<WAN Connection Check>\r\n"); lcd.cls(); lcd.printf("Internet conn.."); GetMyIP(); if (wanIP!="none") { lcd.printf("Done\n"); printf("OK: %s\r\n",wanIP); } else { lcd.printf("Fail\n"); printf("No connection\r\n"); } wdog.feed(); //-----------------RTC INIT------------------------ lcd.printf("RTClock Init..."); printf("<RTC Init>\r\n"); if (wanIP!="none") { UpdateTime(); strftime(buf,sizeof(buf), "%A %m/%d/%Y %H:%M:%S\n", localtime(&ctTime)); printf("Time is now : %s JST\r\n", buf); lcd.printf("Done\n"); } else { printf("Cannot connect NTP Server!!\r\n"); lcd.printf("Fail\n"); } wdog.feed(); //-------Init index.htm in local filesystem--------- 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); //--------------HTTP SERVER------------------------- FSHandler::mount("/local", "/"); //Mount /wwww path on web root path FSHandler::mount("/sd", "/extern"); //Mount /wwww path on web root path svr.addHandler<FSHandler>("/files");// this does not see the subdirectory svr.addHandler<FSHandler>("/"); //Default handler svr.addHandler<SimpleHandler>("/com"); //Com hander 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)); tempstring =""; tempstring += buf; LogWrite(tempstring); tempstring ="SYSTEM READY"; LogWrite(tempstring); Timer tm; tm.start(); //Listen indefinitely int counter =0; //-------------------MAIN LOOP-------------------- while (true) { Net::poll(); // Network listen if (tm.read()>1) { counter = (counter++)%3600; //Timer counter loop led1=!led1; //Show that we are alive 1 sec timed 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 GetMyIP(); if (wanIP!="none") { IndexInit() ; UpdateTime(); } } //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)); } } } //---------------------------Functions-------------------------- void InitDS1820() { int i; // Initialize the probe array to DS1820 objects for (i = 0; i < MAX_PROBES; i++) probe[i] = new DS1820(p29); // Initialize global state variables probe[0]->search_ROM_setup(); // Loop to find all devices on the data line while (probe[devices_found]->search_ROM() and devices_found<MAX_PROBES-1) devices_found++; // If maximum number of probes are found, // bump the counter to include the last array entry if (probe[devices_found]->ROM[0] != 0xFF) devices_found++; if (devices_found==0) printf("No devices found"); else { probe[0]->convert_temperature(DS1820::all_devices); for (i=0; i<devices_found; i++) { printf("%3.1f \r\n",probe[i]->temperature('c')); } } lcd.printf("%d",devices_found); } //-------------------Get WAN IP adress------------------------- void GetMyIP() { HTTPClient http; HTTPText txt; HTTPResult r = http.get("http://www.whatismyip.com/automation/n09230945NL.asp", &txt); if (r==HTTP_OK) { sprintf(wanIP,"%s", txt.gets()); } else { sprintf(wanIP,"none"); } } //-----------------Create Index HTM in local------------------- void IndexInit() { FILE *fs_src; FILE *fs_tgt; char buffer[ COPY_BLOCK_SIZE ]; printf( "file copier started.\r\n" ); printf( " source:%s >>> target:%s\r\n", SOURCE_FILE, TARGET_FILE ); if ( NULL == (fs_src = fopen( SOURCE_FILE, "rb" )) ) { error( "couldn't open source file" ); } if ( NULL == (fs_tgt = fopen( TARGET_FILE, "wb" )) ) { error( "couldn't open target file" ); } /* while ( size = fread( s, sizeof( char ), COPY_BLOCK_SIZE, fs_src ) ) { fwrite( s, sizeof( char ), size, fs_tgt ); total += size; led1 = (0x1 << progress_ind++ % 4); printf( " %d bytes copied\r", total ); } */ string temp; char token[] = "ServerAddress"; while (fgets(buffer, COPY_BLOCK_SIZE, fs_src)) { temp = string(buffer); int j=0; for (int i=0;i<COPY_BLOCK_SIZE;i++) { if (buffer[i]==token[j]) { j++; } else { j=0; } if (j==12) break; if (buffer[i]==0) { break; } } if (j==12) { //Change to find string element search by char. fprintf(fs_tgt," <param name=\"ServerAddress\" value=\"%s\">",myUrl.c_str()); } else { fprintf(fs_tgt,"%s",temp.c_str()); } } led1 = 0xF; fclose( fs_src ); fclose( fs_tgt ); printf( "done\r\n" ); } //------------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); if (wanIP!="none") { if (IPshowflag) { lcd.printf("IP: %s ", localIP); } else { lcd.printf("IP: %s ", wanIP); } IPshowflag = !IPshowflag; } else { //DO nothing only one ip address is shown } } if (counter%1==0) { //Every sec lcd.locate(0,3); ctTime = time(NULL); ctTime += (clockoffset*3600); strftime(buf,sizeof(buf), "%Y/%m/%d %H:%M:%S", localtime(&ctTime)); lcd.printf("%s", buf); } } //----------------Update time--------------------- void UpdateTime() { time_t ctTime; ctTime = time(NULL); Host server(IpAddr(), 123, "0.hu.pool.ntp.org"); ntp.setTime(server); ctTime = time(NULL); 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; char buffer[ 100 ]; int linecounter = 0; fs_src = fopen( CONFIG_FILE, "rb" ); while (fgets(buffer, 100, fs_src)) { linecounter++; switch (linecounter) { case 2 : sscanf(buffer,"%d.%d.%d.%d",&ipConfig[0],&ipConfig[1],&ipConfig[2],&ipConfig[3]); break; case 4 : sscanf(buffer,"%d.%d.%d.%d",&maskConfig[0],&maskConfig[1],&maskConfig[2],&maskConfig[3]); break; case 6 : sscanf(buffer,"%d.%d.%d.%d",&gatewayConfig[0],&gatewayConfig[1],&gatewayConfig[2],&gatewayConfig[3]); break; case 8 : sscanf(buffer,"%d.%d.%d.%d",&dnsConfig[0],&dnsConfig[1],&dnsConfig[2],&dnsConfig[3]); break; case 10: if (buffer[0]=='t' | buffer[0]=='T') getIPfromDHCP= true; else getIPfromDHCP = false; break; case 13: sscanf(buffer,"%d",&interval); break; case 15: sscanf(buffer,"%d",&clockoffset); break; case 18: myUrl = buffer; break; } } fclose( fs_src ); } //---------------Load status-------------------------- void LoadStatus() { FILE *fs_src; char buffer[ 100 ]; int linecounter = 0; fs_src = fopen( STATUS_FILE, "rb" ); while (fgets(buffer, 100, fs_src)) { linecounter++; switch (linecounter) { case 1: sscanf(buffer,"%d",&logging); break; case 2: sscanf(buffer,"%s",logfile); break; } } fclose( fs_src ); } //-----------------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()); 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; }