杰瑞科技汇

Flask如何实现WiFi控制?

Of course! The phrase "Python Flask WiFi" can mean a few different things. I'll cover the most common interpretations, from simple to advanced, with complete code examples for each.

Flask如何实现WiFi控制?-图1
(图片来源网络,侵删)

Here are the main ways you can combine Flask and WiFi:

  1. Building a Web Interface to Control WiFi-Connected Hardware (Most Common)

    Example: A Raspberry Pi runs a Flask app. The app serves a webpage with buttons. When you click a button, the Flask app sends a command to an Arduino (connected via WiFi) to turn an LED on or off.

  2. Building a Flask App that Runs on a Device with WiFi

    • Example: You deploy a Flask application on a Raspberry Pi or a small server. The app is accessible on your local network (e.g., http://192.168.1.50:5000) and can be controlled from any device on the same network.
  3. A Flask App to Manage the WiFi Connection of the Host Device

    Example: A Flask app running on a Raspberry Pi that lets you connect to new WiFi networks or view the current connection status through a web browser.

Let's dive into each one.


Scenario 1: Flask Web Interface to Control WiFi Hardware (e.g., an ESP32/ESP8266)

This is the most powerful and common use case. You'll create a web UI that acts as a remote control for a physical device.

Concept:

  • Client (Hardware): An ESP32 or ESP8266 microcontroller. It creates its own WiFi access point or connects to your router. It hosts a simple web server that listens for commands.
  • Server (Flask App): A Python Flask application running on your computer or a Raspberry Pi. It serves a user-friendly HTML page.
  • Communication: The user interacts with the Flask web page. The page sends an HTTP request to the hardware device, which then performs an action (like turning on an LED).

Part A: The Flask Web Server (Your Computer)

This server will display the control panel.

  1. Install Flask:

    pip install Flask
  2. Create the Flask App (app.py):

    from flask import Flask, render_template, request
    app = Flask(__name__)
    # Replace with the IP address of your ESP32/ESP8266
    # Find this in the Arduino IDE serial monitor after uploading the code below.
    DEVICE_IP = "192.168.4.1" 
    @app.route('/')
    def index():
        """Renders the main control page."""
        return render_template('index.html')
    @app.route('/control')
    def control():
        """Handles the control commands."""
        command = request.args.get('command')
        if command:
            # Construct the URL for the device
            device_url = f"http://{DEVICE_IP}/?command={command}"
            try:
                # We use a simple request to trigger the device's action
                # The device doesn't need to send a response back to us.
                import requests
                requests.get(device_url, timeout=1)
                return f"Command '{command}' sent successfully!"
            except requests.exceptions.RequestException as e:
                return f"Error sending command: {e}"
        return "No command received."
    if __name__ == '__main__':
        # Run on 0.0.0.0 to be accessible from other devices on the network
        app.run(host='0.0.0.0', port=5000, debug=True)
  3. Create the HTML Template (templates/index.html):

    • Create a folder named templates in the same directory as app.py.
    • Inside templates, create index.html:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>WiFi LED Control</title>
        <style>
            body { font-family: sans-serif; text-align: center; margin-top: 50px; }
            h1 { color: #333; }
            .button { padding: 15px 30px; font-size: 18px; margin: 10px; cursor: pointer; border: none; border-radius: 5px; }
            .on { background-color: #28a745; color: white; }
            .off { background-color: #dc3545; color: white; }
        </style>
    </head>
    <body>
        <h1>WiFi LED Controller</h1>
        <p>Click a button to control the LED on the device.</p>
        <a href="/control?command=on" class="button on">Turn LED ON</a>
        <a href="/control?command=off" class="button off">Turn LED OFF</a>
    </body>
    </html>

Part B: The WiFi Hardware (ESP32/ESP8266 with Arduino IDE)

This code makes the device listen for web requests.

  1. Hardware Setup:

    • An ESP32 or ESP8266 board.
    • An LED and a 220-ohm resistor. Connect the resistor from a GPIO pin (e.g., GPIO 2) to the LED's anode (+), and the LED's cathode (-) to GND.
  2. Arduino Code:

    • Install the "ESP32" or "ESP8266" board support in the Arduino IDE.
    • Paste this code into the Arduino IDE and upload it to your board.
    #include <WiFi.h> // For ESP32
    // #include <ESP8266WiFi.h> // For ESP8266
    const char* ssid = "YourNetworkName"; // Your WiFi network name
    const char* password = "YourPassword"; // Your WiFi password
    WiFiServer server(80); // Create a web server on port 80
    const int ledPin = 2; // GPIO pin the LED is connected to
    void setup() {
      Serial.begin(115200);
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);
      // Connect to WiFi
      WiFi.begin(ssid, password);
      Serial.print("Connecting to WiFi...");
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("\nWiFi connected!");
      Serial.print("IP Address: ");
      Serial.println(WiFi.localIP()); // Print the IP address
      server.begin();
    }
    void loop() {
      WiFiClient client = server.available(); // Listen for incoming clients
      if (client) {
        Serial.println("New Client Connected.");
        String currentLine = "";
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.write(c);
            currentLine += c;
            if (c == '\n') {
              // If the line is blank, it means the HTTP request is complete
              if (currentLine.endsWith("\r\n\r\n")) {
                // Check the request for a command
                if (currentLine.indexOf("GET /?command=on") >= 0) {
                  digitalWrite(ledPin, HIGH);
                  Serial.println("LED turned ON");
                } else if (currentLine.indexOf("GET /?command=off") >= 0) {
                  digitalWrite(ledPin, LOW);
                  Serial.println("LED turned OFF");
                }
                // Send a simple HTTP response
                client.println("HTTP/1.1 200 OK");
                client.println("Content-type:text/html");
                client.println();
                client.println("<html><body><h1>Command Received!</h1></body></html>");
                client.println();
                break;
              }
              currentLine = "";
            }
          }
        }
        client.stop();
        Serial.println("Client Disconnected.");
      }
    }

How to Run:

  1. Upload the Arduino code to your ESP32/ESP8266.
  2. Open the Arduino IDE's Serial Monitor to see the IP address assigned to your device (e.g., 168.1.105).
  3. Update the DEVICE_IP variable in your app.py file with this IP address.
  4. Run the Flask app: python app.py.
  5. Open a web browser on your computer (or any device on the same network) and go to http://<your_computer_ip>:5000. You should see the control panel and be able to turn the LED on and off!

Scenario 2: Flask App Running on a WiFi Device (e.g., Raspberry Pi)

This is simpler. You're just hosting a web application on a device that has WiFi.

Concept:

  • A Raspberry Pi is connected to your WiFi network.
  • You install Flask on it.
  • You run a Flask app, making it accessible on your local network.

Code (app.py): This is the same app.py as in Scenario 1.

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_wifi():
    return "Hello from my Raspberry Pi on the WiFi network!"
if __name__ == '__main__':
    # host='0.0.0.0' is crucial. It makes the app accessible from other devices,
    # not just from the Pi itself.
    app.run(host='0.0.0.0', port=5000, debug=True)

How to Run:

  1. Set up your Raspberry Pi and connect it to your WiFi.
  2. SSH into your Pi.
  3. Install Flask: pip install Flask.
  4. Save the code above as app.py.
  5. Run it: python app.py.
  6. Find your Pi's IP address (e.g., using hostname -I).
  7. From another computer on your network, open a browser and go to http://<your_pi_ip_address>:5000.

Scenario 3: Flask App to Manage the Host's WiFi

This is more advanced and requires interacting with the operating system. This is highly OS-dependent.

Concept:

  • A Flask app on a Raspberry Pi (Linux) that can scan for WiFi networks and connect to new ones.
  • WARNING: This involves executing shell commands, which can be a security risk if not handled carefully. Only use this in a trusted environment.

Example for Raspberry Pi (Linux):

  1. Install nmcli: This is the command-line tool for NetworkManager, which manages networking on most modern Linux distros.

    sudo apt update
    sudo apt install network-manager
  2. Flask App (wifi_manager.py):

    import subprocess
    from flask import Flask, render_template, request, redirect, url_for
    app = Flask(__name__)
    def run_command(command):
        """Runs a shell command and returns its output."""
        try:
            output = subprocess.check_output(command, shell=True, text=True)
            return output
        except subprocess.CalledProcessError as e:
            return f"Error: {e}"
    @app.route('/')
    def index():
        """Shows current connection and available networks."""
        current_connection = run_command("nmcli connection show --active")
        scan_results = run_command("nmcli device wifi list")
        return render_template('wifi.html', current=current_connection, networks=scan_results)
    @app.route('/connect', methods=['POST'])
    def connect():
        """Connects to a selected WiFi network."""
        ssid = request.form['ssid']
        password = request.form['password']
        # This command creates a new connection and connects to it
        # --type wifi: Specifies the connection type
        # -- ifname wlan0: Specifies the wireless interface (may be different on your system)
        # -- wifi-mode infrastructure: For a standard router
        # -- wifi-sec.key-mgmt wpa-psk: For WPA/WPA2 security
        command = f"nmcli device wifi connect '{ssid}' password '{password}' ifname wlan0"
        result = run_command(command)
        return redirect(url_for('index'))
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, debug=True)
  3. HTML Template (templates/wifi.html):

    <!DOCTYPE html>
    <html>
    <head>
        <title>Pi WiFi Manager</title>
        <style> body { font-family: monospace; white-space: pre; } </style>
    </head>
    <body>
        <h1>Current Connection</h1>
        <hr>
        <p>{{ current }}</p>
        <hr>
        <h1>Available Networks</h1>
        <p>{{ networks }}</p>
        <hr>
        <h2>Connect to a New Network</h2>
        <form action="/connect" method="post">
            <label for="ssid">SSID:</label><br>
            <input type="text" id="ssid" name="ssid" required><br><br>
            <label for="password">Password:</label><br>
            <input type="password" id="password" name="password"><br><br>
            <input type="submit" value="Connect">
        </form>
    </body>
    </html>

How to Run:

  1. Follow the setup steps for Scenario 2.
  2. Run the app: python wifi_manager.py.
  3. Access it from another device on the network at http://<your_pi_ip>:5000.

Summary

Scenario Goal Key Technology Complexity
Control Hardware Web UI to control a device over WiFi Flask (Python) + Arduino (C++) High
Host an App Run a web service on a WiFi-enabled device Flask (Python) Low
Manage WiFi Web UI to control the host's WiFi connection Flask (Python) + Shell Commands Medium
分享:
扫描分享到社交APP
上一篇
下一篇