/**
 * /TempLogger.cpp
 * @version 1.0
 * @desc Body file of the TempLogger class
 * @author Fándly Gergő Zoltán (fandlygergo@gmail.hu, systemtest.tk)
 * @copy 2018 Fándly Gergő Zoltán
 * License:
    Firmware for the Profile F1 fertilizer machine.
    Copyright (C) 2018  Fándly Gergő Zoltán

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 **/

#include "modules.h"

TempLogger::TempLogger(){
    init();
}

void TempLogger::run(){

}

float TempLogger::getMin(){
    float m=100;
    int c=getCount();
    for(int i=0; i<c; i++){
        float t=getTemp(i);
        if(t<m){
            m=t;
        }
    }
    return m;
}

float TempLogger::getMax(){
    float m=-100;
    int c=getCount();
    for(int i=0; i<c; i++){
        float t=getTemp(i);
        if(t>m){
            m=t;
        }
    }
    return m;
}

float TempLogger::getAvg(){
    float sum=0;
    int c=getCount();
    for(int i=0; i<c; i++){
        sum+=getTemp(i);
    }
    return sum/c;
}

byte TempLogger::getCount(){
    return memory.getTempCount();
}

float TempLogger::getTemp(byte n){
    return memory.getTemp(n);
}

float TempLogger::now(){
    //request temp read
    sensor.request(sensorAddress);

    //wait for temp read
    while(sensor.available());

    //return sensor reading
    return sensor.readTemperature(sensorAddress);
}

void TempLogger::init(){
    //init oneWire
    oneWire=oneWire(8);

    //search DS18B20 address
    oneWire.reset_search();
    while(oneWire.search(sensorAddress)){
        if(sensorAddress[0]!=0x28){
            continue;
        }

        if(OneWire::crc8(sensorAddress, 7) != sensorAddress[7]){
            Serial.println(F("E: 0x01 OneWire bus connection error."))
            break;
        }
    }

    Serial.print(F("I: 0x02 DS18B20 address found"));

    //init DS18B20
    sensor=DS18B20(&oneWire);
    sensor.begin();

    //request first temp read
    sensor.request(sensorAddress);

    //log first temperature to memory
    lastSave=-100;
    saveTemp();
}

void TempLogger::saveTemp(){

}
