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

#include "FreeRTOS.h"
#include "task.h"
#include "shell.h"
#include "queue.h"
#include "semphr.h"
#include "stm32f10x.h"
#include "bsp_usart.h"
#include "string.h"

Shell shell;
char shellBuffer[512];

static SemaphoreHandle_t  shellMutex;

/**
 * @brief 用户shell写
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际写入的数据长度
 */
short userShellWrite(char *data, unsigned short len)
{
   Usart_SendString(USART1,data);
   return len;
}


/**
 * @brief 用户shell读
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际读取到
 */
/* 自定义接口函数 */
extern uint8_t g_debugRxBuf[];
extern uint8_t g_debugRxFlag;
extern uint16_t g_debugRxLen;

void userShellRun(void)
{
	if(g_debugRxFlag)
	{
		for(uint8_t i=0;i<=g_debugRxLen;i++)
		{
			shellHandler(&shell,g_debugRxBuf[i]);
		}
		g_debugRxLen = 0;
		g_debugRxFlag = 0;
		memset(g_debugRxBuf,0x00,255);
	}
}


short userShellRead(char *data, unsigned short len)
{
	userShellRun();
	vTaskDelay(20);
	return 0; 

}

/**
 * @brief 用户shell上锁
 * 
 * @param shell shell
 * 
 * @return int 0
 */
int userShellLock(Shell *shell)
{
		xSemaphoreTake(shellMutex, portMAX_DELAY);
    return 0;
}

/**
 * @brief 用户shell解锁
 * 
 * @param shell shell
 * 
 * @return int 0
 */
int userShellUnlock(Shell *shell)
{
    xSemaphoreGive(shellMutex);
    return 0;
}

/**
 * @brief 用户shell初始化
 * 
 */
void userShellInit(void)
{
    shellMutex = xSemaphoreCreateMutex();

    shell.write = userShellWrite;
    shell.read = userShellRead;
    shell.lock = userShellLock;
    shell.unlock = userShellUnlock;
    shellInit(&shell, shellBuffer, 512);
    if (xTaskCreate(shellTask, "shell", 256, &shell, 5, NULL) != pdPASS)
    {
        printf("shell task creat failed");
    }
}

