修复bug。临时提交
This commit is contained in:
17
.idea/workspace.xml
generated
17
.idea/workspace.xml
generated
@@ -5,13 +5,12 @@
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="eceeff5e-51c1-459c-a911-d21ec090a423" name="Changes" comment="">
|
||||
<change beforePath="$PROJECT_DIR$/.gitignore" beforeDir="false" afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/Entity/Variables.py" beforeDir="false" afterPath="$PROJECT_DIR$/Entity/Variables.py" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/Module/DeviceInfo.py" beforeDir="false" afterPath="$PROJECT_DIR$/Module/DeviceInfo.py" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/Module/FlaskService.py" beforeDir="false" afterPath="$PROJECT_DIR$/Module/FlaskService.py" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/Module/FlaskSubprocessManager.py" beforeDir="false" afterPath="$PROJECT_DIR$/Module/FlaskSubprocessManager.py" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/Module/Main.py" beforeDir="false" afterPath="$PROJECT_DIR$/Module/Main.py" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/Utils/LogManager.py" beforeDir="false" afterPath="$PROJECT_DIR$/Utils/LogManager.py" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/Utils/Requester.py" beforeDir="false" afterPath="$PROJECT_DIR$/Utils/Requester.py" afterDir="false" />
|
||||
</list>
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
@@ -101,13 +100,23 @@
|
||||
<workItem from="1755512435623" duration="6297000" />
|
||||
<workItem from="1755520236323" duration="4470000" />
|
||||
<workItem from="1755526764397" duration="34000" />
|
||||
<workItem from="1755581609798" duration="2778000" />
|
||||
<workItem from="1755589366202" duration="357000" />
|
||||
<workItem from="1755589736021" duration="836000" />
|
||||
<workItem from="1755590590103" duration="5151000" />
|
||||
<workItem from="1755604973651" duration="15000" />
|
||||
<workItem from="1755606718587" duration="4204000" />
|
||||
<workItem from="1755667295017" duration="706000" />
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
<component name="TypeScriptGeneratedFilesManager">
|
||||
<option name="version" value="3" />
|
||||
</component>
|
||||
<component name="UnknownFeatures">
|
||||
<option featureType="com.intellij.fileTypeFactory" implementationName="*.bat" />
|
||||
</component>
|
||||
<component name="com.intellij.coverage.CoverageDataManagerImpl">
|
||||
<SUITE FILE_PATH="coverage/iOSAI$Main.coverage" NAME="Main Coverage Results" MODIFIED="1755525511400" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="" />
|
||||
<SUITE FILE_PATH="coverage/iOSAI$Main.coverage" NAME="Main Coverage Results" MODIFIED="1755668871814" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -4,7 +4,7 @@ from typing import Dict, Any
|
||||
from Entity.AnchorModel import AnchorModel
|
||||
|
||||
# wda apple bundle id
|
||||
WdaAppBundleId = "com.vv.wda.xctrunner"
|
||||
WdaAppBundleId = "com.yolo.wda.xctrunner"
|
||||
# 全局主播列表
|
||||
anchorList: list[AnchorModel] = []
|
||||
# 线程锁
|
||||
|
||||
@@ -6,6 +6,7 @@ import warnings
|
||||
from queue import Queue
|
||||
from typing import Any, Dict
|
||||
from Utils.AiUtils import AiUtils
|
||||
from Utils.LogManager import LogManager
|
||||
from Utils.Requester import Requester
|
||||
|
||||
import tidevice
|
||||
@@ -27,11 +28,12 @@ dataQueue = Queue()
|
||||
|
||||
def start_socket_listener():
|
||||
port = int(os.getenv('FLASK_COMM_PORT', 0))
|
||||
LogManager.info(f"Received port from environment: {port}")
|
||||
print(f"Received port from environment: {port}")
|
||||
if port <= 0:
|
||||
print("⚠️ 未获取到通信端口,跳过Socket监听")
|
||||
LogManager.info("未获取到通信端口,跳过Socket监听")
|
||||
print("未获取到通信端口,跳过Socket监听")
|
||||
return
|
||||
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
# 设置端口复用,避免端口被占用时无法绑定
|
||||
@@ -41,30 +43,38 @@ def start_socket_listener():
|
||||
try:
|
||||
s.bind(('127.0.0.1', port))
|
||||
print(f"[INFO] Socket successfully bound to port {port}")
|
||||
LogManager.info(f"[INFO] Socket successfully bound to port {port}")
|
||||
except Exception as bind_error:
|
||||
print(f"[ERROR] ❌ 端口绑定失败: {bind_error}")
|
||||
print(f"[ERROR]端口绑定失败: {bind_error}")
|
||||
LogManager.info(f"[ERROR]端口绑定失败: {bind_error}")
|
||||
return
|
||||
|
||||
# 开始监听
|
||||
s.listen()
|
||||
LogManager.info(f"[INFO] Socket listener started on port {port}, waiting for connections...")
|
||||
print(f"[INFO] Socket listener started on port {port}, waiting for connections...")
|
||||
|
||||
while True:
|
||||
try:
|
||||
LogManager.info(f"[INFO] Waiting for a new connection on port {port}...")
|
||||
print(f"[INFO] Waiting for a new connection on port {port}...")
|
||||
conn, addr = s.accept()
|
||||
LogManager.info(f"[INFO] Connection accepted from: {addr}")
|
||||
print(f"[INFO] Connection accepted from: {addr}")
|
||||
|
||||
raw_data = conn.recv(1024).decode('utf-8').strip()
|
||||
LogManager.info(f"[INFO] Raw data received: {raw_data}")
|
||||
print(f"[INFO] Raw data received: {raw_data}")
|
||||
|
||||
data = json.loads(raw_data)
|
||||
LogManager.info(f"[INFO] Parsed data: {data}")
|
||||
print(f"[INFO] Parsed data: {data}")
|
||||
dataQueue.put(data)
|
||||
except Exception as conn_error:
|
||||
print(f"[ERROR] ❌ 连接处理失败: {conn_error}")
|
||||
LogManager.error(f"[ERROR]连接处理失败: {conn_error}")
|
||||
print(f"[ERROR]连接处理失败: {conn_error}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] ❌ Socket服务启动失败: {e}")
|
||||
LogManager.error(f"[ERROR]Socket服务启动失败: {e}")
|
||||
print(f"[ERROR]Socket服务启动失败: {e}")
|
||||
|
||||
|
||||
# 在独立线程中启动Socket服务
|
||||
@@ -83,15 +93,6 @@ def passToken():
|
||||
print(e)
|
||||
return ResultData(data="").toJson()
|
||||
|
||||
@app.route('/getName', methods=['POST'])
|
||||
def getName():
|
||||
data = request.get_json()
|
||||
accountToken = data['token']
|
||||
print(accountToken)
|
||||
return accountToken
|
||||
|
||||
|
||||
|
||||
# 获取设备列表
|
||||
@app.route('/deviceList', methods=['GET'])
|
||||
def deviceList():
|
||||
@@ -108,6 +109,7 @@ def deviceList():
|
||||
return ResultData(data=listData).toJson()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
LogManager.error("获取设备列表失败:", e)
|
||||
return ResultData(data=[]).toJson()
|
||||
|
||||
# 获取设备应用列表
|
||||
|
||||
@@ -9,6 +9,9 @@ import time
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union, Dict, List
|
||||
|
||||
from Utils.LogManager import LogManager
|
||||
|
||||
|
||||
class FlaskSubprocessManager:
|
||||
_instance: Optional['FlaskSubprocessManager'] = None
|
||||
_lock: threading.Lock = threading.Lock()
|
||||
@@ -22,7 +25,7 @@ class FlaskSubprocessManager:
|
||||
|
||||
def _init_manager(self):
|
||||
self.process: Optional[subprocess.Popen] = None
|
||||
self.comm_port = 34567
|
||||
self.comm_port = 34566
|
||||
self._stop_event = threading.Event()
|
||||
atexit.register(self.stop)
|
||||
|
||||
@@ -37,6 +40,7 @@ class FlaskSubprocessManager:
|
||||
"""启动 Flask 子进程(兼容打包后的 exe 和源码运行)"""
|
||||
with self._lock:
|
||||
if self.process is not None:
|
||||
LogManager.warning("子进程正在运行中!")
|
||||
raise RuntimeError("子进程已在运行中!")
|
||||
|
||||
env = os.environ.copy()
|
||||
@@ -59,6 +63,7 @@ class FlaskSubprocessManager:
|
||||
cmd = [sys.executable, "-m", "Module.Main", "--role=flask"]
|
||||
cwd = str(Path(__file__).resolve().parent) # Module 目录
|
||||
|
||||
LogManager.info(f"[DEBUG] spawn: {cmd} (cwd={cwd}) exists(exe)={os.path.exists(cmd[0])}")
|
||||
print(f"[DEBUG] spawn: {cmd} (cwd={cwd}) exists(exe)={os.path.exists(cmd[0])}")
|
||||
|
||||
self.process = subprocess.Popen(
|
||||
@@ -73,6 +78,8 @@ class FlaskSubprocessManager:
|
||||
env=env,
|
||||
cwd=cwd,
|
||||
)
|
||||
|
||||
LogManager.info(f"Flask子进程启动 (PID: {self.process.pid}, 端口: {self.comm_port})")
|
||||
print(f"Flask子进程启动 (PID: {self.process.pid}, 端口: {self.comm_port})")
|
||||
|
||||
def print_output(stream, stream_name):
|
||||
@@ -97,9 +104,11 @@ class FlaskSubprocessManager:
|
||||
s.sendall((data + "\n").encode('utf-8'))
|
||||
return True
|
||||
except ConnectionRefusedError:
|
||||
LogManager.error(f"连接被拒绝,确保子进程在端口 {self.comm_port} 上监听")
|
||||
print(f"连接被拒绝,确保子进程在端口 {self.comm_port} 上监听")
|
||||
return False
|
||||
except Exception as e:
|
||||
LogManager.error(f"发送失败: {e}")
|
||||
print(f"发送失败: {e}")
|
||||
return False
|
||||
|
||||
@@ -107,11 +116,14 @@ class FlaskSubprocessManager:
|
||||
with self._lock:
|
||||
if self.process and self.process.poll() is None:
|
||||
print(f"[INFO] Stopping Flask child process (PID: {self.process.pid})...")
|
||||
LogManager.info(f"[INFO] Stopping Flask child process (PID: {self.process.pid})...")
|
||||
self.process.terminate()
|
||||
self.process.wait()
|
||||
print("[INFO] Flask child process stopped.")
|
||||
LogManager.info("[INFO] Flask child process stopped.")
|
||||
self._stop_event.set()
|
||||
else:
|
||||
LogManager.info("[INFO] No Flask child process to stop.")
|
||||
print("[INFO] No Flask child process to stop.")
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from Module.DeviceInfo import Deviceinfo
|
||||
@@ -19,15 +18,13 @@ def _run_flask_role():
|
||||
port = int(os.getenv("FLASK_COMM_PORT", "34567")) # 固定端口的兜底仍是 34567
|
||||
app_factory = getattr(FlaskService, "create_app", None)
|
||||
app = app_factory() if callable(app_factory) else FlaskService.app
|
||||
app.run(host="0.0.0.0", port=port, debug=False, use_reloader=False)
|
||||
app.run(host="0.0.0.0", port=port + 1, debug=False, use_reloader=False)
|
||||
|
||||
if "--role=flask" in sys.argv:
|
||||
_run_flask_role()
|
||||
sys.exit(0)
|
||||
|
||||
# 项目入口
|
||||
# ... 省略前面的 import 和函数 ...
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 清空日志等
|
||||
LogManager.clearLogs()
|
||||
|
||||
@@ -2,6 +2,7 @@ import logging
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class LogManager:
|
||||
@@ -52,9 +53,10 @@ class LogManager:
|
||||
def error(cls, text, udid="system"):
|
||||
cls._setupLogger(udid, "errorLogger", "error.log", level=logging.ERROR).error(f"[{udid}] {text}")
|
||||
|
||||
# 清空日志
|
||||
@classmethod
|
||||
def clearLogs(cls):
|
||||
"""启动时清空 log 目录"""
|
||||
"""启动时清空 log 目录下所有文件"""
|
||||
print("开始清空日志...")
|
||||
|
||||
# 关闭所有 handler
|
||||
@@ -63,14 +65,18 @@ class LogManager:
|
||||
for handler in logger.handlers[:]:
|
||||
try:
|
||||
handler.close()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
logger.removeHandler(handler)
|
||||
|
||||
# 删除并重建日志目录
|
||||
if os.path.exists(cls.logDir):
|
||||
shutil.rmtree(cls.logDir)
|
||||
print(f"删除了 {cls.logDir}")
|
||||
os.makedirs(cls.logDir, exist_ok=True)
|
||||
print(f"重新创建了 {cls.logDir}")
|
||||
# 仅删除目录里的所有文件和子目录
|
||||
log_path = Path(cls.logDir)
|
||||
if log_path.exists():
|
||||
for item in log_path.iterdir():
|
||||
if item.is_file():
|
||||
item.unlink()
|
||||
elif item.is_dir():
|
||||
import shutil
|
||||
shutil.rmtree(item)
|
||||
|
||||
print("日志清空完成")
|
||||
|
||||
Reference in New Issue
Block a user