/**
 * @file shell_port.c
 * @author Letter (NevermindZZT@gmail.com)
 * @brief 
 * @version 0.1
 * @date 2019-02-22
 * 
 * @copyright (c) 2019 Letter
 * 
 */

#include "shell.h"
#include "hal_data.h"
//#include "cevent.h"
#include "log.h"


Shell shell;
char shellBuffer[256];
#if (HELL_TASK_WHILE == 1)
#include "FreeRTOS.h"
#include "task.h"
static SemaphoreHandle_t shellMutex;
#endif
/**
 * @brief 用户shell写
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际写入的数据长度
 */
short userShellWrite(char *data, unsigned short len)
{
 //   serialTransmit(&debugSerial, (uint8_t *)data, len, 0x1FF);
 
    g_uart9.p_api->write(g_uart9.p_ctrl, (uint8_t const *const)data, (uint32_t)len);
    /* 等待发送完毕 */
    uart9_wait_for_tx();
    return (short)len;
}


/**
 * @brief 用户shell读
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际读取到
 */
short userShellRead(char *data, unsigned short len)
{
	(void)data;
	(void)len;
 //   return serialReceive(&debugSerial, (uint8_t *)data, len, 0);
	return 0;
}

/**
 * @brief 用户shell上锁
 * 
 * @param shell shell
 * 
 * @return int 0
 */
int userShellLock(Shell *sh)
{
	(void)(sh);
#if (HELL_TASK_WHILE == 1)
    xSemaphoreTakeRecursive(shellMutex, portMAX_DELAY);
#endif
    return 0;
}

/**
 * @brief 用户shell解锁
 * 
 * @param shell shell
 * 
 * @return int 0
 */
int userShellUnlock(Shell *sh)
{	
	(void)(sh);
#if (HELL_TASK_WHILE == 1)
    xSemaphoreGiveRecursive(shellMutex);
#endif
    return 0;
}


void uartLogWrite(char *buffer, short len);
Log uartLog = {
    .write = uartLogWrite,
    .active = 1,
    .level = LOG_DEBUG
};

void uartLogWrite(char *buffer, short len)
{
    if (uartLog.shell)
    {
        shellWriteEndLine(uartLog.shell, buffer, len);
    }
}

/**
 * @brief 用户shell初始化
 * 
 */
void userShellInit(void)
{

#if (HELL_TASK_WHILE == 1)
    shellMutex = xSemaphoreCreateMutex();
    shell.lock = userShellLock;
    shell.unlock = userShellUnlock;
#endif
    shell.write = userShellWrite;
  //  shell.read = userShellRead;
    shellInit(&shell, shellBuffer, sizeof(shellBuffer));
    logRegister(&uartLog, &shell);
#if (HELL_TASK_WHILE == 1)
    if (xTaskCreate(shellTask, "shell", 256, &shell, 5, NULL) != pdPASS)
    {
        logError("shell task creat failed");
    }
#endif
}
// CEVENT_EXPORT(EVENT_INIT_STAGE2, userShellInit);

