如何将测量值发送到服务器并同时从传感器接收数据?

How to send measurements to a server and receive data from sensor at the same time?

我正在尝试处理来自我的传感器的数据,同时将数据上传到服务器 (Thingspeak)。

问题是,每当服务器连接(使用 wifi)结束时(我找不到延长会话以防止超时的方法),重新连接需要时间,并且在此期间,我无法处理数据来自传感器,导致我的数据偶尔出现漏洞。

我听说有一些方法可以通过使用回调函数来解决这个问题,以某种方式让核心在每次尝试连接到服务器时等待服务器的响应,同时处理我的数据从传感器获取。

我现在的代码是这样的

loop
{
    while(now==prev)
    {
        processdata;
    }
    prev=now;
    count++;
    if(count==15)
    {
        count=0;
        senddata();
    }
}
senddata()
{
    if(!serverconnected)
    {
        if(!send connect request()) error message; //after this function calls,
        if(!receive connection confirmed()) error message; //takes too long time until this function finishes executing.
    }
    send data.
}

注释部分的实际函数名称是

client.connect(host, port)
client,verify(fingerprint, host)

功能来自 WiFiClientSecure.h

有没有办法使用回调方法来解决这个问题? 在搜索解决方案时,我发现了以下头文件

espconn.h

这似乎有我可以使用的回调函数...但我不确定这是否使用不同的方法建立与服务器的 wifi 连接,也不确定如何使用这些函数本身。

只要您使用 rest api,您就无法轻松地让会话保持活动状态。所以你最好有 websocket 或 MQTT 之类的协议,会话由它们处理,你只负责随时将数据立即推送到服务器。

link 描述了如何在 Thingspeak 上完成 mqtt 客户端连接并将数据推送到它。

一些代码从 link 中删减:

#include <PubSubClient.h>

WiFiClient client;
PubSubClient mqttClient(client);
const char* server = "mqtt.thingspeak.com";

mqttClient.setServer(server, 1883);