#include <SD.h>
#include <Wire.h>
#include "BMP085.h"
#include "DHT.h"
#include "TSL2561.h"
#include "Chronodot.h"

#define TIMING  1000 // milliseconds
#define DHTPIN  2
#define DHTTYPE DHT22
#define SDPIN   4

BMP085  bmp;
DHT     dht(DHTPIN, DHTTYPE);
TSL2561 tsl(TSL2561_ADDR_FLOAT);
Chronodot chronodot;
File    file;

void setup() {
    Serial.begin(9600);
    pinMode(5, OUTPUT);

    //----- SD Card
    Serial.println("INIT SD Card");

    if (!SD.begin(4)) {
        Serial.println("FAILED");
        return;
     }
    Serial.println("DONE");

    //----- Sensors
    Serial.println("INIT Sensors");

    bmp.begin();
    dht.begin();
    tsl.begin();
    chronodot.begin();

    // You can change the gain on the fly, to adapt to brighter/dimmer light situations
    //tsl.setGain(TSL2561_GAIN_0X);         // set no gain (for bright situtations)
    tsl.setGain(TSL2561_GAIN_16X);      // set 16x gain (for dim situations)

    // Changing the integration time gives you a longer time over which to sense light
    // longer timelines are slower, but are good in very low light situtations!
    tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS);  // shortest integration time (bright light)
    //tsl.setTiming(TSL2561_INTEGRATIONTIME_101MS);  // medium integration time (medium light)
    //tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS);  // longest integration time (dim light)

    if (!SD.exists("data.tsv")) {
        file = SD.open("data.tsv", FILE_WRITE);

        if (file) {
            Serial.print("Creating data.tsv");
            file.println("#Time\t\tT [°C]\tP [Pa]\tAlt [m]\tHr [%]\tLx [lux]");
            file.close();
            Serial.println("DONE");
        } else {
            Serial.println("Error opening data.tsv");
        }
    }
}

void loop() {
    float   temperature = bmp.readTemperature();
    int32_t pressure    = bmp.readPressure();
    float   altitude    = bmp.readAltitude();

    float humidity = dht.readHumidity();

    uint32_t lum = tsl.getFullLuminosity();
    uint16_t lightIr   = lum >> 16;
    uint16_t lightFull = lum & 0xFFFF;

    DateTime time = chronodot.now();

    file = SD.open("data.tsv", FILE_WRITE);

    if (file) {
        Serial.print("Writing to data.tsv...");
        file.print(time.year()); file.print("-"); file.print(time.month()); file.print("-"); file.print(time.day()); file.print(" "); file.print(time.hour()); file.print(":"); file.print(time.minute()); file.print(":"); file.print(time.second()); file.print("\t");
        file.print(temperature); file.print("\t");
        file.print(pressure); file.print("\t");
        file.print(altitude); file.print("\t");
        file.print(humidity); file.print("\t");
        file.println(tsl.calculateLux(lightFull, lightIr));
        file.close();
    Serial.println("DONE");
    } else {
        Serial.println("Error opening data.tsv");
    }
  
    delay(TIMING);
}
