/*
 * AppTaskBle.c
 *
 *  Created on: 2022年1月19日
 *      Author: 陈杰
 */
#include "AppTaskBle.h"

const BleAtCmdFunc_t BleAtCmdFunc[] = {
    {AT_Cmd_Test, "AT", at_callbackFunc},
    {AT_GetMac, "AT+MAC?", at_callbackFunc},
    {AT_NameChk, "AT+NAME?", at_callbackFunc},
    {AT_NameSet, "AT+NAME=", at_callbackFunc},
    {AT_AutoConnSet, "AT+AUTOCONN=", at_callbackFunc},
    {AT_LogMsgSet, "AT+LOGMSG=", at_callbackFunc},
    {AT_RoleChk, "AT+ROLE?", at_callbackFunc},
    {AT_RoleSet, "AT+ROLE=", at_callbackFunc},
    {AT_Conn, "AT+CONN=", at_callbackFunc},
    {AT_DisCon, "AT+DISCON", at_callbackFunc},
    {AT_Reset, "AT+RESET", at_callbackFunc}};
void AtcmdTransmit(sint8 CmdIdx, uint8 *SetValuePtr, uint16 SetValueLen, uint8 *CmdRead, sint8 *retFunc);
static void bleInit(void);
static sint8 bleRoleSetFunc(void);
void BleTask(void *pvParameters)
{
	uint8 AtCmdRead[200] = {0};
	bleInit();
	uint8 bleWorkState = 0;
	sint8 ret = -1;
	for (;;)
	{
		vTaskDelay(pdMS_TO_TICKS(100));
		switch (bleWorkState)
		{
		case 0: //等待连接或者主动连接
		{
			if (BleSetRoleFlg) //是否更改角色
			{
				if(bleRoleSetFunc()==0)
				{
					BleSetRoleFlg=0;
				}
			}
			if (BleCurrentRole == 1)
			{
				if (MasterConnectEnble == 1 && MasterConnectFlg == 0) //主机蓝牙主动请求连接
				{
					AtcmdTransmit(AT_Conn, BleTargetMacAddr, sizeof(BleTargetMacAddr), AtCmdRead, &ret);
					if (ret == 0) //连接成功
					{
						MasterConnectFlg = 1;
						bleWorkState = 1;
					}
					else
					{
						MasterConnectFlg = 0;
					}
				}
			}
			uint8 *retptr = NULL;
			uint8 *pSend = NULL;
			uint32 sendLen = 0;
			memset(RX_Buffer[UART_LPUART2],0x00,sizeof(RX_Buffer[UART_LPUART2]));
			UART_Receive_Data(UART_LPUART2, RX_Buffer[UART_LPUART2], 100*1000);
			memcpy(AtCmdRead,RX_Buffer[UART_LPUART2],sizeof(AtCmdRead));
			retptr = (uint8 *)strstr(AtCmdRead, (uint8 *)("STA:connect"));
			if (retptr)
			{
				bleWorkState = 1;
				MasterConnectFlg = 1;
			}
			break;
		}
		case 1: //已连接
		{
			if (BleCurrentRole == 1)
			{
				if (MasterDisconnectEnble == 1 && MasterDisconnectFlg == 0)
				{
					//主机蓝牙断开指令，Mod拉低，才能发送命令
					Dio_WriteChannel(DioConf_DioChannel_PTE7_GPIO_OUT_MCU_BT_MOD,STD_OFF);
					memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
					AtcmdTransmit(AT_DisCon, NULL, 0, AtCmdRead, &ret);
					if (ret == 0)
					{
						memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
						AtcmdTransmit(AT_Reset, NULL, 0, AtCmdRead, &ret);
						if(ret == 0)
						{
							MasterDisconnectFlg = 1;
							Dio_WriteChannel(DioConf_DioChannel_PTE7_GPIO_OUT_MCU_BT_MOD,STD_ON);
						}
					}
					else
					{
						MasterDisconnectFlg = 0;
					}
				}
			}
			/*已连接状态下的数据交换在此进行
			UartTramsit;
			*/
			uint8 *pSend = NULL;
			uint32 sendLen = 0;
			UART_Receive_Data(UART_LPUART2, RX_Buffer[UART_LPUART2], 100*1000);
			memcpy(AtCmdRead,RX_Buffer[UART_LPUART2],sizeof(AtCmdRead));
			uint8 *retptr = NULL;
			retptr = (uint8 *)strstr(AtCmdRead, (uint8 *)("STA:disconnec"));
			if (retptr)
			{
				bleWorkState = 0;
				MasterDisconnectFlg = 1;
			}
			break;
		}
		default:
			bleWorkState = 0;
			break;
		}
	}
}
void AtcmdTransmit(sint8 CmdIdx, uint8 *SetValuePtr, uint16 SetValueLen, uint8 *CmdRead, sint8 *retFunc)
{
	uint8 ATCmd_Send[50];
	uint16 ATCmd_SendLen;
	memset(ATCmd_Send, 0x00, sizeof(ATCmd_Send));
	ATCmd_SendLen = mstrlen(BleAtCmdFunc[CmdIdx].str);
	memcpy(ATCmd_Send, BleAtCmdFunc[CmdIdx].str, ATCmd_SendLen);
	if (SetValuePtr != NULL)
	{
		memcpy(&ATCmd_Send[ATCmd_SendLen], SetValuePtr, SetValueLen);
	}
	ATCmd_SendLen = ATCmd_SendLen + SetValueLen;
	memset(RX_Buffer[UART_LPUART2], 0x00, sizeof(RX_Buffer[UART_LPUART2]));
	UART_Query_Data(UART_LPUART2, UART_LPUART2, ATCmd_Send, ATCmd_SendLen, RX_Buffer[UART_LPUART2], 100*1000);
	memcpy(CmdRead,RX_Buffer[UART_LPUART2],50);
	*retFunc = BleAtCmdFunc[CmdIdx].cb(ATCmd_Send, CmdRead, CmdIdx);
	return;
}
void ReceiveTask(void *pvParameters)
{
    (void)pvParameters;
    BaseType_t operation_status;
    static TickType_t xLastWakeTime;
    xLastWakeTime = xTaskGetTickCount();
    for (;;)
    {
    	//UART_Receive_Data(UART_LPUART2, RX_Buffer[UART_LPUART2], 100*1000);
    	vTaskDelay(pdMS_TO_TICKS(1000));
    	vTaskDelayUntil(&xLastWakeTime, 100);
//        operation_status = xSemaphoreTake(sem_handle, portMAX_DELAY);
//        configASSERT(operation_status == pdPASS);
    }
}
static void bleInit(void)
{
	uint8 AtCmdRead[50];
	sint8 ret = -1;
	uint8 bleInitStep = 0;
	uint8 BleCurrentName[6];
	while (1)
	{
		switch (bleInitStep)
		{
		case 0: //AT同步
		{
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_Cmd_Test, NULL, 0, AtCmdRead, &ret);
			if (ret == 0)
			{
				bleInitStep++;
			}
			else
			{
				bleInitStep = 0;
			}
			break;
		}
		case 1: //获取Mac地址
		{
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_GetMac, NULL, 0, AtCmdRead, &ret);
			memcpy(BleMacAddr, &AtCmdRead[4], sizeof(BleMacAddr));
			if (ret == 0)
			{
				bleInitStep++;
			}
			else
			{
				bleInitStep = 0;
			}
			break;
		}
		case 2: //广播名称设置
		{
			uint8 NameChk = 0; //默认不需要设置
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_NameChk, NULL, 0, AtCmdRead, &ret);
			for (uint8 i = 0; i < 6; i++)
			{
				if (mstrlen(AtCmdRead) != 16)
				{
					NameChk = 1;
					break;
				}
				else
				{
					BleCurrentName[i] = (CharToHex(AtCmdRead[(i * 2) + 4]) << 4) + CharToHex(AtCmdRead[(i * 2 + 1) + 4]);
					if (BleMacAddr[i] != BleCurrentName[i])
					{
						NameChk = 1;
						break;
					}
				}
			}
			if (NameChk)
			{
				uint8 NameTemp[12] = {0};
				for (uint8 i = 0; i < 6; i++)
				{
					NameTemp[(i * 2)] = HexToChar(BleMacAddr[i] >> 4);
					NameTemp[(i * 2) + 1] = HexToChar(BleMacAddr[i] & 0x0F);
				}
				memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
				AtcmdTransmit(AT_NameSet, NameTemp, 12, AtCmdRead, &ret);
			}
			if (ret == 0)
			{
				bleInitStep++;
			}
			else
			{
				bleInitStep = 0;
			}
			break;
		}
		case 3: //关闭自动连接
		{
			uint8 CmdTemp = '0';
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_AutoConnSet, &CmdTemp, 1, AtCmdRead, &ret);
			if (ret == 0)
			{
				bleInitStep++;
			}
			else
			{
				bleInitStep = 0;
			}
			break;
		}
		case 4: //打开log输出
		{
			uint8 CmdTemp = '1';
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_LogMsgSet, &CmdTemp, 1, AtCmdRead, &ret);
			if (ret == 0)
			{
				bleInitStep++;
			}
			else
			{
				bleInitStep = 0;
			}
			break;
		}
		case 5://角色获取
		{
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_RoleChk, NULL, 0, AtCmdRead, &ret);
			BleCurrentRole = CharToHex(AtCmdRead[4]);
			if (ret == 0 &&(BleCurrentRole==0||BleCurrentRole==1))
			{
				bleInitStep++;
			}
			else
			{
				bleInitStep = 0;
			}
			break;
		}
		case 6:
		{
			return;
		}
		default:
			bleInitStep = 0;
			break;
		}
	}
	return;
}
static sint8 bleRoleSetFunc(void)
{
	uint8 AtCmdRead[50];
	sint8 ret = -1;
	uint8 BleRoleSetStep = 0;
	while (1)
	{
		switch (BleRoleSetStep)
		{
		case 0: //AT同步
		{
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_Cmd_Test, NULL, 0, AtCmdRead, &ret);
			if (ret == 0)
			{
				BleRoleSetStep++;
			}
			else
			{
				return -1;
			}
			break;
		}
		case 1: //角色检查
		{
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_RoleChk, NULL, 0, AtCmdRead, &ret);
			BleCurrentRole = CharToHex(AtCmdRead[4]);
			if (ret == 0)
			{
				if (BleCurrentRole == BleSetRole)
				{
					return 0;
				}
				else
				{
					BleRoleSetStep++;
				}
			}
			else
			{
				BleRoleSetStep = 0;
			}
			break;
		}
		case 2: //角色设置
		{
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			uint8 RoleTemp;
			RoleTemp = HexToChar(BleSetRole);
			AtcmdTransmit(AT_RoleSet, &RoleTemp, 1, AtCmdRead, &ret);
			if (ret == 0)
			{
				BleRoleSetStep++;
			}
			else
			{
				BleRoleSetStep = 0;
			}
			break;
		}
		case 3: //蓝牙模块重启
		{
			memset(AtCmdRead, 0x00, sizeof(AtCmdRead));
			AtcmdTransmit(AT_Reset, NULL, 0, AtCmdRead, &ret);
			BleRoleSetStep = 0;
			break;
		}
		default:
			BleRoleSetStep = 0;
			break;
		}
	}
	return 0;
}
sint8 at_callbackFunc(uint8 *PSendStr, uint8 *ptr, BleAtCmd CmdIdx)
{
    uint16 pReadLen = 0;
    sint8 returnvalue = -1;
    uint8 *retptr = NULL;
    switch (CmdIdx)
    {
    case AT_Cmd_Test:
    {
        pReadLen = ATstrdel(ptr);
        retptr = (uint8 *)strstr(ptr, (uint8 *)("OK"));
        if (retptr)
        {
            returnvalue = 0;
        }
        else
        {
            returnvalue = -1;
        }
        break;
    }
    case AT_RoleChk:
    {
        pReadLen = ATstrdel(ptr);
        retptr = (uint8 *)strstr(ptr, (uint8 *)("OK"));
        if (retptr)
        {
            returnvalue = 0;
        }
        else
        {
            returnvalue = -1;
        }
        break;
    }
    default:
    {
        pReadLen = ATstrdel(ptr);
        retptr = (uint8 *)strstr(ptr, (uint8 *)("OK"));
        if (retptr)
        {
            returnvalue = 0;
        }
        else
        {
            returnvalue = -1;
        }
        break;
    }
    }
    return returnvalue;
}
