#include "Adafruit_FONA.h"
#include "string.h"
//#include <DHT.h>

#define FONA_RX 2 
#define FONA_TX 3
#define FONA_RST 4
#define DHTTYPE DHT11   // DHT 11


// this is a large buffer for replies
char replybuffer[255];

#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;

// Use this for FONA 800 and 808s
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
uint8_t type;

int dustpin=8;                   // Dust Sensor Pin #1
int dustpin2=9;                  // Dust Sensor Pin #2
//const int dhtPin = 11;           // Analog input pin that the DHT11 is attached to
const int redbuttonPin = 7;      // the number of the redpushbutton pin
const int greenbuttonPin = 6;    // the number of the greenpushbutton pin
const int numReadings = 1;      // the peak flow number of readings (make larger to average more values)
int readings[numReadings];      // the readings from the analog(peakflow) input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

int inputPin = A2;
// variables will change:
int peakflowValue = 0;        // value read from the peakflow meter
int dhtValue = 0;             // value read from the DHT11 sensor
int redbuttonState = 0;       // variable for reading the redpushbutton status
int greenbuttonState = 0;     // variable for reading the greenpushbutton status
int lastButtonState = 0;      // previous state of the button
int buttonPushCounter = 0;    // counter for the number of button presses

float hum;
float temp;

unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 2000; 
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;

//DHT dht(dhtPin,DHTTYPE); //Initialize DHT sensor
void setup() {
  while (!Serial);

  Serial.begin(115200);
//  dht.begin();
  Serial.println(F("FONA basic test"));
  Serial.println(F("Initializing....(May take 3 seconds)"));

  fonaSerial->begin(4800);
  if (! fona.begin(*fonaSerial)) {
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
 type = fona.type();
  Serial.println(F("FONA is OK"));
  Serial.print(F("Found "));
  switch (type) {
    case FONA800H:
      Serial.println(F("FONA 800H")); break;
    default: 
      Serial.println(F("???")); break;
  }
  
  // Print module IMEI number.
  char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
  uint8_t imeiLen = fona.getIMEI(imei);
   if (imeiLen > 0) {
    Serial.print("Module IMEI: "); Serial.println(imei);
  }
  
  // Optionally configure a GPRS APN, username, and password.
  // You might need to do this to access your network's GPRS/data
  // network.  Contact your provider for the exact APN, username,
  // and password values.  Username and password are optional and
  // can be removed, but APN is required.
  fona.setGPRSNetworkSettings(F("wholesale"), F(""), F(""));
pinMode(redbuttonPin, INPUT);
delay(500);
fona.enableGPRS(true);
Serial.print("fona GPRS enabled");
delay(50);

//Get the Network time and set the Arduino clock (only do this once so we do not have to repeat this over and over!)
char buffer[23];
        fona.getTime(buffer, 23);  // make sure replybuffer is at least 23 bytes!
        Serial.print(F("Time = ")); Serial.println(buffer);

//char buffer = TIME = "16/02/25,18:17:20-20" 
//We need a format that looks like this...."02-25-2016%2011:43:16"

for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;}

    starttime = millis();
}


void loop() {   
   {
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = analogRead(inputPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println(average);
  delay(1);        // delay in between reads for stability
}

    duration = pulseIn(dustpin, LOW);
  lowpulseoccupancy = lowpulseoccupancy+duration;
 
  if ((millis()-starttime) >= sampletime_ms)//if the sampel time = = 30s
  {
    ratio = lowpulseoccupancy/(sampletime_ms*10.0);  // Integer percentage 0=&gt;100
    concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; // using spec sheet curve on http://www.howmuchsnow.com/arduino/airquality/grovedust/
    Serial.print("concentration of pollution = ");
    Serial.print(concentration);
    //Serial.println(" pcs/0.01cf");
    Serial.println("\n");
    lowpulseoccupancy = 0;
    starttime = millis();
  }

    redbuttonState = digitalRead(redbuttonPin);
    greenbuttonState = digitalRead(greenbuttonPin);
    peakflowValue = average;
//    hum = dht.readHumidity();
//    temp= dht.readTemperature();
    
    
    if(1==1){
    Serial.print("  The RedButton state = ");
    Serial.print(redbuttonState);
    Serial.print("  The Greenbutton state = ");
    Serial.print(greenbuttonState);
    Serial.print("  The Peak Flow value: ");
    Serial.print(peakflowValue);
    Serial.print("    ");
//    Serial.print("  The Temp is: ");
//    Serial.print(temp);
//    Serial.print("  The Humidity is: ");
//    Serial.print(hum);
//    Serial.print("Location: ");
    }

//REDBUTTON STATUS POST IF CHANGES
    
    if(redbuttonState==0){
      // Post data to website
        uint16_t statuscode;
        int16_t length;
        Serial.print("  The redbutton was depressed ");
        Serial.print(redbuttonState);
        Serial.print("  ");
        
        char reddata[100];
        strlcpy(reddata, "value=" ,100);
        char * temp = (char*)malloc(20);
        strlcat(reddata, itoa(redbuttonState, temp, 20), 100);
        strlcat(reddata, "&table_name=", 100);
        strlcat(reddata, "redbutton", 100);
       // strlcat(reddata, "&recdate=02-26-2016%2018:45:21", 100);
        char url[80]={"http://ilab.engr.utk.edu/hits/smarthome/insertdatapoint.php"};
        fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) reddata, strlen(reddata), &statuscode, (uint16_t *)&length);
        fona.HTTP_POST_end();
        delay(500);
     }

  if(greenbuttonState==1){
// Post data to website
        uint16_t statuscode;
        int16_t length;
        Serial.print("  The green button was depressed We will now send this fact to the Server ");
        Serial.print(greenbuttonState);
        Serial.print("  ");
        
        char greendata[100];
        strlcpy(greendata, "value=" ,100);
        char * temp = (char*)malloc(20);
        strlcat(greendata, itoa(greenbuttonState, temp, 20), 100);
        strlcat(greendata, "&table_name=", 100);
        strlcat(greendata, "greenbutton", 100);
       // strlcat(greendata, "&recdate=02-25-2018%2015:45:21", 100);
        char url[80]={"http://ilab.engr.utk.edu/hits/smarthome/insertdatapoint.php"};
        fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) greendata, strlen(greendata), &statuscode, (uint16_t *)&length);
        fona.HTTP_POST_end();
        delay(600);

//LOCATION
        uint16_t returncode;
        fona.getGSMLoc(&returncode, replybuffer, 250);
        if (returncode == 0){
          Serial.print("The location: ");
          Serial.println(replybuffer);
          char (replybuffer);
          
          char locationdata[100];
          strlcpy(locationdata, "value=" ,100);
          char * temp = (char*)malloc(20);
          strlcat(locationdata, itoa(replybuffer, temp, 20), 100);
          strlcat(locationdata, "&table_name=", 100);
          strlcat(locationdata, "location", 100);
          char url[80]={"http://ilab.engr.utk.edu/hits/smarthome/insertdatapoint.php"};
          fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) locationdata, strlen(locationdata), &statuscode, (uint16_t *)&length);
//          fona.HTTP_POST_end();
//          delay(600); 
        }
  }
 //Peak Flow Sensor
    for(static bool first = true; first;first=false){
      if (peakflowValue<690 && peakflowValue>0) {
        // Post data to website
        uint16_t statuscode;
        int16_t length;
        Serial.print("The Peak Flow Value is: ");
        Serial.print(peakflowValue);

        delay(100);
        char peakdata[100];
        strlcpy(peakdata, "value=" ,100);
        char * temp = (char*)malloc(20);
        strlcat(peakdata, itoa(peakflowValue, temp, 20), 100);
        strlcat(peakdata, "&table_name=", 100);
        strlcat(peakdata, "peakflow", 100);
       // strlcat(peakdata, "&recdate=02-26-2016%2018:45:21", 100);
        char url[80]={"http://ilab.engr.utk.edu/hits/smarthome/insertdatapoint.php"};

       //if(!fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) {
       fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) peakdata, strlen(peakdata), &statuscode, (uint16_t *)&length);
       //delay(70);
       fona.HTTP_POST_end();
       delay(500);
     }
    }
//AIR QUALITY SENSOR
    if(concentration>400) {
    // Post data to website
        uint16_t statuscode;
        int16_t length;
        Serial.print("The pollution is: ");
        Serial.print(concentration);

        int airconcentration = 14;//concentration*100;

        char pollutiondata[100];
        strlcpy(pollutiondata, "value=" ,100);
        char * temp = (char*)malloc(20);
        strlcat(pollutiondata, itoa(airconcentration, temp, 20), 100);
        strlcat(pollutiondata, "&table_name=", 100);
        strlcat(pollutiondata, "pollution", 100);
       // strlcat(pollutiondata, "&recdate=02-26-2016%2014:45:21", 100);
        char url[80]={"http://ilab.engr.utk.edu/hits/smarthome/insertdatapoint.php"};
        Serial.print(pollutiondata);
        delay(1000);
        Serial.print(pollutiondata);

       //if(!fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) {
       fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) pollutiondata, strlen(pollutiondata), &statuscode, (uint16_t *)&length);
       delay(70);
       fona.HTTP_POST_end();
       delay(1000);
     } 
}

