首页 > 解决方案 > C ++异步从其他函数获取数据

问题描述

这不是编码,而是主要是架构问题......

例如,我有一个loop()函数,我从某个源(在我的例子中是 UART)获取数据。代码很像这样(伪代码):

loop() {
  auto data = UART.GetData();
  // differ data from each other and push it to corresponding message queue or golang-style channel?
  Console.Print(data);
}

我需要实现一个异步 REST HTTP 函数,它将从 UART 预订(订购)数据并等待它到来。请记住,此时其他异步 REST HTTP 函数也可能会从 UART 请求数据。异步 REST HTTP 函数的代码如下:

handler(AsyncRequest &req) {
  UART.RequestNeededData(); // This function returns nothing. Data will be handled in loop() method
  auto data = // somehow get this data from other method, in this case it's loop() (get data from message queue or Golang-style channel?)
  req.SendDataToClient(data);
}

UART 运行它自己的协议来区分请求的数据和响应。把它当作 req/res 数据包。我需要将请求的数据从handler()函数传递回handler().

希望您了解我需要做什么,并可以帮助我解决这个问题。如果您有任何问题,请发表评论。

标签: c++asynchronousarduinouart

解决方案


我用队列模板类解决​​了类似的问题:

 QueuePendingCommands<char> queue(100); //-> Max 100 chars in this queue

处理程序初始化适当的队列并用数据填充它

 auto data = UART.GetData();
 if (data = fullfillConditionA )
     if (data != '\n') 
        QueuePendingCommandsA.push(data);
     else
        processResponse(QueuePendingCommandsA);
  else if (data = fullfillConditionB )
     if (data != '\n') 
        QueuePendingCommandsB.push(data);
     else
        processResponse(QueuePendingCommandsB);
 else ....

在我的情况下,有一个定义的最终字符(例如'#'或'\n'),将其推入队列会触发清空队列并填充响应:

void processResponse (inQueue) {
/** Create response - Drain the queued up commands */
 while (inQueue.count() > 0) {
     strcat(response, inQueue.pop());
   }
 .... Do something with the response
 }

因此,对于每个请求,您都会写入一个已定义的队列,并在收到特殊字符后触发响应(也是固定数量的字符,条件或超时可能会触发队列的清空)


推荐阅读