
#include "dwt.h"
#include "fly_param.h"
#include "iec10x.h"
#include "iec10x_conf.h"
#include "iec10x_prio_queue.h"
#include "iec10x_type.h"
#include "main.h"
#include "nor_flash.h"
#include <string.h>

#define TEST_BUF_SIZE 2048

#define TEST_SECTOR_NO 127 /* 测试扇区号，值域【0,128】 */

uint8_t g_TestBuf[TEST_BUF_SIZE]; /* 数据测试用缓冲区 */

/*******************************************************************************
 * Function Name  : fly_init
 * Description    : fly_init program
 * Input          : None
 * Output         : None
 * Return         : None
 *******************************************************************************/
static int fly_init(void)
{

    return 0;
}

static void *fly_malloc(unsigned char nbyte)
{

    return malloc(nbyte);
}

static void fly_free(void *pblock)
{

    free(pblock);
}

static iec_32u fly_set_time(PCP56Time2a_T time)
{

    return RET_SUCESS;
}
static iec_32u fly_get_time(PCP56Time2a_T time)
{

    return RET_SUCESS;
}

static iec_8s fly_get_station_info(iec_16u *Addr, iec_8u n, iec_8u *MaxNum)
{

    *MaxNum = WTP_SUPPORT_END_NUMBER;
    *Addr   = n;
    return RET_SUCESS;
}

static float fly_get_station_temp(iec_16u Addr)
{

    return 30;
}

static iec_16u fly_get_link_addr(void)
{

    return 0x0001;
}

static void fly_close_link(void)
{

    // GPRSFlag = SYSTEM_FLAG_GPRS_CLOSE;
    // IEC104_STATE_FLAG_INIT = IEC104_FLAG_CLOSED;
}

void delay_ms(iec_16u ms)
{

    us_delay(ms * 1000);
}

iec_8u fly_send(int socketfd, char *buf, int len)
{
    int i;
    if (-1 == write(socketfd, buf, len))
    {
        LOG("-%s-,Send error \n", __FUNCTION__);
        return RET_ERROR;
    }

    // for (i = 0; i < len; i++)
    // {
    // NOR_WriteByte(TEST_SECTOR_NO * NOR_SECTOR_SIZE, buf[i]);
    if (NOR_WriteBuffer(buf, TEST_SECTOR_NO * NOR_SECTOR_SIZE + 1, len) == NOR_SUCCESS)
    {
        printf("send sram buffer ok!\r\n");
    }
    // }
    printf("Send Ok!\r\n");

    return RET_SUCESS;
}
void fly_lock(void)
{
    INT8U err;
    OSMutexPend(net_mutex, 0, &err);
    // pthread_mutex_lock(&mutex);
}
void fly_unlock()
{
    OSMutexPost(net_mutex);
    // pthread_mutex_unlock(&mutex);
}

static IEC10X_T fly = {
    "Linux",
    fly_init,
    delay_ms,
    fly_close_link,
    fly_malloc,
    fly_free,
    IEC10X_PrioEnQueue,
    IEC10X_PrioDeQueue,
    IEC10X_PrioFindQueueHead,
    IEC10X_HighestPrio, /* Get the highest Prio Queue*/
    IEC10X_PrioInitQueue,
    IEC10X_Prio_ClearQueue,
    fly_send,
    fly_set_time,
    fly_get_time,
    fly_get_station_info,
    fly_get_station_temp,
    fly_get_link_addr,

#ifdef IEC10XLOCK
    fly_lock,
    fly_unlock
#endif
};

iec_32u RegisterIec10x(void)
{
    return RegisterIEC10XMoudle(&fly);
}
