4180 Final Project

Dependencies:   4DGL-uLCD-SE mbed Servo

main.cpp

Committer:
ecarrick
Date:
2016-05-01
Revision:
27:2bd737c0a8af
Parent:
26:f08205fa22d3

File content as of revision 27:2bd737c0a8af:

#include "mbed.h"
#include "wifi.h"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <iterator>
#include <stdio.h>
#include <ctype.h>
#include "uLCD_4DGL.h"
#include "Servo.h"

#include <list>
#include <mpr121.h>

LocalFileSystem local("local");
Servo lock(p25); // a pwm pin, 0 for unlocked; 1 for locked;

DigitalOut myled(LED1);
DigitalOut ledr(p5);
DigitalOut ledg(p6);
DigitalOut ledb(p7);

Serial pc(USBTX,USBRX);
//uLCD_4DGL lcd(p28,p27,p30); // serial tx, serial rx, reset pin;

// Create the interrupt receiver object on pin 26
InterruptIn interrupt(p26);

// Setup the i2c bus on pins 28 and 27
I2C i2c(p9, p10);

// Setup the Mpr121:
// constructor(i2c object, i2c address of the mpr121)
Mpr121 mpr121(&i2c, Mpr121::ADD_VSS);

// log for web page
vector<string> accessLog;
unsigned logLength = 5;
volatile bool updateAccessLog = false;

// save to file flag
volatile bool saveToFileFlag = false;
volatile bool newData = false;

// time
time_t rtc;

vector<char> im;
vector<char> tempim;
vector<char> pass;
vector<char> name;
vector<char> final;
vector<char> ans;

string print_vector(vector<char>& vec){
    string str;
    str.append(vec.begin(),vec.end());
    return str;
}

vector<char> password;
unsigned maxLength = 18; //random length chosen
unsigned minLength = 6;  //random length chosen

void print_to_serial()
{
    for(unsigned i=0; i< im.size(); i++) {
        pc.printf("%c",im[i]);
    }
    pc.printf("\r\n");
}

//function for debugging
void printPW()
{
    for (int i=0; i<password.size(); i++) {
        pc.printf("%c", password[i]);
    }
    pc.printf("\r\n");
}

bool foundResult = false;
void checkResult(vector<char> pass, vector<char> name)
{
    /*
    for (int i=0; i<pass.size(); i++) {
        pc.printf("%d", int(pass[i]));
    }
    */
    
    //pc.printf("\r\n");
    // This function will check the keypad values and check if the passcode exists or not

    if (pass.size()==6) {
        if (password == pass) {
            //pc.printf("Found");
            final = name;
            final.push_back(' ');
            final.insert(final.end(),pass.begin(),pass.end());
            foundResult=true;
            ledb =0;
            ledr =0;
            ledg =1;
            lock = 0;
            //wait(0.01);
            //ledg =0;

        } else {
            //pc.printf("not found");
            //lcd.printf("\nnot found\n");
            final.clear();
        }
    }
}


void checkKeyboard()
{
    //load_from_file();
    //pc.printf("CHECKING PASSWORD\n\r");
    //pc.printf("\n\r");
    bool colon = false;
    vector<char> empty;
    swap(empty, pass);
    vector<char> empty2;
    swap(empty2, name);
    //pass.clear();
    //name.clear();
    for (int i = 0; i<im.size(); i++) {

        // find space
        if (im[i] ==' ') {
            checkResult(pass,name);
            colon = false;
            if(foundResult){
                //foundResult=false;
                break;
            }
            vector<char> empty;
            swap(empty, pass);
            vector<char> empty2;
            swap(empty2, name);            
            //pass.clear();
            //name.clear();

        } else if (im[i] == ':') {
            colon = true;
        } else {
            if(colon)
                pass.push_back(unsigned(im[i]));
            else
                name.push_back(char(im[i]));
        }
    }
}

void fallInterrupt()
{
    int key_code=0;
    int i=0;
    int value=mpr121.read(0x00);
    value +=mpr121.read(0x01)<<8;

    //checks every key for press
    for (i=0; i<=11; i++) {

        //if key 10 (clr) is pressed, clear the last value on the vector will be popped off
        if ((((value>>i)&0x01)==1)&&(i==10)) {

            if (!password.empty()) {
                ledb = 1;
                password.pop_back(); //pop off last value on the vector
                //printPW();//for debugging
                //pc.printf("container size: %d\r\n", password.size());//for dubugging
            }
            break;
        }

        //if key 11 (ENTER) is pressed, the password will be submitted IF it is long enough
        else if ((((value>>i)&0x01)==1)&&(i==11)) {
            if(lock == 0){
                lock = 1.0;
                break;
            }
            //if the password is long enough, check passwords, and clear vector.
            if (password.size() >= minLength) {
                //ledb = 1;
                //ans = password;
                //pc.printf("ENTER KEY PRESSED\n\r");
                //printPW();
                //for(unsigned k =0; k<password.size(); k++)
                //    ans.push_back(password[k]);
                checkKeyboard();
                rtc = time(NULL);
                char time_s[128];
                struct tm * p = localtime(&rtc);
                strftime(time_s, 128, "%T %F", p);
                if(foundResult){
                    foundResult=false;
                    char buf[128];
                    sprintf(buf,"SUCCESS %s %s", print_vector(name).c_str(), time_s);
                    if(accessLog.size()<logLength){
                        accessLog.push_back(buf);
                    } else{
                        vector<string> empty;
                        swap(accessLog,empty);
                        //accessLog.clear();
                        accessLog.push_back(buf);
                    }
                } else{
                    ledr = 1;
                    char buf[128];
                    sprintf(buf,"FAILURE %s %s", print_vector(password).c_str(), time_s);
                    if(accessLog.size()<logLength){
                        accessLog.push_back(buf);
                    } else{
                        vector<string> empty;
                        swap(accessLog,empty);
                        //accessLog.clear();
                        accessLog.push_back(buf);
                    }
                }
                //update_log(accessLog);
                updateAccessLog = true;
                wait(0.005);
                ledg=0;
                ledr=0;
                vector<char> empty;
                swap(empty, password);
                //password.clear();
            }

            else {
                //pc.printf("The password must be at least %d characters long\r\n", minLength);
            }
            break;
        }

        //if keys 0 through 9 are pressed
        else if (((value>>i)&0x01)==1) {

            //if max pw length has not been reached, push onto password vector
            if (password.size() < maxLength) {
                ledb = 1;

                
                key_code=i;
                password.push_back((char)(key_code+48));
                //printPW(); //for debugging
                //pc.printf("times: %d\r\n", password.size());

                if (password.size() == maxLength) {
                    //pc.printf("Max password length reached. Press clr to delete character. Press any number key to reset.\r\n");
                    ledb = 0;
                    ledr = 1;
                    wait(0.05);
                    ledr = 0;
                    vector<char> empty;
                    swap(empty, password);
                    //password.clear();
                }
            }

            //if max password length has been reached
            else {
                //pc.printf("Maximum password length reached, password has been cleared. \r\n");
                //password.clear();
                vector<char> empty;
                swap(empty, password);
            }
            break;
        }

    }
    wait(0.005);
    ledb = 0;

}

void save_to_file()
{
    FILE * fp = fopen("/local/users.txt", "w");
    if(fp != NULL) {
        for(unsigned i=0; i< im.size(); i++) {
            fprintf(fp,"%c",im[i]);
        }
    }
    fclose(fp);
}

void load_from_file()
{
    FILE * fp = fopen("/local/users.txt", "r");
    if(fp != NULL) {
        im.clear();
        do {
            im.push_back(fgetc(fp));
        } while(im.back() != '#');
    }
    fclose(fp);
}

int i = 0;



//Interrupt
void Rx_interrupt()
{
    if(!newData){
        // at the start of getting new data we need to indicate we are receiving data
        // the first character will clear the temporary IM and save the char
        ledb = 1;
        tempim.clear();
        char c = pc.getc();
        if(c=='!')
            print_to_serial();
        else{
            tempim.push_back(c);
            newData = true;
        }
    }
    else{
        // get the next character
        char c = pc.getc();
        // unless we see a #, then we expect more characters
        if (c!='#') {
            tempim.push_back(c); //writing all the characters into vector
        // if we see a #, the string is complete, reset all of the flags and update im
        } else {
            ledb=0;
            tempim.push_back(c);
            saveToFileFlag = true;
            im = tempim;
            newData = false;
        }
    }
    return;
}


int main()
{
    // notify over PC serial that we have reset the mbed
    pc.printf("\r\n\r\nMBED RESET\r\n");
    // ensure the lock starts in the locked position
    // lock = 0 is unlocked
    lock = 1.0;
    
    // to show it's setting up, we keep the LED blue, when a function completes it flashes
    // when the LED flashes green 3 times the setup is complete
    ledb=1;     
    // setup and connect to the WiFi
    pc.printf("Setting up WIFI\r\n");
    setup_wifi();
    ledb = 0;
    wait(0.3);
    ledb = 1;
    // send the HTTP socket functions to the ESP8266 module
    pc.printf("Setting Up HTTP\r\n");
    setup_http();
    ledb = 0;
    wait(0.3);
    ledb = 1;
    // send the NTP connection functions to the WiFi module
    pc.printf("Setting up NTP\r\n");
    setup_ntp();
    ledb = 0;
    wait(0.3);
    ledb = 1;
    // use NTP and update the mbed RTC
    pc.printf("Updating NTP\r\n");
    update_ntp();
    ledb = 0;
    wait(0.3);
    ledb = 1;
    // verify to the user over the PC serial port the time obtained
    rtc = time(NULL);
    pc.printf("%s\r\n", ctime(&rtc));

    // load the user/password information saved on the device
    load_from_file();
    print_to_serial();
    ledb = 1;
    wait(0.3);
    ledb = 0;
    // register the iterrupts for handling the keypad 
    interrupt.fall(&fallInterrupt);
    interrupt.mode(PullUp);
    ledb = 1;
    wait(0.3);
    ledb = 0;
    //interupt driven read from serial port C# program
    // sets saveToFileFlag;
    pc.attach(&Rx_interrupt, Serial::RxIrq);
    ledb = 1;
    wait(0.3);
    ledb = 0;
    // blink green three times to indicate full boot
    ledg = 1; wait(0.3);ledg = 0;
    wait(0.3); ledg = 1; wait(0.3);
    ledg = 0; wait(0.3);ledg = 1;
    wait(0.3); ledg = 0;
    
    while(1){
        if(updateAccessLog){
            update_log(accessLog);
            updateAccessLog = false;
        }
        
        if(saveToFileFlag){
            pc.printf("\r\nSAVING TO FILE\r\n");
            save_to_file();
            saveToFileFlag = false;
        }
        
        wait(1);
        //sleep();
    
    }
    
}