Trouble Sending Data from ESP32 to Django Project on Local Computer

I’m trying to send data from my ESP32 to a Django project deployed on my computer. However, the ESP32 seems cannot fetch the address of Django project, here are details:

My computer and ESP32 chip are connected to the same Wi-Fi network. The Django project is running on 127.0.0.1:8000, and I’m attempting to send data from the ESP32 to xxx.xxx.xxx.xxx:8000/suitcase/esp32_test (where xxx.xxx.xxx.xxx is my computer’s IP address). However, the ESP32 was unable to successfully transmit data to this address, Django local terminal didn’t show anything about ESP32’s message. I’ve tried changing the server address in the ESP32 code to 127.0.0.1:8000, but it apparently didn’t resolve the issue. What could be causing this problem and how can I troubleshoot it?

The esp32 code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#include <HardwareSerial.h>
#include <HTTPClient.h>
#include "WiFi.h"
#define GPSRX_PIN 16
#define GPSTX_PIN 17
#define GPS_SERIAL Serial2
const String serverAddress = "xxx.xxx.xxx.xxx:8000/suitcase/esp32_test";
void initWiFi(String ssid, String password) {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("***********Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.RSSI());
}
bool HaveUsefulData(String data){
if(data.startsWith("$GNGLL")){
return true;
}else{
return false;
}
}
String ExtractProxy(String data){
int commaIndex = data.indexOf(',');
if (commaIndex != -1 && data.length() > commaIndex + 13) {
String longitude = data.substring(commaIndex + 1, commaIndex + 10);
String latitude = data.substring(commaIndex + 14, commaIndex + 24);
return "{'latitude': "+ latitude +", 'longitude': "+ longitude +"}";
}else{
return "";
}
}
void SendProxyToServer(String proxy){
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverAddress);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
Serial.println("check2");
int httpResponseCode = http.POST(proxy);
if (httpResponseCode > 0) {//*********where the program cannot get in **************//
Serial.println("check3");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
};
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
GPS_SERIAL.begin(115200, SERIAL_8N1, GPSTX_PIN, GPSRX_PIN);
const String ssid = "Redmi K70 Pro";
const String password = "password";
initWiFi(ssid, password);
}
void loop() {
static String ubxData = "";
while (GPS_SERIAL.available()) {
char c = GPS_SERIAL.read();
ubxData += c;
if (c == 'n') {
if (HaveUsefulData(ubxData)){
String ProxyJSON = ExtractProxy(ubxData);
Serial.println(ProxyJSON);
if(ProxyJSON != ""){
Serial.println("check1");
SendProxyToServer(ProxyJSON);
}
}
ubxData = "";
}
}
}
</code>
<code>#include <HardwareSerial.h> #include <HTTPClient.h> #include "WiFi.h" #define GPSRX_PIN 16 #define GPSTX_PIN 17 #define GPS_SERIAL Serial2 const String serverAddress = "xxx.xxx.xxx.xxx:8000/suitcase/esp32_test"; void initWiFi(String ssid, String password) { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("***********Connecting to WiFi .."); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(1000); } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Serial.println(WiFi.RSSI()); } bool HaveUsefulData(String data){ if(data.startsWith("$GNGLL")){ return true; }else{ return false; } } String ExtractProxy(String data){ int commaIndex = data.indexOf(','); if (commaIndex != -1 && data.length() > commaIndex + 13) { String longitude = data.substring(commaIndex + 1, commaIndex + 10); String latitude = data.substring(commaIndex + 14, commaIndex + 24); return "{'latitude': "+ latitude +", 'longitude': "+ longitude +"}"; }else{ return ""; } } void SendProxyToServer(String proxy){ if (WiFi.status() == WL_CONNECTED) { HTTPClient http; http.begin(serverAddress); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); Serial.println("check2"); int httpResponseCode = http.POST(proxy); if (httpResponseCode > 0) {//*********where the program cannot get in **************// Serial.println("check3"); Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); } http.end(); } else { Serial.println("WiFi Disconnected"); } }; void setup() { // put your setup code here, to run once: Serial.begin(115200); GPS_SERIAL.begin(115200, SERIAL_8N1, GPSTX_PIN, GPSRX_PIN); const String ssid = "Redmi K70 Pro"; const String password = "password"; initWiFi(ssid, password); } void loop() { static String ubxData = ""; while (GPS_SERIAL.available()) { char c = GPS_SERIAL.read(); ubxData += c; if (c == 'n') { if (HaveUsefulData(ubxData)){ String ProxyJSON = ExtractProxy(ubxData); Serial.println(ProxyJSON); if(ProxyJSON != ""){ Serial.println("check1"); SendProxyToServer(ProxyJSON); } } ubxData = ""; } } } </code>
#include <HardwareSerial.h>
#include <HTTPClient.h>
#include "WiFi.h"
#define GPSRX_PIN 16
#define GPSTX_PIN 17
#define GPS_SERIAL Serial2

const String serverAddress = "xxx.xxx.xxx.xxx:8000/suitcase/esp32_test";

void initWiFi(String ssid, String password) {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("***********Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println("WiFi connected");

  Serial.println("IP address: ");
    Serial.println(WiFi.localIP()); 
    Serial.println(WiFi.RSSI()); 
}

bool HaveUsefulData(String data){
  if(data.startsWith("$GNGLL")){
    return true;
  }else{
    return false;
  }
}

String ExtractProxy(String data){
    int commaIndex = data.indexOf(',');

    if (commaIndex != -1 && data.length() > commaIndex + 13) {

      String longitude = data.substring(commaIndex + 1, commaIndex + 10);

      String latitude = data.substring(commaIndex + 14, commaIndex + 24);


      return "{'latitude': "+ latitude +", 'longitude': "+ longitude +"}";
    }else{
      return "";
    }
}

void SendProxyToServer(String proxy){

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin(serverAddress); 
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    Serial.println("check2");


    int httpResponseCode = http.POST(proxy);
    if (httpResponseCode > 0) {//*********where the program cannot get in **************//
      Serial.println("check3");
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    } else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }


    http.end();
  } else {
    Serial.println("WiFi Disconnected");
  }
};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  GPS_SERIAL.begin(115200, SERIAL_8N1, GPSTX_PIN, GPSRX_PIN);

  const String ssid     = "Redmi K70 Pro";
  const String password = "password";
  initWiFi(ssid, password);
}

void loop() {
  static String ubxData = "";
  while (GPS_SERIAL.available()) {
          char c = GPS_SERIAL.read();
          ubxData += c;
          if (c == 'n') {

              if (HaveUsefulData(ubxData)){
                
                String ProxyJSON = ExtractProxy(ubxData);

                Serial.println(ProxyJSON);

                if(ProxyJSON != ""){
                  Serial.println("check1");
                  SendProxyToServer(ProxyJSON);
                }
                
              }

              ubxData = "";
              }
  }

}

related code in views.py:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@csrf_exempt
def esp32_test(request):
if request.method == 'POST':
longitude = request.POST.get('longitude', '')
latitude = request.POST.get('latitude', '')
print("Received data from ESP32:", request.POST)
return JsonResponse({'message': 'Data received successfully'})
return JsonResponse({'error': 'Invalid request method'})
</code>
<code>@csrf_exempt def esp32_test(request): if request.method == 'POST': longitude = request.POST.get('longitude', '') latitude = request.POST.get('latitude', '') print("Received data from ESP32:", request.POST) return JsonResponse({'message': 'Data received successfully'}) return JsonResponse({'error': 'Invalid request method'}) </code>
@csrf_exempt
def esp32_test(request):
    if request.method == 'POST':

        longitude = request.POST.get('longitude', '')
        latitude = request.POST.get('latitude', '')


        print("Received data from ESP32:", request.POST)


        return JsonResponse({'message': 'Data received successfully'})


    return JsonResponse({'error': 'Invalid request method'})

urls.py:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>urlpatterns = [
path("esp32_test", views.esp32_test, name="esp32_test")
]
</code>
<code>urlpatterns = [ path("esp32_test", views.esp32_test, name="esp32_test") ] </code>
urlpatterns = [
    path("esp32_test", views.esp32_test, name="esp32_test")
]

everytime the ESP32 chip sent request to Django I will get this error on the serial monitor

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{'latitude': xxxxx.xxxx, 'longitude': xxxx.xxxx}
check1
check2
Error code: -1
</code>
<code>{'latitude': xxxxx.xxxx, 'longitude': xxxx.xxxx} check1 check2 Error code: -1 </code>
{'latitude': xxxxx.xxxx, 'longitude': xxxx.xxxx}
check1
check2
Error code: -1

the “check3” print instruction cannot be triggered.

I’ve attempted to substitute my computer’s address in the ESP32 code with a test URL from Pipedream, and sent messages from the ESP32 to pipedream.com, the website successfully received the data from my ESP32, under which circumstances the serial monitor show:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{'latitude': xxxxx.xxxx, 'longitude': xxxx.xxxx}
check1
check2
check3
HTTP Response code: 200
</code>
<code>{'latitude': xxxxx.xxxx, 'longitude': xxxx.xxxx} check1 check2 check3 HTTP Response code: 200 </code>
{'latitude': xxxxx.xxxx, 'longitude': xxxx.xxxx}
check1
check2
check3
HTTP Response code: 200

Additionally, I tested the receiving capability of Django using the POST method in Postman with suitable body, and Django was able to receive the data and print it out as well.

I assume that this issue may have association with my network, or I cannot give the correct address of my Django project in ESP32 code, however, I cannot find out ways to solve the problem.Despite these successful tests, I’m still puzzled by the issue of why my Django project isn’t receiving data directly from the ESP32 when connected to my computer. Any advice or suggestions on how to troubleshoot this further would be greatly appreciated!

New contributor

LuneSponight is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật