const float BETA = 3950; // should match the Beta Coefficient of the thermistor
const long WATER = 6000; // Wassermenge für den Brühvorgang
const long PREBREW = 1000; //Wassermengen zum vorbrühen
const int PREBREWP = 2000; // warte 2 sek
const int MAXTEMP = 80; // Max Wassertemperatur

bool ISWATER = true;
bool HAL = false; //simulate HAL Sensor 

unsigned long PrevMillis = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Moin");
  pinMode(2, OUTPUT); // Heizung an
  pinMode(4, OUTPUT); // Pumpe an

  pinMode(6, INPUT_PULLUP); // Kaffee einschalten

  pinMode(12, INPUT_PULLUP); //Hall sensor Wasserstand

  digitalWrite(2, LOW);
  digitalWrite(4, LOW);
 
}

void loop() {
  // put your main code here, to run repeatedly:
  checkWater();

//    Serial.println(digitalRead(12));

  

  if (! ISWATER){
    blink();
  }

  
  if (digitalRead(6) == LOW && ISWATER)
    MakeCoffe();
  PrevMillis = 0;
}

void checkWater(){
  if (digitalRead(12) == LOW ){
    ISWATER = false;
  }else{
    ISWATER = true;
  }
}


void MakeCoffe()
{
 
  while (! temperature() && ISWATER){
    digitalWrite(2, HIGH);
  }

  digitalWrite(2, LOW);
  pumpe();
}

bool temperature (){
  int analogValue = analogRead(A0);
  float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
  if (celsius >= MAXTEMP)
    return true;
  else
    return false;
}

void pumpe(){
  //Serial.println("Pumpe");
  unsigned long t = millis();
  if (PrevMillis == 0){
    PrevMillis = t;
  }
  
  unsigned long time = WATER+PREBREWP;

  while (t - PrevMillis <= time ){
    checkWater();
    if (! ISWATER){
      delay(1000);
      time += 1000;
      blink();
      continue;
    }
      
    Serial.println("Pumpe: "+String(t- PrevMillis));
    if (t - PrevMillis == PREBREW ){
      Serial.println("Prebrew");
      delay(PREBREWP);
      }
    digitalWrite(4, HIGH);
    t = millis();
  }

  digitalWrite(4, LOW);
    
}

void blink(){
  digitalWrite(2, HIGH);
  delay(500);
  digitalWrite(2, LOW);
  delay(500);
}