#include <math.h>

//--- made by SKA ---
//--- test EtherEncLib 
// adapted by Renato Aloi
// May 2015
// removed SD Card part for future implementation

#include <SPI.h>
#include <EtherEncLib.h>
#if (ESP8266)
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#endif



static unsigned char ipaddr[] = { 192, 168, 1, 125 };
static unsigned char macaddr[] = { 0x00, 0x11, 0x22, 0x44, 0x00, 0x25 };

EtherEncLib eElib(80);

const PROGMEM char resp200Txt[] = {"HTTP/1.0 200 OK\n\rContent-Type: text/html\n\rPragma: no-cache\n\r\n\r"};

//sensor start

int DustSensePin = 13;

//copy and paste for 50 zeros
//this should probably not be global...
//Int means max 65535 or so. May need to move to long
//making this too high runs into memory problems
//This resolution will be relatively good enough for now.

//If we need more space, then store only the first value in an unsigned int or long, then
//bit shift it down to reduce size, and store in array in a lower size var.
unsigned int reading[30] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
unsigned long sampletime_ms = 60000;//sample 30s ;
unsigned long starttime = 0;
unsigned char x = 0;
unsigned char toplimit = 0;
unsigned long sum = 0; //highest number possible - 32 bit unsigned, so 4 billion
unsigned int average = 0;
unsigned int sumcutdown = 0;


void setup() 
{
  Serial.println(F("Setup begin"));
#if (ESP8266)
    Serial.begin(115200);
    pinMode(5,OUTPUT);	//--- ? -- SS pin must be output # by Renato Aloi
#else
    Serial.begin(9600);
    pinMode(8,OUTPUT);	//--- ? -- SS pin must be output # by Renato Aloi
#endif

  eElib.begin(ipaddr,macaddr);
  Serial.println(F("------ program start -----------"));
  //Serial.println(F("NO SDCARD version")); // by Renato Aloi
  
  pinMode(DustSensePin,INPUT);
    starttime = millis();//get the current time;
}

void loop() {
  
    reading[x] = pulseIn(DustSensePin, LOW, 500000);
    
    
    //Print out readings on serial, as they come
    if (reading[x] != 0){
        Serial.println(reading[x]);
        x=x+1;
          if(x>50){
            x = 0;
          }
      }
      
      
      
       if ((millis()-starttime) > sampletime_ms){
        //reset these, no need to display on webpage anymore
        sum = 0;
        average = 0;
      
      
        toplimit = x; // don't read the zeros
      
     /* 
      if(toplimit == 0){
      toplimit = 1; //to avoid divide by zero, in case sum / toplimit is both zero
      }
      */
      for (x=0; x<toplimit; x++){
        sum = sum + reading[x];
        
      }
      average = sum / toplimit;
      //see work docs. Bit shift to allow for lower resolution for built in print functions.
      //outputting an int - 16 bit, but we originally have a 32 bit)
      sumcutdown = sum >> 4;
      //Serial.print("Average Get!:  ");
      //Serial.println(average); //average when 0 is 65535, so it's invalid (dividing by zero  - sum divided by top limit which are both zero)
                                 //but we don't even want the average. It's just for testing here.
      Serial.print("Sum Get!:  ");
      Serial.println(sum); //this is what we care about
      Serial.print("Sumcutdown Get!:  ");
      Serial.println(sumcutdown); //bit shifted
      
      //reset everything that can be reset after a minute
      
      x = 0;
      toplimit = 0;
      for (x=0; x<toplimit; x++){
        reading[x] = 0;
      }
      starttime = millis();
    }
    
  if ( eElib.available() ) 
  {
    Serial.println(eElib.getParams());
    eElib.print((char *)&resp200Txt[0],strlen_P(&resp200Txt[0]));
    if (eElib.isIndexHtml)
    {
      eElib.print("<pre><H1>Hello World!</H1>");
      //eElib.print("<form method=POST>");
      eElib.print("<br>");
      eElib.print("The Sum is: ");
     
      eElib.print((unsigned)sumcutdown);
      //eElib.print("</form></body>");
      eElib.print("</pre>");
    }
    /*
    else if (eElib.isPost)
    {
      eElib.print("<HTML><body><H1>POST Params: ");
      eElib.print(eElib.getParams());
      eElib.print("</H1></body>");
      eElib.print("</HTML>");
    }
    else if (eElib.isGet)
    {
      eElib.print("<HTML><body><H1>GET Params: ");
      eElib.print(eElib.getParams());
      eElib.print("</H1></body>");
      eElib.print("</HTML>");
    }*/
    eElib.close();
  }
}


//unused
/*
int ipow(int base, int exp)
{
    int result = 1;
    for (;;)
    {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        if (!exp)
            break;
        base *= base;
    }

    return result;
}*/
