-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
172 lines (145 loc) · 5.54 KB
/
main.py
File metadata and controls
172 lines (145 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
from config import init_config
from modules.rocker import MCP3208_Joystick
init_config()
import os
import importlib.util
import threading
from typing import List, Callable, Any
import signal
from pathlib import Path
from loguru import logger
import time
from core.forwarding import run_servers
from modules.wheel.wheel import MotorControl
# 配置loguru
logger.remove() # 移除默认的处理器
logger.add(
"logs/app_{time}.log", # 日志文件路径
rotation="1 day", # 每天轮换一次
retention="7 days", # 保留30天的日志
format="<green>[{time:YYYY-MM-DD HH:mm:ss}]</green>"
"<cyan>[{name}]</cyan>"
"<magenta>[{function}]</magenta>"
"<level>[{level}]</level>"
" <level>{message}</level>",
level="INFO",
enqueue=True, # 异步写入
)
logger.add(
sink=lambda msg: print(msg, flush=True), # 输出到控制台
format="<green>[{time:YYYY-MM-DD HH:mm:ss}]</green>"
"<cyan>[{name}]</cyan>"
"<magenta>[{function}]</magenta>"
"<level>[{level}]</level>"
" <level>{message}</level>",
colorize=True, # 启用颜色
level="INFO" # 设置日志级别
)
# 用于存储所有运行的线程
running_threads: List[threading.Thread] = []
stop_event = threading.Event()
def import_and_collect_runners(driver_path: str) -> List[Callable[[], Any]]:
"""
导入driver文件夹中的所有模块的run函数
按照module1/__init__.py, module2/__init__.py的结构导入
"""
runners = []
driver_dir = Path(driver_path)
# 确保driver文件夹存在
if not driver_dir.exists() or not driver_dir.is_dir():
raise FileNotFoundError(f"Driver path '{driver_path}' does not exist or is not a directory")
# 遍历driver文件夹中的所有子文件夹
for module_dir in driver_dir.iterdir():
if not module_dir.is_dir() or module_dir.name.startswith('__'):
continue
init_file = module_dir / '__init__.py'
if not init_file.exists():
logger.warning(f"No __init__.py found in {module_dir}")
continue
try:
# 动态导入模块
module_name = module_dir.name
spec = importlib.util.spec_from_file_location(
module_name,
str(init_file)
)
if spec is None or spec.loader is None:
logger.warning(f"Could not load spec for module: {module_name}")
continue
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# 检查模块是否有run函数
if hasattr(module, 'run'):
run_func = getattr(module, 'run')
# 检查是否是可调用对象
if not callable(run_func):
logger.warning(f"'run' in {module_name} is not callable")
continue
runners.append((module_dir.name, run_func))
logger.success(f"Successfully loaded run function from {module_name}")
else:
logger.warning(f"Module {module_name} does not contain a run function")
except Exception as e:
logger.exception(f"Error loading module {module_dir.name}")
continue
return runners
def run_module(name: str, run_func: Callable) -> None:
"""
运行单个模块的run函数并处理异常
"""
try:
logger.info(f"Starting module: {name}")
run_func()
except Exception as e:
logger.exception(f"Error in module {name}")
finally:
logger.info(f"Module {name} stopped")
def main():
global running_threads
ascii_art = r"""
____ _ ____
| _ \ (_) / ___| ___ _ __ ___ ___ _ __
| |_) | | | \___ \ / _ \ | '_ \ / __| / _ \ | '__|
| __/ | | ___) | | __/ | | | | \__ \ | (_) | | |
|_| |_| |____/ \___| |_| |_| |___/ \___/ |_|
"""
logger.info(ascii_art)
logger.info("Here we go!")
driver_path = os.path.join(os.path.dirname(__file__), 'modules')
try:
# 收集所有的run函数
runners = import_and_collect_runners(driver_path)
if not runners:
logger.warning("No valid run functions found in any module")
return
# 为每个模块创建线程
logger.info(f"Starting {len(runners)} modules")
logger.info('Starting forwarding and relay servers...')
servers_thread = threading.Thread(target=run_servers, daemon=True)
servers_thread.start()
running_threads.append(servers_thread)
for name, run_func in runners:
thread = threading.Thread(target=run_module, args=(name, run_func), daemon=True)
thread.start()
running_threads.append(thread)
# Keep the main thread alive
while not stop_event.is_set():
time.sleep(1)
except Exception as e:
logger.exception("Main execution failed")
finally:
logger.info("Main process ended")
def shutdown(signum, frame):
logger.info("Received shutdown signal, shutting down...")
stop_event.set()
if __name__ == "__main__":
signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SIGTERM, shutdown)
try:
logger.info("=== Starting application ===")
# 运行主函数
main()
except KeyboardInterrupt:
logger.info("Received keyboard interrupt, shutting down...")
finally:
logger.info("=== Application terminated ===")