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