wifi json
This commit is contained in:
parent
36a995c510
commit
bc99f15219
10
README.md
10
README.md
|
@ -62,6 +62,7 @@ Description=Hotspot Service
|
||||||
After=network.target
|
After=network.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
|
ExecPre=/bin/sleep 5
|
||||||
ExecStart=create_ap wlan0 eth0 Takway-Toys --no-virt
|
ExecStart=create_ap wlan0 eth0 Takway-Toys --no-virt
|
||||||
User=root
|
User=root
|
||||||
|
|
||||||
|
@ -174,7 +175,7 @@ nmcli dev wifi connect Innoxsz-Public password innox2023
|
||||||
- 断开Wi-Fi连接:
|
- 断开Wi-Fi连接:
|
||||||
|
|
||||||
```
|
```
|
||||||
nmcli dev disconnect iface wlan0
|
nmcli dev disconnect wlan0
|
||||||
```
|
```
|
||||||
|
|
||||||
- 扫描Wi-Fi:
|
- 扫描Wi-Fi:
|
||||||
|
@ -187,3 +188,10 @@ nmcli dev wifi
|
||||||
```
|
```
|
||||||
nmcli dev status
|
nmcli dev status
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### create_ap
|
||||||
|
|
||||||
|
```
|
||||||
|
sudo create_ap wlan0 eth0 Takway-Toys --no-virt
|
||||||
|
+```
|
|
@ -5,6 +5,7 @@ import psutil
|
||||||
import signal
|
import signal
|
||||||
import time
|
import time
|
||||||
import datetime
|
import datetime
|
||||||
|
import json
|
||||||
from flask import Flask, render_template, request, redirect, url_for, make_response
|
from flask import Flask, render_template, request, redirect, url_for, make_response
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -23,16 +24,16 @@ app = Flask(__name__)
|
||||||
def close_app():
|
def close_app():
|
||||||
if led_enabled:
|
if led_enabled:
|
||||||
orangepi.set_led_off('blue')
|
orangepi.set_led_off('blue')
|
||||||
|
|
||||||
# 获取当前Flask应用程序的进程ID
|
# 获取当前Flask应用程序的进程ID
|
||||||
flask_pid = os.getpid()
|
flask_pid = os.getpid()
|
||||||
|
|
||||||
# 获取所有名为'python3'的进程ID
|
# 获取所有名为'python3'的进程ID
|
||||||
python_pids = [p.info['pid'] for p in psutil.process_iter(attrs=['pid', 'name']) if p.info['name'] == 'python3']
|
python_pids = [p.info['pid'] for p in psutil.process_iter(attrs=['pid', 'name']) if p.info['name'] == 'python3']
|
||||||
|
|
||||||
# 关闭Flask应用程序进程
|
# 关闭Flask应用程序进程
|
||||||
os.kill(flask_pid, signal.SIGTERM)
|
os.kill(flask_pid, signal.SIGTERM)
|
||||||
|
|
||||||
# 关闭Python进程
|
# 关闭Python进程
|
||||||
for pid in python_pids:
|
for pid in python_pids:
|
||||||
os.kill(pid, signal.SIGTERM)
|
os.kill(pid, signal.SIGTERM)
|
||||||
|
@ -54,8 +55,8 @@ def close_hotspot():
|
||||||
orangepi.set_led_off('red')
|
orangepi.set_led_off('red')
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
print(f"{datetime.datetime.now()}: Error stopping hotspot: {e}")
|
print(f"{datetime.datetime.now()}: Error stopping hotspot: {e}")
|
||||||
|
|
||||||
|
|
||||||
# 检测 Wi-Fi 连接状态
|
# 检测 Wi-Fi 连接状态
|
||||||
def check_wifi_connection():
|
def check_wifi_connection():
|
||||||
cmd = "nmcli dev status"
|
cmd = "nmcli dev status"
|
||||||
|
@ -71,13 +72,13 @@ def check_wifi_connection():
|
||||||
if led_enabled:
|
if led_enabled:
|
||||||
orangepi.set_led_off('blue')
|
orangepi.set_led_off('blue')
|
||||||
return True, wifi_ssid
|
return True, wifi_ssid
|
||||||
return False
|
return False, None
|
||||||
|
|
||||||
def scan_wifi():
|
def scan_wifi():
|
||||||
subprocess.run(['nmcli', 'dev', 'wifi', 'rescan'], check=True)
|
subprocess.run(['nmcli', 'dev', 'wifi', 'rescan'], check=True)
|
||||||
cmd = "nmcli dev wifi"
|
cmd = "nmcli dev wifi"
|
||||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||||
|
|
||||||
ssid_list = []
|
ssid_list = []
|
||||||
wifi_list = []
|
wifi_list = []
|
||||||
output = result.stdout.strip()
|
output = result.stdout.strip()
|
||||||
|
@ -108,11 +109,11 @@ def scan_wifi():
|
||||||
# 去除mac地址
|
# 去除mac地址
|
||||||
ssid = ssid.split(' ')[1:]
|
ssid = ssid.split(' ')[1:]
|
||||||
ssid = ''.join(ssid)
|
ssid = ''.join(ssid)
|
||||||
|
|
||||||
if ssid in ssid_list:
|
if ssid in ssid_list:
|
||||||
continue
|
continue
|
||||||
ssid_list.append(ssid)
|
ssid_list.append(ssid)
|
||||||
|
|
||||||
# 提取强度
|
# 提取强度
|
||||||
strength = None
|
strength = None
|
||||||
for i in range(len(columns)):
|
for i in range(len(columns)):
|
||||||
|
@ -122,18 +123,30 @@ def scan_wifi():
|
||||||
# print("MAC地址:", mac_address)
|
# print("MAC地址:", mac_address)
|
||||||
# print("Wi-Fi名称:", ssid)
|
# print("Wi-Fi名称:", ssid)
|
||||||
# print("强度:", strength)
|
# print("强度:", strength)
|
||||||
|
|
||||||
wifi_list.append({'ssid': ssid, 'signal': strength, 'mac': mac_address})
|
wifi_list.append({'ssid': ssid, 'signal': strength, 'mac': mac_address})
|
||||||
if len(wifi_list) == 15:
|
if len(wifi_list) == 15:
|
||||||
break
|
break
|
||||||
# save wifi_list to file
|
# save wifi_list to file
|
||||||
with open('wifi_list.txt', 'w') as f:
|
with open('wifi_list.json', 'w') as f:
|
||||||
for wifi in wifi_list:
|
json.dump(wifi_list, f)
|
||||||
print(f"{wifi}")
|
|
||||||
f.write(f"{wifi}\n")
|
|
||||||
|
|
||||||
return wifi_list
|
return wifi_list
|
||||||
|
|
||||||
|
def load_saved_wifi():
|
||||||
|
try:
|
||||||
|
with open('wifi_list.json', 'r') as f:
|
||||||
|
wifi_list = json.load(f)
|
||||||
|
return wifi_list
|
||||||
|
except FileNotFoundError:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def save_wifi(ssid, password):
|
||||||
|
wifi_list = load_saved_wifi()
|
||||||
|
wifi_list.append({'ssid': ssid, 'password': password})
|
||||||
|
with open('wifi_list.json', 'w') as f:
|
||||||
|
json.dump(wifi_list, f)
|
||||||
|
|
||||||
# 连接 Wi-Fi
|
# 连接 Wi-Fi
|
||||||
def connect_wifi(ssid, password):
|
def connect_wifi(ssid, password):
|
||||||
# 连接到用户选择的 Wi-Fi 网络
|
# 连接到用户选择的 Wi-Fi 网络
|
||||||
|
@ -142,6 +155,7 @@ def connect_wifi(ssid, password):
|
||||||
output_str = output.decode('utf-8') # 将输出转换为字符串
|
output_str = output.decode('utf-8') # 将输出转换为字符串
|
||||||
if "successfully" in output_str:
|
if "successfully" in output_str:
|
||||||
print(f"{datetime.datetime.now()}: Successfully connected to Wi-Fi: {ssid}")
|
print(f"{datetime.datetime.now()}: Successfully connected to Wi-Fi: {ssid}")
|
||||||
|
save_wifi(ssid, password) # 保存连接成功的Wi-Fi信息
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
print(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {output_str}")
|
print(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {output_str}")
|
||||||
|
@ -169,13 +183,13 @@ def disconnect_wifi():
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
def index():
|
def index():
|
||||||
global wifi_list
|
global wifi_list
|
||||||
|
|
||||||
response = make_response(render_template('index.html', wifi_list=wifi_list))
|
response = make_response(render_template('index.html', wifi_list=wifi_list))
|
||||||
response.headers.set('Content-Type', 'text/html')
|
response.headers.set('Content-Type', 'text/html')
|
||||||
response.headers.set('Apple-Web-App-Capable', 'yes')
|
response.headers.set('Apple-Web-App-Capable', 'yes')
|
||||||
response.headers.set('Apple-Mobile-Web-App-Status-Bar-Style', 'black-translucent')
|
response.headers.set('Apple-Mobile-Web-App-Status-Bar-Style', 'black-translucent')
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# 提交 Wi-Fi 信息
|
# 提交 Wi-Fi 信息
|
||||||
@app.route('/submit', methods=['POST'])
|
@app.route('/submit', methods=['POST'])
|
||||||
def submit():
|
def submit():
|
||||||
|
@ -184,20 +198,23 @@ def submit():
|
||||||
ssid = request.form['ssid']
|
ssid = request.form['ssid']
|
||||||
password = request.form['password']
|
password = request.form['password']
|
||||||
print(f"{datetime.datetime.now()}: Connecting to Wi-Fi: {ssid} with password {password}")
|
print(f"{datetime.datetime.now()}: Connecting to Wi-Fi: {ssid} with password {password}")
|
||||||
|
|
||||||
# 关闭热点
|
# 关闭热点
|
||||||
close_hotspot()
|
close_hotspot()
|
||||||
|
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
# 连接到用户选择的 Wi-Fi 网络
|
# 连接到用户选择的 Wi-Fi 网络
|
||||||
if connect_wifi(ssid, password):
|
if connect_wifi(ssid, password):
|
||||||
close_app()
|
close_app()
|
||||||
|
|
||||||
if not check_wifi_connection():
|
connected, wifi_ssid = check_wifi_connection()
|
||||||
|
if not connected:
|
||||||
print(f"{datetime.datetime.now()}: Wi-Fi连接失败。")
|
print(f"{datetime.datetime.now()}: Wi-Fi连接失败。")
|
||||||
wifi_list = scan_wifi()
|
wifi_list = scan_wifi()
|
||||||
start_hotspot()
|
start_hotspot()
|
||||||
|
else:
|
||||||
|
save_wifi(wifi_ssid, password) # 保存连接成功的Wi-Fi信息
|
||||||
|
|
||||||
return redirect(url_for('index'))
|
return redirect(url_for('index'))
|
||||||
|
|
||||||
|
|
||||||
|
@ -207,24 +224,25 @@ if __name__ == '__main__':
|
||||||
disconnect_wifi()
|
disconnect_wifi()
|
||||||
wifi_list = scan_wifi()
|
wifi_list = scan_wifi()
|
||||||
print(wifi_list)
|
print(wifi_list)
|
||||||
|
|
||||||
start_hotspot()
|
start_hotspot()
|
||||||
|
|
||||||
# app.run(host='0.0.0.0', port=80)
|
# app.run(host='0.0.0.0', port=80)
|
||||||
|
|
||||||
if connect_wifi("Innoxsz-Public", "innox2023"):
|
if connect_wifi("Innoxsz-Public", "innox2023"):
|
||||||
close_app()
|
close_app()
|
||||||
|
|
||||||
if led_enabled:
|
if led_enabled:
|
||||||
orangepi.set_led_on('blue')
|
orangepi.set_led_on('blue')
|
||||||
|
|
||||||
if check_wifi_connection():
|
connected, wifi_ssid = check_wifi_connection()
|
||||||
|
if connected:
|
||||||
print(f"{datetime.datetime.now()}: 系统已自动连接到 Wi-Fi 网络,退出程序")
|
print(f"{datetime.datetime.now()}: 系统已自动连接到 Wi-Fi 网络,退出程序")
|
||||||
close_app()
|
close_app()
|
||||||
else:
|
else:
|
||||||
wifi_list = scan_wifi()
|
wifi_list = load_saved_wifi()
|
||||||
|
if not wifi_list:
|
||||||
|
wifi_list = scan_wifi()
|
||||||
print(f"{datetime.datetime.now()}: 未连接到 Wi-Fi 网络")
|
print(f"{datetime.datetime.now()}: 未连接到 Wi-Fi 网络")
|
||||||
start_hotspot()
|
start_hotspot()
|
||||||
app.run(host='0.0.0.0', port=80)
|
app.run(host='0.0.0.0', port=80)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue