Связь между сервером Flask и несколькими клиентами Arduino - PullRequest
0 голосов
/ 27 апреля 2020

Я ищу решение. У меня такая ситуация:

веб-сервер (python Flask) - Raspberry

клиент / сервер (arduino) - ESP 8266, ESP01, ESP32-светодиод и датчики

В моем raspberry мой веб-сервер предоставляет мне веб-страницу со списком клиентов и их IP-адресом с подключением к их веб-серверу. Теперь я могу sh создать кнопку в строках клиента для включения или выключения светодиода. Я пытаюсь сделать это без открытия веб-страницы на клиенте, а только отправить команду клиентам. Я знаю, что возможно создать socketIO, но я бы нашел решение без него. спасибо за помощь

from flask import Flask, render_template, request

app = Flask(__name__)

lista = []


def addlist(l):
    ip = []
    for i in lista:
        ip.append(i.get("ip"))
    if l.get("ip") in ip:
        c = 0
        for i in lista:
            if l.get("ip") == i.get("ip"):
                lista[c] = l
            c+=1
    else:
        lista.append(l)


@app.route("/")
def index():
    print(lista)
    return render_template('index.html', elenco=lista)


@app.route("/data", methods=["GET", "POST"])
def data():
    if request.method == "GET":
        addlist(request.args)
    return render_template('index.html', elenco=lista)


if __name__ == "__main__":
    app.run(host="192.192.192.192", port=5000)

код клиента в Arduino ide



#ifdef ESP8266
  #include <ESP8266WiFi.h>       // Built-in
  #include <ESP8266WiFiMulti.h>  // Built-in
#else
  #include <WiFi.h>       // Built-in
  #include <WiFiMulti.h>  // Built-in
#endif
#include <WiFiClient.h> // Built-in
#include <Wire.h>       // Built-in

// Local ESP web-server address
String UploadData;

const char* ServerHost = "192.192.192.192"; // this is the IP address of the central sensor server
uint16_t port = 5000;

String tipo;

WiFiClient client;

#ifdef ESP8266
  ESP8266WiFiMulti wifiMulti;
#else
  WiFiMulti wifiMulti;
#endif


void setup() {

  Serial.begin(115200);
  WiFi.begin("namessd", "password");
  tipo = "LED";

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting..");
  }
  Serial.println("Connected to WiFi Network");
  Serial.print(WiFi.localIP().toString());
  Serial.print("  -  ");
  Serial.println(tipo);
}

void loop() {
  UploadData = "data?ip=" + WiFi.localIP().toString();
  UploadData += "&tipo=" + tipo;

  Serial.println(UploadData);
  SendHttpPOST();
  delay(5000);
}

void SendHttpPOST() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting connection...");
    Serial.print(ServerHost);
    Serial.print(":");
    Serial.print(port);
    if (client.connect(ServerHost,port)) {
      Serial.println("connected");
    } else {
      Serial.println(" try again in 500 ms");
      delay(500);// Wait 0.5 seconds before retrying
    }
  }
  client.println("GET /"+UploadData+" HTTP/1.1\n\r");
  Serial.println("GET /"+UploadData+" HTTP/1.1\n\r");
  client.println("Host: "+String(ServerHost));
  Serial.println("Host: "+String(ServerHost));
  delay(500); // Essential delay to enable the webserver to receive the HTTP and process it
  Serial.println("Connection: close");
  client.println("Connection: close"); 
  client.stop();
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table, td {
            border: 1px solid black;
        }

        th, td {
            padding: 10px;
        }
</style>
</head>
<body>
{% if elenco %}
    {{ elenco }} <br/>
    <table>
    {% for e in elenco %}
        <tr>
        {% for y in e %}
            <td>
            {% if y == "ip" %}
                <a href="http://{{ e.get(y) }}:5000">{{ e.get(y) }}</a>  - INSERT BUTTON NEAR THIS
            {% else %}
                {{ e.get(y) }}
            {% endif %}
            </td>
        {% endfor %}
        </tr><br/>
    {% endfor %}
    </table>
{% else %}
    <h1>No sensors on line</h1>
{% endif %}

</form>
</body>
</html>
...