Compare commits
113
Commits
fdc60139c7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0536c06da | ||
|
|
ec949435ee | ||
|
|
86ef89c3dd | ||
|
|
e6c17f9479 | ||
|
|
6179153ade | ||
|
|
af86072a98 | ||
|
|
a4247c1639 | ||
|
|
ec9f077b74 | ||
|
|
54bce42162 | ||
|
|
374d118fe1 | ||
|
|
e28046d4ed | ||
|
|
e5d3c79a8c | ||
|
|
93c29b4a11 | ||
|
|
b763ae0ae4 | ||
|
|
5ce861a562 | ||
|
|
2238cdbc30 | ||
|
|
ebd6db5823 | ||
|
|
d4cf53189d | ||
|
|
815dda7720 | ||
|
|
ef8b952a6e | ||
|
|
61275fd77f | ||
|
|
a13591b2be | ||
|
|
fd1a26d0c3 | ||
|
|
1323e45dbd | ||
|
|
0e1e3f442d | ||
|
|
c2e884a599 | ||
|
|
ca91fdd9f5 | ||
|
|
f9b644b88f | ||
|
|
f8ddd7e620 | ||
|
|
9d5ec815d5 | ||
|
|
19eea8ffcb | ||
|
|
190c5266e4 | ||
|
|
9dfd4f7c90 | ||
|
|
3b8ae02e10 | ||
|
|
c0e8bdd6af | ||
|
|
9ac857e9ac | ||
|
|
a07f6b2954 | ||
|
|
3e88c60997 | ||
|
|
a64b22c329 | ||
|
|
002d44e0e7 | ||
|
|
9949c7f58c | ||
|
|
9454163063 | ||
|
|
98386d3df0 | ||
|
|
aa0b1bc76a | ||
|
|
e10b628bf9 | ||
|
|
938ff45751 | ||
|
|
533fb1b0ad | ||
|
|
0f40754aa5 | ||
|
|
a81a235eea | ||
|
|
45191faaba | ||
|
|
23ba0136e6 | ||
|
|
da097b35d6 | ||
|
|
ad1a9a06dd | ||
|
|
a4885963d8 | ||
|
|
83db094f02 | ||
|
|
b65699231d | ||
|
|
765991626a | ||
|
|
c60a2e89da | ||
|
|
19188b9aa2 | ||
|
|
159a83a412 | ||
|
|
f8b4b7fa8c | ||
|
|
da770aafeb | ||
|
|
9aba50be67 | ||
|
|
a8da95f25b | ||
|
|
bc99f15219 | ||
|
|
36a995c510 | ||
|
|
c117adaaec | ||
|
|
2ef7074fcd | ||
|
|
ea08fb8cbc | ||
|
|
e2eb4248fc | ||
|
|
1e58c5e1ba | ||
|
|
75c7598bac | ||
|
|
b050a67182 | ||
|
|
b16550383b | ||
|
|
f6ee8b1125 | ||
|
|
c4d3a9ef4f | ||
|
|
601196b923 | ||
|
|
1aa4079807 | ||
|
|
ac7913d1f7 | ||
|
|
1b55622b26 | ||
|
|
87395e5380 | ||
|
|
ab86caf687 | ||
|
|
543628ea29 | ||
|
|
6e99d3378c | ||
|
|
0694c52a86 | ||
|
|
85959cc0f7 | ||
|
|
2fc8896339 | ||
|
|
4021cdd7b3 | ||
|
|
88e00938c5 | ||
|
|
0df010ef89 | ||
|
|
3f16602292 | ||
|
|
26f62a7611 | ||
|
|
f68676c6f8 | ||
|
|
effd91fece | ||
|
|
81d93783bb | ||
|
|
5f47968283 | ||
|
|
bac826b237 | ||
|
|
25d73178a6 | ||
|
|
20f4f4316b | ||
|
|
dc8ba69b8d | ||
|
|
121c58b243 | ||
|
|
11873fdf98 | ||
|
|
8dd05a406f | ||
|
|
1d453dc6c1 | ||
|
|
d73eec7673 | ||
|
|
31b531e713 | ||
|
|
c65a3352a2 | ||
|
|
6553a3ce96 | ||
|
|
6e5dbc2a6b | ||
|
|
155ed8b46a | ||
|
|
6ce468850c | ||
|
|
6922061719 | ||
|
|
8b1c300f96 |
No files matched your search
@@ -0,0 +1,198 @@
|
||||
|
||||
## Linux嵌入板卡自发热点连接无线网络
|
||||
|
||||
|
||||
### 介绍
|
||||
|
||||
Linux嵌入板卡发出热点供客户端连接,客户端通过浏览器访问热点,连接到Linux嵌入板卡的热点,并进行交互。
|
||||
|
||||
- 连接逻辑:
|
||||
|
||||
1. 扫描Wi-Fi,并将Wi-Fi list保存为json格式,存储在本地,命名为`scaned_wifi_list.json`;
|
||||
2. 检查Wi-Fi连接状态,若已连接,则退出程序;
|
||||
3. 关闭Wi-Fi,并启动热点和web服务器,web服务器监听80端口,并提供一个页面,页面中包含Wi-Fi列表;
|
||||
4. 等待用户选择 Wi-Fi 网络并输入密码,并连接到用户选择的 Wi-Fi 网络;
|
||||
5. 如果Wi-Fi连接成功,则显示Wi-Fi连接成功页面,并提供交互页面;
|
||||
6. 如果Wi-Fi连接失败,则重新扫描Wi-Fi,并提示用户重新连接.
|
||||
|
||||
- 灯光指示逻辑:
|
||||
|
||||
1. 当红灯亮起时,热点开启,等待客户端连接,连接成功后,红灯熄灭;
|
||||
2. 当蓝灯亮起时,程序正常启动,如果蓝灯不亮起,则程序未启动,如果蓝灯熄灭,则已连接Wi-Fi,程序已关闭.
|
||||
|
||||
### 环境准备
|
||||
|
||||
#### (1) 安装依赖项:
|
||||
|
||||
```
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y hostapd dnsmasq
|
||||
```
|
||||
|
||||
#### (2) 克隆项目到本地并安装依赖:
|
||||
|
||||
```
|
||||
// 克隆项目到本地 https or ssh
|
||||
git clone http://43.132.157.186:3000/gaohz/wifi_hotpot.git
|
||||
cd wifi_hotpot
|
||||
```
|
||||
|
||||
#### (3) 安装Python端环境依赖:
|
||||
|
||||
```
|
||||
sudo pip install flask psutil
|
||||
```
|
||||
|
||||
#### (4) 配置开机自启动服务项:
|
||||
|
||||
##### (4.1) 配置WiFi热点服务项:
|
||||
|
||||
|
||||
1. 创建一个service文件:
|
||||
|
||||
```
|
||||
sudo vim /etc/systemd/system/hotspot.service
|
||||
```
|
||||
|
||||
2. 在打开的文件中,添加以下内容:
|
||||
|
||||
```
|
||||
[Unit]
|
||||
Description=Hotspot Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecPre=/bin/sleep 2
|
||||
ExecStart=create_ap wlan0 eth0 Takway-Toys --no-virt
|
||||
User=root
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
请确保将`wlan0`替换为你的无线网卡接口,将`eth0`替换为你的有线网卡接口,`Takway-Toys`替换为你想要设置的热点名称。
|
||||
|
||||
3. 保存并关闭文件。
|
||||
|
||||
4. 重新加载systemd配置:
|
||||
|
||||
```
|
||||
sudo systemctl daemon-reload
|
||||
```
|
||||
|
||||
5. 启用并启动Hotspot service:
|
||||
|
||||
```
|
||||
# sudo systemctl enable hotspot.service
|
||||
sudo systemctl start hotspot.service
|
||||
```
|
||||
|
||||
|
||||
6. 如果需要停止Hotspot service,可以使用以下命令:
|
||||
|
||||
```
|
||||
sudo systemctl stop hotspot.service
|
||||
```
|
||||
|
||||
7. 如果需要查看Hotspot service的状态:
|
||||
|
||||
```
|
||||
sudo systemctl status hotspot.service
|
||||
```
|
||||
|
||||
##### (4.2) 配置WiFi热点管理服务项:
|
||||
|
||||
|
||||
- 编辑
|
||||
```
|
||||
sudo vim /etc/systemd/system/wifi_hotspot.service
|
||||
```
|
||||
|
||||
- 内容:
|
||||
```
|
||||
[Unit]
|
||||
Description=WiFi Hotspot Wrapper
|
||||
After=network.target
|
||||
Wants=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/bin/bash /home/orangepi/wifi_hotpot/start_hotpots.sh
|
||||
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 stop wifi_hotspot.service
|
||||
```
|
||||
|
||||
- 查看输出
|
||||
```
|
||||
sudo systemctl status wifi_hotspot.service
|
||||
```
|
||||
|
||||
#### (5) 配置热点信息:
|
||||
|
||||
|
||||
- 手动连接`http://192.168.12.1/`
|
||||
|
||||
- 连接成功后,输入用户名密码,即可进入交互界面。
|
||||
|
||||
|
||||
|
||||
## 其他参考命令
|
||||
|
||||
- 创建热点:
|
||||
|
||||
```
|
||||
sudo systemctl start hotspot.service
|
||||
```
|
||||
|
||||
- 关闭热点:
|
||||
|
||||
```
|
||||
sudo systemctl stop hotspot.service
|
||||
```
|
||||
|
||||
- 开启Wi-Fi连接:
|
||||
|
||||
```
|
||||
nmcli dev wifi connect Innoxsz-Public password innox2023
|
||||
```
|
||||
|
||||
- 断开Wi-Fi连接:
|
||||
|
||||
```
|
||||
nmcli dev disconnect wlan0
|
||||
```
|
||||
|
||||
- 扫描Wi-Fi:
|
||||
|
||||
```
|
||||
nmcli dev wifi
|
||||
```
|
||||
|
||||
- 检查Wi-Fi连接状态:
|
||||
```
|
||||
nmcli dev status
|
||||
```
|
||||
|
||||
|
||||
### create_ap
|
||||
|
||||
```
|
||||
sudo create_ap wlan0 eth0 Takway-Toys --no-virt
|
||||
+```
|
||||
@@ -0,0 +1,3 @@
|
||||
interface wlan0
|
||||
static ip_address=192.168.43.1/24
|
||||
nohook wpa_supplicant
|
||||
@@ -0,0 +1,15 @@
|
||||
interface=wlan0
|
||||
driver=nl80211
|
||||
ssid=Takway-Toys
|
||||
hw_mode=g
|
||||
channel=6
|
||||
ieee80211n=1
|
||||
wmm_enabled=1
|
||||
macaddr_acl=0
|
||||
auth_algs=1
|
||||
ignore_broadcast_ssid=0
|
||||
wpa=2
|
||||
wpa_passphrase=1234567890
|
||||
wpa_key_mgmt=WPA-PSK
|
||||
wpa_pairwise=CCMP
|
||||
rsn_pairwise=CCMP
|
||||
@@ -0,0 +1,76 @@
|
||||
import wifi_manager
|
||||
import subprocess
|
||||
import datetime
|
||||
import json
|
||||
|
||||
def scan_wifi():
|
||||
try:
|
||||
subprocess.run(['nmcli', 'dev', 'wifi', 'rescan'], check=True)
|
||||
cmd = "nmcli dev wifi"
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"{datetime.datetime.now()}: Error scanning Wi-Fi: {e}")
|
||||
network_error_light_1()
|
||||
return []
|
||||
print(f"{datetime.datetime.now()}: Wi-Fi scan complete...")
|
||||
ssid_list = []
|
||||
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}")
|
||||
|
||||
# ['94:14:57:15:13:50', 'Meeting', 'MG', 'Infra', '1', '130', 'Mbit/s', '100', '****', 'WPA1', 'WPA2']
|
||||
|
||||
# 提取MAC地址
|
||||
mac_address = columns[0]
|
||||
if columns[0] == '*': # 已连接的WiFi 第一位为*
|
||||
mac_address = columns[1]
|
||||
|
||||
# 提取Wi-Fi名称
|
||||
wifi_name = []
|
||||
for i in range(1, len(columns)):
|
||||
if columns[i] == 'Infra':
|
||||
_wifi_name = ' '.join(columns[1:i])
|
||||
wifi_name.append(_wifi_name)
|
||||
columns = columns[i+1:]
|
||||
break
|
||||
ssid = wifi_name[0]
|
||||
if ':' in ssid:
|
||||
# 94:14:57:15:13:50 Meeting
|
||||
# 去除mac地址
|
||||
ssid = ssid.split(' ')[1:]
|
||||
ssid = ''.join(ssid)
|
||||
if ssid == '--':
|
||||
continue
|
||||
if ssid in ssid_list:
|
||||
continue
|
||||
ssid_list.append(ssid)
|
||||
|
||||
# 提取强度
|
||||
strength = None
|
||||
for i in range(len(columns)):
|
||||
if columns[i] == 'Mbit/s':
|
||||
strength = columns[i+1]
|
||||
break
|
||||
print("MAC地址:", mac_address)
|
||||
print("Wi-Fi名称:", ssid)
|
||||
print("强度:", strength)
|
||||
|
||||
wifi_list.append({'ssid': ssid, 'signal': strength, 'mac': mac_address})
|
||||
if len(wifi_list) == 15:
|
||||
break
|
||||
with open('scaned_wifi_list.json', 'w') as f:
|
||||
json.dump(wifi_list, f)
|
||||
print(f"{datetime.datetime.now()}: Wi-Fi scaned list: {wifi_list}")
|
||||
|
||||
|
||||
return wifi_list
|
||||
|
||||
if __name__ == '__main__':
|
||||
wifi_list = scan_wifi()
|
||||
@@ -0,0 +1,4 @@
|
||||
# run this script to start the hotpot server
|
||||
python3 wifi_manager.py
|
||||
# cd to the TakwayBoard directory and start the client
|
||||
cd ../TakwayBoard && python3 ws_client.py
|
||||
@@ -7,7 +7,7 @@
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
</head>
|
||||
<body>
|
||||
<div class="pageTitle">配置</div>
|
||||
<div class="pageTitle">Takway.AI Wi-Fi连接</div>
|
||||
<div class="inputLabel">WIFI 名称</div>
|
||||
<div class="inputDiv">
|
||||
<div class="select-menu">
|
||||
|
||||
+510
@@ -0,0 +1,510 @@
|
||||
import subprocess
|
||||
import re
|
||||
import os
|
||||
import psutil
|
||||
import signal
|
||||
import time
|
||||
import datetime
|
||||
import json
|
||||
from flask import Flask, render_template, request, redirect, url_for, make_response
|
||||
import socket
|
||||
|
||||
import logging
|
||||
|
||||
logging.basicConfig(
|
||||
filename='app.log', # 日志文件的名称
|
||||
filemode='a', # 'a'代表追加模式,如果文件存在则追加内容
|
||||
level=logging.DEBUG, # 日志级别,DEBUG是最低的级别,会记录所有级别的日志
|
||||
format='%(asctime)s - %(levelname)s - %(message)s' # 日志的格式
|
||||
)
|
||||
|
||||
wifi_credential_file = '/home/orangepi/.config/wifi_credentials.json'
|
||||
|
||||
try:
|
||||
from takway.board import OrangePi
|
||||
led_enabled = True
|
||||
orangepi = OrangePi()
|
||||
except ImportError:
|
||||
led_enabled = False
|
||||
logging.info("Error importing OrangePi")
|
||||
|
||||
# blue: APP
|
||||
# red: hotspot
|
||||
|
||||
def network_error_light_1():
|
||||
error_time = datetime.datetime.now()
|
||||
while led_enabled:
|
||||
orangepi.set_led_off('blue')
|
||||
orangepi.set_led_on('red')
|
||||
time.sleep(0.25)
|
||||
orangepi.set_led_on('blue')
|
||||
orangepi.set_led_off('red')
|
||||
time.sleep(0.25)
|
||||
if error_time + datetime.timedelta(seconds=2) < datetime.datetime.now():
|
||||
break
|
||||
# close_app()
|
||||
|
||||
def network_error_light_2():
|
||||
error_time = datetime.datetime.now()
|
||||
while led_enabled:
|
||||
orangepi.set_led_on('green')
|
||||
time.sleep(0.25)
|
||||
orangepi.set_led_off('green')
|
||||
time.sleep(0.25)
|
||||
if error_time + datetime.timedelta(seconds=2) < datetime.datetime.now():
|
||||
break
|
||||
# close_app()
|
||||
|
||||
def edit_line_in_file(file_path, search_string, replacement_string):
|
||||
edit = False
|
||||
try:
|
||||
# 读取文件内容
|
||||
with open(file_path, 'r') as file:
|
||||
lines = file.readlines()
|
||||
|
||||
# 替换包含特定内容的行
|
||||
with open(file_path, 'r+') as file:
|
||||
file.seek(0) # 移动到文件开头
|
||||
file.truncate() # 清空文件内容
|
||||
for line in lines:
|
||||
if search_string in line:
|
||||
file.write(replacement_string + '\n')
|
||||
edit = True
|
||||
logging.info(f"The line has been edited. \noriginal line: {line}, \nnew line: {replacement_string}")
|
||||
else:
|
||||
file.write(line)
|
||||
return edit
|
||||
except FileNotFoundError:
|
||||
logging.info(f"The file {file_path} does not exist.")
|
||||
return edit
|
||||
except IOError as e:
|
||||
logging.info(f"An error occurred: {e}")
|
||||
return edit
|
||||
|
||||
# 获取私有IP地址
|
||||
def save_local_ip():
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(("8.8.8.8", 80))
|
||||
local_ip = s.getsockname()[0]
|
||||
s.close()
|
||||
# save local_ip to file
|
||||
with open('local_ip.txt', 'w') as f:
|
||||
f.write(local_ip)
|
||||
logging.info(f"Local IP address: {local_ip}")
|
||||
return local_ip
|
||||
except Exception as e:
|
||||
logging.info(f"Error getting private IP: {e}")
|
||||
return None
|
||||
|
||||
def edit_dns():
|
||||
# 编辑 /etc/resolv.conf 文件,添加 DNS 服务器
|
||||
# nameserver 8.8.8.8
|
||||
# nameserver 8.8.4.4
|
||||
# 读取文件内容
|
||||
dns_exist = False
|
||||
with open('/etc/resolv.conf', 'r+') as file:
|
||||
lines = file.readlines()
|
||||
for line in lines:
|
||||
if 'nameserver' in line:
|
||||
dns_exist = True
|
||||
if not dns_exist:
|
||||
file.write('nameserver 8.8.8.8' + '\n')
|
||||
file.write('nameserver 8.8.4.4' + '\n')
|
||||
logging.info(f"DNS server added.")
|
||||
else:
|
||||
logging.info(f"DNS server already exist.")
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
def close_app():
|
||||
if led_enabled:
|
||||
orangepi.set_led_off('blue')
|
||||
|
||||
# 保存Wi-Fi IP地址
|
||||
save_local_ip()
|
||||
|
||||
logging.info(f"Exit Wi-Fi hotspot...")
|
||||
|
||||
# 获取当前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)
|
||||
|
||||
def start_hotspot():
|
||||
try:
|
||||
subprocess.Popen('sudo systemctl start hotspot.service', shell=True)
|
||||
if led_enabled:
|
||||
orangepi.set_led_on('red')
|
||||
logging.info("Start hotspot.service.")
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.info(f"Error starting create_ap service: {e}")
|
||||
|
||||
def close_hotspot():
|
||||
# 关闭热点
|
||||
try:
|
||||
subprocess.Popen('sudo systemctl stop hotspot.service', shell=True)
|
||||
logging.info(f"Stopping hotspot.service")
|
||||
if led_enabled:
|
||||
orangepi.set_led_off('red')
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.info(f"Error stopping hotspot.service: {e}")
|
||||
|
||||
|
||||
def init_networkmanager_file():
|
||||
file_path = '/etc/NetworkManager/NetworkManager.conf'
|
||||
search_string = 'unmanaged-devices=interface-name:'
|
||||
replacement_string = '' # 如果不需要替换为其他内容,可以设置为空字符串
|
||||
if edit_line_in_file(file_path, search_string, replacement_string):
|
||||
'''
|
||||
# 从 /etc/NetworkManager/NetworkManager.conf 文件中移除或注释掉 [keyfile] 部分的 unmanaged-devices 条目,因为它可能阻止了 NetworkManager 管理 wlan0 接口。编辑文件如下:
|
||||
```
|
||||
[keyfile]
|
||||
#unmanaged-devices=interface-name:ap0;interface-name:wlan0
|
||||
```
|
||||
sudo systemctl restart NetworkManager
|
||||
'''
|
||||
# network_error_light_1()
|
||||
logging.info(f"Wi-Fi NetworkManager Error: restart NetworkManager.")
|
||||
subprocess.Popen('sudo systemctl restart NetworkManager', shell=True)
|
||||
time.sleep(2) # 不得修改该时间,保留足够长时间给NetworkManager重启完成,并连接以往WiFi。
|
||||
|
||||
# 检测 Wi-Fi 连接状态
|
||||
def check_wifi_connection():
|
||||
cmd = "nmcli dev status"
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
output = result.stdout.strip()
|
||||
lines = output.split("\n")[1:] # Skip the header line
|
||||
for line in lines:
|
||||
columns = line.split()
|
||||
logging.info(columns)
|
||||
'''
|
||||
['wlan0', 'wifi', 'disconnected', '--']
|
||||
['p2p-dev-wlan0', 'wifi-p2p', 'disconnected', '--']
|
||||
['eth0', 'ethernet', 'unavailable', '--']
|
||||
['lo', 'loopback', 'unmanaged', '--']
|
||||
'''
|
||||
if len(columns) >= 4 and columns[2] == "connected":
|
||||
wifi_ssid = columns[3]
|
||||
if led_enabled:
|
||||
orangepi.set_led_off('blue')
|
||||
logging.info(f"Wi-Fi connected: {wifi_ssid}")
|
||||
return True, wifi_ssid
|
||||
elif len(columns) >= 4 and columns[2] == "connecting":
|
||||
wifi_ssid = columns[4]
|
||||
check_connecting_loop()
|
||||
if led_enabled:
|
||||
orangepi.set_led_on('blue')
|
||||
logging.info(f"Wi-Fi connecting: {wifi_ssid}")
|
||||
return True, wifi_ssid
|
||||
return False, None
|
||||
|
||||
def check_connecting_loop():
|
||||
connecting = True
|
||||
while connecting:
|
||||
cmd = "nmcli dev status"
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
output = result.stdout.strip()
|
||||
lines = output.split("\n")[1:] # Skip the header line
|
||||
for line in lines:
|
||||
columns = line.split()
|
||||
if len(columns) >= 4 and columns[2] == "connected":
|
||||
wifi_ssid = columns[3]
|
||||
connecting = False
|
||||
break
|
||||
|
||||
def get_known_wifi():
|
||||
# 定义一个空列表来存储解析后的连接信息
|
||||
connections = []
|
||||
|
||||
cmd = "nmcli connection show"
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
output = result.stdout.strip()
|
||||
lines = output.split("\n")[1:] # Skip the header line
|
||||
# output = result.stdout.strip()
|
||||
# 按行分割输出
|
||||
# lines = output.strip().split('\n')[1:] # 跳过标题行
|
||||
|
||||
# 遍历每一行以解析连接信息
|
||||
for line in lines:
|
||||
if line.strip(): # 确保跳过空行
|
||||
# 分割每一行以获取字段
|
||||
fields = line.split()
|
||||
if len(fields) >= 4:
|
||||
# 创建一个字典来存储当前连接的信息
|
||||
connection_info = {
|
||||
'ssid': fields[0],
|
||||
# 'uuid': fields[1],
|
||||
'type': fields[2],
|
||||
# 'device': fields[3] if fields[3] != '--' else None # 如果设备列为'--',则设为None
|
||||
}
|
||||
# 将连接信息添加到列表中
|
||||
if connection_info['type'] == 'wifi': # 只处理wifi连接信息
|
||||
connections.append(connection_info)
|
||||
logging.info(f"Known Wi-Fi connections: {connections}")
|
||||
return connections
|
||||
|
||||
def check_known_wifi(scan_wifi_list):
|
||||
known_wifi_exist = False
|
||||
known_wifi_list = get_known_wifi()
|
||||
logging.info(f"Known Wi-Fi list: {known_wifi_list}")
|
||||
logging.info(f"Scan Wi-Fi list: {scan_wifi_list}")
|
||||
for known_wifi in known_wifi_list:
|
||||
for wifi in scan_wifi_list:
|
||||
if known_wifi['ssid'] == wifi['ssid']:
|
||||
known_wifi_exist = True
|
||||
logging.info(f"Known Wi-Fi exist: {known_wifi['ssid']}")
|
||||
if not known_wifi_exist:
|
||||
return False
|
||||
while known_wifi_exist:
|
||||
logging.info(f"Known Wi-Fi exist, wait for connecting...")
|
||||
connected, _ = check_wifi_connection()
|
||||
if led_enabled:
|
||||
for i in range(2):
|
||||
orangepi.set_led_off('blue')
|
||||
time.sleep(0.25)
|
||||
orangepi.set_led_on('blue')
|
||||
time.sleep(0.25)
|
||||
if connected:
|
||||
orangepi.set_led_off('blue')
|
||||
break
|
||||
return True
|
||||
|
||||
def force_scan_wifi():
|
||||
wifi_list = []
|
||||
while True:
|
||||
logging.info(f"wifi_list=={wifi_list}, 正在重新扫描Wi-Fi...")
|
||||
init_networkmanager_file() # 初始化 NetworkManager 配置文件
|
||||
# 扫描Wi-Fi
|
||||
wifi_list = scan_wifi()
|
||||
if wifi_list != []:
|
||||
logging.info(f"Wi-Fi scan finished: {wifi_list}")
|
||||
break
|
||||
if led_enabled:
|
||||
for i in range(4):
|
||||
orangepi.set_led_on('red')
|
||||
time.sleep(0.25)
|
||||
orangepi.set_led_off('red')
|
||||
time.sleep(0.25)
|
||||
else:
|
||||
time.sleep(2) # 等待2秒,确保wifi scan完成
|
||||
return wifi_list
|
||||
|
||||
|
||||
def scan_wifi():
|
||||
try:
|
||||
# subprocess.run(['nmcli', 'dev', 'wifi', 'rescan'], check=True)
|
||||
cmd = "nmcli dev wifi"
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.info(f"Error scanning Wi-Fi: {e}")
|
||||
# network_error_light_1()
|
||||
return []
|
||||
logging.info(f"Wi-Fi scan complete...")
|
||||
ssid_list = []
|
||||
wifi_list = []
|
||||
output = result.stdout.strip()
|
||||
lines = output.split("\n")[1:] # Skip the header line
|
||||
for line in lines:
|
||||
columns = line.split()
|
||||
'''
|
||||
logging.info(columns)
|
||||
for i, column in enumerate(columns):
|
||||
logging.info(f"{i}: {column}")
|
||||
'''
|
||||
# ['94:14:57:15:13:50', 'Meeting', 'MG', 'Infra', '1', '130', 'Mbit/s', '100', '****', 'WPA1', 'WPA2']
|
||||
|
||||
# 提取MAC地址
|
||||
mac_address = columns[0]
|
||||
if columns[0] == '*': # 已连接的WiFi 第一位为*
|
||||
mac_address = columns[1]
|
||||
|
||||
# 提取Wi-Fi名称
|
||||
wifi_name = []
|
||||
for i in range(1, len(columns)):
|
||||
if columns[i] == 'Infra':
|
||||
_wifi_name = ' '.join(columns[1:i])
|
||||
wifi_name.append(_wifi_name)
|
||||
columns = columns[i+1:]
|
||||
break
|
||||
ssid = wifi_name[0]
|
||||
if ':' in ssid:
|
||||
# 94:14:57:15:13:50 Meeting
|
||||
# 去除mac地址
|
||||
ssid = ssid.split(' ')[1:]
|
||||
ssid = ''.join(ssid)
|
||||
if ssid == '--':
|
||||
continue
|
||||
if ssid in ssid_list:
|
||||
continue
|
||||
ssid_list.append(ssid)
|
||||
|
||||
# 提取强度
|
||||
strength = None
|
||||
for i in range(len(columns)):
|
||||
if columns[i] == 'Mbit/s':
|
||||
strength = columns[i+1]
|
||||
break
|
||||
# logging.info("MAC地址:", mac_address)
|
||||
# logging.info("Wi-Fi名称:", ssid)
|
||||
# logging.info("强度:", strength)
|
||||
|
||||
wifi_list.append({'ssid': ssid, 'signal': strength, 'mac': mac_address})
|
||||
if len(wifi_list) == 15:
|
||||
break
|
||||
with open('scaned_wifi_list.json', 'w') as f:
|
||||
json.dump(wifi_list, f)
|
||||
logging.info(f"Wi-Fi scaned list: {wifi_list}")
|
||||
|
||||
return wifi_list
|
||||
|
||||
# 连接 Wi-Fi
|
||||
def connect_wifi(ssid, password):
|
||||
# 连接到用户选择的 Wi-Fi 网络
|
||||
try:
|
||||
output = subprocess.check_output(['nmcli', 'dev', 'wifi', 'connect', ssid, 'password', password])
|
||||
output_str = output.decode('utf-8') # 将输出转换为字符串
|
||||
if "successfully" in output_str:
|
||||
logging.info(f"Successfully connected to Wi-Fi: {ssid}")
|
||||
save_wifi(ssid, password) # 保存连接成功的Wi-Fi信息
|
||||
return True
|
||||
else:
|
||||
logging.info(f"Error connecting to Wi-Fi: {output_str}")
|
||||
return False
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.info(f"Error connecting to Wi-Fi: {e}")
|
||||
return False
|
||||
|
||||
# 关闭 Wi-Fi
|
||||
def disconnect_wifi():
|
||||
try:
|
||||
output = subprocess.check_output(['nmcli', 'dev', 'disconnect', 'iface', 'wlan0'])
|
||||
output_str = output.decode('utf-8') # 将输出转换为字符串
|
||||
if "successfully disconnected" in output_str:
|
||||
logging.info(f"Wi-Fi disconnected successfully")
|
||||
else:
|
||||
logging.info(f"Error disconnecting from Wi-Fi: {output_str}")
|
||||
except Exception as e:
|
||||
logging.info(f"Error disconnecting from Wi-Fi: {e}")
|
||||
|
||||
def connect_saved_wifi(scaned_wifi_list):
|
||||
wifi_list = load_saved_wifi()
|
||||
if wifi_list == []:
|
||||
return False, None
|
||||
for wifi in wifi_list:
|
||||
if wifi['ssid'] in [item['ssid'] for item in scaned_wifi_list]:
|
||||
if connect_wifi(wifi['ssid'], wifi['password']):
|
||||
return True, wifi['ssid']
|
||||
return check_wifi_connection()
|
||||
|
||||
|
||||
def load_saved_wifi():
|
||||
try:
|
||||
with open(wifi_credential_file, 'r') as f:
|
||||
wifi_list = json.load(f)
|
||||
logging.info(f"Loaded saved Wi-Fi file `{wifi_credential_file}`: {wifi_list}")
|
||||
return wifi_list
|
||||
except:
|
||||
logging.info(f"No saved Wi-Fi file `{wifi_credential_file}`found.")
|
||||
return []
|
||||
|
||||
def save_wifi(ssid, password):
|
||||
wifi_list = load_saved_wifi()
|
||||
if ssid not in [item['ssid'] for item in wifi_list]:
|
||||
wifi_list.append({'ssid': ssid, 'password': password})
|
||||
with open(wifi_credential_file, 'w') as f:
|
||||
json.dump(wifi_list, f)
|
||||
logging.info(f"Saved Wi-Fi file `{wifi_credential_file}`: {wifi_list}")
|
||||
|
||||
|
||||
# 主页
|
||||
@app.route('/')
|
||||
def index():
|
||||
global 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():
|
||||
if led_enabled:
|
||||
orangepi.set_led_on('red')
|
||||
ssid = request.form['ssid']
|
||||
password = request.form['password']
|
||||
logging.info(f"Connecting to Wi-Fi: {ssid} with password {password}")
|
||||
|
||||
# 关闭热点
|
||||
close_hotspot()
|
||||
|
||||
wifi_list = force_scan_wifi()
|
||||
|
||||
# 连接到用户选择的 Wi-Fi 网络
|
||||
if connect_wifi(ssid, password):
|
||||
close_app()
|
||||
|
||||
connected, wifi_ssid = check_wifi_connection()
|
||||
if not connected:
|
||||
logging.info(f"Wi-Fi连接失败。")
|
||||
start_hotspot()
|
||||
else:
|
||||
save_wifi(ssid, password) # 保存连接成功的Wi-Fi信息
|
||||
close_app()
|
||||
|
||||
return redirect(url_for('index'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
debug_mode = False # 设置为 True 以跳过 Wi-Fi 连接状态检测
|
||||
if debug_mode:
|
||||
disconnect_wifi()
|
||||
|
||||
if led_enabled:
|
||||
orangepi.set_led_on('blue')
|
||||
|
||||
logging.info(f"Starting Wi-Fi Manager...")
|
||||
|
||||
edit_dns()
|
||||
|
||||
init_networkmanager_file() # 初始化 NetworkManager 配置文件
|
||||
|
||||
# 扫描Wi-Fi
|
||||
wifi_list = force_scan_wifi()
|
||||
# wifi_list = scan_wifi()
|
||||
# time.sleep(2) # 等待2秒,确保wifi scan完成
|
||||
|
||||
connected = check_known_wifi(wifi_list)
|
||||
if connected:
|
||||
logging.info(f"系统已自动连接到 Wi-Fi 网络,退出程序")
|
||||
close_app()
|
||||
|
||||
connected, wifi_ssid = check_wifi_connection()
|
||||
if connected:
|
||||
logging.info(f"系统已自动连接到 Wi-Fi 网络,退出程序")
|
||||
close_app()
|
||||
|
||||
|
||||
'''
|
||||
# 连接保存的Wi-Fi
|
||||
connected, wifi_ssid = connect_saved_wifi(wifi_list)
|
||||
if connected:
|
||||
logging.info(f"系统已自动连接到 Wi-Fi 网络 {wifi_ssid},退出程序")
|
||||
close_app()
|
||||
'''
|
||||
|
||||
logging.info(f"未连接到 Wi-Fi 网络, 开始热点模式")
|
||||
# force_scan_wifi()
|
||||
|
||||
start_hotspot()
|
||||
app.run(host='0.0.0.0', port=80)
|
||||
-164
@@ -1,164 +0,0 @@
|
||||
import subprocess
|
||||
import os
|
||||
import time
|
||||
from flask import Flask, render_template, request, redirect, url_for, make_response
|
||||
|
||||
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}")
|
||||
|
||||
def scan_wifi():
|
||||
try:
|
||||
subprocess.run(['nmcli', 'dev', 'wifi', 'rescan'], check=True)
|
||||
time.sleep(1)
|
||||
output = subprocess.check_output(['nmcli', 'dev', 'wifi'])
|
||||
wifi_list = []
|
||||
lines = output.decode().splitlines()
|
||||
print(lines)
|
||||
print(len(lines))
|
||||
# for new in lines.split("', '"):
|
||||
# print(f"new: {new}")
|
||||
print("###### ")
|
||||
for idx, line in enumerate(lines[1:]):
|
||||
print(f"{idx}: {line}")
|
||||
|
||||
# 分割字符串以空格为分隔符
|
||||
columns = line.split()
|
||||
|
||||
# 提取第一列和第三列的值
|
||||
mac_address = columns[0]
|
||||
|
||||
ssid = " ".join(columns[1:3])
|
||||
if "Infra" in ssid:
|
||||
ssid = ssid.replace(" Infra", "")
|
||||
print("ssid: ", ssid.strip())
|
||||
|
||||
# 提取第六列的强度值
|
||||
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
|
||||
|
||||
return wifi_list
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error scanning for Wi-Fi networks: {e}")
|
||||
return []
|
||||
|
||||
def scan_wifi_table():
|
||||
import csv
|
||||
import subprocess
|
||||
from io import StringIO
|
||||
|
||||
# 调用 nmcli dev wifi 命令并获取输出
|
||||
output = subprocess.check_output(['nmcli', 'dev', 'wifi']).decode()
|
||||
|
||||
# 创建一个内存中的文件对象
|
||||
file_object = StringIO(output)
|
||||
|
||||
# 使用csv模块读取文件对象,并指定分隔符为whitespace
|
||||
reader = csv.reader(file_object, delimiter=' ')
|
||||
|
||||
# 将数据存储到二维列表中
|
||||
data = [row for row in reader]
|
||||
|
||||
# 打印表格数据
|
||||
for row in data:
|
||||
print(row)
|
||||
|
||||
# 连接 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():
|
||||
wifi_list = scan_wifi()
|
||||
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():
|
||||
ssid = request.form['ssid']
|
||||
password = request.form['password']
|
||||
print(f"Connecting to Wi-Fi: {ssid} with password {password}")
|
||||
connect_wifi(ssid, password)
|
||||
stop_hotspot() # 关闭热点
|
||||
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()
|
||||
|
||||
print("Starting Flask server")
|
||||
print("----------------------------")
|
||||
wf_list = scan_wifi()
|
||||
print("----------------------------")
|
||||
print(wf_list)
|
||||
|
||||
|
||||
'''
|
||||
# 启动 Flask 服务器
|
||||
app.run(host='0.0.0.0', port=80, debug=True)
|
||||
'''
|
||||
|
||||
Reference in new issue
Block a user