LISHUZUOXUN_yangjiang/LSZXNetWork/NetworkDriverLinux/wifi_ap.py

100 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import re
from ping3 import ping
from AcrossPlatform.get_platform import GLOBAL_DIR
from LSZXNetWork.NetworkDriverLinux.wifi import DEFAULT_DEVICE, LAN_DEVICE
from LogRecord.log_recorder import GLOBAL_LOG
DEFAULT_IP_SEGMENT = r"192.168.[0-9]{1,3}.[0-9]{1,3}"
AP_CONF_DIR = os.path.join(GLOBAL_DIR, "LSZXNetWork/NetworkDriverLinux/start_wifi_ap.sh")
PATTERN_AP_CONF_DIR = os.path.join(GLOBAL_DIR, "LSZXNetWork/NetworkDriverLinux/pattern_start_wifi_ap.sh")
STOP_AP_CONF_DIR = os.path.join(GLOBAL_DIR, "LSZXNetWork/NetworkDriverLinux/stop_wifi_ap.sh")
PATTERN_STOP_AP_CONF_DIR = os.path.join(GLOBAL_DIR, "LSZXNetWork/NetworkDriverLinux/pattern_stop_wifi_ap.sh")
MASTER_IP = "192.168.137.1"
WLAN_DEVICE_TAG = "<wlan>"
LAN_DEVICE_TAG = "<lan>"
SSID_DEVICE_TAG = "<ssid>"
PASS_DEVICE_TAG = "<passphrase>"
# 获得同个网段下的设备
def get_machine_ip_address():
echo = os.popen("arp -a | awk '{print $2}' | tr -d '()'").read()
ip_list = re.findall(DEFAULT_IP_SEGMENT, echo)
ip_list = list(filter(lambda x: not x.endswith("255") and not x.endswith("138.1"), ip_list))
return ip_list
# 结束wifi
def stop_wifi_ap():
with open(PATTERN_STOP_AP_CONF_DIR, "r") as file:
conf = file.read()
conf = conf.replace(WLAN_DEVICE_TAG, DEFAULT_DEVICE)
conf = conf.replace(LAN_DEVICE_TAG, LAN_DEVICE)
with open(STOP_AP_CONF_DIR, "w") as file:
file.write(conf)
os.popen(f"sudo bash {STOP_AP_CONF_DIR}").read()
def kill_port(port):
os.popen(f"sudo fuser -k {port}/tcp").read()
def get_wifi_ap_status():
try:
if isinstance(ping("192.168.137.1", timeout=500, unit="ms"), float):
return True
else:
return False
except Exception as e:
GLOBAL_LOG.write(f"AP状态获取出错原因是{e.args}")
return False
class WiFiAP:
def __init__(self):
stop_wifi_ap()
self.ssid = None
self.password = None
def reboot(self):
stop_wifi_ap()
if self.ssid:
self.set_ssid(ssid=self.ssid)
self.set_password(password=self.password)
self.start()
def set_ssid(self, ssid):
self.ssid = ssid
def set_password(self, password):
self.password = password
def edit_ap_conf(self):
with open(PATTERN_AP_CONF_DIR, "r") as file:
conf = file.read()
conf = conf.replace(WLAN_DEVICE_TAG, DEFAULT_DEVICE)
conf = conf.replace(LAN_DEVICE_TAG, LAN_DEVICE)
conf = conf.replace(SSID_DEVICE_TAG, self.ssid)
conf = conf.replace(PASS_DEVICE_TAG, self.password)
with open(AP_CONF_DIR, "w") as file:
file.write(conf)
@staticmethod
def start_cmd():
os.popen(f"sudo bash {AP_CONF_DIR}").read()
def start(self):
if self.ssid:
self.edit_ap_conf()
self.start_cmd()
@staticmethod
def stop():
stop_wifi_ap()
@staticmethod
def kill_wifi():
stop_wifi_ap()