//Gammeldam Stoker Control

// HUSK!! LINJE 42-235 FRA SOMMER TIL VINTER!!!


#include <stdarg.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <NewPing.h>
#include "rgb_lcd.h"
#include <Wire.h>
#include "RTClib.h"
#include "TimerOne.h"

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>

//Ethernet
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,0,177);
// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);

File dataFile;

//RTC
RTC_DS1307 RTC;

//LCD
rgb_lcd lcd;


// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 22
#define TEMPERATURE_PRECISION 9
 
//HC-SR04
#define TRIGGER_PIN  27 
#define ECHO_PIN     26 
#define MAX_DISTANCE 100
#define kedel_Low 45 //Sommer =10 Vinter =45
int led = 29;
int ledy = 28;
void setRGB (int r,int g, int b);

 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
 
//Hall_sensor
const int  buttonPin = 30;    // the pin that the pushbutton is attached to
 
// Variables will change:
int buttonPushCounter120min = 0;   // counter for the impulses during 15min NYE
int buttonPushPulsesIn1Hour = 0;   // The calculated result for 1 hour (not sure if it should be int or long) NYE

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

int logCompare = 0;
int logInterval = 15; //Minutes

int displayCompare = 0;
int displayInterval = 3; //Seconds
int displayState = 0;

int sd_write_count = 0;
 
// US sensor
unsigned int uS;
 
//DS18B20
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
 
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
 
// arrays to hold device addresses
DeviceAddress udeTemp, indeTemp, kedelTemp, returTemp, varmvandsTemp;
 
//const int chipSelect = 4;

void setup(void)
{
    
  pinMode(led, OUTPUT);
  pinMode(ledy, OUTPUT);
  
  // start serial port
  Serial.begin(9600);
  
  //RTC
  Wire.begin();
  RTC.begin();
  
 // Serial.println("Dallas Temperature IC Control Library Demo");
 
  // Start up the library
  sensors.begin();
 
  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(sensors.getDeviceCount(), DEC);
  Serial.println(" devices.");
  
  if (! RTC.isrunning()) {
  Serial.println("RTC is NOT running!");
  // following line sets the RTC to the date & time this sketch was compiled
  // uncomment it & upload to set the time, date and start run the RTC!
  RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  
  //DS18B20
  // method 1: by index
  if (!sensors.getAddress(udeTemp, 1)) Serial.println("Unable to find address for Device 0");
   
  if (!sensors.getAddress(indeTemp, 2)) Serial.println("Unable to find address for Device 2");
  
  if (!sensors.getAddress(kedelTemp, 0)) Serial.println("Unable to find address for Device 0");
   
  if (!sensors.getAddress(returTemp, 4)) Serial.println("Unable to find address for Device 3");
  
  if (!sensors.getAddress(varmvandsTemp, 3)) Serial.println("Unable to find address for Device 4");
 
 
  // set the resolution to 9 bit
  sensors.setResolution(udeTemp, TEMPERATURE_PRECISION);
  sensors.setResolution(indeTemp, TEMPERATURE_PRECISION);
  sensors.setResolution(kedelTemp, TEMPERATURE_PRECISION);
  sensors.setResolution(returTemp, TEMPERATURE_PRECISION);
  sensors.setResolution(varmvandsTemp, TEMPERATURE_PRECISION);
   
   
 
  Serial.print("Device 1 Resolution: ");
  Serial.print(sensors.getResolution(udeTemp), DEC);
  Serial.println();
 
  Serial.print("Device 2 Resolution: ");
  Serial.print(sensors.getResolution(indeTemp), DEC);
  Serial.println();
   
  Serial.print("Device 0 Resolution: ");
  Serial.print(sensors.getResolution(kedelTemp), DEC);
  Serial.println();
 
  Serial.print("Device 4 Resolution: ");
  Serial.print(sensors.getResolution(returTemp), DEC);
  Serial.println();
   
  Serial.print("Device 3 Resolution: ");
  Serial.print(sensors.getResolution(varmvandsTemp), DEC);
  Serial.println();
  
  //Hall_sensor 
  Timer1.initialize(10000);         // initialize timer1, and set a 10ms second period   
  Timer1.attachInterrupt(my_loop);  // attaches my_loop() as a timer overflow interrupt
  
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  //pinMode(53, OUTPUT);
  
  // see if the card is present and can be initialized:
  if (!SD.begin(4)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    //return;
  } else {
  Serial.println("card initialized.");
  
  //Reset
  dataFile = SD.open("datalog.csv", FILE_WRITE);
  dataFile.print("RESET");
  dataFile.println();
  dataFile.close();
  dataFile = SD.open("datalog1.csv", FILE_WRITE);
  dataFile.print("RESET");
  dataFile.println();
  dataFile.close();
  dataFile = SD.open("Alarmer.txt", FILE_WRITE);
  dataFile.print("RESET");
  dataFile.println();
  dataFile.close();
  };

}
 
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
   Serial.print(deviceAddress[i], HEX);
  }
}
 
void my_loop()
{
  // this is called every 10ms. Keep it as short as possible. Do not use delay() inside !!
  // Hall sensor
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
       buttonPushCounter++;
       buttonPushCounter120min++; // count the pulses for the next 15min NYE
    }
  }
   
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;
   
}
 
void loop(void)
{
  
  char date[11];
  char time[9];
  int pillebeholdning;
  int pillebeholdning_min = 25; //Sommer =10 Vinter =25 
  
  DateTime now = RTC.now();
  
  sprintf(date, "%02d-%02d-%04d", now.day(), now.month(), now.year());
  sprintf(time, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
  
  sensors.requestTemperatures();
  if (sensors.getTempC(kedelTemp)<= kedel_Low) {
    digitalWrite(led, HIGH);
    lcd.setRGB(255, 0, 0);//red,green,blue
    lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("<<ALARM>>");
        lcd.setCursor(0,1);
        lcd.print("<Kedeltemp LOW>");
        dataFile = SD.open("Alarmer.txt", FILE_WRITE);
        dataFile.print(date);
        dataFile.print(',');
        dataFile.print(time);
        dataFile.print(',');//fra ; til ,
        dataFile.print("Kedel temperatur LOW");
        dataFile.println();
      dataFile.close();
    delay(500);
  } else { 
    digitalWrite(led, LOW);
    lcd.setRGB(0, 0, 50);//red,green,blue
  }
  
  //HC-SR04
  delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  pillebeholdning = 100-sonar.ping()/US_ROUNDTRIP_CM;
  if (pillebeholdning <= pillebeholdning_min) {
    digitalWrite(ledy, HIGH);
    lcd.setRGB(0, 255, 0);//red,green,blue
    lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("<<ALARM>>");
        lcd.setCursor(0,1);
        lcd.print("pillebeholdning");
        lcd.setCursor(0,1);
        dataFile = SD.open("Alarmer.txt", FILE_WRITE);
        dataFile.print(date);
        dataFile.print(',');
        dataFile.print(time);
        dataFile.print(',');//fra ; til ,
        dataFile.print("pillebeholdning LOW");
        dataFile.println();
      dataFile.close();
    delay(500);
  } else { 
    digitalWrite(ledy, LOW);
    lcd.setRGB(0, 0, 50);//red,green,blue
  }
  
  if (now.second()/displayInterval != displayCompare) {
      
    displayCompare = now.second()/displayInterval;
    
    switch (displayState) {
    
      case 1:
   
        Serial.print("Udetemp.: ");
        Serial.print(sensors.getTempC(udeTemp));
        Serial.println(" C");
        
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Udetemp.:");
        lcd.setCursor(0,1);
        lcd.print(sensors.getTempC(udeTemp));
        lcd.print(" C");
        
        displayState++;
        break;
      
      case 2:
       
        Serial.print("Indetemp.: ");
        Serial.print(sensors.getTempC(indeTemp));
        Serial.println(" C");
      
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Indetemp.:");
        lcd.setCursor(0,1);
        lcd.print(sensors.getTempC(indeTemp));
        lcd.print(" C");
        
        displayState++;
        break;
        
      case 3:
        
        Serial.print("Kedeltemp.: ");
        Serial.print(sensors.getTempC(kedelTemp));
        Serial.println(" C");
      
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Kedeltemp.:");
        lcd.setCursor(0,1);
        lcd.print(sensors.getTempC(kedelTemp));
        lcd.print(" C");
        
        displayState++;
        break;
        
      case 4:
    
        Serial.print("Returtemp.: ");
        Serial.print(sensors.getTempC(returTemp));
        Serial.println(" C");
        
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Returtemp.:");
        lcd.setCursor(0,1);
        lcd.print(sensors.getTempC(returTemp));
        lcd.print(" C");
        
        displayState++;
        break;
        
      case 5:
    
        Serial.print("Varmvandstemp.: ");
        Serial.print(sensors.getTempC(varmvandsTemp));
        Serial.println(" C");
        
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Varmvandstemp.:");
        lcd.setCursor(0,1);
        lcd.print(sensors.getTempC(varmvandsTemp));
        lcd.print(" C");
        
        displayState++;
        break;
     
      case 6:
      
//        Serial.print("Pillebeholdning: ");
//        Serial.print(pillebeholdning);
//        Serial.println("%");
        
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Pillebeholdning:");
        lcd.setCursor(0,1);
        lcd.print(pillebeholdning);
        lcd.print("%");
        
        displayState++;
        break;
        
      case 7:
    
        Serial.print("Pillesnegl: ");
        Serial.print(buttonPushCounter);
        Serial.println(" omg.");
        
        //lcd.begin(16, 2);
        //lcd.setRGB(0, 0, 50);//red,green,blue
        //lcd.clear();
        //lcd.setCursor(0,0);
        //lcd.print("Pillesnegl: ");
        //lcd.setCursor(0,1);
        //lcd.print(buttonPushCounter);
        //lcd.print(" omg.");
        
        //displayState++;
        //break;
        
      case 8:
     
        Serial.print("Pilleforbrug: ");
        Serial.print(buttonPushCounter*(0.03));
        Serial.println(" kg.");
        
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Pilleforbrug:");
        lcd.setCursor(0,1);
        lcd.print(buttonPushCounter*(0.03));
        lcd.print(" kg.");
        
        displayState++;
        break;
        
        
        case 9:
     
        Serial.print("Pilleforbrug: ");
        Serial.print(buttonPushPulsesIn1Hour);
        Serial.println("kg.i timen");
        
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Pilleforbrug:");
        lcd.setCursor(0,1);
        lcd.print(buttonPushPulsesIn1Hour);
        lcd.print("kg.i timen");
        
        displayState++;
        break;
        
        
     default:    
        
        Serial.println();
        Serial.println("**************************************");
        Serial.println("* Gammeldam Stoker Control vers. 2.0 *");
        Serial.println("* Created by Jonny Rethmeier         *");
        Serial.println("**************************************");
        Serial.println();
        Serial.print(date);
        Serial.print(" ");
        Serial.print(time);
        Serial.println();
    
        lcd.begin(16, 2);
        lcd.setRGB(0, 0, 50);//red,green,blue
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Gammeldam Stoker");
        lcd.setCursor(0,1);
        lcd.print(time);
        
        displayState = 1;
        
    }
    
  }

  //Web service
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
	  client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<body bgcolor=\"black\">");//nye
          client.print("<font color=\"grey\">");//nye
          client.println("<!DOCTYPE HTML>");
          client.println("<html><body><h1>Gammeldam Stoker Control vers. 2.0</h1>");
          
          //Dato and tid
          client.print("<p>");
          client.print(date);
          client.print(" ");
          client.print(time);
          client.println("</p>");
          
          //Udetemperatur
          
          client.print("<table border=\"1\"><tr><td><font color=\"white\">Udetemperatur: </td><td align=\"right\">");
          if (sensors.getTempC(udeTemp) > 0) {
            client.print("<font color=\"yellow\">");
          } else {
            client.print("<font color=\"red\">");
          }
          client.print(sensors.getTempC(udeTemp));
          client.println(" &deg;C</font></td></tr>");
          
          //Indetemperatur
          
          client.print("<tr><td><font color=\"white\">Indetemperatur: </td><td align=\"right\">");
          client.print("<font color=\"yellow\">");//nye
          client.print(sensors.getTempC(indeTemp));
          client.println(" &deg;C</td></tr>");
          
          //Kedeltemperatur
          client.print("<tr><td><font color=\"white\">Kedeltemperatur: </td><td align=\"right\">");
          if (digitalRead(led) == HIGH) {
            client.print("<font color=\"red\">");
          } else {
            client.print("<font color=\"yellow\">");
          }
          client.print(sensors.getTempC(kedelTemp));
          client.println(" &deg;C</font></td></tr>");
          
          //Returtemperatur
          client.print("<tr><td><font color=\"white\">Returtemperatur: </td><td align=\"right\">");
          client.print("<font color=\"yellow\">");
          client.print(sensors.getTempC(returTemp));
          client.println(" &deg;C</td></tr>");
          
          //Varmvandsemperatur
          client.print("<tr><td><font color=\"white\">Varmtvandstemperatur: </td><td align=\"right\">");
          client.print("<font color=\"yellow\">");
          client.print(sensors.getTempC(varmvandsTemp));
          client.println(" &deg;C</td></tr>");
          
          //Pillebeholdning
          client.print("<tr><td><font color=\"white\">Pillebeholdning: </td><td align=\"right\">");
          if (digitalRead(ledy) == HIGH) {
            client.print("<font color=\"red\">");
          } else {
            client.print("<font color=\"yellow\">");
          }
          client.print(pillebeholdning);
          client.println("%</font></td></tr>");
          
          //Pillesnegl
          client.print("<tr><td><font color=\"white\">Pillesnegl: </td><td align=\"right\">");
          client.print("<font color=\"yellow\">");
          client.print(buttonPushCounter);
          client.println(" omg.</td></tr>");
          
          //Pilleforbrug
          client.print("<tr><td><font color=\"white\">Pilleforbrug: </td><td align=\"right\">");
          client.print("<font color=\"yellow\">");
          client.print(buttonPushCounter*(0.03));
          client.println(" kg</td></tr>");
          
          
          //Pilleforbrug pr.time
          client.print("<tr><td><font color=\"white\">Pilleforbrug: </td><td align=\"right\">");
          client.print("<font color=\"yellow\">");
          client.print(buttonPushPulsesIn1Hour*(0.03));
          client.println(" kg i timen</td></tr>");
          
          
          
          
          //Antal skrivning til SD-kort
          client.print("<tr><td><font color=\"white\">Antal skrivninger til SD-kort: </td><td align=\"right\">");
          client.print("<font color=\"yellow\">");
          client.print(sd_write_count);
          client.println("</td></tr>");
          client.print("<tr><td><font color=\"white\">Written by: Rethmeier: </td><td align=\"right\">");
          client.print(2015);
          client.println("</td></tr>");
          client.println("</table></body></html>");
          
          break;
          
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }

  //Write data to logfile.
  if (now.minute()/logInterval != logCompare) {
    
    logCompare = now.minute()/logInterval;
    
    buttonPushPulsesIn1Hour = buttonPushCounter120min/2; // Calculate the pulses for 60min = 1h NYE
    buttonPushCounter120min = 0; // reset the counter for the next 15min interval NYE
   
    dataFile = SD.open("datalog.csv", FILE_WRITE);
    
    if (dataFile) {
      
    //if (now.hour()/loglnInterval != loglnCompare) 
    //loglnCompare = now.hour()/loglnInterval;
    //dataFile.println();
     
      dataFile.print(date);
      dataFile.print(',');
      dataFile.print(time);
      dataFile.print(',');//fra ; til ,
      
      dataFile.print(sensors.getTempC(udeTemp));
      dataFile.print(',');
      
      dataFile.print(sensors.getTempC(indeTemp));
      dataFile.print(',');
      
      dataFile.print(sensors.getTempC(kedelTemp));
      dataFile.print(',');
      
      dataFile.print(sensors.getTempC(returTemp));
      dataFile.print(',');
      
      dataFile.print(sensors.getTempC(varmvandsTemp));
      dataFile.print(',');
      
      dataFile.println();
      dataFile.close();
      
      dataFile = SD.open("datalog1.csv", FILE_WRITE);
      
      //if (now.hour()/loglnInterval != loglnCompare) 
      //loglnCompare = now.hour()/loglnInterval;
      //dataFile.println();
      
      
      dataFile.print(date);
      dataFile.print(',');
      dataFile.print(time);
      dataFile.print(',');//fra ; til ,
      
      dataFile.print(pillebeholdning);
      dataFile.print(',');
      
      dataFile.print(buttonPushCounter);
      dataFile.print(',');
      
      dataFile.print(buttonPushCounter*(0,03));
      dataFile.print(',');
      
      dataFile.println();
      dataFile.close();
      
      Serial.println("Data written to logfile.");
      sd_write_count = sd_write_count+1;
    
    } else {
      Serial.println("Could not write data to logfile.");
    }
    
  }
  
}


