Bootstrap

地平线x3派 SoftAp热点开机启动

基于Python3.10 实现开启 SoftAp 热点

可以将python的执行放入开机启动服务中,,实现开机后自动开启热点功能

热点名称: 开发板 Hostname

热点密码 12345678

热点地址 192.168.4.1

一下是python代码

""" 在地平线旭日X3派中开启 Soft AP 热点
热点名称  【hostname】
热点密码  12345678
热点地址  192.168.4.1

"""


import socket
import subprocess
import time
import os

def run_command(command):
    """运行系统命令并捕获错误信息"""
    try:
        result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"命令执行失败: {e.stderr}")

def get_hostname():
    """获取当前设备的主机名"""
    return socket.gethostname()

def clean_hostapd_ctrl_interface():
    """删除残留的控制接口文件"""
    ctrl_file = "/var/run/hostapd/wlan0"
    if os.path.exists(ctrl_file):
        print(f"发现残留控制接口文件 {ctrl_file},正在删除...")
        os.remove(ctrl_file)

def reset_wireless_interface():
    """重置无线接口 wlan0"""
    print("重置 wlan0 接口...")
    run_command("sudo ifconfig wlan0 down")
    run_command("sudo ip addr flush dev wlan0")
    time.sleep(1)
    run_command("sudo ifconfig wlan0 up")

def stop_conflicting_services():
    """停止 wpa_supplicant 以避免冲突"""
    print("停止 wpa_supplicant 服务...")
    run_command("sudo systemctl stop wpa_supplicant")
    run_command("sudo systemctl mask wpa_supplicant")

def configure_hostapd(ssid):
    """配置 hostapd.conf 文件,使用主机名作为 SSID"""
    print(f"配置 /etc/hostapd/hostapd.conf,SSID: {ssid}")
    with open("/etc/hostapd/hostapd.conf", "w") as f:
        f.write(
            f"""interface=wlan0
driver=nl80211
ssid={ssid}
channel=6
hw_mode=g
ieee80211n=1
ignore_broadcast_ssid=0
wpa=2
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP
wpa_passphrase=12345678
"""
        )

def start_hostapd():
    """启动 hostapd 服务"""
    clean_hostapd_ctrl_interface()
    reset_wireless_interface()
    print("启动 hostapd 服务...")
    run_command("sudo hostapd -B /etc/hostapd/hostapd.conf")

def configure_dhcp():
    """配置 isc-dhcp-server 服务"""
    print("配置 isc-dhcp-server...")
    with open("/etc/dhcp/dhcpd.conf", "w") as f:
        f.write(
            """authoritative;
subnet 192.168.4.0 netmask 255.255.255.0 {
    range 192.168.4.100 192.168.4.254;
    option subnet-mask 255.255.255.0;
    option routers 192.168.4.1;
    option broadcast-address 192.168.4.31;
    default-lease-time 600;
    max-lease-time 7200;
}
"""
        )
    with open("/etc/default/isc-dhcp-server", "w") as f:
        f.write('INTERFACESv4="wlan0"\n')

    print("启动并启用 DHCP 服务器...")
    run_command("sudo systemctl start isc-dhcp-server")
    run_command("sudo systemctl enable isc-dhcp-server")

def main():
    """主程序:获取主机名、启用热点并配置 DHCP"""
    hostname = get_hostname()
    print(f"当前设备主机名:{hostname}")

    stop_conflicting_services()
    time.sleep(1)

    configure_hostapd(ssid=hostname)
    time.sleep(1)

    start_hostapd()
    time.sleep(1)

    run_command("sudo ifconfig wlan0 192.168.4.1 netmask 255.255.255.0")
    time.sleep(1)
    
    configure_dhcp()
    print(f"热点 '{hostname}' 已成功启动并运行!")


if __name__ == "__main__":
    main()

;