![](/img/trans.png)
[英]How do I make a secure API request from an Arduino ESP32, programmed in the Arduino IDE using ArduinoJson?
[英]Can't get data from Googlesheet using esp32 and Arduinojson
我是 esp32 的新手,現在我正在嘗試使用 ArduinoJson 獲取數據,在我的 googlesheet“A1”中有一個數字,我想讓 esp32 獲取它,我將我的 googlesheet 發送到互聯網並使用以下網址: https: //spreadsheets.google.com/feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1 。 我的號碼是對象>提要>條目>0>內容>$t。
問題來了:當我使用esp32獲取這個json數據時,我無法獲取,甚至我的esp32連接到googlesheet
如果您需要,這是我的完整代碼:
#include <ArduinoJson.h>
#include <WiFi.h>
#include <SPI.h>
WiFiClient client;
const char* ssid = "wwwwwwwww";
const char* password = "wwwwwwww";
const char* server = "spreadsheets.google.com";
const char* resource = "/feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1";
const unsigned long HTTP_TIMEOUT = 10000; // max respone time from server
const size_t MAX_CONTENT_SIZE = 1024; // max size of the HTTP response
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
struct clientData {
char item[8];
};
void setup() {
Serial.begin(9600);
while (!Serial) {
}
Serial.println("Serial ready");
Serial.print("Connecting to wifi: ");
Serial.println(ssid);
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());
}
void loop() {
if(connect(server)) {
if(sendRequest(server, resource) && skipResponseHeaders()) {
clientData clientData;
if(readReponseContent(&clientData)) {
printclientData(&clientData);
}
}
}
disconnect();
wait();
}
bool connect(const char* hostName) {
Serial.print("Connect to ");
Serial.println(hostName);
bool ok = client.connect(hostName, 80);
Serial.println(ok ? "Connected" : "Connection Failed!");
return ok;
}
bool sendRequest(const char* host, const char* resource) {
Serial.print("GET ");
Serial.println(resource);
client.print("GET ");
client.print(resource);
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Connection: close");
client.println();
return true;
}
bool skipResponseHeaders() {
// HTTP headers end with an empty line
char endOfHeaders[] = "\r\n\r\n";
client.setTimeout(HTTP_TIMEOUT);
bool ok = client.find(endOfHeaders);
if (!ok) {
Serial.println("No response or invalid response!");
}
return ok;
}
bool readReponseContent(struct clientData* clientData) {
const size_t bufferSize = 5*JSON_ARRAY_SIZE(1) +
JSON_ARRAY_SIZE(5) + 10*JSON_OBJECT_SIZE(1) +
6*JSON_OBJECT_SIZE(2) + 7*JSON_OBJECT_SIZE(3) +
JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(7) + JSON_OBJECT_SIZE(15);
DynamicJsonBuffer jsonBuffer(bufferSize);
JsonObject& root = jsonBuffer.parseObject(client);
if (!root.success()) {
Serial.println("JSON parsing failed!");
return false;
}
strcpy(clientData->item, root["feed"]["entry"][0]["content"]["$t"]);
return true;
}
void printclientData(const struct clientData* clientData) {
Serial.print("Time = ");
Serial.println(clientData->item);
}
void disconnect() {
Serial.println("Disconnect");
client.stop();
}
void wait() {
Serial.println("Wait 20 seconds");
delay(20000);
}
串行輸出:
Connecting to wifi: wwwwwwwwww
..
WiFi connected
IP address:
xxx.xxx.x.xx
Connect to spreadsheets.google.com
Connected
GET /feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1
JSON parsing failed!
Disconnect
Wait 20 seconds
如果我基於您的 json 輸出並使用ArduinoJson Assistant計算 bufferSize,我會得到:
const size_t capacity = 5*JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(5) + 10*JSON_OBJECT_SIZE(1) + 6*JSON_OBJECT_SIZE(2) + 7*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(7) + JSON_OBJECT_SIZE(15) + 2270;
注意到最后的+ 2270
了嗎? 您解析 json 失敗,因為您在 bufferSize 中缺少 2270 個字節(即您的 bufferSize 太小)。
更新
我沒有嘗試調試您的代碼,但我手頭有我的 Web 客戶端代碼,所以我只需運行它就可以了。
我的代碼基於 HTTPClient,它是 ESP32 Arduino Core 的一部分,您可以在 ESP-Arduino github 上進一步閱讀。 它基於您使用的 Arduino WifiClient,但具有更簡單易用的 API,尤其是用於獲取響應負載。 我建議你看看。
我將 ArduinoJson 添加到我的代碼中,以查看解析接收到的 json 是否有任何問題,但 mines 是基於 v6 語法的,如果您仍然覺得使用 v5 更容易,則可以將其轉換為 v5 語法。 順便說一句,json 文檔包含 Unicode,我必須在程序頂部添加#define ARDUINOJSON_DECODE_UNICODE 1
才能使其工作,否則我會得到一個deserialization error: NotSupported
。
#define ARDUINOJSON_DECODE_UNICODE 1
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>
HTTPClient http;
const char* ssid = "your_SSID";
const char* password = "your_password";
const char* url = "https://spreadsheets.google.com/feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1";
void setup() {
Serial.begin(115200);
while (!Serial) {}
Serial.print("Connecting to wifi: "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.print(".");
}
Serial.println();
Serial.print("IP address: "); Serial.println(WiFi.localIP());
http.begin(url);
int httpCode = http.GET(); //send GET request
if (httpCode != 200) {
Serial.print("Error on HTTP request: ");
Serial.println(httpCode);
} else {
String payload = http.getString();
Serial.println(payload);
// the following is based on ArduinoJson v6 API
StaticJsonDocument<4000> doc;
DeserializationError err = deserializeJson(doc, payload);
if (err) {
Serial.print("deserialization error ");
Serial.println(err.c_str());
}
JsonObject feed = doc["feed"];
const char* clientData = feed["entry"][0]["content"]["$t"];
Serial.println(clientData);
}
http.end(); //Free the resources
}
void loop() {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.