/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * File Name          : freertos.c
  * Description        : Code for freertos applications
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under Ultimate Liberty license
  * SLA0044, the "License"; You may not use this file except in compliance with
  * the License. You may obtain a copy of the License at:
  *                             www.st.com/SLA0044
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */     
#include "i2c.h"
#include "sai.h"
#include "a7131.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define BUFF_SIZE       1024
#define FRAME_SIZE      63
#define SAI_IN_SIZE     84
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */
uint8_t cmbBuff[BUFF_SIZE];
uint8_t audioBuff[BUFF_SIZE];
uint8_t txBuff[BUFF_SIZE];
__IO int16_t UpdatePointer = -1;
/* USER CODE END Variables */
osThreadId SPIHandle;
uint32_t SPIBuffer[ 128 ];
osStaticThreadDef_t SPIControlBlock;
osThreadId SAIHandle;
uint32_t SAIBuffer[ 128 ];
osStaticThreadDef_t SAIControlBlock;
osSemaphoreId txSemHandle;
osStaticSemaphoreDef_t txSemCBlock;

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */
void CS4265_init(void);
/* USER CODE END FunctionPrototypes */

void SPITask(void const * argument);
void SAITask(void const * argument);

void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */

/* GetIdleTaskMemory prototype (linked to static allocation support) */
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize );

/* USER CODE BEGIN GET_IDLE_TASK_MEMORY */
static StaticTask_t xIdleTaskTCBBuffer;
static StackType_t xIdleStack[configMINIMAL_STACK_SIZE];
  
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize )
{
  *ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer;
  *ppxIdleTaskStackBuffer = &xIdleStack[0];
  *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
  /* place for user code */
}                   
/* USER CODE END GET_IDLE_TASK_MEMORY */

/**
  * @brief  FreeRTOS initialization
  * @param  None
  * @retval None
  */
void MX_FREERTOS_Init(void) {
  /* USER CODE BEGIN Init */
       
  /* USER CODE END Init */

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* Create the semaphores(s) */
  /* definition and creation of txSem */
  osSemaphoreStaticDef(txSem, &txSemCBlock);
  txSemHandle = osSemaphoreCreate(osSemaphore(txSem), 1);

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  /* add semaphores, ... */
  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
  /* USER CODE END RTOS_TIMERS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  /* USER CODE END RTOS_QUEUES */

  /* Create the thread(s) */
  /* definition and creation of SPI */
  osThreadStaticDef(SPI, SPITask, osPriorityNormal, 0, 128, SPIBuffer, &SPIControlBlock);
  SPIHandle = osThreadCreate(osThread(SPI), NULL);

  /* definition and creation of SAI */
  osThreadStaticDef(SAI, SAITask, osPriorityNormal, 0, 128, SAIBuffer, &SAIControlBlock);
  SAIHandle = osThreadCreate(osThread(SAI), NULL);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

}

/* USER CODE BEGIN Header_SPITask */
/**
  * @brief  Function implementing the SPI thread.
  * @param  argument: Not used 
  * @retval None
  */
/* USER CODE END Header_SPITask */
void SPITask(void const * argument)
{
  /* USER CODE BEGIN SPITask */
  memset(cmbBuff,0x00,BUFF_SIZE);
  
  /* Infinite loop */
  printf("SPITask Loop \n");
  for(;;)
  {
    while(UpdatePointer==-1);

    int position = UpdatePointer;
    UpdatePointer = -1;

    memcpy(cmbBuff+position,audioBuff+position,SAI_IN_SIZE);
    if(UpdatePointer != -1)
    {
      //memory overlap handler
    }

    if(position==SAI_IN_SIZE)
    {
      for (int i=0; i<FRAME_SIZE; i+=3)
      {
        memcpy(txBuff+i,cmbBuff+5+((i/3)*8),3);
      }

      WriteFIFOData(FRAME_SIZE,(uint8_t *)txBuff);
      StrobeCmd( CMD_TX );
      while(GPIO_PIN_SET == HAL_GPIO_ReadPin(WTR_GPIO_Port,WTR_Pin));
    }

    if(UpdatePointer != -1)
    {
      //memory overlap handler
    }
  }
  /* USER CODE END SPITask */
}

/* USER CODE BEGIN Header_SAITask */
/**
* @brief Function implementing the SAI thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_SAITask */
void SAITask(void const * argument)
{
  /* USER CODE BEGIN SAITask */
  if(HAL_OK == HAL_SAI_Receive_DMA(&hsai_BlockA1, (uint8_t *)audioBuff, FRAME_SIZE*2/3))
  {
    Error_Handler();
  }
  /* Infinite loop */
  CS4265_init();
  printf("SAITask Loop \n");
  for(;;)
  {
    osDelay(1);
  }
  /* USER CODE END SAITask */
}

/* Private application code --------------------------------------------------*/
/* USER CODE BEGIN Application */

void CS4265_init(void)
{
  uint8_t ret;
  uint8_t addr[] = {
    0x00, 0x00, 0x08, 0x18, 0x10, 0x00, 0x40, 0x00, 
    0x00, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00
  };

  for(int i=2;i<0x14;i++)
  {
    if(HAL_I2C_Mem_Write(&hi2c1, (uint16_t)I2C_ADDRESS, i, I2C_MEMADD_SIZE_8BIT, &addr[i], 1, 100)!= HAL_OK)
      Error_Handler();
    if(HAL_I2C_Mem_Read(&hi2c1, (uint16_t)I2C_ADDRESS, i, I2C_MEMADD_SIZE_8BIT, &ret, 1, 100)!= HAL_OK)
      Error_Handler();
    if(ret!=addr[i])
      Error_Handler();
  }
}

void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai)
{
  UpdatePointer=SAI_IN_SIZE;
}

void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai)
{
  UpdatePointer=0;
}

/* USER CODE END Application */

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