Measure system

Dependencies:   EthernetNetIf mbed RF12B

MeasureSystem.cpp

Committer:
benecsj
Date:
2011-03-03
Revision:
0:8d62137f7ff4
Child:
1:b26ab2467b1a

File content as of revision 0:8d62137f7ff4:

#define MEASURE_C


#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"

//--------------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        LOGGER_FILE        "/sd/syslog/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 string wanIP;
static string localIP;
int logging;
int fileindex;
bool getIPfromDHCP;
int interval;
int ipConfig[4];
int maskConfig[4];
int gatewayConfig[4];
int dnsConfig[4];
//---------------------MAIN-----------------------
int main() {
    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("/sd/syslog", 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]);
    localIP = string(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.c_str());

    } 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();
    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());
    //--------------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();
                }
            }

            wdog.feed();
            tm.start();
        }

    }


}


//---------------------------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) {
        wanIP =  txt.gets();
    } else {
        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.
            if (wanIP!="none") {

                temp = wanIP;
            } else {
                temp =localIP;
            }
            fprintf(fs_tgt,"      <param name=\"ServerAddress\" value=\"%s\">",temp.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) {
    if (counter%4==0) {
        lcd.locate(0,2);
        lcd.locate(0,2);
        if (wanIP!="none") {
            if (IPshowflag) {
                lcd.printf("IP: %s        ", localIP.c_str());
            } else {
                lcd.printf("IP: %s        ", wanIP.c_str());
            }
            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
}

//---------------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;
        }

    }

    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,"%d",&fileindex);
                break;
        }

    }

    fclose( fs_src );

}

    //---------------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);
}