1

我正在使用 ESP8266 模块来在线推送感官数据。我为 thingspeak 设置了它,并使用一个简单的 GET 请求来发送值。

现在我试图用 plotly 数据流服务复制这个过程,但我不知道我的请求有什么问题。

传统库(Wifi、以太网等)有一个 println() 方法,可以打印到套接字。我必须为 ESP 实现我自己的库,因为我找不到任何可靠的东西,并且注意到设备在向套接字发送某些内容后经常会将自己置于“忙碌”状态,这阻止了我发送请求块像这样的块:

client.println("POST / HTTP/1.1")
client.println("Host: arduino.plot.ly")
client.println("{\"x\":15, \"y\": 3, \"streamtoken\": \"urqcbfmjot\"\"}")

所以我试着一次写完请求。我通过深入了解依赖 Wifi 工作的 plotly 的 arduino 库找到了请求的参数(这就是为什么我不能将它与 ESP 一起使用)。到目前为止,我未能推送任何数据。这是负责发送请求的代码块:

void pushData(String temp, String humid, String pres, String lum)
{
    bool status = esp8266.openTCPConnection(IP, PORT);

    char call[] = "POST / HTTP/1.1\r\n";
    strcat(call, "Host: arduino.plot.ly\r\n");
    strcat(call, "User-Agent: Arduino\r\n");
    strcat(call, "Transfer-Encoding: chunked\r\n");
    strcat(call, "Connection: close\r\n");
    strcat(call, "\r\n");
    strcat(call, "\r\n{\"x\":15, \"y\": 3, \"streamtoken\": \"urqcbfmjot\"\"}\n\r\n");

    if (!status) return;

    esp8266.send(call);
}

void Esp8266::send(String content)
{
    String cmd;
    String msg = "Sent : ";
    bool status;

    printDebug("Writing to TCP connection");
    printDebug("Content to write :");
    printDebug(content);
    cmd = "AT+CIPSEND=" + String(content.length());
    espSerial.println(cmd);
    printDebug("Sent : " + cmd);

    status = checkResponse(">", 10);
    if (status)
    {
        espSerial.print(content);
        printDebug("Content sent");

        } else {
        printDebug("Cursor error");
        closeTCPConnection();
    }

}

我可能会补充一点,我已经成功地使用 cUrl测试了他们文档中提供的请求,但在我的实现中它也失败了。请求是:

POST  HTTP/1.1
Host: stream.plot.ly
plotly-streamtoken: urqcbfmjot

{ "x": 10, "y": 2 }

任何帮助将不胜感激。作为参考,这里是我的项目的存储库

随意使用我的图表进行测试。主机是 stream.plot.ly(来自文档)或 arduino.plot.ly(来自图书馆)。我的流令牌是urqcbfmjot,这是情节的链接

4

1 回答 1

1

您需要以分块格式发送数据。

POST / HTTP/1.1
Host: stream.plot.ly
Transfer-Encoding: chunked
plotly-streamtoken: urqcbfmjot

14
{ "x": 10, "y": 2 }

您的带有单个数据更新的 HTTP 请求应如下所示:

char call[] = "POST / HTTP/1.1\r\n";
strcat(call, "Host: stream.plot.ly\r\n");
strcat(call, "Transfer-Encoding: chunked\r\n");
strcat(call, "plotly-streamtoken: urqcbfmjot\r\n");
strcat(call, "\r\n");
strcat(call, "11\r\n"); // 11 is the length of the JSON string + "\n" in hexadecimal format
strcat(call, "{\"x\":15, \"y\": 3}\n\r\n");

要发送另一个数据点,您不需要建立另一个连接。如果你保持现有的流连接打开,你可以发送下一个块

esp8266.send("12\r\n{\"x\":30, \"y\": 10}\n\r\n");

但根据文档,

客户端停止写入数据的时间超过一分钟。如果一分钟后没有从客户端接收到任何数据,则流连接将被关闭。(可以通过在 60 秒窗口内写入心跳来维持连接,心跳只是换行符)。

如果您在一分钟内没有发送任何内容,服务器将关闭连接。"1\r\n\n\r\n"如果您不必在一分钟内发送任何内容,则可以发送一个只包含换行符的块。

但是,如果连接因任何其他原因断开并尝试重新连接,您可能仍需要检测断开连接。

于 2015-09-09T23:47:10.267 回答