English 中文(简体)
ESP32 with Flask server to display data in web
原标题:

`I m attempting to send data from an ESP32 to a Flask application on my PC for real-time visualization. I ve followed tutorials and reviewed the codes, yet I m still encountering a connection refused error on the ESP32. I ve double-checked IP addresses and ports, and I m confident they match. Any insights into why this issue might be occurring?

app.py code

from flask import Flask, render_template, request, jsonify
import json

app = Flask(__name__, template_folder= template )

# Almacena los datos recibidos del ESP32
data = { gasto : [],  presion : [],  vibracion : []}


@app.route( / )
def index():
    return render_template( index.html )


@app.route( /data , methods=[ POST ])
def receive_data():
    try:
        content = request.get_json()

        gasto = content[ gasto ]
        presion = content[ presion ]
        vibracion = content[ vibracion ]

        data[ gasto ].append(gasto)
        data[ presion ].append(presion)
        data[ vibracion ].append(vibracion)

        print(f"Received data: gasto={gasto}, presion={presion}, vibracion={vibracion}")
        return jsonify({ success : True})
    except Exception as e:
        print(f"Error receiving data: {str(e)}")
        return jsonify({ success : False,  error : str(e)})


@app.route( /get_data )
def get_data():
    return jsonify(data)


if __name__ ==  __main__ :
    app.run(debug=True)

esp32 code

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "ASUS_F4";       // Nombre de tu red Wi-Fi
const char* password = "banana_6424"; // Contraseña de tu red Wi-Fi
const char* serverAddress = "http://192.168.50.177:5000/data"; // Cambia la dirección IP con la de tu PC

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 WiFi");
}

void loop() {
  float gasto = 123.45; // Valor simulado de gasto
  float presion = 67.89; // Valor simulado de presión
  float vibracion = 0.12; // Valor simulado de vibración

  // Crea un objeto JSON
  DynamicJsonDocument jsonDoc(200);
  jsonDoc["gasto"] = gasto;
  jsonDoc["presion"] = presion;
  jsonDoc["vibracion"] = vibracion;

  // Serializa el JSON en una cadena
  String payload;
  serializeJson(jsonDoc, payload);

  // Crea una instancia de HTTPClient
  HTTPClient http;
 Serial.println("Server Address: " + String(serverAddress));
  // Envía la solicitud POST al servidor
  http.begin(serverAddress);
  http.addHeader("Content-Type", "application/json");
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    Serial.printf("HTTP Response code: %d
", httpResponseCode);
    String response = http.getString();
    Serial.println(response);
  } else {
    Serial.printf("HTTP Request failed: %s
", http.errorToString(httpResponseCode).c_str());
  }

  http.end();

  delay(5000); // Espera 5 segundos antes de enviar el siguiente dato
}

Thxs

Monitoring a system and display data on a website`

问题回答

There are a few things you could try:

  • Make sure that the ESP32 is connected to the same network where the Flask server is running.
  • Try to communicate with the server using the browser, or curl / Postman to send the exact same request that the ESP32 would send. Ideally you can try doing this from a different computer connected to the same network. If this doesn t work, then you know the problem isn t on the ESP32 side.




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签