/**
  ******************************************************************************
  * @file    mbedtls_net.c
  * @author  MCD Application Team
  * @brief   This file provides network porting layer of mbedTLS.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics International N.V. 
  * All rights reserved.</center></h2>
  *
  * Redistribution and use in source and binary forms, with or without 
  * modification, are permitted, provided that the following conditions are met:
  *
  * 1. Redistribution 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 other 
  *    contributors to this software may be used to endorse or promote products 
  *    derived from this software without specific written permission.
  * 4. This software, including modifications and/or derivative works of this 
  *    software, must execute solely and exclusively on microcontroller or
  *    microprocessor devices manufactured by or for STMicroelectronics.
  * 5. Redistribution and use of this software other than as permitted under 
  *    this license is void and will automatically terminate your rights under 
  *    this license. 
  *
  * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT 
  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
  * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
  * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT 
  * SHALL STMICROELECTRONICS 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.
  *
  ******************************************************************************
  */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include "mbedtls/config.h"
#include "mbedtls/net_sockets.h"
#include "wifi.h"

#define MBEDTLS_NET_PRINT(_f, _a ...)  \
            printf("%s %d: "_f,  __FUNCTION__, __LINE__, ##_a)

#define WIFI_WRITE_TIMEOUT   30000
#define WIFI_READ_TIMEOUT    4000
#define WIFI_PAYLOAD_SIZE    1200
#define WIFI_READ_RETRY_TIME 1

void mbedtls_net_init(mbedtls_net_context *ctx)
{
    ctx->fd = -1;
}

int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host, const char *port, int proto)
{
    WIFI_Status_t ret;
    WIFI_Protocol_t type;
    uint8_t ip_addr[20]; /*This array can be used as string or integer array*/
    int     trials=1;
    int socket = 0;
    
    do
    {
      ret = WIFI_GetHostAddress((char *)host, ip_addr);
      if (ret != WIFI_STATUS_OK) {
        MBEDTLS_NET_PRINT("net_connect: get host addr fail - %d , trial : %d/5\n", ret , trials);
      }
      trials++;
    }
    while(ret != WIFI_STATUS_OK);
    
    type = proto == MBEDTLS_NET_PROTO_UDP ?
                    WIFI_UDP_PROTOCOL : WIFI_TCP_PROTOCOL;
    ret = WIFI_OpenClientConnection(socket, type, "", ip_addr, atoi(port), 0);
    if (ret != WIFI_STATUS_OK) {
        MBEDTLS_NET_PRINT("net_connect: open client fail - %d\n", ret);
        return MBEDTLS_ERR_NET_CONNECT_FAILED;
    }

    ctx->fd = socket;

    return ret;
}

int mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len)
{
    WIFI_Status_t ret;
    uint16_t send_size;
    uint16_t once_len;
    uint8_t *pdata = (uint8_t *)buf;
    uint16_t send_total = 0;
    int fd = ((mbedtls_net_context *) ctx)->fd;

    if (fd < 0) {
        MBEDTLS_NET_PRINT("net_send: invalid socket fd\n");
        return MBEDTLS_ERR_NET_INVALID_CONTEXT;
    }

    do {
        if (len > WIFI_PAYLOAD_SIZE) {
            MBEDTLS_NET_PRINT("net_send: buffer length = %d, split data sending\n", len);
            once_len = WIFI_PAYLOAD_SIZE;
            len -= WIFI_PAYLOAD_SIZE;
        } else {
            once_len = len;
            len = 0;
        }

        ret = WIFI_SendData((uint8_t)fd,
                            pdata, once_len,
                            &send_size, WIFI_WRITE_TIMEOUT);
        if (ret != WIFI_STATUS_OK) {
            MBEDTLS_NET_PRINT("net_send: send data fail - %d\n", ret);
            return MBEDTLS_ERR_NET_SEND_FAILED;
        }
        pdata += once_len;
        send_total += send_size;
    } while (len > 0);


    return send_total;
}

int mbedtls_net_recv_timeout(void *ctx, unsigned char *buf, size_t len,
                      uint32_t timeout )
{
    WIFI_Status_t ret;
    uint16_t recv_size;
    int fd = ((mbedtls_net_context *) ctx)->fd;
    
    if (fd < 0) {
        MBEDTLS_NET_PRINT("net_recv_timeout: invalid socket fd\n");
        return(MBEDTLS_ERR_NET_INVALID_CONTEXT);
    }

    if (timeout==0) 
    {
      timeout=30000;
    }
    if (timeout > 30000)
    {
     printf("Limits timeout to 30000 instead of %d\n",timeout);
     timeout=30000;
    }
    
    if (len > WIFI_PAYLOAD_SIZE) {
        len = WIFI_PAYLOAD_SIZE;
    }

    do 
    {
        ret = WIFI_ReceiveData((uint8_t)fd,
                                buf, (uint16_t)len,
                                &recv_size, timeout);
        if (ret != WIFI_STATUS_OK) {
            MBEDTLS_NET_PRINT("net_recv_timeout: receive data fail - %d\n", ret);
            return MBEDTLS_ERR_NET_RECV_FAILED;
        }
        if (recv_size == 0)   return MBEDTLS_ERR_SSL_TIMEOUT ;
            
        
    } while (ret == WIFI_STATUS_OK && recv_size == 0);
    return recv_size;
}

void mbedtls_net_free(mbedtls_net_context *ctx)
{
    WIFI_Status_t ret;

    if (ctx->fd == -1)
        return;

    ret = WIFI_CloseClientConnection((uint32_t)ctx->fd);
    if (ret != WIFI_STATUS_OK) {
        MBEDTLS_NET_PRINT("net_free: close client fail - %d\n", ret);
        return;
    }

    ctx->fd = -1;
}


