我是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服务器上,然后保存到数据库中。有人知道问题出在哪里吗?
1条答案
按热度按时间db2dz4w81#
上面的人让我回到了正确的轨道上。他们是对的,我给了错误的地址,因为127.0.0.1是用于本地主机上的应用程序。所以首先我需要将地址更改为0.0.0.0,以允许连接到服务器到其他设备连接到网络。
然后,我需要检查我的计算机的IP,因为它是托管服务器,所以这应该是我应该连接的IP。我检查IP使用(Linux):
然后我需要在www.example.com的Django设置中添加地址settings.py
那么我只需要更改ESP82666的代码,以连接到正确的IP:
而且效果很完美!谢谢大家的贡献,终于我可以继续我的项目了。