#include <VirtualWire.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>

//   Connections Light sensor
//   ===========
//   Connect SCL to analog 5
//   Connect SDA to analog 4
//   Connect VDD to 3.3V DC
//   Connect GROUND to common ground

// The RFID module's TX pin needs to be connected to the Arduino. 

 #define rxPin 4 
 #define txPin 1 
 
// Create a software serial object for the connection to the RFID module
SoftwareSerial rfid = SoftwareSerial( rxPin, txPin );
// Create a software serial object for the connection to the light sensor
Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);

String allowedTags[] = { // The code for the RFID tags
  "a8006bbcadd2",
  "a8006d81185c",
  "86000e55f32e",
  "86006c23eb22",
}


// List of names to associate with the matching tag IDs
String tagName[] = {
  "Winter",
  "Spring",
  "Summer",
  "Fall",
  
};

//Initial state for the RFID redader
int season=-1;
int newSeason=-1;
int tempSeason = 5;

const int led_pin = 13;
const int transmit_pin = 12;
const int receive_pin = 11;

void setup()
{
    Serial.begin(9600); // connect to the serial port
    
    delay(2000);
    rfid.begin(9600);     // Serial port for connection to RFID module
    
    Serial.println("RFID Reader Initialized");
    
    delay(1000);
    
    if(!tsl.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!");
    while(1);
  }
  else{
    Serial.println("Light sensor Initialized");
    }
    
    //Setup Light sensor
    tsl.enableAutoRange(true);            /* Auto-gain ... switches automatically between 1x and 16x */
    tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS);      /* fast but low resolution */
  

    delay(1000);
    
    vw_set_tx_pin(transmit_pin);
    vw_set_rx_pin(receive_pin);
    vw_setup(2000);       // Bits per sec
    pinMode(led_pin, OUTPUT);
    
    Serial.println("433mHZ Initialized");
}

void loop()
{
  //Setup for RFID
  byte i         = 0;
  byte val       = 0;
  byte checksum  = 0;
  byte bytesRead = 0;
  byte tempByte  = 0;
  byte tagBytes[6];    // "Unique" tags are only 5 bytes but we need an extra byte for the checksum
  char tagValue[10];
  String ourValues;
  
  // Get a new sensor event
  sensors_event_t event;
  tsl.getEvent(&event);
  
  if (event.light > 200)
  {
    Serial.print(event.light); Serial.println(" lux. Lights on");
    if (tempSeason == 5){
      tempSeason = season;
      newSeason = 4;
    }
  }
  else if (event.light <= 200)
  {
    Serial.print(event.light); Serial.println(" lux. Lights off. Starting stars");
    if (tempSeason != 5){
      newSeason = tempSeason;
      season = 5;
      tempSeason = 5;
      }
  
  
  if((val = rfid.read()) == 2) {        // Check for header
    bytesRead = 0;
    while (bytesRead < 12) {            // Read 10 digit code + 2 digit checksum
      val = rfid.read();
      Serial.println(1);
      // Append the first 10 bytes (0 to 9) to the raw tag value
      if (bytesRead < 10)
      {
        tagValue[bytesRead] = val;
      }

      // Check if this is a header or stop byte before the 10 digit reading is complete
      if((val == 0x0D)||(val == 0x0A)||(val == 0x03)||(val == 0x02)||(val == 0x01)||(val == 0x04)||(val == 0x05)||(val == 0x06)||(val == 0x07)||(val == 0x08)||(val == 0x09)||(val == 0x0B)||(val == 0x0C)||(val == 0x0E)||(val == 0x0F)) {
        break;                          // Stop reading
      }

      // Ascii/Hex conversion:
      if ((val >= '0') && (val <= '9')) {
        val = val - '0';
      }
      else if ((val >= 'A') && (val <= 'F')) {
        val = 10 + val - 'A';
      }

      ourValues = ourValues + String(val, HEX);
      Serial.println(); //do NOT delete this line!
      
      // Every two hex-digits, add a byte to the code:
      if (bytesRead & 1 == 1) {
        // Make space for this hex-digit by shifting the previous digit 4 bits to the left
        tagBytes[bytesRead >> 1] = (val | (tempByte << 4));

        if (bytesRead >> 1 != 5) {                // If we're at the checksum byte,
          checksum ^= tagBytes[bytesRead >> 1];   // Calculate the checksum... (XOR)
        };
      } else {
        tempByte = val;                           // Store the first hex digit first
      };

      bytesRead++;                                // Ready to read next digit
    }

    for (int i=0; i<4; i++) {
      if (ourValues == allowedTags[i]) {
        //Serial.print(tagName[i]);
        newSeason = i;
        //Serial.println('season: ' + newSeason);
        break;
      }
    }

    bytesRead = 0;
    if (season != newSeason){
      season = newSeason;
    }

  }


  }
  else
  {
    /* If event.light = 0 lux the sensor is probably saturated
       and no reliable data could be generated! */
    Serial.println("Sensor overload");
  }
  


  
    //code for sending the right message to the wall
    char msg = 5;
  switch (newSeason) {
     case 0: msg = 0; Serial.println(0); break;
     case 1: msg = 1;  Serial.println(1);break;
     case 2: msg = 2;  Serial.println(2); break;
     case 3: msg = 3;  Serial.println(3);break;
     case 4: msg = 4;  Serial.println(4);break; 
      
  }

  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  vw_send((uint8_t *)msg, 1);
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  delay(250);
}
