/**
  ******************************************************************************
  * @file    VAPC-meter
  * @author  Vladimir N. Shilov <shilow@ukr.net>
  * @version V0.0.1
  * @date    2015.05.15
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * ----------------------------------------------------------------------------
  * "THE BEER-WARE LICENSE" (Revision 42):
  * <shilow@ukr.net> wrote this file.  As long as you retain this notice you
  * can do whatever you want with this stuff. If we meet some day, and you think
  * this stuff is worth it, you can buy me a beer in return.   Shilov V.N.
  * ----------------------------------------------------------------------------
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "stm8l15x.h"
#include "rtos.h"
#include "max7219.h"
#include "adc.h"

/** @addtogroup STM8L15x_StdPeriph_Template
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define LED_RED_PORT    GPIOC
#define LED_RED_PIN     GPIO_Pin_4
#define LED_GREEN_PORT  GPIOB
#define LED_GREEN_PIN   GPIO_Pin_7

/* Private macro -------------------------------------------------------------*/
#define LED_RED_ON      LED_RED_PORT->ODR &= (uint8_t)(~LED_RED_PIN)
#define LED_RED_OFF     LED_RED_PORT->ODR |= LED_RED_PIN
#define LED_GREEN_ON    LED_GREEN_PORT->ODR &= (uint8_t)(~LED_GREEN_PIN)
#define LED_GREEN_OFF   LED_GREEN_PORT->ODR |= LED_GREEN_PIN

/* Private constant ----------------------------------------------------------*/
// перевод числа 0-7 в номер индикатора
static const max7219_reg_t dig[8] = {
	Digit0,
	Digit1,
	Digit2,
	Digit3,
	Digit4,
	Digit5,
	Digit6,
	Digit7
};

// перевод значения 0x00 - 0x0F в код индикатора
static const max7219_sym_t num[16] = {
	Sym_0,
	Sym_1,
	Sym_2,
	Sym_3,
	Sym_4,
	Sym_5,
	Sym_6,
	Sym_7,
	Sym_8,
	Sym_9,
	Sym_A,
	Sym_b,
	Sym_C,
	Sym_d,
	Sym_E,
	Sym_F
};

/* Private variables ---------------------------------------------------------*/
uint16_t Voltage = 0;
uint16_t Current = 0;
uint16_t RefVolt = 0;

extern uint16_t VoltageFastBuffer[];
extern uint16_t CurrentFastBuffer[];
extern uint16_t RefVoltFastBuffer[];

/* Private function prototypes -----------------------------------------------*/
static void GPIO_Config(void);
static void CLK_Config(void);

/* RTOS function prototypes -----------------------------------------------*/
static void ShowTopLineV(void);
static void ShowTopLineC(void);
static void ShowBotLine(void);
static void ProcessFastBuffer(void);

/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
void main(void)
{
  /* Clock configuration -----------------------------------------*/
  CLK_Config();

  /* GPIO Configuration  -----------------------------------------*/
  GPIO_Config();

  /* RTOS Configuration */
  RTOS_Init();

   /* ADC Configuration and start */
  Init_ADC();

  /* MAX7219 Configuration */
  MAX7219_Init();

  /* ROTS tasks */
  RTOS_SetTask(ProcessFastBuffer,0,100);
  RTOS_SetTask(ShowTopLineV,101,4000);
  RTOS_SetTask(ShowTopLineC,2101,4000);
  RTOS_SetTask(ShowBotLine,101,100);

  /* Infinite loop */
  while (1)
  {
      RTOS_DispatchTask();
      Delay(1);
  }
}

/*
 * Фильтрация и усреднение данных из быстрого буфера,
 * вычесление значений, перенос в медленный буфер.
 */
static void ProcessFastBuffer(void){
    uint16_t volt=0, curr=0, ref=0;

    /* Summarize buffers values */
    uint8_t i;
    for(i=0;i<FAST_BUFFER_SIZE;i++){
        volt += VoltageFastBuffer[i];
        curr += CurrentFastBuffer[i];
        ref += RefVoltFastBuffer[i];
    }

    /* Calculate voltage value*/
    Voltage = ((volt / FAST_BUFFER_SIZE) * ADC_VOLT_RATIO) / 1000;

    /* Calculate current value*/
    Current = ((curr / FAST_BUFFER_SIZE) * ADC_RATIO) / 1000;

    /* Calculate reference voltage value*/
    RefVolt = ((ref / FAST_BUFFER_SIZE) * ADC_RATIO) / 1000;
}

/*
 * Output to top indicator line
 */
static void ShowTopLineV(void){
    uint8_t voltage1000 = 0;
    uint8_t voltage100 = 0;
    uint8_t voltage10 = 0;
    uint8_t voltage1 = 0;

    /* Thousands voltage value*/
    voltage1000 = (uint8_t)(Voltage / 1000);
    /* Hundreds voltage value */
    voltage100 = (uint8_t)((Voltage % 1000) / 100);
    /* Tens voltage value */
    voltage10 = (uint8_t)((Voltage % 100 ) / 10);
    /* Ones voltage value */
    voltage1 = (uint8_t)(Voltage % 10);

    LED_RED_ON;

    MAX7219_WriteData(dig[0], num[voltage1000]);
    MAX7219_WriteData(dig[1], num[voltage100]);
    MAX7219_WriteData(dig[2], num[voltage10]);
    MAX7219_WriteData(dig[3], num[voltage1]);
}

static void ShowTopLineC(void){
    LED_RED_OFF;
    uint8_t tmp = Current / 1000;
    MAX7219_WriteData(dig[0], num[tmp]);
    tmp = (Current % 1000) / 100;
    MAX7219_WriteData(dig[1], num[tmp]);
    tmp = (Current % 100) / 10;
    MAX7219_WriteData(dig[2], num[tmp]);
    tmp = Current % 10;
    MAX7219_WriteData(dig[3], num[tmp]);
}

/*
 * Output to bottom indicator line
 */
static void ShowBotLine(void){
    uint8_t voltage1000 = 0;
    uint8_t voltage100 = 0;
    uint8_t voltage10 = 0;
    uint8_t voltage1 = 0;

    /* Thousands voltage value*/
    voltage1000 = (uint8_t)(RefVolt / 1000);
    /* Hundreds voltage value */
    voltage100 = (uint8_t)((RefVolt % 1000) / 100);
    /* Tens voltage value */
    voltage10 = (uint8_t)((RefVolt % 100 ) / 10);
    /* Ones voltage value */
    voltage1 = (uint8_t)(RefVolt % 10);

    MAX7219_WriteData(dig[4], num[voltage1000]);
    MAX7219_WriteData(dig[5], num[voltage100]);
    MAX7219_WriteData(dig[6], num[voltage10]);
    MAX7219_WriteData(dig[7], num[voltage1]);
}


/**
  * @brief  Configure GPIO for button available on the VAPC board
  * @param  None
  * @retval None
  */
static void GPIO_Config(void)
{
  /* Configure GPIO used to drive LEDs */
  GPIO_Init(LED_RED_PORT, LED_RED_PIN, GPIO_Mode_Out_PP_High_Fast);
  GPIO_Init(LED_GREEN_PORT, LED_GREEN_PIN, GPIO_Mode_Out_PP_High_Fast);

  /* Enable general interrupts */
  enableInterrupts();
}

/**
  * @brief  Configure system clock to run at Maximum clock speed
  * @param  None
  * @retval None
  */
static void CLK_Config(void)
{
  CLK_DeInit();

  /* Configure the clock source */
  CLK_SYSCLKSourceConfig(CLK_SYSCLKSource_HSI);

  /* Configure the System clock frequency to run at 16Mhz */
  CLK_SYSCLKDivConfig(CLK_SYSCLKDiv_1);

  CLK_HSICmd(ENABLE);
}


#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
