/*
 * AMS_HighLevel.c
 *
 *  Created on: 20.07.2022
 *      Author: max
 */

#include "AMS_HighLevel.h"
#include "ADBMS_Abstraction.h"
#include "TMP1075.h"
#include "24LC02.h"
#include "stm32f3xx_hal.h"
#include <stdint.h>
#include <string.h>

Cell_Module module = {};

uint16_t amsuv = 0;
uint16_t amsov = 0;

uint8_t numberofCells = 15;
uint8_t numberofAux = 0;

uint8_t packetChecksumFails = 0;
#define MAX_PACKET_CHECKSUM_FAILS 5

uint8_t deviceSleeps = 0;
#define MAX_DEVICE_SLEEP 3 //TODO: change to correct value

struct pollingTimes {
  uint32_t S_ADC_OW_CHECK;
  uint32_t TMP1075;
};

struct pollingTimes pollingTimes = {0, 0};

uint8_t AMS_Init(SPI_HandleTypeDef* hspi) {
  uint8_t ret = initAMS(hspi, numberofCells, numberofAux);
  amsov = DEFAULT_OV;
  amsuv = DEFAULT_UV;

  pollingTimes = (struct pollingTimes) {HAL_GetTick(), HAL_GetTick()};

  return ret;
}

uint8_t AMS_Idle_Loop() {
  if (!amsWakeUp()) {
    //error_data.data_kind = SEK_INTERNAL_BMS_TIMEOUT; //we don't receive data for the wakeup command
    //set_error_source(ERROR_SOURCE_INTERNAL);         //so we can't tell if we timed out
  }
  
  packetChecksumFails += amsAuxAndStatusMeasurement(&module);

  if (module.status.SLEEP) {
    deviceSleeps++;
    if (deviceSleeps > MAX_DEVICE_SLEEP) {

    } else {
      amsReset();
    }
  }

  packetChecksumFails += amsCellMeasurement(&module);
  packetChecksumFails += amsCheckUnderOverVoltage(&module);

  if(eeprom_write(0, 7) != 0){
    while(1){}
  }
  int eepromBuf;
  if(eeprom_read(0, &eepromBuf) != 0){
    while(1){}
  }

  if (eepromBuf != 7){
    while(1){}
  }

  return 0;
}