ESP8266 是一款低成本的Wi-Fi模块,常用于物联网项目。它可以通过其内置的TCP/IP协议栈连接到互联网,并可以与各种在线服务进行通信。
Firestore 是一种NoSQL文档数据库,由Google提供,适用于移动和Web应用程序。它以其灵活性、实时性和可扩展性而闻名。
REST API(Representational State Transfer Application Programming Interface)是一种基于HTTP协议的网络应用程序接口设计风格,用于分布式系统之间的数据交互。
以下是一个使用ESP8266通过HTTP POST请求向Firestore发送数据的示例代码:
#include <ESP8266WiFi.h>
#include <WiFiClientSecureBearSSL.h>
const char* ssid = "YourSSID";
const char* password = "YourPassword";
const char* firestoreProjectId = "your-firestore-project-id";
const char* firestoreApiKey = "your-firestore-api-key";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to the WiFi network");
}
void loop() {
if (sendDataToFirestore()) {
Serial.println("Data sent successfully!");
} else {
Serial.println("Failed to send data.");
}
delay(5000); // Send data every 5 seconds
}
bool sendDataToFirestore() {
const char* path = "/v1/projects/";
String url = String(path) + firestoreProjectId + "/databases/(default)/documents/sensor_data";
WiFiClientSecure client;
client.setInsecure(); // Disable SSL verification for simplicity
if (!client.connect("firestore.googleapis.com", 443)) {
Serial.println("Connection to Firestore failed");
return false;
}
String json = "{\"field1\":\"value1\",\"field2\":2}";
String authHeader = "Authorization: Bearer " + String(firestoreApiKey);
String contentType = "Content-Type: application/json";
client.println("POST " + url + " HTTP/1.1");
client.println("Host: firestore.googleapis.com");
client.println(authHeader);
client.println(contentType);
client.println("Content-Length: " + String(json.length()));
client.println();
client.println(json);
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.stop();
return true;
}
问题1:连接失败
问题2:认证失败
问题3:数据格式错误
通过以上步骤,你应该能够成功地从ESP8266发送POST请求到Firestore。
领取专属 10元无门槛券
手把手带您无忧上云