
#define BUFFER_SIZE 64
char inData[BUFFER_SIZE]; // reading xbee values
int i;  // index for reading
/* ------------------------------------- XBee ------------------------------------- */
#include <SoftwareSerial.h>
SoftwareSerial XBSerial(A3, A4); // A3 to RX | A4 to TX
/* ------------------------------------- Sensor ------------------------------------- */
#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
/* ------------------------------------- LCD ------------------------------------- */
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println(F("DHTxx test!"));
  XBSerial.begin(9600);  // HC-05 default speed in AT command more
  /* LCD */
  lcd.begin(16, 2);
  lcd.print("Starting Process");
  dht.begin();

}

void loop() {
  i=0; // initialize
  
  float h = dht.readHumidity();
  // Temperature as Celsius (default)
  float t = dht.readTemperature();
  // Temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  while(XBSerial.available()>0){
    inData[i] = XBSerial.read();
    //Serial.write(inData[i]);
    i++;
  }
  
  String inDataString = String(inData);
  Serial.println(inDataString);
  if (inDataString.indexOf("CMD_TMP")>-1){
    String tString = String(t);
    XBSerial.write("OK");
    XBSerial.print(t);
    Serial.println("Asked for temperature");
  }
  else if (inDataString.indexOf("CMD_HMD")>-1){
    XBSerial.write(h);
    Serial.println("Asked for humidity");
  }
  else {
    XBSerial.write("NO");
    //Serial.println("Asked for nothing");
  }
  inDataString = "";
  delay(2500);
  // LCD
  lcd.setCursor(0, 0);
  //***********//
  lcd.setCursor(0, 0);
  lcd.print("                ");
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.setCursor(0, 1);
  lcd.print("                ");
  lcd.setCursor(0, 1);
  lcd.print(t);
  delay(100);
  lcd.setCursor(0, 0);
  lcd.print("                 ");
  lcd.setCursor(0, 0);
  lcd.print("Humidity:");
  lcd.setCursor(0, 1);
  lcd.print("                 ");
  lcd.setCursor(0, 1);
  lcd.print(h);


  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);
  /*Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));*/
}
