/*
 * File:   ControlChargeTime.c
 * Author: hamilton
 *
 * Created on August 1, 2018, 11:46 AM
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "xc.h"
#include "math.h"
#include "UART.h"
#include "config.h"
#include "extern.h"
#include "conv.h"
#include "CalibrationConstants.h"
#include "libq.h"
#include "Maxon.h"

/*  Routine to Turn on and off Backup battery charger based on time */

/*  Based on timer_ctr that is incremented at the CAN packet rate, 
    the battery charger is turned on for an extended period of time at 
    powerup, and on a duty cycle thereafter.  CHARGETIME_ON_POWERUP, CHARGE_TIME,
 * and CHARGE_PERIOD in config.h specify these in minutes.
 
 */

void ControlChargeTimes() {

    static int first_time = 1;
    static unsigned long chargetime_on_powerup;
    static unsigned long charge_time;
    static unsigned long charge_period;

    static int  charger_on_voltage;
    static int  charger_off_voltage;


    if (first_time) {
        chargetime_on_powerup = CHARGETIME_ON_POWERUP * CAN_PACKET_RATE * 60;
        charge_time = CHARGE_TIME * CAN_PACKET_RATE * 60;
        charge_period = CHARGE_PERIOD * CAN_PACKET_RATE * 60;

        charger_on_voltage = ConvertEngUnitsToFract(CHARGER_ON_VOLTAGE, BattVoltage_cnt, BattVoltage_eng);
        charger_off_voltage = ConvertEngUnitsToFract(CHARGER_OFF_VOLTAGE, BattVoltage_cnt, BattVoltage_eng);

        first_time = 0;
    }

    switch (Status.bits.ChargeMode) {
        case CHARGE_ON:
            CHARGE_ENABLE = 1;
            Status.bits.ChargeEnabled = 1;
            break;
        case CHARGE_OFF:
            CHARGE_ENABLE = 0;
            Status.bits.ChargeEnabled = 0;
            break;
        case CHARGE_AUTO_TIME:

            if ((CAN_PacketSend_ctr < chargetime_on_powerup) || (CAN_PacketSend_ctr % charge_period < charge_time)) {
                CHARGE_ENABLE = 1;
                Status.bits.ChargeEnabled = 1;
            } else {
                CHARGE_ENABLE = 0;
                Status.bits.ChargeEnabled = 0;

            }
            break;
        case CHARGE_AUTO_VOLT:
            if(Status.bits.ChargeEnabled && (BattVoltage_Buf > charger_off_voltage)) {
                CHARGE_ENABLE = 0;
                Status.bits.ChargeEnabled = 0;
            }
            if(!Status.bits.ChargeEnabled && (BattVoltage_Buf < charger_on_voltage)) {
                CHARGE_ENABLE = 1;
                Status.bits.ChargeEnabled = 1;
            }
            break;
    }
    return;
}
