2024-05-20 23:07:29 +08:00
|
|
|
import subprocess
|
|
|
|
import re
|
|
|
|
import os
|
2024-05-25 00:24:51 +08:00
|
|
|
import psutil
|
|
|
|
import signal
|
2024-05-20 23:07:29 +08:00
|
|
|
import time
|
2024-05-21 01:42:24 +08:00
|
|
|
import datetime
|
2024-05-20 23:07:29 +08:00
|
|
|
from flask import Flask, render_template, request, redirect, url_for, make_response
|
|
|
|
|
2024-05-24 23:16:37 +08:00
|
|
|
try:
|
|
|
|
from takway.board import OrangePi
|
|
|
|
led_enabled = True
|
|
|
|
orangepi = OrangePi()
|
|
|
|
except ImportError:
|
|
|
|
led_enabled = False
|
|
|
|
print("Error importing OrangePi")
|
|
|
|
|
2024-05-25 00:24:51 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
app = Flask(__name__)
|
2024-05-24 23:16:37 +08:00
|
|
|
|
2024-05-25 00:02:37 +08:00
|
|
|
def close_app():
|
2024-05-25 00:33:37 +08:00
|
|
|
if led_enabled:
|
|
|
|
orangepi.set_led_off('red')
|
2024-05-25 00:02:37 +08:00
|
|
|
# 获取当前Flask应用程序的进程ID
|
|
|
|
flask_pid = os.getpid()
|
|
|
|
|
|
|
|
# 获取所有名为'python3'的进程ID
|
|
|
|
python_pids = [p.info['pid'] for p in psutil.process_iter(attrs=['pid', 'name']) if p.info['name'] == 'python3']
|
|
|
|
|
|
|
|
# 关闭Flask应用程序进程
|
|
|
|
os.kill(flask_pid, signal.SIGTERM)
|
|
|
|
|
|
|
|
# 关闭Python进程
|
|
|
|
for pid in python_pids:
|
|
|
|
os.kill(pid, signal.SIGTERM)
|
2024-05-24 23:16:37 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
def start_hotspot():
|
|
|
|
try:
|
|
|
|
subprocess.Popen('sudo systemctl start hotspot.service', shell=True)
|
|
|
|
if led_enabled:
|
|
|
|
orangepi.set_led_on('blue')
|
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
print(f"{datetime.datetime.now()}: Error starting create_ap service: {e}")
|
2024-05-24 23:16:37 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
def close_hotspot():
|
|
|
|
# 关闭热点
|
|
|
|
try:
|
|
|
|
subprocess.Popen('sudo systemctl stop hotspot.service', shell=True)
|
|
|
|
print(f"{datetime.datetime.now()}: Stopping create_ap service")
|
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
print(f"{datetime.datetime.now()}: Error stopping hotspot: {e}")
|
|
|
|
|
|
|
|
|
2024-05-20 23:07:29 +08:00
|
|
|
# 检测 Wi-Fi 连接状态
|
|
|
|
def check_wifi_connection():
|
2024-05-21 01:42:24 +08:00
|
|
|
cmd = "nmcli dev status"
|
|
|
|
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
2024-05-24 23:16:37 +08:00
|
|
|
time.sleep(1)
|
2024-05-21 01:42:24 +08:00
|
|
|
output = result.stdout.strip()
|
|
|
|
lines = output.split("\n")[1:] # Skip the header line
|
|
|
|
for line in lines:
|
|
|
|
columns = line.split()
|
|
|
|
print(columns)
|
|
|
|
if len(columns) >= 4 and columns[2] == "connected":
|
2024-05-25 21:59:11 +08:00
|
|
|
wifi_ssid = columns[3]
|
2024-05-25 00:33:37 +08:00
|
|
|
if led_enabled:
|
|
|
|
orangepi.set_led_off('blue')
|
2024-05-25 21:59:11 +08:00
|
|
|
return True, wifi_ssid
|
2024-05-20 23:07:29 +08:00
|
|
|
return False
|
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
def scan_wifi():
|
|
|
|
subprocess.run(['nmcli', 'dev', 'wifi', 'rescan'], check=True)
|
|
|
|
cmd = "nmcli dev wifi"
|
2024-05-25 22:23:17 +08:00
|
|
|
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
2024-05-25 21:59:11 +08:00
|
|
|
|
|
|
|
wifi_list = []
|
|
|
|
output = result.stdout.strip()
|
|
|
|
lines = output.split("\n")[1:] # Skip the header line
|
|
|
|
for line in lines:
|
|
|
|
columns = line.split()
|
|
|
|
print(columns)
|
|
|
|
for i, column in enumerate(columns):
|
|
|
|
print(f"{i}: {column}")
|
|
|
|
exit()
|
|
|
|
'''
|
|
|
|
# 分割字符串以空格为分隔符
|
|
|
|
columns = line.split()
|
|
|
|
|
|
|
|
# 提取第一列和第三列的值
|
|
|
|
mac_address = columns[0]
|
|
|
|
|
|
|
|
ssid = " ".join(columns[1:3])
|
|
|
|
if "Infra" in ssid:
|
|
|
|
ssid = ssid.replace(" Infra", "")
|
|
|
|
if ":" in ssid:
|
|
|
|
# "72:A6:CC:8C:89:6C Takway-AI"
|
|
|
|
# 去除字符串中的MAC地址
|
|
|
|
ssid = re.sub(r'\b\w{2}(:\w{2}){5}\b', '', ssid)
|
2024-05-20 23:07:29 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
# 提取第六列的强度值
|
|
|
|
last_info = columns[4:8]
|
|
|
|
# 去除所有的空格
|
|
|
|
columns = line.replace(" ", "")
|
|
|
|
# 提取"Mbit/s"后的三位以内数字
|
|
|
|
strength = int(columns[columns.index("Mbit/s")+6:columns.index("Mbit/s")+8])
|
|
|
|
|
|
|
|
# print("MAC地址:", mac_address)
|
|
|
|
# print("SSID:", ssid)
|
|
|
|
# print("强度:", strength)
|
|
|
|
|
|
|
|
wifi_list.append({'ssid': ssid, 'signal': strength})
|
|
|
|
if len(wifi_list) == 15:
|
|
|
|
break
|
|
|
|
'''
|
|
|
|
# save wifi_list to file
|
|
|
|
with open('wifi_list.txt', 'w') as f:
|
|
|
|
for wifi in wifi_list:
|
|
|
|
f.write(f"{wifi['ssid']},{wifi['signal']}\n")
|
|
|
|
|
|
|
|
return wifi_list
|
2024-05-20 23:07:29 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
'''
|
2024-05-20 23:07:29 +08:00
|
|
|
def scan_wifi():
|
2024-05-25 21:59:11 +08:00
|
|
|
subprocess.run(['nmcli', 'dev', 'wifi', 'rescan'], check=True)
|
|
|
|
cmd = "nmcli dev wifi"
|
|
|
|
output = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
|
|
|
|
|
|
wifi_list = []
|
|
|
|
lines = output.decode().splitlines()
|
|
|
|
for idx, line in enumerate(lines[1:]):
|
|
|
|
print(f"{idx}: {line}")
|
2024-05-20 23:13:24 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
# 分割字符串以空格为分隔符
|
|
|
|
columns = line.split()
|
|
|
|
|
|
|
|
# 提取第一列和第三列的值
|
|
|
|
mac_address = columns[0]
|
2024-05-20 23:13:24 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
ssid = " ".join(columns[1:3])
|
|
|
|
if "Infra" in ssid:
|
|
|
|
ssid = ssid.replace(" Infra", "")
|
|
|
|
if ":" in ssid:
|
|
|
|
# "72:A6:CC:8C:89:6C Takway-AI"
|
|
|
|
# 去除字符串中的MAC地址
|
|
|
|
ssid = re.sub(r'\b\w{2}(:\w{2}){5}\b', '', ssid)
|
2024-05-20 23:07:29 +08:00
|
|
|
|
2024-05-25 21:59:11 +08:00
|
|
|
# 提取第六列的强度值
|
|
|
|
last_info = columns[4:8]
|
|
|
|
# 去除所有的空格
|
|
|
|
columns = line.replace(" ", "")
|
|
|
|
# 提取"Mbit/s"后的三位以内数字
|
|
|
|
strength = int(columns[columns.index("Mbit/s")+6:columns.index("Mbit/s")+8])
|
|
|
|
|
|
|
|
# print("MAC地址:", mac_address)
|
|
|
|
# print("SSID:", ssid)
|
|
|
|
# print("强度:", strength)
|
|
|
|
|
|
|
|
wifi_list.append({'ssid': ssid, 'signal': strength})
|
|
|
|
if len(wifi_list) == 15:
|
|
|
|
break
|
|
|
|
|
|
|
|
# save wifi_list to file
|
|
|
|
with open('wifi_list.txt', 'w') as f:
|
|
|
|
for wifi in wifi_list:
|
|
|
|
f.write(f"{wifi['ssid']},{wifi['signal']}\n")
|
|
|
|
|
|
|
|
return wifi_list
|
|
|
|
'''
|
2024-05-20 23:07:29 +08:00
|
|
|
|
|
|
|
# 连接 Wi-Fi
|
|
|
|
def connect_wifi(ssid, password):
|
|
|
|
# 连接到用户选择的 Wi-Fi 网络
|
|
|
|
try:
|
2024-05-25 21:59:11 +08:00
|
|
|
output = subprocess.check_output(['nmcli', 'dev', 'wifi', 'connect', ssid, 'password', password])
|
|
|
|
output_str = output.decode('utf-8') # 将输出转换为字符串
|
|
|
|
if "successfully" in output_str:
|
|
|
|
print(f"{datetime.datetime.now()}: Successfully connected to Wi-Fi: {ssid}")
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
print(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {output_str}")
|
|
|
|
return False
|
2024-05-20 23:07:29 +08:00
|
|
|
except subprocess.CalledProcessError as e:
|
2024-05-25 00:00:33 +08:00
|
|
|
print(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {e}")
|
2024-05-20 23:07:29 +08:00
|
|
|
return False
|
2024-05-25 21:59:11 +08:00
|
|
|
|
|
|
|
# 关闭 Wi-Fi
|
|
|
|
def disconnect_wifi():
|
|
|
|
try:
|
|
|
|
output = subprocess.check_output(['nmcli', 'dev', 'disconnect', 'iface', 'wlan0'])
|
2024-05-25 22:19:52 +08:00
|
|
|
time.sleep(1)
|
2024-05-25 21:59:11 +08:00
|
|
|
output_str = output.decode('utf-8') # 将输出转换为字符串
|
|
|
|
if "successfully disconnected" in output_str:
|
2024-05-25 22:13:04 +08:00
|
|
|
print(f"{datetime.datetime.now()}: Wi-Fi disconnected successfully")
|
|
|
|
else:
|
|
|
|
print(f"{datetime.datetime.now()}: Error disconnecting from Wi-Fi: {output_str}")
|
2024-05-25 22:21:14 +08:00
|
|
|
except Exception as e:
|
|
|
|
print(f"{datetime.datetime.now()}: Error disconnecting from Wi-Fi: {e}")
|
2024-05-25 21:59:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
2024-05-20 23:07:29 +08:00
|
|
|
# 主页
|
|
|
|
@app.route('/')
|
|
|
|
def index():
|
|
|
|
global wifi_list
|
|
|
|
print(wifi_list)
|
|
|
|
|
|
|
|
response = make_response(render_template('index.html', wifi_list=wifi_list))
|
|
|
|
response.headers.set('Content-Type', 'text/html')
|
|
|
|
response.headers.set('Apple-Web-App-Capable', 'yes')
|
|
|
|
response.headers.set('Apple-Mobile-Web-App-Status-Bar-Style', 'black-translucent')
|
|
|
|
return response
|
|
|
|
|
|
|
|
# 提交 Wi-Fi 信息
|
|
|
|
@app.route('/submit', methods=['POST'])
|
|
|
|
def submit():
|
2024-05-25 00:33:37 +08:00
|
|
|
if led_enabled:
|
|
|
|
orangepi.set_led_on('red')
|
2024-05-20 23:07:29 +08:00
|
|
|
ssid = request.form['ssid']
|
|
|
|
password = request.form['password']
|
2024-05-25 00:00:33 +08:00
|
|
|
print(f"{datetime.datetime.now()}: Connecting to Wi-Fi: {ssid} with password {password}")
|
2024-05-20 23:07:29 +08:00
|
|
|
connected = connect_wifi(ssid, password)
|
|
|
|
|
|
|
|
time.sleep(5)
|
|
|
|
# 检查是否成功连接Wi-Fi
|
|
|
|
if check_wifi_connection() and connected:
|
2024-05-25 00:00:33 +08:00
|
|
|
# connected successfully, close flask
|
2024-05-25 00:02:37 +08:00
|
|
|
close_app()
|
2024-05-25 00:00:33 +08:00
|
|
|
|
2024-05-20 23:07:29 +08:00
|
|
|
else:
|
2024-05-25 00:00:33 +08:00
|
|
|
print(f"{datetime.datetime.now()}: Wi-Fi连接失败。")
|
|
|
|
restart_hotspot()
|
2024-05-20 23:07:29 +08:00
|
|
|
|
|
|
|
return redirect(url_for('index'))
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2024-05-25 22:10:04 +08:00
|
|
|
debug_mode = True # 设置为 True 以跳过 Wi-Fi 连接状态检测
|
2024-05-25 21:59:11 +08:00
|
|
|
if debug_mode:
|
|
|
|
disconnect_wifi()
|
2024-05-20 23:07:29 +08:00
|
|
|
|
2024-05-25 22:10:04 +08:00
|
|
|
scan_wifi()
|
|
|
|
|
|
|
|
'''
|
2024-05-25 00:33:37 +08:00
|
|
|
if led_enabled:
|
|
|
|
orangepi.set_led_on('blue')
|
2024-05-25 21:59:11 +08:00
|
|
|
|
|
|
|
if check_wifi_connection():
|
|
|
|
print(f"{datetime.datetime.now()}: 系统已自动连接到 Wi-Fi 网络,退出程序")
|
|
|
|
close_app()
|
|
|
|
else:
|
|
|
|
print(f"{datetime.datetime.now()}: 未连接到 Wi-Fi 网络")
|
2024-05-20 23:07:29 +08:00
|
|
|
|
2024-05-25 00:00:33 +08:00
|
|
|
print(f"{datetime.datetime.now()}: Starting Flask server")
|
2024-05-20 23:07:29 +08:00
|
|
|
print("----------------------------")
|
|
|
|
wifi_list = scan_wifi()
|
|
|
|
print("----------------------------")
|
|
|
|
|
|
|
|
restart_hotspot()
|
|
|
|
# 启动 Flask 服务器
|
|
|
|
app.run(host='0.0.0.0', port=80)
|
2024-05-25 22:10:04 +08:00
|
|
|
'''
|
2024-05-20 23:07:29 +08:00
|
|
|
|