当前位置:   article > 正文

手撸 串口交互命令行 及 AT应用层协议解析框架_串口at解析框架

串口at解析框架

        在嵌入式系统开发中,命令行接口(CLI)和AT命令解析是常见的需求。CLI提供了方便的调试接口,而AT命令则常用于模块间的通信控制。本文将介绍如何手动实现一个串口交互的命令行及AT应用层协议解析框架,适用于FreeRTOS系统。

流程图:

        这个回调函数 HAL_UART_RxCpltCallback 是用于处理 UART(通用异步收发传输器)接收到的数据。在接收数据的过程中会首先对接收到的字符进行判断,并且判断接收缓冲区是否还有空间,如果已满,则调用 ProcessReceivedFrame 处理数据,并在每次接受满之后重启UART中断。

  1. void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
  2. {
  3. // 用于检查当前触发中断的 UART 实例是否是我们期望处理的那个实例 xPort。
  4. if (huart->Instance == xPort.Instance)
  5. {
  6. // 如果这是接收到的第一个字节,清空接收缓冲区
  7. if (rx_index == 0)
  8. {
  9. //如果当前接收到的数据是本次接收的第一个字节(rx_index 为 0),
  10. //则将接收缓冲区清空。
  11. memset(rx_buffer, '\0', xPort_RX_BUFFER_SIZE);
  12. }
  13. // 如果接收到回车符 '\r',目前没有处理逻辑
  14. if (received_char == '\r') // || cRxedChar == '\r'
  15. {
  16. // 这里可以添加处理回车符的逻辑
  17. }
  18. // 如果接收到换行符 '\n'
  19. else if (received_char == '\n') // || cRxedChar == '\r'
  20. {
  21. if (rx_index != 0)
  22. {
  23. // 处理接收到的一帧数据
  24. // 在此处添加处理逻辑,例如将数据复制到另一个缓冲区或进行解析
  25. ProcessReceivedFrame(rx_buffer, &rx_index);
  26. }
  27. }
  28. else
  29. {
  30. // 将接收到的字符存储到接收缓冲区
  31. rx_buffer[rx_index++] = (char)received_char;
  32. // 检查接收缓冲区是否已满
  33. if (rx_index >= xPort_RX_BUFFER_SIZE)
  34. {
  35. // 处理接收到的一帧数据
  36. ProcessReceivedFrame(rx_buffer, &rx_index);
  37. }
  38. }
  39. // 重新启动 UART 接收中断,以接收下一个字节
  40. HAL_UART_Receive_IT(&xPort, &received_char, 1);
  41. }
  42. }

        结合之前对 HAL_UART_RxCpltCallback 函数的理解,现在我们详细解释如何通过ProcessReceivedFrame 函数处理接收到的数据:

        首先通过 osPoolAlloc 从内存池中分配内存,以存储接收到的数据,接着使用 memset 函数将分配的内存初始化为零。然后将当前帧数据的长度存储到 message->len 中,并使用 strncpy 函数将缓冲区的数据拷贝到 message->buff 中,最后将拷贝的数据放入消息队列中,等待处理。重置缓冲区长度指针 plength 为 0,表示缓冲区已处理完毕。使用 memset 函数将缓冲区清空,以准备接收新的数据。

  1. void ProcessReceivedFrame(char *buffer, uint8_t* plength)
  2. {
  3. // // 处理接收到的一帧数据
  4. // // 例如,打印接收到的数据
  5. // buffer[length - 2] = '\0'; // 替换 "\r\n" 为字符串终止符
  6. // printf("Received frame: %s\n", buffer);
  7. // osMessagePut(uartQueueHandle, (uint32_t)buffer, osWaitForever);
  8. USART_Msg_Def *message;
  9. message = (USART_Msg_Def *)osPoolAlloc(uartmsgPoolHandle); // 申请内存
  10. //osPoolAlloc There is dirt in this memory pool
  11. memset(message->buff, '\0', xPort_RX_BUFFER_SIZE);
  12. message->len = *plength;
  13. strncpy(message->buff, buffer, message->len); // 数据拷贝
  14. osMessagePut(uartQueueHandle, (uint32_t)message, osWaitForever); // 写入队列
  15. *plength = 0;
  16. memset(buffer, '\0', xPort_RX_BUFFER_SIZE);
  17. }

vUARTCommandConsoleStart 函数通过以下步骤来启动 UART 命令控制台任务:

  • 注册 CLI 命令:调用 vRegisterSampleCLICommands 函数,注册一些示例 CLI 命令,这些命令将在命令控制台任务中使用。
  • 创建一个互斥量 xTxMutex,用于保护对 UART 发送操作的访问,确保线程安全。使用 configASSERT 确保互斥量创建成功。如果创建失败,程序将进入断言。
  • 使用 xTaskCreate 创建一个新的任务,该任务将实现 UART 命令控制台。
  • 启动 UART 接收功能,以便命令控制台可以接收来自 UART 的数据。
  1. void vUARTCommandConsoleStart(void)
  2. {
  3. uint16_t usStackSize = 512;
  4. UBaseType_t uxPriority = 0;
  5. // 注册示例 CLI 命令
  6. vRegisterSampleCLICommands();
  7. // 创建用于访问 UART Tx 的信号量(互斥量)
  8. xTxMutex = xSemaphoreCreateMutex();
  9. configASSERT(xTxMutex);
  10. // 创建处理命令控制台的任务
  11. xTaskCreate(prvUARTCommandConsoleTask, // 实现命令控制台的任务函数
  12. "CLI", // 任务名称,用于调试
  13. usStackSize, // 分配给任务的堆栈大小
  14. NULL, // 任务参数,这里未使用,传递 NULL
  15. uxPriority, // 任务优先级
  16. NULL); // 任务句柄,这里未使用,传递 NULL
  17. // 启动 UART 接收
  18. StartUARTReception();
  19. }

 prvUARTCommandConsoleTask 函数是一个 FreeRTOS 任务,用于处理 UART 命令控制台。这个任务从消息队列中读取接收到的 UART 数据,并将其传递给命令解释器进行处理。

  1. static void prvUARTCommandConsoleTask(void *pvParameters)
  2. {
  3. char *pcOutputString;
  4. BaseType_t xReturned;
  5. (void)pvParameters;
  6. /* Obtain the address of the output buffer. Note there is no mutual
  7. exclusion on this buffer as it is assumed only one command console interface
  8. will be used at any one time. */
  9. pcOutputString = FreeRTOS_CLIGetOutputBuffer();
  10. /* Send the welcome message. */
  11. vSerialPutString(pcWelcomeMessage, (uint16_t)strlen((char*)pcWelcomeMessage));
  12. for (;;)
  13. {
  14. osEvent eEventTmp;
  15. USART_Msg_Def *message;
  16. // 等待从消息队列中接收消息
  17. eEventTmp = osMessageGet(uartQueueHandle, 0);
  18. if (eEventTmp.status == osEventMessage)
  19. {
  20. // 处理接收到的数据帧
  21. message = (USART_Msg_Def *)eEventTmp.value.p;
  22. char cInputString[cmdMAX_INPUT_SIZE];
  23. memcpy(cInputString, message->buff, cmdMAX_INPUT_SIZE);
  24. int8_t cInputLen = message->len;
  25. osPoolFree(uartmsgPoolHandle, message); // 释放内存
  26. #if debug
  27. char tmp[50];
  28. sprintf(tmp, "len=%d,strlen=%d\n", cInputLen, strlen(cInputString));
  29. HAL_UART_Transmit(&xPort, (const uint8_t *)tmp, strlen(tmp), portMAX_DELAY);
  30. #endif
  31. if (xSemaphoreTake(xTxMutex, cmdMAX_MUTEX_WAIT) == pdPASS)
  32. {
  33. vSerialPutString(cInputString, cInputLen);
  34. vSerialPutString(pcNewLine, (uint16_t)strlen((char*)pcNewLine));
  35. do
  36. {
  37. /* Get the next output string from the command interpreter. */
  38. xReturned = FreeRTOS_CLIProcessCommand(cInputString, pcOutputString, configCOMMAND_INT_MAX_OUTPUT_SIZE);
  39. /* Write the generated string to the UART. */
  40. vSerialPutString(pcOutputString, (uint16_t)strlen((char*)pcOutputString));
  41. } while (xReturned != pdFALSE);
  42. vSerialPutString("\r\n>", 3);
  43. memset(cInputString, 0x00, cmdMAX_INPUT_SIZE);
  44. /* Must ensure to give the mutex back. */
  45. xSemaphoreGive(xTxMutex);
  46. }
  47. }
  48. osDelay(1);
  49. }
  50. }

这个任务实现了一个简单的 UART 命令控制台,通过消息队列接收 UART 输入数据,使用命令解释器处理输入命令,并将结果输出到 UART。任务使用互斥量确保对 UART 发送操作的线程安全。通过这种方式,系统可以处理并执行来自 UART 的命令,同时确保并发访问的安全性。

 

下面这段代码注册了两个CLI(命令行接口)命令:EchoAT

  1. /* FreeRTOS includes. */
  2. #include "FreeRTOS.h"
  3. #include "task.h"
  4. /* Standard includes. */
  5. #include <stdint.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. /* FreeRTOS+CLI includes. */
  10. #include "FreeRTOS_CLI.h"
  11. #include "CLI.h"
  12. static BaseType_t prvATCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
  13. static const CLI_Command_Definition_t xATCommand =
  14. {
  15. "AT",
  16. "\r\nATcmd:\r\n +RST +MODE=0/1 +M=1/2,0~180\r\n",
  17. prvATCommand, /* The function to run. */
  18. 0 /* The user can enter any number of commands. */
  19. };
  20. static BaseType_t prvATCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
  21. {
  22. BaseType_t xReturn;
  23. char *p = pcCommandString+2;
  24. ATcmdAnalyse(p);
  25. strncat(pcWriteBuffer, "\r\nOK", strlen("\r\nOK"));
  26. // strncpy( pcWriteBuffer, "what can i say, man!!!\r\n", xWriteBufferLen );
  27. xReturn = pdFALSE;
  28. return xReturn;
  29. }
  30. /*-----------------------------------------------------------*/
  31. /*
  32. * Implements the task-stats command.
  33. */
  34. static BaseType_t prvParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
  35. /* Structure that defines the "echo_parameters" command line command. This
  36. takes a variable number of parameters that the command simply echos back one at
  37. a time. */
  38. static const CLI_Command_Definition_t xParameterEcho =
  39. {
  40. "Echo",
  41. "\r\nEcho <...>:\r\n Take variable number of parameters, echos each in turn\r\n",
  42. prvParameterEchoCommand, /* The function to run. */
  43. -1 /* The user can enter any number of commands. */
  44. };
  45. static BaseType_t prvParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
  46. {
  47. const char *pcParameter;
  48. BaseType_t xParameterStringLength, xReturn;
  49. static UBaseType_t uxParameterNumber = 0;
  50. /* Remove compile time warnings about unused parameters, and check the
  51. write buffer is not NULL. NOTE - for simplicity, this example assumes the
  52. write buffer length is adequate, so does not check for buffer overflows. */
  53. (void)pcCommandString;
  54. (void)xWriteBufferLen;
  55. configASSERT(pcWriteBuffer);
  56. if (uxParameterNumber == 0)
  57. {
  58. /* The first time the function is called after the command has been
  59. entered just a header string is returned. */
  60. sprintf(pcWriteBuffer, "The parameters were:\r\n");
  61. /* Next time the function is called the first parameter will be echoed
  62. back. */
  63. uxParameterNumber = 1U;
  64. /* There is more data to be returned as no parameters have been echoed
  65. back yet. */
  66. xReturn = pdPASS;
  67. }
  68. else
  69. {
  70. /* Obtain the parameter string. */
  71. pcParameter = FreeRTOS_CLIGetParameter(
  72. pcCommandString, /* The command string itself. */
  73. uxParameterNumber, /* Return the next parameter. */
  74. &xParameterStringLength /* Store the parameter string length. */
  75. );
  76. if (pcParameter != NULL)
  77. {
  78. /* Return the parameter string. */
  79. memset(pcWriteBuffer, 0x00, xWriteBufferLen);
  80. sprintf(pcWriteBuffer, "%d: ", (int)uxParameterNumber);
  81. strncat(pcWriteBuffer, (char *)pcParameter, (size_t)xParameterStringLength);
  82. strncat(pcWriteBuffer, "\r\n", strlen("\r\n"));
  83. /* There might be more parameters to return after this one. */
  84. xReturn = pdTRUE;
  85. uxParameterNumber++;
  86. }
  87. else
  88. {
  89. /* No more parameters were found. Make sure the write buffer does
  90. not contain a valid string. */
  91. pcWriteBuffer[0] = 0x00;
  92. /* No more data to return. */
  93. xReturn = pdFALSE;
  94. /* Start over the next time this command is executed. */
  95. uxParameterNumber = 0;
  96. }
  97. }
  98. return xReturn;
  99. }
  100. /*-----------------------------------------------------------*/
  101. void vRegisterSampleCLICommands(void)
  102. {
  103. /* Register all the command line commands defined immediately above. */
  104. FreeRTOS_CLIRegisterCommand(&xParameterEcho);
  105. FreeRTOS_CLIRegisterCommand(&xATCommand);
  106. }

1. AT 命令

  1. static BaseType_t prvATCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
  2. static const CLI_Command_Definition_t xATCommand =
  3. {
  4. "AT",
  5. "\r\nATcmd:\r\n +RST +MODE=0/1 +M=1/2,0~180\r\n",
  6. prvATCommand, /* The function to run. */
  7. 0 /* The user can enter any number of commands. */
  8. };
  • xATCommand 是一个 CLI_Command_Definition_t 结构体,定义了一个名为 AT 的命令。
  • 第一个参数是命令名称 "AT"
  • 第二个参数是该命令的帮助信息,用于显示在命令行上。
  • 第三个参数是该命令的处理函数 prvATCommand
  • 第四个参数表示用户可以输入任意数量的该命令。

2. AT 命令处理函数

  1. static BaseType_t prvATCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
  2. {
  3. BaseType_t xReturn;
  4. char *p = pcCommandString[2];
  5. ATcmdAnalyse(p);
  6. strncat(pcWriteBuffer, "\r\nOK", strlen("\r\nOK"));
  7. xReturn = pdFALSE;
  8. return xReturn;
  9. }
  • prvATCommand 是处理 AT 命令的函数。
  • 它接收三个参数:pcWriteBuffer(写缓冲区),xWriteBufferLen(写缓冲区长度)和 pcCommandString(命令字符串)。
  • 函数将命令字符串的第三个字符传递给 ATcmdAnalyse 函数进行分析处理。
  • 处理完毕后,将字符串 "\r\nOK" 追加到写缓冲区中,并返回 pdFALSE

 3. Echo 命令

  1. static BaseType_t prvParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
  2. static const CLI_Command_Definition_t xParameterEcho =
  3. {
  4. "Echo",
  5. "\r\nEcho <...>:\r\n Take variable number of parameters, echos each in turn\r\n",
  6. prvParameterEchoCommand, /* The function to run. */
  7. -1 /* The user can enter any number of commands. */
  8. };
  • xParameterEcho 是一个 CLI_Command_Definition_t 结构体,定义了一个名为 Echo 的命令。
  • 第一个参数是命令名称 "Echo"
  • 第二个参数是该命令的帮助信息,用于显示在命令行上。
  • 第三个参数是该命令的处理函数 prvParameterEchoCommand
  • 第四个参数表示用户可以输入任意数量的该命令。

4. Echo 命令处理函数 

  1. static BaseType_t prvParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
  2. {
  3. const char *pcParameter;
  4. BaseType_t xParameterStringLength, xReturn;
  5. static UBaseType_t uxParameterNumber = 0;
  6. // 省略部分代码...
  7. return xReturn;
  8. }
  • prvParameterEchoCommand 是处理 Echo 命令的函数。
  • 它接收三个参数:pcWriteBuffer(写缓冲区),xWriteBufferLen(写缓冲区长度)和 pcCommandString(命令字符串)。
  • 函数通过调用 FreeRTOS_CLIGetParameter 逐个获取命令参数,并将其逐个写入写缓冲区中。
  • 如果没有更多参数,返回 pdFALSE

5. 注册命令函数

  1. void vRegisterSampleCLICommands(void)
  2. {
  3. FreeRTOS_CLIRegisterCommand(&xParameterEcho);
  4. FreeRTOS_CLIRegisterCommand(&xATCommand);
  5. }
  • vRegisterSampleCLICommands 函数用于注册以上定义的两个命令。
  • 调用 FreeRTOS_CLIRegisterCommand 函数注册 EchoAT 命令。

这些命令通过 FreeRTOS 的 CLI 模块注册,可以在命令行界面中使用。

这段代码实现了一个简单的命令行接口(CLI),允许通过注册命令的方式来扩展功能。主要包括命令注册、命令处理和帮助命令的实现。

  1. /* Standard includes. */
  2. #include <string.h>
  3. #include <stdint.h>
  4. /* FreeRTOS includes. */
  5. #include "FreeRTOS.h"
  6. #include "task.h"
  7. /* Utils includes. */
  8. #include "FreeRTOS_CLI.h"
  9. typedef struct xCOMMAND_INPUT_LIST
  10. {
  11. const CLI_Command_Definition_t *pxCommandLineDefinition;
  12. struct xCOMMAND_INPUT_LIST *pxNext;
  13. } CLI_Definition_List_Item_t;
  14. /*
  15. * The callback function that is executed when "help" is entered. This is the
  16. * only default command that is always present.
  17. */
  18. static BaseType_t prvHelpCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
  19. /*
  20. * Return the number of parameters that follow the command name.
  21. */
  22. static int8_t prvGetNumberOfParameters(const char *pcCommandString);
  23. /* The definition of the "help" command. This command is always at the front
  24. of the list of registered commands. */
  25. static const CLI_Command_Definition_t xHelpCommand =
  26. {
  27. "Help",
  28. "\r\nHelp:\r\n Lists all the registered commands\r\n",
  29. prvHelpCommand,
  30. 0};
  31. /* The definition of the list of commands. Commands that are registered are
  32. added to this list. */
  33. static CLI_Definition_List_Item_t xRegisteredCommands =
  34. {
  35. &xHelpCommand, /* The first command in the list is always the help command, defined in this file. */
  36. NULL /* The next pointer is initialised to NULL, as there are no other registered commands yet. */
  37. };
  38. /* A buffer into which command outputs can be written is declared here, rather
  39. than in the command console implementation, to allow multiple command consoles
  40. to share the same buffer. For example, an application may allow access to the
  41. command interpreter by UART and by Ethernet. Sharing a buffer is done purely
  42. to save RAM. Note, however, that the command console itself is not re-entrant,
  43. so only one command interpreter interface can be used at any one time. For that
  44. reason, no attempt at providing mutual exclusion to the cOutputBuffer array is
  45. attempted.
  46. configAPPLICATION_PROVIDES_cOutputBuffer is provided to allow the application
  47. writer to provide their own cOutputBuffer declaration in cases where the
  48. buffer needs to be placed at a fixed address (rather than by the linker). */
  49. static char cOutputBuffer[configCOMMAND_INT_MAX_OUTPUT_SIZE];
  50. /*-----------------------------------------------------------*/
  51. BaseType_t FreeRTOS_CLIRegisterCommand(const CLI_Command_Definition_t *const pxCommandToRegister)
  52. {
  53. static CLI_Definition_List_Item_t *pxLastCommandInList = &xRegisteredCommands;
  54. CLI_Definition_List_Item_t *pxNewListItem;
  55. BaseType_t xReturn = pdFAIL;
  56. /* Check the parameter is not NULL. */
  57. configASSERT(pxCommandToRegister);
  58. /* Create a new list item that will reference the command being registered. */
  59. pxNewListItem = (CLI_Definition_List_Item_t *)pvPortMalloc(sizeof(CLI_Definition_List_Item_t));
  60. configASSERT(pxNewListItem);
  61. if (pxNewListItem != NULL)
  62. {
  63. taskENTER_CRITICAL();
  64. {
  65. /* Reference the command being registered from the newly created
  66. list item. */
  67. pxNewListItem->pxCommandLineDefinition = pxCommandToRegister;
  68. /* The new list item will get added to the end of the list, so
  69. pxNext has nowhere to point. */
  70. pxNewListItem->pxNext = NULL;
  71. /* Add the newly created list item to the end of the already existing
  72. list. */
  73. pxLastCommandInList->pxNext = pxNewListItem;
  74. /* Set the end of list marker to the new list item. */
  75. pxLastCommandInList = pxNewListItem;
  76. }
  77. taskEXIT_CRITICAL();
  78. xReturn = pdPASS;
  79. }
  80. return xReturn;
  81. }
  82. /*-----------------------------------------------------------*/
  83. BaseType_t FreeRTOS_CLIProcessCommand(const char *const pcCommandInput, char *pcWriteBuffer, size_t xWriteBufferLen)
  84. {
  85. static const CLI_Definition_List_Item_t *pxCommand = NULL;
  86. BaseType_t xReturn = pdTRUE;
  87. const char *pcRegisteredCommandString;
  88. size_t xCommandStringLength;
  89. /* Note: This function is not re-entrant. It must not be called from more
  90. thank one task. */
  91. if (pxCommand == NULL)
  92. {
  93. /* Search for the command string in the list of registered commands. */
  94. for (pxCommand = &xRegisteredCommands; pxCommand != NULL; pxCommand = pxCommand->pxNext)
  95. {
  96. pcRegisteredCommandString = pxCommand->pxCommandLineDefinition->pcCommand;
  97. xCommandStringLength = strlen(pcRegisteredCommandString);
  98. /* To ensure the string lengths match exactly, so as not to pick up
  99. a sub-string of a longer command, check the byte after the expected
  100. end of the string is either the end of the string or a space before
  101. a parameter. */
  102. if ((pcCommandInput[xCommandStringLength] == ' ') || (pcCommandInput[xCommandStringLength] == 0x00))
  103. {
  104. if (strncmp(pcCommandInput, pcRegisteredCommandString, xCommandStringLength) == 0)
  105. {
  106. /* The command has been found. Check it has the expected
  107. number of parameters. If cExpectedNumberOfParameters is -1,
  108. then there could be a variable number of parameters and no
  109. check is made. */
  110. if (pxCommand->pxCommandLineDefinition->cExpectedNumberOfParameters >= 0)
  111. {
  112. if (prvGetNumberOfParameters(pcCommandInput) != pxCommand->pxCommandLineDefinition->cExpectedNumberOfParameters)
  113. {
  114. xReturn = pdFALSE;
  115. }
  116. }
  117. break;
  118. }
  119. }
  120. else if ((strncmp("AT", pcRegisteredCommandString, 2) == 0) && (strncmp("AT", pcCommandInput, 2) == 0))
  121. {
  122. break;
  123. }
  124. }
  125. }
  126. if ((pxCommand != NULL) && (xReturn == pdFALSE))
  127. {
  128. /* The command was found, but the number of parameters with the command
  129. was incorrect. */
  130. strncpy(pcWriteBuffer, "error cmd para(s). Enter \"Help\".\r\n\r\n", xWriteBufferLen);
  131. pxCommand = NULL;
  132. }
  133. else if (pxCommand != NULL)
  134. {
  135. /* Call the callback function that is registered to this command. */
  136. xReturn = pxCommand->pxCommandLineDefinition->pxCommandInterpreter(pcWriteBuffer, xWriteBufferLen, pcCommandInput);
  137. /* If xReturn is pdFALSE, then no further strings will be returned
  138. after this one, and pxCommand can be reset to NULL ready to search
  139. for the next entered command. */
  140. if (xReturn == pdFALSE)
  141. {
  142. pxCommand = NULL;
  143. }
  144. }
  145. else
  146. {
  147. /* pxCommand was NULL, the command was not found. */
  148. strncpy(pcWriteBuffer, "Command not recognised. Enter 'help' to view a list of available commands.\r\n\r\n", xWriteBufferLen);
  149. xReturn = pdFALSE;
  150. }
  151. return xReturn;
  152. }
  153. /*-----------------------------------------------------------*/
  154. char *FreeRTOS_CLIGetOutputBuffer(void)
  155. {
  156. return cOutputBuffer;
  157. }
  158. /*-----------------------------------------------------------*/
  159. const char *FreeRTOS_CLIGetParameter(const char *pcCommandString, UBaseType_t uxWantedParameter, BaseType_t *pxParameterStringLength)
  160. {
  161. UBaseType_t uxParametersFound = 0;
  162. const char *pcReturn = NULL;
  163. *pxParameterStringLength = 0;
  164. while (uxParametersFound < uxWantedParameter)
  165. {
  166. /* Index the character pointer past the current word. If this is the start
  167. of the command string then the first word is the command itself. */
  168. while (((*pcCommandString) != 0x00) && ((*pcCommandString) != ' '))
  169. {
  170. pcCommandString++;
  171. }
  172. /* Find the start of the next string. */
  173. while (((*pcCommandString) != 0x00) && ((*pcCommandString) == ' '))
  174. {
  175. pcCommandString++;
  176. }
  177. /* Was a string found? */
  178. if (*pcCommandString != 0x00)
  179. {
  180. /* Is this the start of the required parameter? */
  181. uxParametersFound++;
  182. if (uxParametersFound == uxWantedParameter)
  183. {
  184. /* How long is the parameter? */
  185. pcReturn = pcCommandString;
  186. while (((*pcCommandString) != 0x00) && ((*pcCommandString) != ' '))
  187. {
  188. (*pxParameterStringLength)++;
  189. pcCommandString++;
  190. }
  191. if (*pxParameterStringLength == 0)
  192. {
  193. pcReturn = NULL;
  194. }
  195. break;
  196. }
  197. }
  198. else
  199. {
  200. break;
  201. }
  202. }
  203. return pcReturn;
  204. }
  205. /*-----------------------------------------------------------*/
  206. static BaseType_t prvHelpCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
  207. {
  208. static const CLI_Definition_List_Item_t *pxCommand = NULL;
  209. BaseType_t xReturn;
  210. (void)pcCommandString;
  211. if (pxCommand == NULL)
  212. {
  213. /* Reset the pxCommand pointer back to the start of the list. */
  214. pxCommand = &xRegisteredCommands;
  215. }
  216. /* Return the next command help string, before moving the pointer on to
  217. the next command in the list. */
  218. strncpy(pcWriteBuffer, pxCommand->pxCommandLineDefinition->pcHelpString, xWriteBufferLen);
  219. pxCommand = pxCommand->pxNext;
  220. if (pxCommand == NULL)
  221. {
  222. /* There are no more commands in the list, so there will be no more
  223. strings to return after this one and pdFALSE should be returned. */
  224. xReturn = pdFALSE;
  225. }
  226. else
  227. {
  228. xReturn = pdTRUE;
  229. }
  230. return xReturn;
  231. }
  232. /*-----------------------------------------------------------*/
  233. static int8_t prvGetNumberOfParameters(const char *pcCommandString)
  234. {
  235. int8_t cParameters = 0;
  236. BaseType_t xLastCharacterWasSpace = pdFALSE;
  237. /* Count the number of space delimited words in pcCommandString. */
  238. while (*pcCommandString != 0x00)
  239. {
  240. if ((*pcCommandString) == ' ')
  241. {
  242. if (xLastCharacterWasSpace != pdTRUE)
  243. {
  244. cParameters++;
  245. xLastCharacterWasSpace = pdTRUE;
  246. }
  247. }
  248. else
  249. {
  250. xLastCharacterWasSpace = pdFALSE;
  251. }
  252. pcCommandString++;
  253. }
  254. /* If the command string ended with spaces, then there will have been too
  255. many parameters counted. */
  256. if (xLastCharacterWasSpace == pdTRUE)
  257. {
  258. cParameters--;
  259. }
  260. /* The value returned is one less than the number of space delimited words,
  261. as the first word should be the command itself. */
  262. return cParameters;
  263. }
  • 注册命令

    调用 FreeRTOS_CLIRegisterCommand 函数注册新的命令。这个函数会将新的命令节点添加到链表末尾。

  • 处理命令

    调用 FreeRTOS_CLIProcessCommand 函数处理输入的命令字符串。这个函数会遍历注册的命令链表,找到匹配的命令,并调用相应的回调函数处理。

  • 帮助命令

    当输入 Help 命令时,prvHelpCommand 回调函数会被调用,输出所有注册命令的帮助信息。

 

这段代码实现了一个简单的 AT 指令解析器。

  1. #include "CLI.h"
  2. #include "string.h"
  3. // "\r\nATcmd:\r\n +RST +MODE=0/1 +M=1/2,0~180\r\n",
  4. typedef enum
  5. {
  6. AT = 0,
  7. MODE,
  8. M,
  9. RST,
  10. /**将指令添加到上面**/
  11. MAXCMDNUM
  12. } ATCommand;
  13. typedef enum
  14. {
  15. ATERROR = 0,
  16. ATSUCCESS ,
  17. ATERRORCODE1,
  18. }ATStatus;
  19. typedef ATStatus (*pFuncCallback)(char *str);
  20. typedef struct
  21. {
  22. ATCommand ATCommandName;
  23. char *ATStr; // 发送的AT指令
  24. pFuncCallback ATCallback; // AT指令接收完成,指令处理回调函数
  25. } ATCommandConfig;
  26. ATStatus MODE_Callback(char *str);
  27. ATStatus M_Callback(char *str);
  28. ATStatus RST_Callback(char *str);
  29. static const ATCommandConfig ATCommandList[] =
  30. {
  31. {MODE, "MODE", MODE_Callback},
  32. {M, "M", M_Callback},
  33. {RST, "RST", RST_Callback},
  34. NULL,
  35. };
  36. static void ATcmdGetRun(pATcmd, pATcmdLen, pATvalue)
  37. {
  38. ATCommandConfig *pxCommand;
  39. const char *pcRegisteredCommandString;
  40. for (pxCommand = &ATCommandList[0]; pxCommand != NULL; pxCommand++)
  41. {
  42. pcRegisteredCommandString = pxCommand->ATStr;
  43. if (strncmp(pATcmd, pcRegisteredCommandString, pATcmdLen) == 0)
  44. {
  45. pxCommand->ATCallback(pATvalue);
  46. }
  47. }
  48. }
  49. void ATcmdAnalyse(char *pATcmd)
  50. {
  51. if ('+' == pATcmd[0])
  52. {
  53. pATcmd++;
  54. char *pATvalue;
  55. uint8_t pATcmdLen = 0; // ATcmd lenth
  56. pATvalue = strstr(pATcmd, "=");
  57. if (pATvalue)
  58. {
  59. pATcmdLen = pATvalue - pATcmd; // ATcmd lenth
  60. pATvalue++;
  61. }
  62. else
  63. {
  64. pATvalue = NULL;
  65. pATcmdLen = strlen(pATcmd);
  66. }
  67. ATcmdGetRun(pATcmd, pATcmdLen, pATvalue);
  68. }
  69. }
  70. /*--------------------------------------------------
  71. In fact, the last step callback function of
  72. the at instruction cannot directly control the hardware.
  73. There should be a third intermediate layer SDK
  74. --------------------------------------------------*/
  75. ATStatus MODE_Callback(char *str)
  76. {
  77. //挂起舵机的任务
  78. }
  79. ATStatus M_Callback(char *str)
  80. {
  81. //Sg90MotorCtl(舵机1/2 , 舵机角度)
  82. //控制舵机运行到具体角度
  83. //内部需要对舵机能够转动的最大角度进行限位
  84. }
  85. ATStatus RST_Callback(char *str)
  86. {
  87. //重启 mcu
  88. }

让我们逐步解释它的功能和结构:

  1. 枚举类型定义:

    • ATCommand 枚举定义了一组 AT 指令的名称,包括 ATMODEMRST,以及一个特殊的枚举 MAXCMDNUM,用于表示指令数量上限。
  2. AT 状态枚举:

    • ATStatus 枚举定义了一组 AT 操作的状态,包括成功、失败以及可能的其他错误码。
  3. 函数指针定义:

    • pFuncCallback 是一个函数指针类型,指向一个接受 char* 参数并返回 ATStatus 类型的函数。
  4. AT 指令配置结构体:

    • ATCommandConfig 结构体定义了一个 AT 指令的配置,包括指令名称、发送的指令字符串以及指令完成时的回调函数。
  5. AT 指令配置列表:

    • ATCommandList 是一个数组,存储了所有 AT 指令的配置信息,包括指令名称、发送的指令字符串和回调函数。列表以 NULL 结尾。
  6. AT 指令解析函数:

    • ATcmdAnalyse 函数用于解析接收到的 AT 指令。它接收一个指向 AT 指令字符串的指针,并根据指令名称调用相应的回调函数。
  7. AT 指令回调函数:

    • MODE_CallbackM_CallbackRST_Callback 是对应于不同指令的回调函数,用于执行具体的操作。这些函数会根据指令参数进行不同的处理。
  8. AT 指令执行函数:

    • ATcmdGetRun 函数根据接收到的 AT 指令名称,在配置列表中查找对应的配置,并调用相应的回调函数执行操作。

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/906893
推荐阅读
相关标签
  

闽ICP备14008679号