I have a Python script that is running on Raspberry Pi. I have created a hotspot on a Raspberry Pi and I connected my device and my phone to the hotspot of the Raspberry Pi.
The script that run on Raspberry Pi is:
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'))
If I tun this script from my PC that is connected to Raspberry Pi hotspot named iCast it will work fine.
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}")
This script run successfully, and I can see a message in the console:
WiFi credentials sent successfully.
But if I do the same request from my react-native app using axis it has this issue.
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));
});
};
My iPhone is connected to the iCast hotspot, but it has internet access as same for my PC.
Now my question is that how can I connect and send a post request form my mobile app to the Raspberry Pi?
My issue is that when I do request form the app it says network error.
To connect and send data from React Native to your Raspberry Pi, use fetch or Axios in your React Native app to make HTTP requests to your Flask API running on the Raspberry Pi. Ensure your Flask API has routes defined to handle GET or POST requests that your app will make. For instance,
fetch(http://raspberrypi.local:5000/route, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })to send JSON data. Replace
http://raspberrypi.local:5000/routewith your Pi's actual IP address and port. Ensure both devices are on the same network.