Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
向Arduino中的Google脚本发送HTTP请求_Http_Arduino - Fatal编程技术网

向Arduino中的Google脚本发送HTTP请求

向Arduino中的Google脚本发送HTTP请求,http,arduino,Http,Arduino,我使用下面的代码发送和接收一个HTTP请求到自定义网站,没有问题。但是,当我尝试将主机更改为以下模式时,会收到一条失败消息。您只需将此地址放入浏览器即可查看实际响应 我需要更改const char*host=“djxmmx.net”;到const char*host=“” #包括 const char*ssid=“电话”; const char*password=“aa”; const char*host=“djxmmx.net”; const uint16_t port=17; 无效设置(){

我使用下面的代码发送和接收一个HTTP请求到自定义网站,没有问题。但是,当我尝试将主机更改为以下模式时,会收到一条失败消息。您只需将此地址放入浏览器即可查看实际响应

我需要更改const char*host=“djxmmx.net”;到const char*host=“”

#包括
const char*ssid=“电话”;
const char*password=“aa”;
const char*host=“djxmmx.net”;
const uint16_t port=17;
无效设置(){
序列号开始(115200);
延迟(10);
//我们从连接WiFi网络开始
Serial.println();
Serial.println();
串行打印(“连接到”);
序列号println(ssid);
/*将ESP8266显式设置为WiFi客户端,否则默认为,
将尝试同时充当客户端和访问点,并可能导致
WiFi网络上的其他WiFi设备出现网络问题*/
WiFi.模式(WiFi_STA);
WiFi.begin(ssid,密码);
while(WiFi.status()!=WL_已连接){
延迟(500);
连续打印(“.”);
}
Serial.println(“”);
Serial.println(“WiFi连接”);
Serial.println(“IP地址:”);
Serial.println(WiFi.localIP());
}
void循环(){
串行打印(“连接到”);
串行打印(主机);
序列号。打印(“:”);
Serial.println(端口);
//使用WiFiClient类创建TCP连接
无线客户端;
如果(!client.connect(主机、端口)){
Serial.println(“连接失败”);
延迟(5000);
返回;
}
//这将向服务器发送一个字符串
Serial.println(“向服务器发送数据”);
client.println(“你好,来自ESP8266”);
无符号长超时=毫秒();
while(client.available()==0){
如果(毫秒()-超时>5000){
Serial.println(“>>>客户端超时!”);
client.stop();
延迟(60000);
返回;
}
}
//从服务器读取回复的所有行,并将它们打印到串口
Serial.println(“从远程服务器接收”);
while(client.available()){
char ch=static_cast(client.read());
连续打印(ch);
}
//关闭连接
//Serial.println();
//Serial.println(“关闭连接”);
//client.stop();
//延迟(300000);//每5分钟执行一次,不要淹没远程服务
}

您可以使用前面提到的一些帮助来实现这一点。这需要在此链接中的Google应用程序中设置数据服务器。注意“name=Amir”如何传输数据

    /*  HTTPS on ESP8266 with follow redirects, chunked encoding support
     *  Version 2.1
     *  Author: Sujay Phadke
     *  Github: @electronicsguy
     *  Copyright (C) 2017 Sujay Phadke <electronicsguy123@gmail.com>
     *  All rights reserved.
     *
     *  Example Arduino program
     */

    #include <ESP8266WiFi.h>
    #include "HTTPSRedirect.h"
    #include "DebugMacros.h"

    // Fill ssid and password with your network credentials
    const char* ssid = "AmirPhone";
    const char* password = "aa112233";

    const char* host = "script.google.com";
    // Replace with your own script id to make server side changes
    const char *GScriptId = "AKfycby72HRgl874tst5e0FBHDa_VR6luqofn-ojiYF8KUBPmC2E3aiB";

    const int httpsPort = 443;

    // echo | openssl s_client -connect script.google.com:443 |& openssl x509 -fingerprint -noout
    const char* fingerprint = "";

    // Write to Google Spreadsheet
    String url = String("/macros/s/") + GScriptId + "/exec?name=Amir";
    // Fetch Google Calendar events for 1 week ahead
    String url2 = String("/macros/s/") + GScriptId + "/exec?cal";
    // Read from Google Spreadsheet
    String url3 = String("/macros/s/") + GScriptId + "/exec?read";

    String payload_base =  "";
    String payload = "";

    HTTPSRedirect* client = nullptr;
    // used to store the values of free stack and heap
    // before the HTTPSRedirect object is instantiated
    // so that they can be written to Google sheets
    // upon instantiation
    unsigned int free_heap_before = 0;
    unsigned int free_stack_before = 0;

    void setup() {
      Serial.begin(115200);
      Serial.flush();

      //free_heap_before = ESP.getFreeHeap();
      //free_stack_before = cont_get_free_stack(&g_cont);
      Serial.printf("Free heap before: %u\n", free_heap_before);
      Serial.printf("unmodified stack   = %4d\n", free_stack_before);

      Serial.println();
      Serial.print("Connecting to wifi: ");
      Serial.println(ssid);
      // flush() is needed to print the above (connecting...) message reliably, 
      // in case the wireless connection doesn't go through
      Serial.flush();

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

      // Use HTTPSRedirect class to create a new TLS connection
      client = new HTTPSRedirect(httpsPort);
      client->setPrintResponseBody(true);
      client->setContentTypeHeader("application/json");

      Serial.print("Connecting to ");
      Serial.println(host);

      // Try to connect for a maximum of 5 times
      bool flag = false;
      for (int i=0; i<5; i++){
        int retval = client->connect(host, httpsPort);
        if (retval == 1) {
           flag = true;
           break;
        }
        else
          Serial.println("Connection failed. Retrying...");
      }

      if (!flag){
        Serial.print("Could not connect to server: ");
        Serial.println(host);
        Serial.println("Exiting...");
        return;
      }

      if (client->verify(fingerprint, host)) {
        Serial.println("Certificate match.");
      } else {
        Serial.println("Certificate mis-match");
      }

      // Send memory data to Google Sheets
      payload = payload_base + "\"" + free_heap_before + "," + free_stack_before + "\"}";
      client->POST(url2, host, payload, false);
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      client->POST(url2, host, payload, false);

      // Note: setup() must finish within approx. 1s, or the the watchdog timer
      // will reset the chip. Hence don't put too many requests in setup()
      // ref: https://github.com/esp8266/Arduino/issues/34

      Serial.println("\nGET: Write into cell 'A1'");
      Serial.println("=========================");

      // fetch spreadsheet data
      client->GET(url, host);

      // Send memory data to Google Sheets
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      client->POST(url2, host, payload, false);

      Serial.println("\nGET: Fetch Google Calendar Data:");
      Serial.println("================================");

      // fetch spreadsheet data
      client->GET(url2, host);

      // Send memory data to Google Sheets
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      client->POST(url2, host, payload, false);

      Serial.println("\nSeries of GET and POST requests");
      Serial.println("===============================");

      Serial.printf("Free heap: %u\n", ESP.getFreeHeap());
      Serial.printf("unmodified stack   = %4d\n");//, cont_get_free_stack(&g_cont));

      // delete HTTPSRedirect object
      delete client;
      client = nullptr;
    }

    void loop() {
      static int error_count = 0;
      static int connect_count = 0;
      const unsigned int MAX_CONNECT = 20;
      static bool flag = false;
      //Serial.printf("Free heap: %u\n", ESP.getFreeHeap());
      //Serial.printf("unmodified stack   = %4d\n", cont_get_free_stack(&g_cont));

      if (!flag){
        //free_heap_before = ESP.getFreeHeap();
       // free_stack_before = cont_get_free_stack(&g_cont);
        client = new HTTPSRedirect(httpsPort);
        flag = true;
        client->setPrintResponseBody(true);
        client->setContentTypeHeader("application/json");
      }

      if (client != nullptr){
        if (!client->connected()){
          client->connect(host, httpsPort);
          payload = payload_base + "\"" + free_heap_before + "," + free_stack_before + "\"}";
          client->POST(url2, host, payload, false);
        }
      }
      else{
        DPRINTLN("Error creating client object!");
        error_count = 5;
      }

      if (connect_count > MAX_CONNECT){
        //error_count = 5;
        connect_count = 0;
        flag = false;
        delete client;
        return;
      }

      Serial.println("GET Data from cell 'A1':");
      if (client->GET(url3, host)){
        ++connect_count;
      }
      else{
        ++error_count;
        DPRINT("Error-count while connecting: ");
        DPRINTLN(error_count);
      }

      Serial.println("POST append memory data to spreadsheet:");
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      if(client->POST(url2, host, payload)){
        ;
      }
      else{
        ++error_count;
        DPRINT("Error-count while connecting: ");
        DPRINTLN(error_count);
      }

      /*
      if (!(client.reConnectFinalEndpoint())){
        ++error_count;
        DPRINT("Error-count while connecting: ");
        DPRINTLN(error_count);
      }
      else
        error_count = 0;
      */

      if (error_count > 3){
        Serial.println("Halting processor..."); 
        delete client;
        client = nullptr;
        Serial.printf("Final free heap: %u\n", ESP.getFreeHeap());
        Serial.printf("Final unmodified stack   = %4d\n");//, cont_get_free_stack(&g_cont));
        Serial.flush();
        ESP.deepSleep(0);
      }

      // In my testing on a ESP-01, a delay of less than 1500 resulted 
      // in a crash and reboot after about 50 loop runs.
      delay(4000);

    }


  [1]: https://github.com/electronicsguy/ESP8266/blob/master/HTTPSRedirect/GoogleScript.gs
/*ESP8266上的HTTPS,支持以下重定向和分块编码
*版本2.1
*作者:Sujay Phadke
*Github:@electronicsguy
*版权所有(C)2017 Sujay Phadke
*版权所有。
*
*Arduino项目示例
*/
#包括
#包括“HTTPSRedirect.h”
#包括“DebugMacros.h”
//用网络凭据填写ssid和密码
const char*ssid=“AmirPhone”;
const char*password=“aa112233”;
const char*host=“script.google.com”;
//替换为您自己的脚本id以进行服务器端更改
const char*gscript id=“AKfycby72HRgl874tst5e0FBHDa_VR6luqofn-ojiYF8KUBPmC2E3aiB”;
常数int httpsPort=443;
//echo | openssl s|u client-connectscript.google.com:443 |&openssl x509-fingerprint-noout
常量字符*指纹=”;
//写入谷歌电子表格
字符串url=String(“/macros/s/”)+gscript-id+“/exec?name=Amir”;
//提前一周获取谷歌日历事件
字符串url2=String(“/macros/s/”)+gsscriptid+“/exec?cal”;
//阅读谷歌电子表格
字符串url3=String(“/macros/s/”)+gscript-id+“/exec?read”;
字符串有效载荷_base=“”;
字符串有效载荷=”;
HTTPSRedirect*客户端=空PTR;
//用于存储空闲堆栈和堆的值
//在实例化HTTPSRedirect对象之前
//这样他们就可以被写进谷歌的表单
//实例化时
前无符号int-free\u-heap\u=0;
无符号int free\u stack\u before=0;
无效设置(){
序列号开始(115200);
Serial.flush();
//free_heap_before=特别是getFreeHeap();
//free_stack_before=cont_get_free_stack(&g_cont);
Serial.printf(“之前的空闲堆:%u\n”,之前的空闲堆);
Serial.printf(“未修改的堆栈=%4d\n”,之前的堆栈为free\u);
Serial.println();
串行打印(“连接到wifi:”);
序列号println(ssid);
//需要使用flush()可靠地打印上述(连接…)消息,
//以防无线连接无法通过
Serial.flush();
WiFi.模式(WiFi_STA);
WiFi.begin(ssid,密码);
while(WiFi.status()!=WL_已连接){
延迟(500);
连续打印(“.”);
}
Serial.println(“”);
Serial.println(“WiFi连接”);
Serial.println(“IP地址:”);
Serial.println(WiFi.localIP());
//使用HTTPSRedirect类创建新的TLS连接
客户=新的HTTPSRedirect(httpsPort);
客户端->设置打印响应库(true);
客户端->setContentTypeHeader(“应用程序/json”);
串行打印(“连接到”);
Serial.println(主机);
//尝试连接最多5次
布尔标志=假;
用于(int i=0;iconnect(主机,httpsPort);
如果(retval==1){
flag=true;
打破
}
其他的
Serial.println(“连接失败。重试…”);
}
如果(!标志){
Serial.print(“无法连接到服务器:”);
Serial.println(主机);
Serial.println(“退出…”);
返回;
}
如果(客户端->验证(指纹、主机)){
Serial.println(“证书匹配”);
}否则{
Serial.println(“证书不匹配”);
}
//将内存数据发送到Google工作表
有效载荷=有效载荷\u base+“\”“+空闲\u heap\u before+”,“+空闲\u stack\u before+”\“}”;
客户端->POST(url2,主机,有效负载,false);
payload=payload\u base;//+“\”“+特别是getFreeHeap()+”,
    /*  HTTPS on ESP8266 with follow redirects, chunked encoding support
     *  Version 2.1
     *  Author: Sujay Phadke
     *  Github: @electronicsguy
     *  Copyright (C) 2017 Sujay Phadke <electronicsguy123@gmail.com>
     *  All rights reserved.
     *
     *  Example Arduino program
     */

    #include <ESP8266WiFi.h>
    #include "HTTPSRedirect.h"
    #include "DebugMacros.h"

    // Fill ssid and password with your network credentials
    const char* ssid = "AmirPhone";
    const char* password = "aa112233";

    const char* host = "script.google.com";
    // Replace with your own script id to make server side changes
    const char *GScriptId = "AKfycby72HRgl874tst5e0FBHDa_VR6luqofn-ojiYF8KUBPmC2E3aiB";

    const int httpsPort = 443;

    // echo | openssl s_client -connect script.google.com:443 |& openssl x509 -fingerprint -noout
    const char* fingerprint = "";

    // Write to Google Spreadsheet
    String url = String("/macros/s/") + GScriptId + "/exec?name=Amir";
    // Fetch Google Calendar events for 1 week ahead
    String url2 = String("/macros/s/") + GScriptId + "/exec?cal";
    // Read from Google Spreadsheet
    String url3 = String("/macros/s/") + GScriptId + "/exec?read";

    String payload_base =  "";
    String payload = "";

    HTTPSRedirect* client = nullptr;
    // used to store the values of free stack and heap
    // before the HTTPSRedirect object is instantiated
    // so that they can be written to Google sheets
    // upon instantiation
    unsigned int free_heap_before = 0;
    unsigned int free_stack_before = 0;

    void setup() {
      Serial.begin(115200);
      Serial.flush();

      //free_heap_before = ESP.getFreeHeap();
      //free_stack_before = cont_get_free_stack(&g_cont);
      Serial.printf("Free heap before: %u\n", free_heap_before);
      Serial.printf("unmodified stack   = %4d\n", free_stack_before);

      Serial.println();
      Serial.print("Connecting to wifi: ");
      Serial.println(ssid);
      // flush() is needed to print the above (connecting...) message reliably, 
      // in case the wireless connection doesn't go through
      Serial.flush();

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

      // Use HTTPSRedirect class to create a new TLS connection
      client = new HTTPSRedirect(httpsPort);
      client->setPrintResponseBody(true);
      client->setContentTypeHeader("application/json");

      Serial.print("Connecting to ");
      Serial.println(host);

      // Try to connect for a maximum of 5 times
      bool flag = false;
      for (int i=0; i<5; i++){
        int retval = client->connect(host, httpsPort);
        if (retval == 1) {
           flag = true;
           break;
        }
        else
          Serial.println("Connection failed. Retrying...");
      }

      if (!flag){
        Serial.print("Could not connect to server: ");
        Serial.println(host);
        Serial.println("Exiting...");
        return;
      }

      if (client->verify(fingerprint, host)) {
        Serial.println("Certificate match.");
      } else {
        Serial.println("Certificate mis-match");
      }

      // Send memory data to Google Sheets
      payload = payload_base + "\"" + free_heap_before + "," + free_stack_before + "\"}";
      client->POST(url2, host, payload, false);
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      client->POST(url2, host, payload, false);

      // Note: setup() must finish within approx. 1s, or the the watchdog timer
      // will reset the chip. Hence don't put too many requests in setup()
      // ref: https://github.com/esp8266/Arduino/issues/34

      Serial.println("\nGET: Write into cell 'A1'");
      Serial.println("=========================");

      // fetch spreadsheet data
      client->GET(url, host);

      // Send memory data to Google Sheets
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      client->POST(url2, host, payload, false);

      Serial.println("\nGET: Fetch Google Calendar Data:");
      Serial.println("================================");

      // fetch spreadsheet data
      client->GET(url2, host);

      // Send memory data to Google Sheets
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      client->POST(url2, host, payload, false);

      Serial.println("\nSeries of GET and POST requests");
      Serial.println("===============================");

      Serial.printf("Free heap: %u\n", ESP.getFreeHeap());
      Serial.printf("unmodified stack   = %4d\n");//, cont_get_free_stack(&g_cont));

      // delete HTTPSRedirect object
      delete client;
      client = nullptr;
    }

    void loop() {
      static int error_count = 0;
      static int connect_count = 0;
      const unsigned int MAX_CONNECT = 20;
      static bool flag = false;
      //Serial.printf("Free heap: %u\n", ESP.getFreeHeap());
      //Serial.printf("unmodified stack   = %4d\n", cont_get_free_stack(&g_cont));

      if (!flag){
        //free_heap_before = ESP.getFreeHeap();
       // free_stack_before = cont_get_free_stack(&g_cont);
        client = new HTTPSRedirect(httpsPort);
        flag = true;
        client->setPrintResponseBody(true);
        client->setContentTypeHeader("application/json");
      }

      if (client != nullptr){
        if (!client->connected()){
          client->connect(host, httpsPort);
          payload = payload_base + "\"" + free_heap_before + "," + free_stack_before + "\"}";
          client->POST(url2, host, payload, false);
        }
      }
      else{
        DPRINTLN("Error creating client object!");
        error_count = 5;
      }

      if (connect_count > MAX_CONNECT){
        //error_count = 5;
        connect_count = 0;
        flag = false;
        delete client;
        return;
      }

      Serial.println("GET Data from cell 'A1':");
      if (client->GET(url3, host)){
        ++connect_count;
      }
      else{
        ++error_count;
        DPRINT("Error-count while connecting: ");
        DPRINTLN(error_count);
      }

      Serial.println("POST append memory data to spreadsheet:");
      payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
      if(client->POST(url2, host, payload)){
        ;
      }
      else{
        ++error_count;
        DPRINT("Error-count while connecting: ");
        DPRINTLN(error_count);
      }

      /*
      if (!(client.reConnectFinalEndpoint())){
        ++error_count;
        DPRINT("Error-count while connecting: ");
        DPRINTLN(error_count);
      }
      else
        error_count = 0;
      */

      if (error_count > 3){
        Serial.println("Halting processor..."); 
        delete client;
        client = nullptr;
        Serial.printf("Final free heap: %u\n", ESP.getFreeHeap());
        Serial.printf("Final unmodified stack   = %4d\n");//, cont_get_free_stack(&g_cont));
        Serial.flush();
        ESP.deepSleep(0);
      }

      // In my testing on a ESP-01, a delay of less than 1500 resulted 
      // in a crash and reboot after about 50 loop runs.
      delay(4000);

    }


  [1]: https://github.com/electronicsguy/ESP8266/blob/master/HTTPSRedirect/GoogleScript.gs