////////////////////////////////////////////////////////////////////////////////
// Official name:     IotParty                                                //
// Hardware platform: Internet of Things domotica                             //
// Pin connections:   Arduino Mega 2560 + Wifi Shield ESP8266                 //
// Created:           April 2016                                              //
// Created by:        HARB rboek2@gmail.com                                   //
// http://robotigs.com/robotigs/includes/bots_header.php?idbot=9              //
// This program replies to a HTTP request made by PHP script on the webserver.//
// know if we have been activated.                                            //
////////////////////////////////////////////////////////////////////////////////
// FUSES (can always be altered by using the STK500)                          //
// On-Chip Debug Enabled: off                            (OCDEN=0)            //
// JTAG Interface Enabled: off                           (JTAGEN=0)           //
// Preserve EEPROM mem through the Chip Erase cycle: On  (EESAVE = 0)         //
// Boot Flash section = 2048 words, Boot startaddr=$3800 (BOOTSZ=00)          //
// Boot Reset vector Enabled, default address=$0000      (BOOTSTR=0)          //
// CKOPT fuse (operation dependent of CKSEL fuses        (CKOPT=0)            //
// Brown-out detection level at VCC=2,7V;                (BODLEVEL=1)         //
// Ext. Cr/Res High Freq.; Start-up time: 16K CK + 64 ms (CKSEL=1111 SUT=11)  //
// LOCKBITS (are dangerous to change, since they cannot be reset)             //
// Mode 1: No memory lock features enabled                                    //
// Application Protect Mode 1: No lock on SPM and LPM in Application Section  //
// Boot Loader Protect Mode 1: No lock on SPM and LPM in Boot Loader Section  //
////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1 Never use this memory location to be AVR compatible      //
////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS                                                            //
// Prog=List=Chip                                                             //
// A0  = 97 = PF0 ADC0             = LDR brick analog input               ADC //
// A1  = 96 = PF1 ADC1             =                                      ADC //
// A2  = 95 = PF2 ADC2             =                                      ADC //
// A3  = 94 = PF3 ADC3             =                                      ADC //
// A4  = 93 = PF4 ADC4/TMK         =                                      ADC //
// A14 = 83 = PK6 ADC14/PCINT22    =                                      ADC //
// A15 = 82 = PK7 ADC15/PCINT23    =                                      ADC //
// 0   =  2 = PE0 RXD0/PCINT8      = Serial monitor, also on-board LED    RX0 //
// 1   =  3 = PE1 TXD0             = Serial monitor, also on-board LED    TX0 //
// 2   =  6 = PE4 OC3B/INT4        = Temperature Humidity Brick input     INT //
// 3   =  7 = PE5 OC3C/INT5        = LED Blue, 2 color LED                INT //
// 4   =  1 = PG5 OCOB             = LED Green, 2 color LED               PWM //
// 5   =  5 = PE3 OC3A/AIN1        = PIR movement sensor, pref interrupt  PWM //
// //Relais 220Vav, digi output 6 to us
// 12  = 25 = PB6 OC1B/PCINT6      =                                      PWM //
// 13  = 26 = PB7 OCOA/OC1C/PCINT7 = On board user LED, on=high off=low   PWM //
// 18  = 46 = PD2 TXD1/INT3        =                                      TX1 //
// 19  = 45 = PD2 RXD1/INT2        =                                      RX1 //
// 20  = 44 = PD1 SDA/INT1         =                                      TWI //
// 21  = 43 = PD0 SCL/INT0         =                                      TWI //
// 44  = 40 = PL5 OC5C             =                                      PWM //
// 45  = 39 = PL4 OC5B             =                                      PWM //
// 46  = 38 = PL3 OC5A             =                                      PWM //
// 50  = 22 = PB3 MISO/PCINT3      =                                      SPI //
// 51  = 21 = PB2 MOSI/PCINT2      =                                      SPI //
// 52  = 20 = PB1 SCK/PCINT1       =                                      SPI //
// 53  = 19 = PB1 SS/PCINT0        =                                      SPI //
////////////////////////////////////////////////////////////////////////////////

// SET PRECOMPILER OPTIONS *****************************************************

// Initialse conditional compiling, uncomment to include, comment to exclude ---
// #define RS232 1                 //Include RS232 sections to output debug info
//  #ifdef RS232       //Only include this part if the variable has been defined

// Define precompiler variables ------------------------------------------------
#define LDR   PF0                     //LDR brick connection, ADC input A0 to us
#define DHTPIN 2               //Temperature Humidity Brick,  digi input 2 to us
#define DHTTYPE DHT11              //DHT 11 Uncomment whatever type you're using
#define LEB    3                     //Blue LED (3), pin will be output pref PWM
#define LEG    4                    //Green LED (4), pin will be output pref PWM
#define PIR    5             //PIR Movement brick connection, digi input 5 to us
#define REL    6                            //Relais 220Vav, digi output 6 to us
#define LED   PB7            //Arduino MEGA onboard LED (13), pin will be output

///Define the needed header files for the precompiler, no charge if not used ---
#include <DHT.h>        //Needed for Temperature Moisture Brick, lib by Adafruit
//#include <IRremote.h>     //Do never use the default by the IDE but replace it
//#include <AFMotor.h>  //Motors shield, Copyright Adafruit Industries LLC, 2009
//#include <TimerOne.h>    //Currently needed for reading wheel speed per second

//DEFINE CONSTANTS AND VARIABLES -----------------------------------------------
//const unsigned int LED = 13;
/*-----( Declare Variables )-----*/
unsigned int ldr1Val  =  0;                    //Last measured LDR readout value
unsigned int tmp1Val  =  0;            //Last measured Temperature readout value
unsigned int hum1Val  =  0;               //Last measured Humidity readout value
unsigned int pir1Val  =  0;               //Last measured Movement readout value
String       inStr1   = "";                //Reads the HTTP request line by line
String       inStr2   = "";                //Reads the HTTP request line by line
String       inStr3   = "";                //Reads the HTTP request line by line
//unsigned int Cntr1    =  0;                                 //For use anywhere
//unsigned int inByte   =  0;                         //For incoming serial data
//END OF PRECOMPILER OPTIONS ---------------------------------------------------

DHT dht(DHTPIN, DHTTYPE);                    //Initialize THB sensor, type DHT11

void setup() { //Setup runs once ***********************************************
  Serial.begin(9600);   //Nothing more needed for the Serial Monitor to function
  dht.begin();
  DDRB |= (1 << LED);                            //Set onboard LED-pin as output
  PORTB |= (1 << LED);                               //Initally onboard LED = on
  pinMode(LEB, OUTPUT);                    //Blue LED set as output. 2 color LED
  pinMode(LEG, OUTPUT);                   //Green LED set as output. 2 color LED
  pinMode(REL, OUTPUT);                    //Relais set as output. 220Vac switch
} //--(End of setup )-----------------------------------------------------------


void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************

  //REFRESH SENSOR READINGS ****************************************************
  ldr1Val = analogRead(LDR);                          //Refresh LDR sensor value
  pir1Val = digitalRead(PIR);                         //Refresh PIR sensor value
  unsigned int hum1Val = dht.readHumidity();   //Refresh air Humidity value SLOW
  unsigned int tmp1Val = dht.readTemperature();    //Read temperature as Celsius
  // Check if any reads failed and exit early (to try again).
  if (isnan(hum1Val) || isnan(tmp1Val)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  // Compute heat index in Fahrenheit (the default)
  //float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  //float hic = dht.computeHeatIndex(tmp1Val, hum1Val, false);

  //CHECK IF WE RECEIVE A HTTP REQUEST *****************************************
  if (Serial.available() > 0) {           //Send data only when you receive data
    String inStr1 = "";                                   //Reset receive string
    inStr1 = String(inStr1 + Serial.readStringUntil(10));   //Read incoming line
    String inStr2 = "";                                   //Reset receive string
    inStr2 = String(inStr2 + Serial.readStringUntil(10));   //Read incoming line
    String inStr3 = "";                                   //Reset receive string
    inStr3 = String(inStr3 + Serial.readStringUntil(10));       //The terminator
    Serial.println("HTTP/1.1 200 OK");                   //Answer to the request
    Serial.println("Connection: close");
    Serial.print("<html>");
    Serial.print("ldr1=");
    Serial.print(ldr1Val);
    Serial.print("&tmp1=");
    Serial.print(tmp1Val);
    Serial.print("&hum1=");
    Serial.print(hum1Val);
    Serial.print("&pir1=");
    Serial.print(pir1Val);
    Serial.print("&li1=0&pr=1");
    Serial.println("</html>");
    Serial.println(inStr3);        //Important copy of finished response symbols
  } //End of if (Serial.available() > 0) //HTTP REQUEST RESPONDED --------------


  if (pir1Val == 1) {                     //Meaning a movement has been detected
    digitalWrite(LEB, LOW);
    digitalWrite(LEG, HIGH);
    digitalWrite(REL, LOW);
  } else {
    digitalWrite(LEB, HIGH);
    digitalWrite(LEG, LOW);
    digitalWrite(REL, HIGH);
  } //End of if (pir1Val = HIGH)
} //End of void loop()                       //KEEP ON RUNNING THIS LOOP FOREVER
//345678911234567892123456789312345678941234567895123456789612345678971234567898