Compare commits

..
113 Commits
Author SHA1 Message Date
IrvingGao c0536c06da [wifi] dns 2024-06-17 20:26:56 +08:00
IrvingGao ec949435ee [wifi] connecting loop 2024-06-17 16:31:48 +08:00
IrvingGao 86ef89c3dd [led] check know wifi 2024-06-13 18:54:01 +08:00
IrvingGao e6c17f9479 [led] check know wifi 2024-06-13 18:38:22 +08:00
IrvingGao 6179153ade [led] check know wifi 2024-06-13 18:36:22 +08:00
IrvingGao af86072a98 [wifi] check know wifi 2024-06-13 18:31:51 +08:00
IrvingGao a4247c1639 [wifi] check know wifi 2024-06-13 18:30:06 +08:00
IrvingGao ec9f077b74 [wifi] check know wifi 2024-06-13 18:24:27 +08:00
IrvingGao 54bce42162 [wifi] check know wifi 2024-06-13 18:20:24 +08:00
IrvingGao 374d118fe1 [wifi] check know wifi 2024-06-13 18:15:09 +08:00
IrvingGao e28046d4ed [led] check know wifi 2024-06-13 18:12:27 +08:00
IrvingGao e5d3c79a8c [led] check know wifi 2024-06-13 18:11:30 +08:00
IrvingGao 93c29b4a11 [wifi] scan 2024-06-13 18:09:43 +08:00
IrvingGao b763ae0ae4 [led] scan led 2024-06-13 17:47:49 +08:00
IrvingGao 5ce861a562 [wifi] close 2024-06-13 17:45:07 +08:00
IrvingGao 2238cdbc30 [wifi] close 2024-06-13 17:37:46 +08:00
IrvingGao ebd6db5823 [wifi] force scan 2024-06-13 17:32:49 +08:00
IrvingGao d4cf53189d [wifi] wifi_list is empty bugs 2024-06-13 17:19:54 +08:00
IrvingGao 815dda7720 [wifi] wifi_list is empty bugs 2024-06-13 17:16:02 +08:00
IrvingGao ef8b952a6e [wifi] passwd file 2024-06-13 17:06:50 +08:00
IrvingGao 61275fd77f [wifi] passwd file 2024-06-13 16:54:34 +08:00
IrvingGao a13591b2be [scan] wifi 2024-06-13 16:47:06 +08:00
IrvingGao fd1a26d0c3 [scan] wifi 2024-06-13 16:41:33 +08:00
IrvingGao 1323e45dbd [scan] wifi 2024-06-13 16:38:33 +08:00
IrvingGao 0e1e3f442d [scan] wifi 2024-06-13 16:37:56 +08:00
IrvingGao c2e884a599 [scan] wifi 2024-06-13 16:30:24 +08:00
IrvingGao ca91fdd9f5 [scan] wifi 2024-06-13 16:29:39 +08:00
IrvingGao f9b644b88f [scan] wifi 2024-06-13 16:27:47 +08:00
IrvingGao f8ddd7e620 [scan] wifi 2024-06-13 16:25:27 +08:00
IrvingGao 9d5ec815d5 [scan] wifi 2024-06-13 16:24:35 +08:00
IrvingGao 19eea8ffcb [scan] wifi 2024-06-13 16:22:20 +08:00
IrvingGao 190c5266e4 [wifi] fix connecting bugs 2024-06-13 16:10:31 +08:00
IrvingGao 9dfd4f7c90 [wifi] fix big bugs 2024-06-13 16:00:39 +08:00
IrvingGao 3b8ae02e10 [wifi] fix big bugs 2024-06-13 15:50:31 +08:00
IrvingGao c0e8bdd6af [wifi] fix big bugs 2024-06-13 15:31:40 +08:00
IrvingGao 9ac857e9ac [log] add logger 2024-06-13 15:17:10 +08:00
IrvingGao a07f6b2954 [log] add logger 2024-06-13 15:11:25 +08:00
IrvingGao 3e88c60997 [wifi] short wait time 2024-06-13 14:03:32 +08:00
IrvingGao a64b22c329 [wifi] fix bug with disconnect 2024-06-13 13:39:38 +08:00
IrvingGao 002d44e0e7 update 2024-06-11 21:38:07 +08:00
IrvingGao 9949c7f58c [wifi] update 2024-06-09 15:06:31 +08:00
IrvingGao 9454163063 [debug] 2024-06-09 13:22:01 +08:00
IrvingGao 98386d3df0 [debug] 2024-06-09 03:41:25 +08:00
IrvingGao aa0b1bc76a [wifi] scan 2024-06-09 03:14:23 +08:00
IrvingGao e10b628bf9 [sh] nohup 2024-06-09 02:55:49 +08:00
IrvingGao 938ff45751 [ip] save ip 2024-06-09 02:48:38 +08:00
IrvingGao 533fb1b0ad update 2024-06-07 15:34:12 +08:00
IrvingGao 0f40754aa5 update bash 2024-05-31 13:09:07 +08:00
IrvingGao a81a235eea update 2024-05-31 12:50:04 +08:00
IrvingGao 45191faaba update 2024-05-31 12:46:49 +08:00
IrvingGao 23ba0136e6 update 2024-05-31 12:43:01 +08:00
IrvingGao da097b35d6 update 2024-05-31 12:37:40 +08:00
IrvingGao ad1a9a06dd update 2024-05-31 12:36:28 +08:00
IrvingGao a4885963d8 update 2024-05-31 12:17:53 +08:00
IrvingGao 83db094f02 [bug] wlan0 unmanaged 2024-05-29 22:47:52 +08:00
IrvingGao b65699231d bash 2024-05-27 23:26:58 +08:00
IrvingGao 765991626a bash 2024-05-27 23:26:06 +08:00
IrvingGao c60a2e89da bash 2024-05-27 23:25:00 +08:00
IrvingGao 19188b9aa2 bash 2024-05-27 23:24:15 +08:00
IrvingGao 159a83a412 bash 2024-05-27 23:22:57 +08:00
IrvingGao f8b4b7fa8c bash 2024-05-27 22:50:14 +08:00
IrvingGao da770aafeb wifi debug 2024-05-27 21:57:07 +08:00
IrvingGao 9aba50be67 wifi debug 2024-05-27 21:50:20 +08:00
IrvingGao a8da95f25b wifi json 2024-05-27 21:22:42 +08:00
IrvingGao bc99f15219 wifi json 2024-05-27 21:20:54 +08:00
IrvingGao 36a995c510 update hostapd conf 2024-05-27 19:46:19 +08:00
IrvingGao c117adaaec update hostapd conf 2024-05-27 19:45:22 +08:00
IrvingGao 2ef7074fcd update hostapd conf 2024-05-27 19:44:19 +08:00
IrvingGao ea08fb8cbc update hostapd conf 2024-05-27 19:29:26 +08:00
IrvingGao e2eb4248fc [v1.0] hotspot 2024-05-25 23:41:36 +08:00
IrvingGao 1e58c5e1ba [v1.0] hotspot 2024-05-25 23:28:40 +08:00
IrvingGao 75c7598bac [v1.0] hotspot 2024-05-25 23:25:49 +08:00
IrvingGao b050a67182 [v1.0] hotspot 2024-05-25 23:24:02 +08:00
IrvingGao b16550383b [v1.0] hotspot 2024-05-25 23:05:31 +08:00
IrvingGao f6ee8b1125 [v1.0] hotspot 2024-05-25 23:04:33 +08:00
IrvingGao c4d3a9ef4f debug hotspot 2024-05-25 22:59:48 +08:00
IrvingGao 601196b923 debug hotspot 2024-05-25 22:57:24 +08:00
IrvingGao 1aa4079807 debug hotspot 2024-05-25 22:53:36 +08:00
IrvingGao ac7913d1f7 debug hotspot 2024-05-25 22:52:14 +08:00
IrvingGao 1b55622b26 debug scan 2024-05-25 22:48:27 +08:00
IrvingGao 87395e5380 debug scan 2024-05-25 22:47:28 +08:00
IrvingGao ab86caf687 debug scan 2024-05-25 22:46:52 +08:00
IrvingGao 543628ea29 debug scan 2024-05-25 22:45:21 +08:00
IrvingGao 6e99d3378c debug scan 2024-05-25 22:44:42 +08:00
IrvingGao 0694c52a86 debug scan 2024-05-25 22:35:54 +08:00
IrvingGao 85959cc0f7 debug scan 2024-05-25 22:35:35 +08:00
IrvingGao 2fc8896339 debug scan 2024-05-25 22:32:53 +08:00
IrvingGao 4021cdd7b3 debug scan 2024-05-25 22:29:03 +08:00
IrvingGao 88e00938c5 debug scan 2024-05-25 22:28:12 +08:00
IrvingGao 0df010ef89 debug scan 2024-05-25 22:26:28 +08:00
IrvingGao 3f16602292 debug scan 2024-05-25 22:23:17 +08:00
IrvingGao 26f62a7611 debug scan 2024-05-25 22:21:14 +08:00
IrvingGao f68676c6f8 debug scan 2024-05-25 22:19:52 +08:00
IrvingGao effd91fece debug scan 2024-05-25 22:18:24 +08:00
IrvingGao 81d93783bb debug scan 2024-05-25 22:13:04 +08:00
IrvingGao 5f47968283 debug scan 2024-05-25 22:10:04 +08:00
IrvingGao bac826b237 renew workflow 2024-05-25 21:59:11 +08:00
IrvingGao 25d73178a6 update board enable 2024-05-25 00:33:37 +08:00
IrvingGao 20f4f4316b update check wifi connetction 2024-05-25 00:29:26 +08:00
IrvingGao dc8ba69b8d update check wifi connetction 2024-05-25 00:24:51 +08:00
IrvingGao 121c58b243 update readme 2024-05-25 00:22:20 +08:00
IrvingGao 11873fdf98 update exit 2024-05-25 00:02:37 +08:00
IrvingGao 8dd05a406f update exit 2024-05-25 00:00:33 +08:00
IrvingGao 1d453dc6c1 update led 2024-05-24 23:16:37 +08:00
IrvingGao d73eec7673 update 2024-05-21 02:01:51 +08:00
IrvingGao 31b531e713 update 2024-05-21 01:53:08 +08:00
IrvingGao c65a3352a2 update 2024-05-21 01:42:24 +08:00
gaohz 6553a3ce96 删除 wifi_manger.py 2024-05-20 23:15:13 +08:00
IrvingGao 6e5dbc2a6b update 2024-05-20 23:13:24 +08:00
IrvingGao 155ed8b46a update 2024-05-20 23:07:29 +08:00
IrvingGao 6ce468850c update 2024-05-19 20:30:23 +08:00
IrvingGao 6922061719 Merge branch 'main' of http://43.132.157.186:3000/gaohz/wifi_hotpot 2024-05-19 19:43:05 +08:00
IrvingGao 8b1c300f96 first commit 2024-05-19 16:01:10 +08:00
8 changed files with 807 additions and 165 deletions

No files matched your search

+198
View File
@@ -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
+```
+3
View File
@@ -0,0 +1,3 @@
interface wlan0
static ip_address=192.168.43.1/24
nohook wpa_supplicant
+15
View File
@@ -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
+76
View File
@@ -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()
+4
View File
@@ -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
+1 -1
View File
@@ -7,7 +7,7 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
</head> </head>
<body> <body>
<div class="pageTitle">配置</div> <div class="pageTitle">Takway.AI Wi-Fi连接</div>
<div class="inputLabel">WIFI 名称</div> <div class="inputLabel">WIFI 名称</div>
<div class="inputDiv"> <div class="inputDiv">
<div class="select-menu"> <div class="select-menu">
+510
View File
@@ -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
View File
@@ -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)
'''