香橙派——自发热点连Wi-Fi

发布于:2024-05-22 ⋅ 阅读:(33) ⋅ 点赞:(0)

1. 安装依赖

sudo apt-get update
sudo apt-get install hostapd dnsmasq
sudo pip install flask

2. 热点功能

(1)开启热点(并断开当前连接的Wi-Fi)

sudo nmcli radio wifi off && \
sudo nmcli radio wifi on && \
sudo systemctl stop dnsmasq && \
sudo systemctl restart NetworkManager && \
nohup sudo create_ap wlan0 eth0 Takway-Toys --no-virt > create_ap.log 2>&1 &

(2)运行Web后端

sudo chmod 777 app.py
sudo python3 app.py
  • app.py
# coding: utf-8
import subprocess
import os
import time
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# 检测 Wi-Fi 连接状态
def check_wifi_connection():
    try:
        # 使用nmcli命令检查Wi-Fi连接状态
        output = subprocess.check_output(['nmcli', 'device', 'status']).decode('utf-8')
        
        # 分析输出以查找Wi-Fi连接状态
        for line in output.split('\n'):
            if 'wifi' in line and 'connected' in line:
                return True
    except subprocess.CalledProcessError as e:
        print(f"Error checking Wi-Fi status: {e}")
    
    return False

# 设置热点
def set_hotspot():
    try:
        subprocess.run(['sudo', 'create_ap', 'wlan0', 'eth0', 'Takway-Toy', '--no-virt'], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Error setting up hotspot: {e}")

# 扫描 Wi-Fi
def scan_wifi():
    try:
        subprocess.run(['nmcli', 'device', 'wifi', 'rescan'], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Error scanning for Wi-Fi networks: {e}")

# 连接 Wi-Fi
def connect_wifi(ssid, password):
    scan_wifi()
    time.sleep(1)
    try:
        subprocess.run(['sudo', 'create_ap', '--stop', 'wlan0'], check=True)
        print("Stopping create_ap service")
    except subprocess.CalledProcessError as e:
        print(f"Error stopping hotspot: {e}")
    
    time.sleep(1)
    
    try:
        subprocess.run(['nmcli', 'dev', 'wifi', 'connect', ssid, 'password', password], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Error connecting to Wi-Fi: {e}")
    
    time.sleep(5)
    # 检查是否成功连接Wi-Fi
    if check_wifi_connection():
        print("成功连接到Wi-Fi,程序即将退出。")
        os._exit(0)  # 成功连接后退出程序
    else:
        print("Wi-Fi连接失败。")

# 主页
@app.route('/')
def index():
    return render_template('index.html')

# 提交 Wi-Fi 信息
@app.route('/submit', methods=['POST'])
def submit():
    ssid = request.form['ssid']
    password = request.form['password']
    print(f"Connecting to Wi-Fi: {ssid} with password {password}")
    connect_wifi(ssid, password)
    return redirect(url_for('index'))

if __name__ == '__main__':
    debug_mode = True  # 设置为 True 以跳过 Wi-Fi 连接状态检测

    if not debug_mode:
        if check_wifi_connection():
            print("已连接到 Wi-Fi 网络")
        else:
            print("未连接到 Wi-Fi 网络")
            set_hotspot()


    # 创建 index.html 文件
    index_html_path = 'index.html'
    if not os.path.exists(index_html_path):
        with open(index_html_path, 'w') as f:
            f.write("""<!DOCTYPE html>
<html>
<head>
    <title>Wi-Fi 设置</title>
</head>
<body>
    <h1>输入 Wi-Fi 信息</h1>
    <form method="post" action="{{ url_for('submit') }}">
        <label for="ssid">Wi-Fi 名称 (SSID):</label>
        <input type="text" id="ssid" name="ssid" required>
        <br>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <input type="submit" value="连接">
    </form>
</body>
</html>""")

    app.run(host='0.0.0.0', port=80, debug=True)
  • 手动连接http://192.168.12.1/

3. 开启自启动脚本

方式一:配置系统开机自启动service服务

香橙派——基本配置教程

sudo vim /etc/systemd/system/wifi_hotspot.service
[Unit]
Description=My Service
After=network.target
 
​
[Service]
Type=simple
WorkingDirectory=/home/orangepi
ExecStart=python3 /home/orangepi/app.py
User=root
 
[Install]
WantedBy=multi-user.target
  • 第二种
[Unit]
Description=WiFi Hotspot Wrapper
After=network.target
Wants=network.target

[Service]
Type=oneshot
ExecStart=python3 /home/orangepi/wifi_hotpot/wifi_manager.py
WorkingDirectory=/home/orangepi/wifi_hotpot
User=root

[Install]
WantedBy=default.target
sudo systemctl daemon-reload
sudo systemctl enable wifi_hotspot.service
# sudo systemctl disable wifi_hotspot.service
sudo systemctl start wifi_hotspot.service
sudo systemctl status wifi_hotspot.service

其他常用命令及脚本

  • 扫描Wi-Fi:
nmcli dev wifi rescan
  • 断开WiFi连接
sudo systemctl stop dnsmasq
sudo systemctl stop NetworkManager
sudo systemctl restart NetworkManager
  • 连接Wi-Fi
nmcli dev wifi connect Innoxsz-Public password innox2023
nmcli dev wifi connect Takway-AI password takway123
  • 开启热点:
# 有密码
sudo create_ap -m nat wlan0 eth0 orangepi orangepi --no-virt
# 无密码
sudo create_ap wlan0 eth0 Takway-AI --no-virt
# nohup
nohup sudo create_ap wlan0 eth0 Takway-Toys --no-virt > create_ap.log 2>&1 &
  • 关闭热点:
sudo create_ap --stop wlan0