[log] add logger
This commit is contained in:
parent
3e88c60997
commit
a07f6b2954
|
@ -9,13 +9,22 @@ 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' # 日志的格式
|
||||
)
|
||||
|
||||
try:
|
||||
from takway.board import OrangePi
|
||||
led_enabled = True
|
||||
orangepi = OrangePi()
|
||||
except ImportError:
|
||||
led_enabled = False
|
||||
print("Error importing OrangePi")
|
||||
logging.info("Error importing OrangePi")
|
||||
|
||||
# blue: APP
|
||||
# red: hotspot
|
||||
|
@ -36,9 +45,9 @@ def network_error_light_1():
|
|||
def network_error_light_2():
|
||||
error_time = datetime.datetime.now()
|
||||
while led_enabled:
|
||||
orangepi.set_led_on('red')
|
||||
orangepi.set_led_on('green')
|
||||
time.sleep(0.25)
|
||||
orangepi.set_led_off('red')
|
||||
orangepi.set_led_off('green')
|
||||
time.sleep(0.25)
|
||||
if error_time + datetime.timedelta(seconds=2) < datetime.datetime.now():
|
||||
break
|
||||
|
@ -60,11 +69,11 @@ def edit_line_in_file(file_path, search_string, replacement_string):
|
|||
else:
|
||||
file.write(line)
|
||||
|
||||
print(f"{datetime.datetime.now()}: The line has been edited.")
|
||||
logging.info(f"{datetime.datetime.now()}: The line has been edited.")
|
||||
except FileNotFoundError:
|
||||
print(f"The file {file_path} does not exist.")
|
||||
logging.info(f"The file {file_path} does not exist.")
|
||||
except IOError as e:
|
||||
print(f"An error occurred: {e}")
|
||||
logging.info(f"An error occurred: {e}")
|
||||
|
||||
|
||||
# 获取私有IP地址
|
||||
|
@ -77,10 +86,10 @@ def save_local_ip():
|
|||
# save local_ip to file
|
||||
with open('local_ip.txt', 'w') as f:
|
||||
f.write(local_ip)
|
||||
print(f"{datetime.datetime.now()}: Local IP address: {local_ip}")
|
||||
logging.info(f"{datetime.datetime.now()}: Local IP address: {local_ip}")
|
||||
return local_ip
|
||||
except Exception as e:
|
||||
print(f"Error getting private IP: {e}")
|
||||
logging.info(f"Error getting private IP: {e}")
|
||||
return None
|
||||
|
||||
app = Flask(__name__)
|
||||
|
@ -111,29 +120,29 @@ def start_hotspot():
|
|||
if led_enabled:
|
||||
orangepi.set_led_on('red')
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"{datetime.datetime.now()}: Error starting create_ap service: {e}")
|
||||
logging.info(f"{datetime.datetime.now()}: Error starting create_ap service: {e}")
|
||||
|
||||
def close_hotspot():
|
||||
# 关闭热点
|
||||
try:
|
||||
subprocess.Popen('sudo systemctl stop hotspot.service', shell=True)
|
||||
print(f"{datetime.datetime.now()}: Stopping create_ap service")
|
||||
logging.info(f"{datetime.datetime.now()}: Stopping create_ap service")
|
||||
if led_enabled:
|
||||
orangepi.set_led_off('red')
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"{datetime.datetime.now()}: Error stopping hotspot: {e}")
|
||||
logging.info(f"{datetime.datetime.now()}: Error stopping hotspot: {e}")
|
||||
|
||||
|
||||
# 检测 Wi-Fi 连接状态
|
||||
def check_wifi_connection():
|
||||
cmd = "nmcli dev status"
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
time.sleep(0.5)
|
||||
time.sleep(2)
|
||||
output = result.stdout.strip()
|
||||
lines = output.split("\n")[1:] # Skip the header line
|
||||
for line in lines:
|
||||
columns = line.split()
|
||||
print(columns)
|
||||
logging.info(columns)
|
||||
'''
|
||||
['wlan0', 'wifi', 'disconnected', '--']
|
||||
['p2p-dev-wlan0', 'wifi-p2p', 'disconnected', '--']
|
||||
|
@ -162,7 +171,7 @@ def check_wifi_connection():
|
|||
network_error_light_1()
|
||||
subprocess.Popen('sudo systemctl restart NetworkManager', shell=True)
|
||||
# subprocess.run(['sudo', 'systemctl', 'restart', 'NetworkManager'], check=True)
|
||||
time.sleep(0.5)
|
||||
time.sleep(2)
|
||||
return check_wifi_connection()
|
||||
return False, None
|
||||
|
||||
|
@ -172,9 +181,10 @@ def scan_wifi():
|
|||
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}")
|
||||
logging.info(f"{datetime.datetime.now()}: Error scanning Wi-Fi: {e}")
|
||||
network_error_light_2()
|
||||
print(f"{datetime.datetime.now()}: Wi-Fi scan complete...")
|
||||
return []
|
||||
logging.info(f"{datetime.datetime.now()}: Wi-Fi scan complete...")
|
||||
ssid_list = []
|
||||
wifi_list = []
|
||||
output = result.stdout.strip()
|
||||
|
@ -182,9 +192,9 @@ def scan_wifi():
|
|||
for line in lines:
|
||||
columns = line.split()
|
||||
'''
|
||||
print(columns)
|
||||
logging.info(columns)
|
||||
for i, column in enumerate(columns):
|
||||
print(f"{i}: {column}")
|
||||
logging.info(f"{i}: {column}")
|
||||
'''
|
||||
# ['94:14:57:15:13:50', 'Meeting', 'MG', 'Infra', '1', '130', 'Mbit/s', '100', '****', 'WPA1', 'WPA2']
|
||||
|
||||
|
@ -216,9 +226,9 @@ def scan_wifi():
|
|||
if columns[i] == 'Mbit/s':
|
||||
strength = columns[i+1]
|
||||
break
|
||||
# print("MAC地址:", mac_address)
|
||||
# print("Wi-Fi名称:", ssid)
|
||||
# print("强度:", strength)
|
||||
# logging.info("MAC地址:", mac_address)
|
||||
# logging.info("Wi-Fi名称:", ssid)
|
||||
# logging.info("强度:", strength)
|
||||
|
||||
wifi_list.append({'ssid': ssid, 'signal': strength, 'mac': mac_address})
|
||||
with open('scaned_wifi_list.json', 'w') as f:
|
||||
|
@ -235,14 +245,14 @@ def connect_wifi(ssid, password):
|
|||
output = subprocess.check_output(['nmcli', 'dev', 'wifi', 'connect', ssid, 'password', password])
|
||||
output_str = output.decode('utf-8') # 将输出转换为字符串
|
||||
if "successfully" in output_str:
|
||||
print(f"{datetime.datetime.now()}: Successfully connected to Wi-Fi: {ssid}")
|
||||
logging.info(f"{datetime.datetime.now()}: Successfully connected to Wi-Fi: {ssid}")
|
||||
save_wifi(ssid, password) # 保存连接成功的Wi-Fi信息
|
||||
return True
|
||||
else:
|
||||
print(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {output_str}")
|
||||
logging.info(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {output_str}")
|
||||
return False
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {e}")
|
||||
logging.info(f"{datetime.datetime.now()}: Error connecting to Wi-Fi: {e}")
|
||||
return False
|
||||
|
||||
# 关闭 Wi-Fi
|
||||
|
@ -252,11 +262,11 @@ def disconnect_wifi():
|
|||
time.sleep(0.5)
|
||||
output_str = output.decode('utf-8') # 将输出转换为字符串
|
||||
if "successfully disconnected" in output_str:
|
||||
print(f"{datetime.datetime.now()}: Wi-Fi disconnected successfully")
|
||||
logging.info(f"{datetime.datetime.now()}: Wi-Fi disconnected successfully")
|
||||
else:
|
||||
print(f"{datetime.datetime.now()}: Error disconnecting from Wi-Fi: {output_str}")
|
||||
logging.info(f"{datetime.datetime.now()}: Error disconnecting from Wi-Fi: {output_str}")
|
||||
except Exception as e:
|
||||
print(f"{datetime.datetime.now()}: Error disconnecting from Wi-Fi: {e}")
|
||||
logging.info(f"{datetime.datetime.now()}: Error disconnecting from Wi-Fi: {e}")
|
||||
|
||||
def connect_saved_wifi(scaned_wifi_list):
|
||||
wifi_list = load_saved_wifi()
|
||||
|
@ -303,7 +313,7 @@ def submit():
|
|||
orangepi.set_led_on('red')
|
||||
ssid = request.form['ssid']
|
||||
password = request.form['password']
|
||||
print(f"{datetime.datetime.now()}: Connecting to Wi-Fi: {ssid} with password {password}")
|
||||
logging.info(f"{datetime.datetime.now()}: Connecting to Wi-Fi: {ssid} with password {password}")
|
||||
|
||||
# 关闭热点
|
||||
close_hotspot()
|
||||
|
@ -318,7 +328,7 @@ def submit():
|
|||
|
||||
connected, wifi_ssid = check_wifi_connection()
|
||||
if not connected:
|
||||
print(f"{datetime.datetime.now()}: Wi-Fi连接失败。")
|
||||
logging.info(f"{datetime.datetime.now()}: Wi-Fi连接失败。")
|
||||
wifi_list = scan_wifi()
|
||||
start_hotspot()
|
||||
else:
|
||||
|
@ -332,7 +342,7 @@ if __name__ == '__main__':
|
|||
if debug_mode:
|
||||
disconnect_wifi()
|
||||
# wifi_list = scan_wifi()
|
||||
# print(wifi_list)
|
||||
# logging.info(wifi_list)
|
||||
|
||||
# start_hotspot()
|
||||
|
||||
|
@ -346,16 +356,17 @@ if __name__ == '__main__':
|
|||
|
||||
connected, wifi_ssid = check_wifi_connection()
|
||||
if connected:
|
||||
print(f"{datetime.datetime.now()}: 系统已自动连接到 Wi-Fi 网络,退出程序")
|
||||
logging.info(f"{datetime.datetime.now()}: 系统已自动连接到 Wi-Fi 网络,退出程序")
|
||||
close_app()
|
||||
|
||||
# 扫描Wi-Fi
|
||||
wifi_list = scan_wifi()
|
||||
|
||||
# 连接保存的Wi-Fi
|
||||
connected, wifi_ssid = connect_saved_wifi(wifi_list)
|
||||
if connected:
|
||||
print(f"{datetime.datetime.now()}: 系统已自动连接到 Wi-Fi 网络 {wifi_ssid},退出程序")
|
||||
logging.info(f"{datetime.datetime.now()}: 系统已自动连接到 Wi-Fi 网络 {wifi_ssid},退出程序")
|
||||
close_app()
|
||||
|
||||
print(f"{datetime.datetime.now()}: 未连接到 Wi-Fi 网络, 开始热点模式")
|
||||
logging.info(f"{datetime.datetime.now()}: 未连接到 Wi-Fi 网络, 开始热点模式")
|
||||
start_hotspot()
|
||||
app.run(host='0.0.0.0', port=80)
|
Loading…
Reference in New Issue