如何从react-native连接并向树莓派发送数据

问题描述 投票:0回答:1

我有一个在树莓派上运行的Python脚本。我在树莓派上创建了一个热点,并将我的设备和手机连接到树莓派的热点。

在树莓派上运行的脚本是

    import threading
    import subprocess
    import time
    import sqlite3
    from flask import Flask, request, jsonify
    
    app = Flask(__name__)
    credentials_queue = []  # Queue to store incoming WiFi credentials
    
    def connect_to_wifi(ssid, password):
        command = f"sudo nmcli device wifi connect '{ssid}' password '{password}'"
        try:
            subprocess.run(command, shell=True, check=True)
            print(f"Successfully connected to {ssid}.")
            return True
        except subprocess.CalledProcessError as e:
            print(f"Error: {e}")
            print(f"Failed to connect to {ssid}. Please check the provided credentials.")
            return False
    
    def turn_off_hotspot():
        subprocess.run("sudo nmcli con down WIFI_AP", shell=True)
    
    def turn_on_hotspot():
        subprocess.run("sudo nmcli con up WIFI_AP", shell=True)
    
    def create_database_table():
        connection = sqlite3.connect('wifi_credentials.db')
        cursor = connection.cursor()
        # 'wifi_credentials' table if it doesn't exist
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS wifi_credentials (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                ssid TEXT NOT NULL,
                password TEXT NOT NULL
            )
        ''')
        connection.commit()
        connection.close()
    
    def save_to_database(ssid, password):
        create_database_table()  # Ensure the table exists
        connection = sqlite3.connect('wifi_credentials.db')
        cursor = connection.cursor()
        cursor.execute("INSERT INTO wifi_credentials (ssid, password) VALUES (?, ?)", (ssid, password))
        connection.commit()
        connection.close()
    
    def process_credentials():
        while True:
            if credentials_queue:
                wifi_data = credentials_queue.pop(0)
                ssid = wifi_data.get('ssid')
                password = wifi_data.get('password')
    
                # Save to the database
                save_to_database(ssid, password)
    
                # Turn off hotspot
                turn_off_hotspot()
    
                # Connect to WiFi
                if connect_to_wifi(ssid, password):
                    print("Successfully connected to WiFi. Processing next set of credentials...")
                else:
                    print("WiFi connection unsuccessful. Waiting for another set of credentials...")
    
                # Wait for 15 seconds for WIFI adapter to switch to client mode
                time.sleep(15)
    
                # Turn on hotspot
                turn_on_hotspot()
    
    def save_to_file(ssid, password):
        with open('wifi_credentials.txt', 'a') as file:
            file.write(f"SSID: {ssid}, Password: {password}\n")
    
    @app.route('/wifi', methods=['POST'])
    def wifi_endpoint():
        data = request.get_json()
        ssid = data.get('ssid')
        password = data.get('password')
    
        # Save to a file
        save_to_file(ssid, password)
    
        turn_off_hotspot()
        time.sleep(15)
        # Connect to WiFi
        if connect_to_wifi(ssid, password):
            print("Successfully connected to WiFi. Processing next set of credentials...")
        else:
            print("WiFi connection unsuccessful. Waiting for another set of credentials...")
            # Turn on hotspot
            turn_on_hotspot()
    
    
    
        return jsonify({'message': 'WiFi credentials received and processed successfully.'})
    
    if __name__ == "__main__":
        # Run Access Point
        turn_on_hotspot()
        # Start Flask app with HTTPS and listen on all available interfaces
        app.run(host='0.0.0.0', port=8999, debug=True, ssl_context=('certs/certificate.crt', 'certs/private.key'))

如果我从连接到名为 iCast 的树莓派热点的电脑上调整此脚本,它将正常工作。

    import requests
    
    # TODO: Change the URL to your Jetson Nano IP address
    url = "https://10.42.0.1:5000/wifi"
    cert_path = "/Users/artemiikhristich/Desktop/TextureExtraction3/Network/certs/certificate.crt"  # Update with your actual certificate path
    data = {"ssid": "MY_WIFI_NAME", "password": "MY_WIFI_NAME_PASSWORD"}
    
    try:
        response = requests.post(url, json=data, verify=False)
        if response.status_code == 200:
            print("WiFi credentials sent successfully.")
        else:
            print(f"Error sending WiFi credentials. Status code: {response.status_code}")
    except requests.RequestException as e:
        print(f"Error: {e}")

此脚本运行成功,我可以在控制台中看到一条消息

WiFi credentials sent successfully.

但是如果我使用 axis 从我的反应本机应用程序执行相同的请求,则会出现此问题。

    const test_iCast_wifi = () => {
        setMyTestLoading(true)
        let data = JSON.stringify({
          ssid: 'HUAWEI_B818_4211',
          password: '4RM9LE059DG',
        });
    
        let config = {
          method: 'post',
          maxBodyLength: Infinity,
          url: 'http://10.42.0.1:5000/wifi',
          headers: {
            'Content-Type': 'application/json',
          },
          data: data,
        };
    
        axios
          .request(config)
          .then(response => {
            setMyTestLoading(false)
            Alert.alert('test_iCast_wifi SUCCESS', JSON.stringify(response));
          })
          .catch(error => {
            setMyTestLoading(false)
            Alert.alert('test_iCast_wifi ERROR', JSON.stringify(error));
          });
      };

我的 iPhone 已连接到 iCast 热点,但它可以像我的电脑一样访问互联网。

现在我的问题是如何从我的移动应用程序连接并向树莓派发送发布请求?

我的问题是,当我向应用程序发出请求时,它显示网络错误。

javascript python react-native raspberry-pi
1个回答
0
投票

要将数据从 React Native 连接到 Raspberry Pi,请在 React Native 应用程序中使用 fetch 或 Axios 向在 Raspberry Pi 上运行的 Flask API 发出 HTTP 请求。确保您的 Flask API 已定义路由来处理您的应用程序将发出的 GET 或 POST 请求。例如, fetch(

http://raspberrypi.local:5000/route
, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) 发送 JSON 数据。将
http://raspberrypi.local:5000/route
替换为 Pi 的实际 IP 地址和端口。确保两台设备位于同一网络上。

© www.soinside.com 2019 - 2024. All rights reserved.