我是 Django 的新手,甚至是 ESP8266 的新手。我正在尝试使用 POST 方法将信息从 ESP8266 发送到我的 Django 服务器。信息如下所示:
Temperature=24.60&Humiditi=30.30&Soil=0.00&Water=0&Light=602.00
所以我的 ESP8266 代码如下所示:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#define POMPA1 D0
const char* ssid = "****";
const char* password = "*****";
String serverName = "http://127.0.0.1:8000/data/";
int POMP1 = HIGH;
char output;
String output_str;
String payload;
String server_output = "rain";
unsigned long lastTime = -20000;
unsigned long currentTime = 0;
unsigned long remeberedTime = 0;
int timeDelay = 20000;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
pinMode(POMPA1, OUTPUT);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(2000);
Serial.print(".");
Serial.println("");
Serial.print("Connected to WiFi network with IP Adress: ");
Serial.println(WiFi.localIP());
Serial.print("DNS IP: ");
Serial.println(WiFi.dnsIP());
}
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
}
void loop() { // run over and over
if (Serial.available()) {
output_str = Serial.readString();
Serial.println(output_str);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCode = http.POST(output_str);
payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
http.end();
}
else {
Serial.println("Server Disconnected");
}
}
Serial.println(payload);
if (payload=="pompa1"){
currentTime = millis();
Serial.println("Let's rain");
if (currentTime >= lastTime + timeDelay) {
remeberedTime = currentTime;
lastTime = currentTime + 10000;
}
if (millis() - remeberedTime <= 10000){
digitalWrite(POMPA1, LOW);
}
else {
digitalWrite(POMPA1, HIGH);
}
}
delay(5000);
}
控制台中的输出是:
-> Connected to WiFi network with IP Adress: 192.168.0.101
-> DNS IP: 192.168.0.1
所以这就是为什么我知道服务器连接没有问题。接下来是我的网址:
urlpatterns =[
path("", data, name="main-page"),
path("data/", get_data, name="get-data")
]
以下是我的观点:
def data(request):
if request.method=="GET":
return HttpResponse("<h1>Tutaj będą twoje wyniki</h1>")
def get_data(request):
if request.method=="POST":
print(request)
return HttpResponse("<h1>Tutaj są twoje wyniki </h1>")
现在,我只想以某种方式从 ESP 获取信息到 Django 服务器,所以接下来,我可以将它们保存在我的数据库中。有人知道问题出在哪里吗?