65 lines
3.1 KiB
Python
65 lines
3.1 KiB
Python
"""Recover the local graphical environment and start the EDA bridge, not a design job."""
|
||
from datetime import datetime
|
||
from zoneinfo import ZoneInfo
|
||
from pathlib import Path
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
|
||
|
||
def note(message):
|
||
stamp=datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
|
||
print(f'[{stamp} +08:00] [启动检查] {message}',file=sys.stderr,flush=True)
|
||
|
||
|
||
def restore_graphics():
|
||
if not sys.platform.startswith('linux'):return False
|
||
try:
|
||
result=subprocess.run(['systemctl','--user','show-environment'],capture_output=True,text=True,timeout=5)
|
||
if result.returncode:return False
|
||
env=dict(line.split('=',1) for line in result.stdout.splitlines() if '=' in line)
|
||
display=env.get('DISPLAY','')
|
||
auth=Path(env.get('XAUTHORITY','/nonexistent'))
|
||
if not display.startswith(':') or not auth.is_file() or auth.stat().st_uid!=os.getuid():return False
|
||
if os.getenv('DISPLAY')==display and os.getenv('XAUTHORITY')==str(auth):return False
|
||
os.environ.update(DISPLAY=display,XAUTHORITY=str(auth))
|
||
for key in ('XDG_RUNTIME_DIR','DBUS_SESSION_BUS_ADDRESS'):
|
||
if env.get(key):os.environ.setdefault(key,env[key])
|
||
note('已恢复当前桌面会话 '+display+' 的显示与授权配置')
|
||
return True
|
||
except (OSError,ValueError,subprocess.TimeoutExpired):return False
|
||
|
||
|
||
def ensure_bridge(executable,cli_call,extra_args=()):
|
||
# doctor is read-only. Never apply these retries to project writes/invoke.
|
||
note('正在检查嘉立创 EDA 桥接')
|
||
try:
|
||
health=cli_call(executable,['doctor'])
|
||
except Exception as exc:
|
||
message=str(exc).lower()
|
||
if not any(token in message for token in ('display','x server','authorization','ozone','timeout')) or not restore_graphics():
|
||
raise RuntimeError('嘉立创启动检查失败:'+str(exc)) from exc
|
||
health=cli_call(executable,['doctor'])
|
||
if not isinstance(health,dict):raise RuntimeError('嘉立创 doctor 返回格式异常')
|
||
if health.get('connected') is True:
|
||
note('嘉立创桥接已连接');return health
|
||
root=Path(os.environ['AI_PCB_API_DATA'])/'logs';root.mkdir(parents=True,exist_ok=True)
|
||
logfile=root/'eda-startup.log'
|
||
note('嘉立创未运行,正在启动编辑器桥接;不会创建绘板任务')
|
||
# Starting the application creates no project and does not open the API server.
|
||
with logfile.open('ab') as stream:
|
||
proc=subprocess.Popen([executable,*extra_args],stdin=subprocess.DEVNULL,stdout=stream,stderr=stream,
|
||
start_new_session=True,env=dict(os.environ))
|
||
last='桥接尚未就绪'
|
||
deadline=time.monotonic()+60
|
||
while time.monotonic()<deadline:
|
||
time.sleep(1)
|
||
try:
|
||
health=cli_call(executable,['doctor'],timeout=5)
|
||
if isinstance(health,dict) and health.get('connected') is True:
|
||
note('嘉立创桥接已连接,继续启动后台');return health
|
||
except Exception as exc:last=str(exc)
|
||
if proc.poll() not in (None,0):break
|
||
raise RuntimeError('嘉立创桥接未能启动,请查看 '+str(logfile)+';'+last)
|