// Temperature and Humidity Logging and Reporting
// Douglas E. Welch, douglas@welchwite.com, douglasewelch.com
// 20160425		Initial program and testing
// 20160428		Production Version 1.0

#include <SimpleDHT.h>
#include <FileIO.h>
#include <HttpClient.h>

int pinDHT11 = 2;
SimpleDHT11 dht11;

int  sensorPin  =  A0;
int  lightLevel =  0;  // variable to  store  the value  coming  from  the sensor

void setup() {
  Serial.begin(9600);
  Bridge.begin();
  FileSystem.begin();
}

void loop() {

  // Get Date and Time from Yun Linux Side
  String dataString;
  dataString += getTimeStamp();
  //dataString += " = ";
  
  // read with raw Temperature and Humidity data.
  byte temperature = 0;
  byte humidity = 0;
  byte data[40] = {0};
  if (dht11.read(pinDHT11, &temperature, &humidity, data)) {
    Serial.print("Read DHT11 failed");
    return;
  }
 
 // Read Light Level Data from Photoresistor
 lightLevel =  analogRead(sensorPin);
 // Convert to 100 point low to high scale
 lightLevel = map(lightLevel, 0, 1023, 100, 0);
 
 // Print Temperature and Humidity
 
 /* Serial.print(dataString);Serial.print(",");
 Serial.print(temperature);  Serial.print(",");
 Serial.print((double)(temperature*9.0)/5.0+32);Serial.print(",");
 Serial.print((int)humidity);
 Serial.print("\n"); */
 
 // Build file logger string
 String logdata = dataString + "," + temperature + "," + humidity + "," + lightLevel;
 
 // Build web update string for IFTTT trigger 
 String web_update = "http://maker.ifttt.com/trigger/weather/with/key/eVfFZ2i4T74yVc925gXKxazLr7_Gmzj8GE9gMWRNjdX";
 web_update = web_update + "?value1=" + temperature + "&value2=" + humidity + "&value3=" + lightLevel;
 
 // Serial.print(logdata + "\n");
 // Serial.print(web_update + "\n");
 
 // Write to SD Card
 File dataFile = FileSystem.open("/mnt/sda1/weather/weather.txt", FILE_APPEND);
 
 if (dataFile) {
    dataFile.println(logdata);
    dataFile.close();
  }
 
 else {
    Serial.println("error opening weather.txt");
  } 
  
// Get data every 5 minutes (300k millis)
  delay(300000);

// Update Google SpreadSheet
  HttpClient client;

  // Make a HTTP request:
  client.get(web_update);

  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  Serial.print("\n");
  Serial.flush();
  
// DHT11 sampling rate is 1HZ.
//  delay(1000);
}

// *********** FUNCTIONS ************
// Functon to get Time Stamp from Yun Linux Side
String getTimeStamp() {
  String result;
  Process time;
  time.begin("date");
  //time.addParameter("+%D-%T");  
  time.run(); 

  while(time.available()>0) {
    char c = time.read();
    if(c != '\n')
      result += c;
  }

  return result;

}