我创建了一个便宜的 Flask 应用程序来出售我的 WiFi。该设备通过 Intranet 上的应用程序进行连接,然后使用 pywifi 连接,然后我使用计划功能来管理时间。现在我需要一种方法,让设备在通话时间用完后断开连接后忘记密码。
def connect_to_wifi(ssid, password):
wifi = PyWiFi()
iface = wifi.interfaces()[0]
profile = Profile()
profile.ssid = ssid
profile.auth = const.AUTH_ALG_OPEN
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher = const.CIPHER_TYPE_CCMP
profile.key = password
iface.remove_all_network_profiles()
iface.add_network_profile(profile)
iface.connect(iface.add_network_profile(profile)) # Attempt to connect
# Check connection status
if iface.status() == const.IFACE_CONNECTED:
print(f"Successfully connected to {ssid}")
else:
print("Failed to connect")
connect_to_wifi('Nimrodian', '12345678nm')
def disconnect_wifi():
iface.disconnect()
#forget paswword mechanism
return schedule.CancelJob
schedule.every(30).minutes.do(disconnect_wifi)
while True:
schedule.run_pending()
time.sleep(1)
一种好的方法是实例化每个连接,假设您可能有不止一个人使用您的服务。
创建
WiFiConnection
类
class WiFiConnection:
def __init__(self, ssid, password):
self.ssid = ssid
self.password = password
self.wifi = PyWiFi()
self.iface = self.wifi.interfaces()[0]
self.profile = None
def connect(self):
# Set up the WiFi profile
self.profile = Profile()
self.profile.ssid = self.ssid
self.profile.auth = const.AUTH_ALG_OPEN
self.profile.akm.append(const.AKM_TYPE_WPA2PSK)
self.profile.cipher = const.CIPHER_TYPE_CCMP
self.profile.key = self.password
self.profile = self.iface.add_network_profile(self.profile)
# Connect to the WiFi network
self.iface.connect(self.profile)
time.sleep(5)
if self.iface.status() == const.IFACE_CONNECTED:
print(f"Successfully connected to {self.ssid}")
else:
print(f"Failed to connect to {self.ssid}")
def disconnect(self):
self.iface.disconnect()
time.sleep(2)
print(f"Disconnected from {self.ssid}")
def forget(self):
self.iface.remove_all_network_profiles()
print(f"Forgot the WiFi credentials for {self.ssid}")
您可以使用此类来创建新连接。
new_connection = WiFiConnection("your_ssid", "your_wifi_password")
使用
WiFiConnection
实例 new_connection
来管理与 connect()
disconnect()
和 forget()
方法的连接
您需要更新您的日程功能以断开特定连接,而不是断开所有人的连接。
def schedule_disconnection(connection, delay_minutes):
def terminate_connection():
connection.disconnect()
connection.forget()
return schedule.CancelJob
# Schedule the termination after a given time
schedule.every(delay_minutes).minutes.do(terminate_connection)
这是一个完整的用法示例:
active_connections = [] # Optional
new_connection = WiFiConnection("your_ssid", "your_wifi_password")
new_connection.connect()
active_connetions.append(new_connection)
# 30 minutes schedule
schedule_disconnection(new_connection, 30)
while True:
schedule.run_pending()
time.sleep(1)
您可以在 Flask 应用程序中实现此功能,让应用程序在用户每次使用该服务时创建一个新连接。