/**
  ******************************************************************************
  * @file    stm32l1xx_hal_pcd_ex.c
  * @author  MCD Application Team
  * @brief   Extended PCD HAL module driver.
  *          This file provides firmware functions to manage the following 
  *          functionalities of the USB Peripheral Controller:
  *           + Configururation of the PMA for EP
  *         
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */ 

/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx_hal.h"

/** @addtogroup STM32L1xx_HAL_Driver
  * @{
  */

/** @defgroup PCDEx PCDEx
  * @brief PCDEx HAL module driver
  * @{
  */

#ifdef HAL_PCD_MODULE_ENABLED

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/


/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions
  * @{
  */

/** @defgroup PCDEx_Exported_Functions_Group2 Extended Peripheral Control functions
  * @brief    Extended Peripheral Control functions
  *
@verbatim   
 ===============================================================================
             ##### Peripheral Control functions #####
 ===============================================================================  
    [..]  This section provides functions allowing to:
      (+) Configure PMA for the EndPoint
      
@endverbatim
  * @{
  */
  
/**
  * @brief Configure PMA for EP
  * @param  hpcd : Device instance
  * @param  ep_addr: endpoint address
  * @param  ep_kind: endpoint Kind
  *                  USB_SNG_BUF: Single Buffer used
  *                  USB_DBL_BUF: Double Buffer used
  * @param  pmaadress: EP address in The PMA: In case of single buffer endpoint
  *                   this parameter is 16-bit value providing the address
  *                   in PMA allocated to endpoint.
  *                   In case of double buffer endpoint this parameter
  *                   is a 32-bit value providing the endpoint buffer 0 address
  *                   in the LSB part of 32-bit value and endpoint buffer 1 address
  *                   in the MSB part of 32-bit value.
  * @retval : status
  */

HAL_StatusTypeDef  HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, 
                        uint16_t ep_addr,
                        uint16_t ep_kind,
                        uint32_t pmaadress)

{
  PCD_EPTypeDef *ep;
  
  /* initialize ep structure*/
  if ((0x80 & ep_addr) == 0x80)
  {
    ep = &hpcd->IN_ep[ep_addr & 0x7F];
  }
  else
  {
    ep = &hpcd->OUT_ep[ep_addr];
  }
  
  /* Here we check if the endpoint is single or double Buffer*/
  if (ep_kind == PCD_SNG_BUF)
  {
    /*Single Buffer*/
    ep->doublebuffer = 0;
    /*Configure te PMA*/
    ep->pmaadress = (uint16_t)pmaadress;
  }
  else /*USB_DBL_BUF*/
  {
    /*Double Buffer Endpoint*/
    ep->doublebuffer = 1;
    /*Configure the PMA*/
    ep->pmaaddr0 =  pmaadress & 0xFFFF;
    ep->pmaaddr1 =  (pmaadress & 0xFFFF0000U) >> 16;
  }
  
  return HAL_OK; 
}

/**
  * @}
  */

/**
  * @}
  */

#endif /* HAL_PCD_MODULE_ENABLED */
/**
  * @}
  */

/**
  * @}
  */

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

/** HAL_PCD_UpdatePMA
  * @brief Update Packet Memory Area Table for endpoints
  * @param  hpcd: PCD handle
  * @retval Status
  */
HAL_StatusTypeDef HAL_PCD_UpdatePMA( PCD_HandleTypeDef *hpcd )
{
   HAL_StatusTypeDef ret = HAL_OK;

   size_t nPMASize = 0x200;  // whole PMA size
   const size_t nEpsCount = 8;  // count of hardware logical enpoints
   const size_t nPMAEntrySize = 8; // the size of single PMA entry for each EP   
   uint8_t epCount = 0; // amount of used endpoints, except EP0 which is always used
  
   if( 0 != hpcd->Instance->BTABLE )
     return HAL_ERROR;  // unsupported   

   // Check each EP to count amount of used endpoints, except EP0
   for( uint8_t epidx = 1; epidx < nEpsCount; ++epidx )   
   {       
       // Check EP IN:
       if( USB_EP_TX_DIS != PCD_GET_EP_TX_STATUS( hpcd->Instance, epidx ) )
       {
           epCount++; // count all used LOGICAL endpoints
       }
       else
       // Check EP OUT:
       if( USB_EP_RX_DIS != PCD_GET_EP_RX_STATUS( hpcd->Instance, epidx ) )
       {
           epCount++; // count all used LOGICAL endpoints
       }      
   }

   // each EP takes @nPMAEntrySize bytes in PMATable, @pmaTableOffset is a table length now
   // First buffer must have address greater than the table size
   uint16_t pmaTableOffset = nPMAEntrySize * (epCount + 1/*EP0*/); 
   
   hpcd->OUT_ep[ 0 ].pmaadress = pmaTableOffset;
   hpcd->OUT_ep[ 0 ].pmaaddr0 = (uint16_t)nPMASize;  // invalid
   hpcd->OUT_ep[ 0 ].pmaaddr1 = (uint16_t)nPMASize;  // invalid 
   hpcd->OUT_ep[ 0 ].doublebuffer = 0; 
   PCD_SET_EP_RX_ADDRESS(hpcd->Instance, 0, hpcd->OUT_ep[ 0 ].pmaadress );
   pmaTableOffset += hpcd->OUT_ep[ 0 ].maxpacket;

   hpcd->IN_ep[ 0 ].pmaadress = pmaTableOffset;
   hpcd->IN_ep[ 0 ].pmaaddr0 = (uint16_t)nPMASize;  // invalid
   hpcd->IN_ep[ 0 ].pmaaddr1 = (uint16_t)nPMASize;  // invalid 
   hpcd->IN_ep[ 0 ].doublebuffer = 0;
   PCD_SET_EP_TX_ADDRESS(hpcd->Instance, 0, hpcd->IN_ep[ 0 ].pmaadress );
   pmaTableOffset += hpcd->IN_ep[ 0 ].maxpacket;

   // Check each EP to configure PMA area for each used endpoint, except EP0
   // check @epCount to reduce amount of cycles
   for( uint8_t epidx = 1; (epidx < 8) && (epCount > 0); ++epidx )   
   {
       uint8_t epUsed = 0;

       // for each direction: @direction = 0 for OUT, and 1 for IN
       for( uint8_t direction = 0; direction <= 1; direction++ )
       {
           PCD_EPTypeDef *ep = NULL;

           // EP OUT:
           if( 0 == direction )
           if( USB_EP_RX_DIS != PCD_GET_EP_RX_STATUS( hpcd->Instance, epidx ) )
           {
               ep = &hpcd->OUT_ep[ epidx ];
           }
       
           // Check EP IN:
           if( 0 != direction )
           if( USB_EP_TX_DIS != PCD_GET_EP_TX_STATUS( hpcd->Instance, epidx ) )
           {
               ep = &hpcd->IN_ep[ epidx ];
           }

           if( NULL != ep )
           {
               epUsed = !0;

               if( 0 == ep->doublebuffer )
               {
                   if( pmaTableOffset + ep->maxpacket >= nPMASize )
                   {
                       ep->pmaadress = (uint16_t)pmaTableOffset; // invalid
                       ep->pmaaddr0 = (uint16_t)nPMASize;  // invalid
                       ep->pmaaddr1 = (uint16_t)nPMASize;  // invalid

                       ret = HAL_ERROR; // error, do not interrupt, try to configure with default values
                   }
                   else
                   {
                       ep->pmaadress = (uint16_t)pmaTableOffset;
                       ep->pmaaddr0 = (uint16_t)nPMASize;  // invalid
                       ep->pmaaddr1 = (uint16_t)nPMASize;  // invalid
                       pmaTableOffset += ep->maxpacket;
                   }
               }
               else
               {
                   if( pmaTableOffset + 2 * ep->maxpacket >= nPMASize )
                   {
                       ep->pmaadress = (uint16_t)pmaTableOffset; // invalid
                       ep->pmaaddr0 = (uint16_t)nPMASize;  // invalid
                       ep->pmaaddr1 = (uint16_t)nPMASize;  // invalid

                       ret = HAL_ERROR; // error, do not interrupt, try to configure with default values
                   }
                   else
                   {
                       ep->pmaadress = (uint16_t)nPMASize; // invalid
                       ep->pmaaddr0 = (uint16_t)pmaTableOffset; 
                       pmaTableOffset += ep->maxpacket;
                       ep->pmaaddr1 = (uint16_t)pmaTableOffset;
                       pmaTableOffset += ep->maxpacket;
                   }
               }           
               
               if( ep->is_in )
                   PCD_SET_EP_TX_ADDRESS(hpcd->Instance, epidx, ep->pmaadress );
               else
                   PCD_SET_EP_RX_ADDRESS(hpcd->Instance, epidx, ep->pmaadress );
           }  
       }

       if( epUsed )
           epCount--;
   } 

   return ret;
}

/**
  * @brief  Retrieve the TX queued packet details
  * @param  hpcd: PCD handle
  * @param  ep_addr: endpoint address
  * @param  pBuf: pointer to the transmission buffer   
  * @param  len: amount of data to be sent
  * @retval HAL status:

  HAL_OK:      there is a packet queued in EP IN
  HAL_BUSY:    there no packet queued in EP IN
  HAL_ERROR:   invalid EP specified
  */
HAL_StatusTypeDef HAL_PCD_EP_GetTxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t * plen )
{
  PCD_EPTypeDef *ep;

  if ((0x80 & ep_addr) != 0x80)
  {
      // Error: OUT EP specified. Only EP IN must be specified
      return HAL_ERROR;
  }

  if( USB_EP_TX_VALID == PCD_GET_EP_TX_STATUS(hpcd->Instance, ep_addr & 0x7F ) )
  {
      if( NULL != plen )
      {
          *plen = PCD_GET_EP_TX_CNT(hpcd->Instance, ep_addr & 0x7F );
      }

      return HAL_OK;
  }

  return HAL_BUSY;
}

