Measure system

Dependencies:   EthernetNetIf mbed RF12B

server/impl/SimpleHandler.cpp

Committer:
benecsj
Date:
2011-05-17
Revision:
3:799d8c61fb03
Parent:
2:afe5826411e3

File content as of revision 3:799d8c61fb03:


/*
Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "MeasureSystem.h"
#include "SimpleHandler.h"
#include "DS1820.h"

extern DS1820* probe[2];
extern int devices_found;

#define CHUNK_SIZE 128

//#define __DEBUG
//#include "dbg/dbg.h"

SimpleHandler::SimpleHandler(const char* rootPath, const char* path, TCPSocket* pTCPSocket) : HTTPRequestHandler(rootPath, path, pTCPSocket) {}

SimpleHandler::~SimpleHandler() {
    HandlerActive = false;
    printf("2-SIMPLE-Handler destroyed\r\n");
}

void SimpleHandler::doGet() {
    printf("2-SIMPLE-In SimpleHandler::doGet()\r\n");
    printf("rootpath: %s  path: %s\r\n",rootPath().c_str(),path().c_str());
    if (path().compare("/currentdata") == 0) {
        CurrentData();
    } else
        if (path().compare("/currenthtml") == 0) {
            CurrentHtml();
        } else if (path().compare("/reset") == 0) {
        ResetMe();
        } else if (path().compare("/deletelogs") == 0) {
            DeleteLogs();
        } else if (path().compare("/deletesyslog") == 0) {
            DeleteSysLog();
        }   else {
            if (0 ==path().find("/interval/")) {
                SetInterval();
            } else if (0 ==path().find("/deletelog/")) {
                DeleteLog();
            } else if (0 ==path().find("/setdate/")) {
                SetDate();
            } else {
                InvalidCommand();
            }

        }


    printf("2-SIMPLE-Exit SimpleHandler::doGet()\r\n");
}

void SimpleHandler::doPost() {
    printf("2-SIMPLE-In SimpleHandler::doPost() STARTED\r\n");

    int res=-1;
    char data[dataLen()+1];
    res = readData(data,dataLen());
    data[dataLen()] = 0;
    printf("2-SIMPLE-<Data received: %d  |  %d>\r\n%s\r\n2-SIMPLE-<END>\r\n",dataLen(),res,data);
    if (res == dataLen()) {
        postOK = 1;
    } else {
        postOK = 0;
    }

    if (path().compare("/start") == 0) {
        MeasureStart();
    } else     if (path().compare("/stop") == 0) {
        printf("CALLING MEASURE STOP\r\n");
        MeasureStop();
    } else     if (path().compare("/saveconfig") == 0 & postOK==1) {
        printf("CALLING CONFIG SAVER\r\n");
        ReceiveConfig(data);
    } else     if (path().compare("/login") == 0 & postOK==1) {
        printf("CALLING USER CHECK\r\n");
        Login(data);
        return;
    } else {
        printf ("PATH = %s\r\n ",path().c_str());
        printf ("INVALID POST COMMAND\r\n");
    }

    string htmltext ("");
    htmltext +="<html>\r\n";
    htmltext +="<head>\r\n";
    htmltext +="</head>\r\n";
    htmltext +="<body bgcolor=""#0000FF"" ";
    htmltext += "text=""#00FFFF"" link=""#AAFFD4"" vlink=""#FFFFFF"" alink=""#FF0000"">\r\n";
    if (postOK ==1) {
        htmltext +="<h2>Post received.</h2>\r\n";
    } else {
        htmltext +="<h2>Post not received.</h2>\r\n";
    }
    htmltext +="<script type=""text/javascript"">\r\n";
    htmltext += "setTimeout(""history.back()"",1500);";
    htmltext +="</script>\r\n";
    htmltext +="</body>\r\n";
    htmltext +="</html>\r\n";

    printf("2-SIMPLE-In SimpleHandler::doPost() htmltext done\r\n");

    char temp[350];
    strcpy(temp, htmltext.c_str());

    setContentLen( strlen(temp) );
    respHeaders()["Connection"] = "close";
    writeData(temp, strlen(temp));
    printf("2-SIMPLE-In SimpleHandler::doPost() DONE\r\n");
}

void SimpleHandler::onReadable() {

}

void SimpleHandler::doHead() {

}

void SimpleHandler::onWriteable() { //Data has been written & buf is free
    printf("2-SIMPLE-SimpleHandler::onWriteable() event\r\n");
    close(); //Data written, we can close the connection
}

void SimpleHandler::onClose() { //Connection is closing
    //Nothing to do
}


//----------------------COM HANDLERS--------------------------------

//-----------------------RESET ME-----------------------------------
void SimpleHandler::ResetMe() {
reset = true;
    char temp[] = "Reset command accepted.";
    setContentLen( strlen(temp) );
    respHeaders()["Connection"] = "close";
    writeData(temp, strlen(temp));
}

void SimpleHandler::SetDate() {
    string text = path();
    string text2 = text.substr (9);
    printf("-------TIME: %s\r\n", text2.c_str());
    long time;
    sscanf(text2.c_str(),"%10d",&time);
    time+=clockoffset*3600;
    set_time(time);
    
    printf("-------TIME: %d\r\n", time);
    char temp[] = "Set date accepted.";
    setContentLen( strlen(temp) );
    respHeaders()["Connection"] = "close";
    writeData(temp, strlen(temp));
}
//--------------------------CURRENT DATA----------------------------
void SimpleHandler::CurrentData() {
    char resp[100] = "";
    char temp[100] ;

    char buf[50];
    ctTime = time(NULL);
    ctTime += (clockoffset*3600);
    strftime(buf,sizeof(buf), "%H:%M:%S\r\n", localtime(&ctTime));
    strcat(resp,buf);

    probe[0]->convert_temperature(DS1820::all_devices);
    for (int i=0; i<devices_found; i++) {
        sprintf(temp,"%d.)%3.1fC  ",(i+1),(probe[i]->temperature('c')));
        strcat(resp,temp);
    }

    setContentLen( strlen(resp) );
    respHeaders()["Connection"] = "close";
    writeData(resp, strlen(resp));
}
//--------------------------CURRENT HTML----------------------------
void SimpleHandler::CurrentHtml() {
    char temp[1000];
    printf("2-SIMPLE- Generating html code\r\n");

    string htmltext ("");
    htmltext +="<html>";
    htmltext +="<head>";
    htmltext += "<title>mbed Measure System</title>";
    htmltext +="</head>";
    htmltext +="<body bgcolor=""#0000FF"" text=""#00FFFF"" link=""#AAFFD4"" vlink=""#FFFFFF"" alink=""#FF0000"">";
    htmltext +="<div align=""center"">";
    htmltext +="<h1>Current values</h1>";

    printf("2-SIMPLE- Reading temps\r\n");

    probe[0]->convert_temperature(DS1820::all_devices);
    for (int i=0; i<devices_found; i++) {
        sprintf(temp,"%d.)  %3.1f C",(i+1),(probe[i]->temperature('c')));
        htmltext +="<h1>";
        htmltext += temp;
        htmltext +="</h1>";
    }

    printf("2-SIMPLE- Generating html code\r\n");

    htmltext +="<h1><a href=""javascript:location.reload(true)"">Refresh</a></h1>";
    htmltext +="<h1><a href=""javascript:history.back()"">Return</a></h1>";
    htmltext +="</div>";
    htmltext +="</body>";
    htmltext +="</html>";

    strcpy(temp, htmltext.c_str());
    setContentLen( strlen(temp) );
    respHeaders()["Connection"] = "close";
    writeData(temp, strlen(temp));
}
//--------------------INVALID COMMAND-----------------------
void SimpleHandler::InvalidCommand() {
    char temp[] = "Invalid com command.";
    setContentLen( strlen(temp) );
    respHeaders()["Connection"] = "close";
    writeData(temp, strlen(temp));
}
//-----------------------READY------------------------------------
void SimpleHandler::Response(char *input) {
    setContentLen( strlen(input) );
    respHeaders()["Connection"] = "close";
    writeData(input, strlen(input));
}
//-------------------DELETE LOGS-------------------------------------
void SimpleHandler::DeleteLogs() {
    DIR *d = opendir(DATA_FOLDER);
    string file;
    struct dirent *p;
    printf("\nList of files in the directory %s:\r\n", DATA_FOLDER);
    while ( (p = readdir(d)) != NULL ) {

        file = "";
        file +=DATA_FOLDER;
        file += "/";
        file +=  p->d_name;
        printf("Deleting - %s\r\n", file.c_str());
        if (logging==1) {
            if (file.find(logfile)==0) {
                continue;
            }
        }
        remove( file.c_str() );
    }
    closedir(d);
    Response("Done");
}
//-------------------------Delete single log file----------------------
void SimpleHandler::DeleteLog() {
    string text = path();
    string text2 = DATA_FOLDER;
    text2 += text.substr (10);

    if (logging==1) {
        if (text2.compare(logfile)==0) {
            Response("CantDelete logging file.");
            return;
        }
    }

    printf("Deleting log: %s\r\n",text2.c_str());
    remove (text2.c_str());
    Response("Done");
}
//-------------------------Delete system log file----------------------
void SimpleHandler::DeleteSysLog() {
    remove (LOGGER_FILE);
    LogWrite("");
    Response("Done");
}


//----------------------SET INTERVAL------------------------------
void SimpleHandler::SetInterval() {
    string text = path();
    string text2 = text.substr (10);
    printf("Interval value: %s\r\n",text2.c_str());

    if (0!= strlen(text2.c_str())) {
        int i =atoi(text2.c_str());
        if (i!=0) {
            interval = i;
            SaveConfig();
        }
    }
    Response("Done");
}
//-----------------------RECEIVE CONFIG-----------------------------
void SimpleHandler::ReceiveConfig(char* data) {
//---Save config--------
    FILE *fs_src;
    fs_src    = fopen( CONFIG_FILE, "w" );
    fprintf(fs_src,"%s",data);
    fclose( fs_src );
//---Load new config----
    LoadConfig();
}
//----------------------LOGIN CHECK---------------------------------
void  SimpleHandler::Login(char* data) {
    bool ok = false;
    char temp[5];

    if (strlen(data)>7) {
        char    buffer[50 ];
        string str ="";
        FILE *fs_src;
        fs_src    = fopen( LOGIN_FILE, "r" );
        while (fgets(buffer, 100, fs_src)) {
            str = buffer;
            printf("Storedlogin:(%s)\r\n",buffer);
            if (str.find(data)==0) {
                ok = true;
            }
        }

        fclose( fs_src );
    }

    if (ok) {
        strcpy(temp, "OK");
    } else {
        strcpy(temp, "NO");
    }

    setContentLen( strlen(temp) );
    respHeaders()["Connection"] = "close";
    writeData(temp, strlen(temp));
    printf("2-SIMPLE-In SimpleHandler::doPost() DONE\r\n");
}