repo_id
stringclasses
1 value
file_path
stringlengths
31
102
content
stringlengths
16
34k
__index_level_0__
int64
0
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\alembic.ini
# A generic, single database configuration. [alembic] # path to migration scripts script_location = migrations/ # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s # Uncomment the line below if you want the files to be prepended with date and time # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file # for all available tokens # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s # sys.path path, will be prepended to sys.path if present. # defaults to the current working directory. prepend_sys_path = . # timezone to use when rendering the date within the migration file # as well as the filename. # If specified, requires the python-dateutil library that can be # installed by adding `alembic[tz]` to the pip requirements # string value is passed to dateutil.tz.gettz() # leave blank for localtime # timezone = # max length of characters to apply to the # "slug" field # truncate_slug_length = 40 # set to 'true' to run the environment during # the 'revision' command, regardless of autogenerate # revision_environment = false # set to 'true' to allow .pyc and .pyo files without # a source .py file to be detected as revisions in the # versions/ directory # sourceless = false # version location specification; This defaults # to alembic//versions. When using multiple version # directories, initial revisions must be specified with --version-path. # The path separator used here should be the separator specified by "version_path_separator" below. # version_locations = %(here)s/bar:%(here)s/bat:alembic//versions # version path separator; As mentioned above, this is the character used to split # version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. # If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. # Valid values for version_path_separator are: # # version_path_separator = : # version_path_separator = ; # version_path_separator = space version_path_separator = os # Use os.pathsep. Default configuration used for new projects. # the output encoding used when revision files # are written from script.py.mako # output_encoding = utf-8 sqlalchemy.url = driver://user:pass@localhost/dbname [post_write_hooks] # post_write_hooks defines scripts or Python functions that are run # on newly generated revision scripts. See the documentation for further # detail and examples # format using "black" - use the console_scripts runner, against the "black" entrypoint hooks = black black.type = console_scripts black.entrypoint = black black.options = -l 79 REVISION_SCRIPT_FILENAME # Logging configuration [loggers] keys = root,sqlalchemy,alembic [handlers] keys = console [formatters] keys = generic [logger_root] level = WARN handlers = console qualname = [logger_sqlalchemy] level = WARN handlers = qualname = sqlalchemy.engine [logger_alembic] level = INFO handlers = qualname = alembic [handler_console] class = StreamHandler args = (sys.stderr,) level = NOTSET formatter = generic [formatter_generic] format = %(levelname)-5.5s [%(name)s] %(message)s datefmt = %H:%M:%S
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\app.py
import asyncio import importlib import logging import os import sys import warnings from threading import RLock from typing import Optional, cast import socketio import uvicorn from fastapi import FastAPI from fastapi.responses import PlainTextResponse from fastapi_socketio import SocketManager from loguru import logger from uvicorn.main import STARTUP_FAILURE from uvicorn.supervisors import ChangeReload, Multiprocess from xyz_max_hmi_server import babel, enums, error_handlers, middlewares from xyz_max_hmi_server.config import settings from xyz_max_hmi_server.exceptions import XYZException from xyz_max_hmi_server.log import init_logging from xyz_max_hmi_server.modules import monitor, pipe from xyz_max_hmi_server.modules.cyber import Cyber from xyz_max_hmi_server.modules.plc import PLCManager from xyz_max_hmi_server.route import EnhancedAPIRoute from xyz_max_hmi_server.utils import openapi from xyz_max_hmi_server.utils.db_util import _migrate_db from xyz_max_hmi_server.utils.utils import compare_versions, timeit LOCK = RLock() class Application(FastAPI): errorhandler = FastAPI.exception_handler def run( self, host: Optional[str] = None, port: Optional[int] = None, reload: bool = False, log_level: int = logging.INFO, **kwargs, ): config = uvicorn.Config( "xyz_max_hmi_server.app:create_app", host=host or settings.server.host, port=port or settings.server.port, reload=reload, factory=True, **kwargs, ) server = uvicorn.Server(config) # NOTE: 解决以代码形式启动时,无法正在加载日志配置的问题 # 日志配置需要在 uvicorn Config 之后加载,不然会被 uvicorn 重置 init_logging(level=log_level) if config.should_reload: sock = config.bind_socket() ChangeReload(config, target=server.run, sockets=[sock]).run() elif config.workers > 1: sock = config.bind_socket() Multiprocess(config, target=server.run, sockets=[sock]).run() else: server.run() if config.uds and os.path.exists(config.uds): os.remove(config.uds) # pragma: py-win32 if ( not server.started and not config.should_reload and config.workers == 1 ): sys.exit(STARTUP_FAILURE) @property def cyber(self) -> Cyber: """获取 Cyber""" if hasattr(self.state, "cyber"): return self.state.cyber self.state.cyber = Cyber() self.state.cyber.init() return self.state.cyber @property def sm(self) -> socketio.AsyncServer: if hasattr(self.state, "sm"): return self.state.sm self.state.sm = SocketManager(self) return cast(socketio.AsyncServer, self.state.sm) @property def plc_manager(self) -> "PLCManager": if hasattr(self.state, "plc_manager"): return self.state.plc_manager self.state.plc_manager = PLCManager() return cast(PLCManager, self.state.plc_manager) @property def status(self) -> enums.SystemStatus: """获取当前状态""" from xyz_max_hmi_server.globals import system_status warnings.warn( "`app.status` 已弃用,请使用 `system_status.status` 获取系统状态", DeprecationWarning, stacklevel=2, ) return system_status.status @status.setter def status(self, value: enums.SystemStatus): """设置当前状态""" from xyz_max_hmi_server.globals import system_status warnings.warn( "`app.status` 已弃用,请使用 `system_status.status` 获取系统状态", DeprecationWarning, stacklevel=2, ) system_status.status = value def set_status_running(self): """设置当前状态为运行中""" from xyz_max_hmi_server import signals warnings.warn( "`set_status_running` 已弃用,请使用 `system_status.set_running`", DeprecationWarning, stacklevel=2, ) self.status = enums.SystemStatus.RUNNING signals.system_running.send(self) def set_status_stop(self): """设置当前状态为已停止""" from xyz_max_hmi_server import signals warnings.warn( "`set_status_stop` 已弃用,请使用 `system_status.set_stop()`", DeprecationWarning, stacklevel=2, ) self.status = enums.SystemStatus.STOPPED signals.system_stop.send(self) def set_status_error(self): """设置当前状态为异常""" from xyz_max_hmi_server import signals warnings.warn( "`set_status_error`() 已弃用, 请使用 `globals.system_status.set_error()`", DeprecationWarning, stacklevel=2, ) self.status = enums.SystemStatus.ERROR signals.system_error.send(self) def create_app(debug: bool = True, hot_swap: bool = False) -> Application: """Create app instance.""" global app from xyz_max_hmi_server.api.api import api_router if app: return app app = Application( title="MAX HMI Server", version=settings.version, debug=debug, ) subapp = load_wcs_adaptor(app) # 加载 Babel babel.init_app(app) @app.get("/") async def index(): return PlainTextResponse("Hello, XYZ!") app.include_router(api_router, prefix="/api") # app.mount("/static", StaticFiles(directory="static"), name="static") init_logging(level=logging.DEBUG if debug else logging.INFO) middlewares.cors.init_app(app) middlewares.pagination.init_app(app) middlewares.sqlalchemy.init_app(app, settings.db.real_database_uri) error_handlers.init_app(app) # 加载通信管道/Cyber订阅 pipe.init_app(app) # 加载内置监听器 monitor.init_app(app) # 模拟 WCS 服务 if settings.dev_mode.mock_wcs: from xyz_max_hmi_server.mock_wcs import start_mock_server start_mock_server() @app.on_event("shutdown") async def shutdown_event(): from xyz_max_hmi_server.modules.monitor.dispatch import dispatcher from xyz_max_hmi_server.modules.pipe.msg_center import MessageCenter # 关闭消息中心 MessageCenter().stop() # 关闭 monitor dispatcher.shutdown() # 关闭 Cyber app.cyber.shutdown() @app.on_event("startup") async def startup_event(): from xyz_max_hmi_server.modules.cycle.service import CycleService from xyz_max_hmi_server.modules.monitor.dispatch import dispatcher from xyz_max_hmi_server.modules.pipe.msg_center import MessageCenter if hot_swap: from xyz_max_hmi_server.utils import subapp subapp.watcher() logger.success("已启用热插拔模式,Adaptor 代码修改后会自动重载") with timeit("初始化数据库"): try: # 初始化数据库 _migrate_db() except Exception as e: raise XYZException("数据库初始化失败, 请升级至最新版本.") from e # WARN: Fucking cyber # 导入了 cyber 包之后,在 Linux 上无法通过 <Control-c> 结束程序(L发送 SIGINT 信号无效) # 使用 <Control-\> 可以(发送 SIGTERM 信号) with timeit("初始化 Cyber"): # 初始化 Cyber app.cyber.init() with timeit("初始化消息中心"): # 初始化消息中心 asyncio.create_task(MessageCenter().start()) with timeit("初始化监听器"): # 初始化 monitor # TODO: 判断是否有启用监听器,没有则不启动 dispatcher.start() with timeit("初始化节拍服务"): # 启动 CycleService CycleService(app).start() with timeit("初始化 Cyber 节点"): # 初始化 Cyber 节点 app.cyber.get_or_create_node(enums.CyberNodeName.Subscriber) app.cyber.get_or_create_node(enums.CyberNodeName.RobotDriver) app.cyber.get_or_create_node(enums.CyberNodeName.CycleRecorder) openapi.init_app(app, subapp) app.router.route_class = EnhancedAPIRoute return app def cached_app() -> Application: """Return cached app instance.""" global app if app is None: app = create_app() app.router.route_class = EnhancedAPIRoute return app def load_wcs_adaptor(app: "Application") -> "Application": """加载 WCS Adaptor.""" sys.path.insert(0, settings.project_dir.resolve().as_posix()) # 1.4.3-pre.16+a4c3b3e7 wcs_adaptor_version = importlib.import_module( "wcs_adaptor.version" ).__version__ app_version = importlib.import_module( "xyz_max_hmi_server.version" ).__version__ if not wcs_adaptor_version or not app_version: raise ImportError("WCS Adaptor 版本信息缺失") if compare_versions(wcs_adaptor_version, app_version) == 1: raise ImportError( "WCS Adaptor 当前版本: {}, 与 HMI Server 当前版本: {} 不匹配, " "请勿使用低版本的 Studio Max 打开本项目。".format( wcs_adaptor_version, app_version ) ) try: subapp = importlib.import_module("wcs_adaptor.main").app app.mount("/adaptor", subapp, name="WCS Adaptor") return subapp except ImportError as e: raise ImportError( "WCS Adaptor 加载失败, 项目目录:" f" {settings.project_dir.absolute()}, " "请确保 Studio Max 是否已加载该项目." ) from e app: "Application" = cast(Application, None)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\babel.py
from fastapi_babel import Babel, BabelConfigs __configs = BabelConfigs( ROOT_DIR=__file__, BABEL_DEFAULT_LOCALE="zh", BABEL_TRANSLATION_DIRECTORY="./templates/common/translations/lang", ) babel: Babel = Babel(configs=__configs) def init_app(app): # noqa: D103 global babel from xyz_max_hmi_server.config import settings dir = (settings.project_dir.resolve() / "translations/lang/").as_posix() configs = BabelConfigs( ROOT_DIR=settings.project_dir.resolve().as_posix(), BABEL_DEFAULT_LOCALE="zh", BABEL_TRANSLATION_DIRECTORY=dir, ) configs.ROOT_DIR = settings.project_dir.resolve().as_posix() configs.BABEL_MESSAGE_POT_FILE = ( settings.project_dir.resolve() / "translations/messages.pot" ).as_posix() configs.BABEL_CONFIG_FILE = ( settings.project_dir.resolve() / "babel.cfg" ).as_posix() babel = Babel(configs=configs) babel.locale = settings.system.language.name.lower() # WARNING: DO NOT USE `babel.init_app(app)` HERE, Because it will cause error: # RuntimeError: Caught handled exception, but response already started. # babel.init_app(app)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\cmdline.py
"""命令行工具""" import atexit import logging import os import shutil import signal import subprocess import sys import time import uuid from datetime import timedelta from pathlib import Path from typing import Any, Dict, Literal, Optional import click import pandas as pd import requests import yaml from alembic import config as alembic_config from click import Context from loguru import logger from rich.console import Console from rich.syntax import Syntax from rich.table import Table from xyz_max_hmi_server import crud, enums from xyz_max_hmi_server.app import create_app from xyz_max_hmi_server.config import SqliteDsn, settings from xyz_max_hmi_server.db.session import start_session from xyz_max_hmi_server.utils import studio_max as studio_max_utils, utils def signal_handler(signum, frame): """处理信号""" sys.exit(0) signal.signal(signal.SIGINT, signal_handler) @click.group(invoke_without_command=True) @click.pass_context @click.option("-V", "--version", is_flag=True, help="Show version and exit.") @click.option("-H", "--help", is_flag=True, help="Show help info.") def main(ctx, version, help): """MAX HMI Server 命令行工具""" if version: click.echo(f"MAX HMI Server {settings.version}") elif help: click.echo(ctx.get_help()) elif ctx.invoked_subcommand is None: runserver() @main.command() @click.option( "-h", "--host", default="0.0.0.0", # noqa: S104 show_default=True, help="Host IP.", ) @click.option( "-p", "--port", default=7002, show_default=True, type=int, help="Port.", ) @click.option( "-w", "--workdir", default=None, type=Path, help="工作目录, 如果不指定则使用 Studio Max 最近打开的工程目录", ) @click.option( "-n", "--project-name", default=lambda: studio_max_utils.get_current_hmi_project_name() or "default", help="项目名称", show_default=True, ) @click.option( "-l", "--level", default="info", help="日志等级", show_default=True, ) @click.option( "-r", "--reload", default=False, is_flag=True, help="当代码发生变化时,自动重启服务器", ) # 热插拔 @click.option( "--hot-swap", default=False, is_flag=True, help="热插拔, 当代码发生变化时,自动重载模块", ) @click.option( "-d", "--debug", default=False, is_flag=True, help="开启调试模式", ) @click.option( "--studio-max-dir", default=os.path.expanduser("~/xyz-studio-max/lib/python/dist-packages"), help="Studio Max 的根目录", show_default=True, type=Path, ) @click.option( "--use-tmp-db", default=False, is_flag=True, help="使用临时数据库", ) @click.option( "-e", "--env", default="prod", help="运行环境, dev: 开发环境, test: 测试环境, prod: 生产环境", show_default=True, type=click.Choice(["dev", "test", "prod"]), ) def runserver( host="0.0.0.0", # noqa: S104 port=7003, level="INFO", reload=False, debug=False, hot_swap=False, workdir=None, *, project_name, studio_max_dir: Optional[Path] = None, use_tmp_db=False, env="prod", ): """启动服务""" if ( studio_max_dir is None and os.environ.get("MAX_HMI_STUDIO_MAX_DIR") is None ): studio_max_dir = Path( os.path.expanduser("~/xyz-studio-max/lib/python/dist-packages") ) if not studio_max_dir.exists(): raise RuntimeError(f"Studio Max 根目录不存在: {studio_max_dir}") sys.path.insert(0, str(studio_max_dir)) def get_project_dir() -> Path: nonlocal workdir if not workdir: workdir = utils.get_workdir() if os.path.exists(workdir / project_name): project_dir = workdir / project_name elif os.path.exists(workdir / "config") and os.path.exists( workdir / "wcs_adaptor" ): # NOTE: 判断 workdir 目录是否存在 config 和 adaptor 目录,如果存在则认为是项目目录 # 这是为了兼容老版本的项目目录 project_dir = workdir logger.warning( ( "当前项目目录结构已弃用, 请使用 `hmi startproject`" " 命令创建新的项目目录或者使用" " `hmi runserver -w <project_dir>` 指定项目目录运行" ), ) else: project_dir = workdir / project_name else: project_dir = Path(workdir) / project_name if not project_dir.exists(): raise RuntimeError(f"{project_dir} 项目目录不存在") return project_dir def set_env(): os.environ.setdefault("MAX_HMI_WORKDIR", str(workdir)) os.environ.setdefault("MAX_HMI_PROJECT_DIR", str(project_dir)) m = { "dev": "development", "test": "testing", "prod": "production", } os.environ.setdefault("MAX_HMI_ENV", m[env]) project_dir = get_project_dir() set_env() if use_tmp_db: if (project_dir / "tmp.db").exists(): os.remove(project_dir / "tmp.db") settings.db.sqlalchemy_database_uri = SqliteDsn( "sqlite:///tmp.db?check_same_thread=false" ) if debug: level = "DEBUG" extra_kwargs: Dict[str, Any] = {"reload": reload} if reload: extra_kwargs["reload_includes"] = ["*.py", "*.yaml"] extra_kwargs["reload_dirs"] = [str(settings.project_dir.absolute())] else: # HACK: 由于 max 的进程管理无法正常关闭进程,因此这里需要手动关闭残留进程 utils.kill_process_on_port(settings.hmi.port) utils.kill_leftover_self_process() utils.kill_leftover_nginx() utils.kill_leftover_nginx() if host != settings.server.host: host = settings.server.host if port != settings.server.port: port = settings.server.port utils.start_nginx(utils.get_studio_max_install_path() / "bin") atexit.register(utils.kill_leftover_nginx) create_app(debug=debug, hot_swap=hot_swap).run( host=host, port=port, log_level=getattr(logging, level.upper()), **extra_kwargs, ) @main.command() @click.pass_context @click.option("-h", "--help", is_flag=True) @click.argument("args", nargs=-1) def alembic(ctx: Context, help: bool, args: list): """Alembic 命令行工具 Examples: NOTICE: 必须加上 `--` 作为分隔符 max-hmi alembic -- revision --autogenerate -m "init" max-hmi alembic -- upgrade head """ with utils.chdir(Path(__file__).parent): argv = list(args) if help: argv.append("--help") alembic_config.main(prog=ctx.command_path, argv=argv) @main.command() @click.option( "-p", "--project-type", type=click.Choice(["dpt", "ind"], case_sensitive=False), default="dpt", show_default=True, help="项目类型", ) @click.option( "-w", "--workdir", default=None, type=Path, help="工作目录, 如果不指定则使用 Studio Max 最近打开的工程目录", ) @click.option( "-e", "--db-engine", default="sqlite", type=click.Choice(["sqlite", "mysql"], case_sensitive=False), show_default=True, help="数据库类型", ) @click.option( "-n", "--project-name", default="default", show_default=True, help="项目名称", ) @click.option( "-l", "--language", default="zh", type=click.Choice(["zh", "en", "ja", "de"], case_sensitive=False), show_default=True, ) def startproject( workdir: Optional[Path], project_type: Literal["dpt", "ind"], db_engine: Literal["sqlite", "mysql"], project_name: str = "default", language: Literal["zh", "en", "ja", "de"] = "zh", ): """创建项目""" if not workdir: workdir = utils.get_workdir() / project_name # FIXME: workdir 命名有歧义, 应该是 project_dir workdir = Path(workdir) if os.path.exists(workdir): click.echo(f"目录 {workdir} 已存在, 请删除后重试") return def _copy(): template_dir = Path(__file__).parent / "templates" path = template_dir / project_type shutil.copytree( template_dir / "common", workdir, ) shutil.copytree( path / "config", workdir / "config", ) shutil.copytree( path / "wcs_adaptor", workdir / "wcs_adaptor", ) if os.path.exists(workdir / "docker-compose.yaml"): shutil.copy( path / "docker-compose.yaml", workdir / "docker-compose.yaml", ) def remake_config(): with open(workdir / "config" / "default.yaml", encoding="utf-8") as f: config = yaml.safe_load(f) with open( workdir / "config" / "default.yaml", "w", encoding="utf-8" ) as f: if db_engine == "mysql": config["db"][ "sqlalchemy_database_uri" ] = "mysql+pymysql://root:[email protected]:3306/max_hmi?charset:utf8mb4" elif db_engine == "sqlite": config["db"][ "sqlalchemy_database_uri" ] = "sqlite:///max_hmi.db?check_same_thread=False" else: click.echo(f"不支持的数据库类型 {db_engine}") return config["system"]["language"] = getattr( enums.LanguageType, language.upper() ).value yaml.safe_dump(config, f) def remake_vscode_settings(): import jinja2 vscode_settings_path = workdir / ".vscode" / "settings.json" with open(vscode_settings_path, encoding="utf-8") as f: template = jinja2.Template(f.read()) with open( workdir / ".vscode" / "settings.json", "w", encoding="utf-8" ) as f: f.write( template.render( studio_max_install_path=settings.studio_max_root_dir.resolve().as_posix() ) ) def console_print(): console = Console() table = Table( show_header=True, header_style="bold cyan", ) console.print("开发模板已创建", style="bold green", justify="default") headers = ("项目名", "项目类型", "数据库类型", "工作目录") for header in headers: table.add_column(header) table.add_row( project_name, project_type, db_engine, str(workdir.absolute()), ) console.print(table) _copy() remake_config() remake_vscode_settings() console_print() @main.group() @click.pass_context def profile(_: Context): """当前项目配置""" pass @profile.command() @click.option( "-n", "--project-name", default=lambda: studio_max_utils.get_current_hmi_project_name() or "default", show_default=True, help="项目名称", ) def show(project_name: str): """打印当前项目的配置信息""" p = utils.get_workdir() / project_name config_file = p / "config/default.yaml" if not config_file.exists(): click.echo(f"配置文件 {config_file} 不存在") return # 平铺展示yaml文件 with open(config_file) as f: content = f.read() console = Console() console.print(f"配置文件: {p}", style="bold green", justify="default") console.print("---", style="bold green", justify="default") syntax = Syntax( content, "yaml", word_wrap=True, ) console.print(syntax) @main.group() @click.pass_context def config(_: click.Context): """HMI Server 配置""" pass @config.command() @click.argument("key") @click.argument("value") def set(key, value): """设置配置项 hmi config set current_project_name <name> """ c = studio_max_utils.HMIServerConfig() c.set(key, value) @config.command() @click.argument("key") def get(key): """获取配置项""" c = studio_max_utils.HMIServerConfig() click.echo(c.get(key)) @main.group() @click.pass_context def db(ctx): """数据库命令""" _ = ctx @db.command() @click.pass_context @click.option("-h", "--help", is_flag=True) @click.option("--autogenerate", is_flag=True) @click.argument("args", nargs=-1) def migrate(ctx: Context, help: bool, autogenerate, args: list): """生成迁移文件""" with utils.chdir(Path(__file__).parent): argv = ["revision"] + list(args) if help: argv.append("--help") if autogenerate: argv.append("--autogenerate") alembic_config.main(prog=ctx.command_path, argv=argv) @db.command() @click.pass_context @click.option("-h", "--help", is_flag=True) @click.argument("args", nargs=-1) def upgrade(ctx: Context, help: bool, args: list): """升级数据库""" with utils.chdir(Path(__file__).parent): argv = ["upgrade"] + list(args) if not args: # 默认升级到最新版本 argv.append("head") if help: argv.append("--help") alembic_config.main( prog=ctx.command_path, argv=argv, ) @db.command() @click.pass_context @click.option("-h", "--help", is_flag=True) @click.argument("args", nargs=-1) def downgrade(ctx: Context, help: bool, args: list): """降级数据库""" with utils.chdir(Path(__file__).parent): argv = ["downgrade"] + list(args) if not args: # 默认降1级 argv.append("-1") if help: argv.append("--help") alembic_config.main( prog=ctx.command_path, argv=argv, ) @db.command() def dump(): """导出数据库""" pass @db.command() def load(): """导入数据库""" pass @main.group() @click.pass_context def mock(ctx): """测试命令""" _ = ctx @mock.command() @click.option("-d", "--data", type=Path, help="测试数据文件, 支持 csv/xlsx 格式") @click.option( "-u", "--url", type=str, default="http://127.0.0.1:7002/adaptor/api/wcs/task", help="创建任务的接口地址", ) @click.option( "--show-server-output", is_flag=True, help="显示服务端输出", ) @click.option( "--random-sku-id", is_flag=True, help="是否随机生成sku_id, 如果数据文件中没有sku_id字段, 则自动生成", ) @click.option( "--sku-id-field", type=str, default="sku_id", help="sku_id字段名", ) @click.option( "--length-field", type=str, default="length", help="长度字段名", ) @click.option( "--width-field", type=str, default="width", help="宽度字段名", ) @click.option( "--height-field", type=str, default="height", help="高度字段名", ) @click.option( "--weight-field", type=str, default="weight", help="重量字段名", ) def run( data: Optional[Path], url: str, show_server_output: bool, random_sku_id: bool, sku_id_field: str, length_field: str, width_field: str, height_field: str, weight_field: str, ): """模拟任务下发, 用于模拟测试. Example: $ python hmi_server.py mock run -d simulation_model2.xlsx --random-sku-id """ console = Console() # 获取当前项目目录 hmi_project_dir = studio_max_utils.get_current_hmi_project_dir() if not hmi_project_dir: raise click.BadParameter("未找到当前 HMI 项目目录, 请先在 HMI 创建项目") os.environ["MAX_HMI_PROJECT_DIR"] = hmi_project_dir.as_posix() if (hmi_project_dir / "tmp.db").exists(): os.remove(hmi_project_dir / "tmp.db") if not data: raise click.BadParameter("请指定测试数据文件") data = Path(data) if not data.exists(): raise click.BadParameter(f"测试数据文件 {data} 不存在") if data.suffix == ".csv": df = pd.read_csv(data) elif data.suffix == ".xlsx": df = pd.read_excel(data) else: raise click.BadParameter(f"不支持的文件格式 {data.suffix}") settings.db.sqlalchemy_database_uri = SqliteDsn( "sqlite:///tmp.db?check_same_thread=False" ) # 启动服务端, 隐藏输出 console.log("正在启动服务端...") p = subprocess.Popen( [ "python", "hmi_server.py", "runserver", "-d", "--use-tmp-db", "-e", "test", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL if not show_server_output else None, ) # 检查服务端是否启动成功 session = requests.Session() for _ in range(15): try: session.get("http://127.0.0.1:7002") console.log("[bold green]服务端已启动") break except requests.exceptions.ConnectionError: time.sleep(1) else: console.log("[bold red]服务端启动失败") return is_completed = False try: with console.status("[bold green]等待中...\n"): # 依次创建任务,直到上一个任务完成后,再创建下一个任务,直到所有任务创建完成 records = df.to_dict(orient="records") for i, row in enumerate(records): console.log(f"正在创建第 {i+1} 个任务, task_id: {row['task_id']}") sku_id = ( str(uuid.uuid4()) if random_sku_id or not row.get(sku_id_field, None) else row.get(sku_id_field) ) sku_info = { "sku_id": sku_id, "length": row.get(length_field, None) or row.get("纸箱长(mm)", None), "width": row.get(width_field, None) or row.get("纸箱宽(mm)", None), "height": row.get(height_field, None) or row.get("纸箱高(mm)", None), "weight": row.get(weight_field, None) or row.get("纸箱重量(kg)", None), } # 创建任务 body = { "task_id": row["task_id"].__str__(), "task_type": enums.TaskType(row["task_type"]).value, "from": row["from"].__str__(), "to": row["to"].__str__(), "target_num": row["target_num"], "sku_info": sku_info, } resp = session.post(url, json=body) if resp.json()["code"] == -1: console.log( f"[bold red]任务 {i} 创建失败, task_id:" f" {row['task_id']}[/bold red]" ) continue # 等待任务完成 last_status = None last_done_num = None while 1: with start_session() as sess: task = crud.task.get_by_task_id( row["task_id"], session=sess ) if not task: console.log( f"[bold green]任务 '{row['task_id']}' 已完成" ) break if last_status is None: console.log(f"[bold green]任务 '{task.task_id} 已创建") if ( task.task_status != last_status or task.done_num != last_done_num ): console.log( f"等待任务 '{row['task_id']}', 当前任务状态: [bold cyan]{task.task_status.name}[/bold cyan], " # noqa: E501 f"任务进度: [bold cyan]{task.done_num}/{task.target_num}[/bold cyan]" # noqa: E501 ) last_status = task.task_status last_done_num = task.done_num time.sleep(1) console.log(f"测试进度: {i+1}/{len(records)}") is_completed = True finally: p.kill() if not is_completed: console.log("[bold yellow]已取消") return console.log("[bold green]测试完成") # 输出测试结果 # TODO: 输出 xlsx 文件 # 第一个 sheet 包括任务总数,总耗时,平均耗时,成功率,失败率 # 第二个 sheet 包括失败的任务及物料信息 table = Table( show_header=True, header_style="bold cyan", ) toal_time = timedelta() error_num = 0 pick_num = 0 with start_session() as sess: records = crud.task_result.all(session=sess) for record in records: toal_time += record.end_time - record.start_time pick_num += record.target_num error_num = crud.error_records.total(session=sess) assert isinstance(pick_num, int) # noqa: S101 error_rate = round(error_num / pick_num, 4) table.add_column("任务总数") table.add_column("总耗时") table.add_column("平均耗时") table.add_column("故障率") table.add_row( str(len(records)), str(toal_time), str(toal_time / len(records)), "{}%".format(error_rate * 100), ) console.print(table)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\config.py
"""配置模块.""" import json import os from pathlib import Path from typing import Any, Dict, Optional, Union import crossplane import yaml from loguru import logger from pydantic import AnyUrl, BaseModel, BaseSettings, Extra, Field, validator from typing_extensions import TypedDict from xyz_max_hmi_server import enums from xyz_max_hmi_server.utils.utils import ( get_studio_max_install_path, get_workdir, ) def rewrite_nginx_conf(port: int): """重写 nginx 配置文件.""" install_path = get_studio_max_install_path() if os.name == "nt": nginx_conf_path = install_path / "bin/nginx-win/conf/nginx.conf" else: nginx_conf_path = install_path / "bin/nginx-linux/conf/nginx.conf" if not os.path.exists(nginx_conf_path): return payload = crossplane.parse(nginx_conf_path) if payload and payload["status"] == "ok": config = payload["config"][0]["parsed"] else: raise Exception("Error parsing nginx.conf") for c in config: if c["directive"] != "http": continue for s in c["block"]: if s["directive"] != "server": continue for _l in s["block"]: if _l["directive"] == "listen": _l["args"][0] = str(port) # elif l["directive"] == "location": # for p in l["block"]: # if p["directive"] != "proxy_pass": # continue # print(p["args"][0]) with open(nginx_conf_path, "w") as f: f.write(crossplane.build(config)) def yaml_config_settings_source(s: "Settings") -> Dict[str, Any]: """加载 yaml 配置文件. Args: s: 配置对象. Returns: dict: 字典对象. Raises: XYZConfigMissingError: 配置文件加载失败. """ encoding: str = s.__config__.env_file_encoding or "utf-8" workdir = get_workdir() if project_dir := os.getenv("MAX_HMI_PROJECT_DIR"): project_dir = Path(project_dir) else: project_dir = Path(workdir / "default") file_path = project_dir / s.__config__.yaml_file # type: ignore if os.path.exists(file_path): logger.info("已加载配置: {}", file_path.absolute()) with open(file_path, encoding=encoding) as f: config = yaml.safe_load(f) else: logger.warning(f"配置文件 {file_path} 不存在, 将使用默认配置") config = {} # HACK: 重写 nginx 配置 nginx_port = config.get("hmi", {}).get("port", 7002) rewrite_nginx_conf(nginx_port) return config class SystemConfig(BaseModel): project_type: enums.ProjectType = Field( default=enums.ProjectType.DPT, title="项目类型" ) language: enums.LanguageType = Field( default=enums.LanguageType.ZH, title="语言" ) @validator("language", always=True) def read_locale_from_qsettins( cls, v: enums.LanguageType ) -> enums.LanguageType: """读取 Studio Max 的语言设置. 优先使用 Studio Max 的语言设置, 如果未设置,则使用 hmi server 中的语言设置 """ from xyz_max_hmi_server.utils.studio_max import XYZRoboticsSettings locale_map = { "zh_CN": 1, "en_US": 2, "ja_JP": 3, "de_DE": 4, "ko_KR": 5, } qsettings = XYZRoboticsSettings() locale = qsettings.get("locale_string", "xyz_studio_max") if locale: if locale not in locale_map: logger.warning( "获取到未知的 Studio Max 语言设置: {}, 将使用默认语言: zh", locale ) v = enums.LanguageType.ZH else: v = enums.LanguageType(locale_map[locale]) else: logger.warning( f"未能获取到 Studio Max 的语言设置,将 HMI Server 的语言设置, 当前语言: {v.name}" ) return v class MySQLDsn(AnyUrl): """MySQL DSN""" allowed_schemes = {"mysql+pymysql"} user_required = True @property def db_name(self) -> str: if t := self.rsplit("/", 1): return t[-1].split("?")[0] raise ValueError("Invalid MySQL DSN") class SqliteDsn(str): """Sqlite DSN""" def __init__(self, url: str) -> None: if not url.startswith("sqlite"): raise ValueError("Invalid Sqlite DSN") self.url = url def __repr__(self): return self.url @property def db_name(self) -> str: if t := self.rsplit("/", 1): return t[-1].rsplit(".", 1)[0] raise ValueError("Invalid Sqlite DSN") class Socket(BaseModel): host: str = Field(description="IP地址") port: int = Field(description="端口号") @validator("port") def validate_port(cls, v: int) -> int: if v < 0 or v > 65535: raise ValueError("端口号必须在 0-65535 之间") return v def __str__(self): return f"{self.host}:{self.port}" def __repr__(self): return f"[Socket] {self.__str__()}" class DatabaseConfig(BaseModel): """数据库配置""" sqlalchemy_track_modifications: bool = False sqlalchemy_database_uri: Union[SqliteDsn, MySQLDsn] = "sqlite:///max_hmi.db?check_same_thread=False" # type: ignore @property def real_database_uri(self): """真实的数据库连接地址. 主要是因为 sqlite 的地址在配置时是相对于项目目录的,所以这里这里将 sqlite 的地址转为绝对路径. """ # noqa: E501 if self.sqlalchemy_database_uri.startswith("sqlite"): p = self.sqlalchemy_database_uri.split("/")[-1] return f"sqlite:///{settings.project_dir.absolute()}/{p}" return self.sqlalchemy_database_uri class HeartbeatConfig(BaseModel): """心跳配置""" enable: bool = False interval: Union[float, int] = 3 class PLCAddress(TypedDict, total=False): """PLC 地址""" grating: int # 光栅 buzzer: int # 蜂鸣器 red: int # 红灯 yellow: int # 黄灯 green: int # 绿灯 estop: int # 急停 class PLCConfig(BaseModel): """PLC 配置""" enable: bool = True device_id: int = 2 address: PLCAddress = { "grating": 100, "buzzer": 200, "yellow": 301, "green": 302, "red": 303, "estop": 400, } # @validator("device_id") # def validate_device_id(cls, v: int) -> int: # """检查 device_id 是否存在于 I/O Device 配置文件中.""" # from xyz_max_hmi_server.io_config import IOConfig # devices = IOConfig().get_devices() # for device in devices: # if device["id"] == v: # return v # raise ValueError( # f"无效的 device_id: {v},该 device_id 不存在于 I/O Device 配置文件中。" # ) class ListenerItem(BaseModel): """监听器配置项""" enable: bool = False interval: Union[float, int] = Field(default=0.5, title="监听间隔", ge=0.2) def __bool__(self): return self.enable class ListenerConfig(BaseModel): """监听器配置""" light: ListenerItem = Field(default_factory=ListenerItem, title="三色灯监听器") estop: ListenerItem = Field(default_factory=ListenerItem, title="急停监听器") robot_connection_status: ListenerItem = Field( default_factory=ListenerItem, title="机器人连接状态监听器" ) vp_status: ListenerItem = Field( default_factory=ListenerItem, title="VP 流图状态监听器" ) wcs_status: ListenerItem = Field( default_factory=ListenerItem, title="WCS 状态监听器" ) class TaskManagerConfig(BaseModel): """任务管理器配置""" enable: bool = True size: int = Field(default=-1, title="任务队列大小", description="默认为 1") class OrderManagerConfig(BaseModel): """订单管理器配置""" enable: bool = True size: int = Field(default=-1, title="订单队列大小", description="默认为 -1,表示无限制") class DevModeConfig(BaseModel): """开发模式下的配置""" mock_wcs: bool = False class NotifyConfig(BaseModel): """通知配置""" enable: bool = True wechat: str = Field(default="", title="企业微信机器人 Webhook") class Settings(BaseSettings): """配置类""" workdir: Path = Field(..., env="WORKDIR") @validator("workdir") def convert_abs_path(cls, v: Path) -> Path: return Path(v).absolute() @property def project_dir(self) -> Path: """当前项目目录.""" return self.workdir / os.environ.get("MAX_HMI_PROJECT_DIR", "default") @property def studio_max_root_dir(self) -> Path: """Studio Max 根目录. current_file_path: ~/xyz-studio-max/lib/python/dist-packages/xyz_max_hmi_server/config.py studio_max_root_dir: ~/xyz-studio-max """ current_file_path = Path(__file__).absolute() return current_file_path.parents[4] @property def robot_server_conf_path(self) -> Path: """机器人服务配置文件路径.""" return ( self.project_dir.parent.parent / "robot_configs/robot_server_config.yml" ) system: SystemConfig = SystemConfig() db: DatabaseConfig = DatabaseConfig() @validator("db") def convert_db_uri(cls, v: DatabaseConfig) -> DatabaseConfig: if os.getenv("MAX_HMI_DB"): data = json.loads(os.getenv("MAX_HMI_DB")) # type: ignore v.sqlalchemy_database_uri = data["sqlalchemy_database_uri"] v.sqlalchemy_track_modifications = data[ "sqlalchemy_track_modifications" ] return v # Deprecated: V1.3.0 heartbeat: HeartbeatConfig = HeartbeatConfig() plc: PLCConfig = PLCConfig() socket: Socket = Socket(host="0.0.0.0", port=7001) hmi: Socket = Socket(host="0.0.0.0", port=7002) server: Socket = Socket(host="0.0.0.0", port=7003) wcs: Socket = Socket(host="0.0.0.0", port=12000) listener: ListenerConfig = ListenerConfig() @validator("wcs") def convert_wcs_uri(cls, v: Socket) -> Socket: if os.getenv("MAX_HMI_WCS"): data = json.loads(os.getenv("MAX_HMI_WCS")) # type: ignore v.host = data["host"] v.port = data["port"] return v task_manager: TaskManagerConfig = TaskManagerConfig() order_manager: OrderManagerConfig = OrderManagerConfig() dev_mode: DevModeConfig = DevModeConfig() notify: NotifyConfig = NotifyConfig() @property def version(self) -> str: """获取版本号.""" from xyz_max_hmi_server import version return version.__version__ class Config: env_prefix = "MAX_HMI_" env_file = ".env", ".env.dev" env_file_encoding: str = "utf-8" yaml_file = "config/default.yaml" yaml_file_encoding: str = "utf-8" extra = Extra.ignore fields = { "workdir": { "env": "max_hmi_workdir", }, "db": { "env": "max_hmi_db", }, "wcs": { "env": "max_hmi_wcs", }, "hmi": { "env": "max_hmi_hmi", }, } @classmethod def customise_sources( cls, init_settings, env_settings, file_secret_settings, ): return ( init_settings, yaml_config_settings_source, env_settings, file_secret_settings, ) class LazySettings: """懒加载配置对象, 仅在第一次访问时加载配置文件.""" def __init__(self) -> None: # noqa self.__settings: Optional[Settings] = None def __getattr__(self, name: str): """当首次访问配置项时加载配置文件.""" if self.__settings is None: self.__settings = Settings(workdir=get_workdir()) return getattr(self.__settings, name) def reload(self): """重载配置文件.""" self.__settings = Settings(workdir=get_workdir()) settings: Settings = LazySettings() # type: ignore
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\enums.py
from enum import Enum, IntEnum class Action(str, Enum): START = "start" PICKED = "after_pick" PLACED = "after_place" FINISH = "finish" RESET = "reset" class LanguageType(Enum): """语言类型.""" ZH = 1 # 汉语 EN = 2 # 英语 JA = 3 # 日语 DE = 4 # 德语 KO = 5 # 韩语 class SystemStatus(IntEnum): """系统状态.""" READY = 0 # 就绪 RUNNING = 1 # 运行中 STOPPED = ERROR = 99 # 异常/停止 class EventType(Enum): """Socket 事件.""" # 订单日志 ORDER_LOG = "order_log" # 运动规划日志 MOTION_PLAN_LOG = "motion_plan_log" # 系统日志 SYSTEM_LOG = "system_log" # 机器人状态 ROBOT_STATUS = "robot_status" # 三色灯 RGB_LIGHT = "light" # WCS 连接状态 WCS_CONNECTION = "wcs_status" # 系统状态 SYSTEM_STATUS = "system_status" # 机械臂驱动 ROBOT_DRIVER_STATUS = "robot_driver_status" class ProjectType(Enum): """项目类型.""" DPT = "dpt" PP = "pp" IND = "ind" class ErrorSources(Enum): """异常来源.""" VP = "vp" VISION = "vision" class MediaType(Enum): """媒体类型.""" # content-type对应表: # https://blog.csdn.net/xiaoyu19910321/article/details/79279364 xls = "application/vnd.ms-excel" xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" png = "image/png" gif = "image/gif" jpg = "image/jpg" json = "application/json" zip = "application/zip" class PlcStatus(Enum): STOPPED = "STOPPED" # 已停止 STARTED = "STARTED" # 已启动 EXCEPTION = "EXCEPTION" # 发生异常 class RobotStatus(Enum): """机器人状态""" MANUAL = 1 # 手动 DISENABLE = 2 # 禁用 NOT_CYCLE = 3 # 非循环 PAUSE = 4 # 暂停 ESTOP = 5 # 急停 ERROR = 6 # 异常 COLLISION = 7 # 碰撞 NORMAL = 8 # 正常 UNKNOWN = 999 # 未知 class RobotMode(str, Enum): """机器人模式""" AUTO = "auto" MANUAL = "manual" class RobotControl(str, Enum): """机器人控制.""" START = "start" STOP = "stop" RESTART = "restart" class RobotDriverStatus(int, Enum): """机械臂驱动状态""" DISCONNECTION = -1 READY = 0 CONNECTED = 1 class TaskStatus(IntEnum): """任务状态枚举类,定义了任务的各种状态""" RECEIVED = 0 # 已接收 PENDING = 1 # 未开始 STARTED = 2 # 已开始 FINISHED = 3 # 已完成 ERROR = 4 # 发生异常 TERMINATED = 5 # 终止 IN_BUFFER = 6 # 在缓冲区 ENDED = 10 # 已结束 class TaskType(IntEnum): """任务类型枚举类,定义了任务的所属类型""" SINGLE_DEPAL = 0 # 单拆 SINGLE_PAL = 1 # 单码 MCD = MULTI_DEPAL = 2 # 混拆 RANDOM_SEQ_MCP = MULTI_PAL_ONLINE = 3 # 混码online CONTROLLED_SEQ_MCP = MULTI_PAL_OFFLINE = 4 # 混码offline ROCKYDUAL_TRUCK_UNLOADING = 5 # RockyDual, 双机械臂卸车任务 ROCKYDUAL_TRUCK_LOADING = 6 # RockyDual, 双机械臂装车任务 PP_DEFAULT = 100 # Piece picking default type PP_CYCLE = 101 # 分拣站循环抓取模式,常用于压测 class OrderType(IntEnum): """订单枚举类.""" SINGLE_DEPAL = 0 # 单拆 SINGLE_PAL = 1 # 单码 # Mixed Case Depalletting, 混拆 MCD = 2 # Random Sequence Mixed Case Palletting, 无序混码 RANDOM_SEQ_MCP = 3 # Controlled Sequence Mixed Case Palletting, 控序混码 CONTROLLED_SEQ_MCP = 4 ROCKYDUAL_TRUCK_UNLOADING = 5 # RockyDual, 双机械臂卸车任务 ROCKYDUAL_TRUCK_LOADING = 6 # RockyDual, 双机械臂装车任务 PP_DEFAULT = 100 # Piece picking default type PP_CYCLE = 101 class OrderStatus(IntEnum): """订单状态枚举类,定义了订单的各种状态""" PENDING = 0 # 未开始 PLANNING = 1 # 规划中 PLANNED = 2 # 规划完成 STARTED = 3 # 已开始 FINISHED = 4 # 已完成 ERROR = 5 # 发生异常 TERMINATED = 6 # 已终止 ENDED = 10 # 已结束 class LogLevel(str, Enum): """日志级别.""" INFO = "info" WARNING = "warning" ERROR = "error" LOG = "log" SUCCESS = "success" class VPStatus(str, Enum): """VP 状态.""" RUNNING = "Running" STOPPING = "Stopping" STOPPED = "Stopped" PAUSING = "Pausing" PAUSED = "Paused" UNKNOWN = "Unknown" class WCSConnectionStatus(int, Enum): """WCS 连接状态.""" DISCONNECTED = 0 CONNECTED = 1 class CyberNodeName(str, Enum): """Cyber 节点名称.""" RobotDriver = "HMI/RobotDriverNode" CycleRecorder = "HMI/CycleRecorderNode" Subscriber = "HMI/SubscriberNode" PLCNode = "HMI/PLCNode" class CyberSubscribeTopicName(str, Enum): """Cyber 订阅的 topic 名称.""" RobotServerLog = "RobotServerLog" RobotServerStatus = "RobotServerStatus" class CMCPPlanningStatus(int, Enum): """控序混码规划状态""" PENDING = 0 PLANNING = 1 SUCCESS = 2 FAILURE = 3
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\error_handlers.py
""" 用于处理异常的函数. """ from typing import TYPE_CHECKING from fastapi import Request from fastapi.exceptions import RequestValidationError from xyz_max_hmi_server.exceptions import ( XYZException, XYZNotFoundError, XYZValidationError, ) from xyz_max_hmi_server.log import logger from xyz_max_hmi_server.responses import ErrorJSONResponse, JSONResponse if TYPE_CHECKING: from xyz_max_hmi_server.app import Application # 异常类型与错误信息的映射 ERROR_CODE_MAPPING = { "type_error.integer": lambda e: f"参数 {e.get('loc')[-1]} 必须为整数", "type_error.number": lambda e: f"参数 {e.get('loc')[-1]} 必须为数字", "type_error.str": lambda e: f"参数 {e.get('loc')[-1]} 必须为字符串", "type_error.bool": lambda e: f"参数 {e.get('loc')[-1]} 必须为布尔值", "type_error.dict": lambda e: f"参数 {e.get('loc')[-1]} 必须为字典", "type_error.list": lambda e: f"参数 {e.get('loc')[-1]} 必须为列表", "type_error.float": lambda e: f"参数 {e.get('loc')[-1]} 必须为浮点数", "type_error.missing": lambda e: f"缺少参数 {e.get('loc')[-1]}", "value_error.any_str.min_length": lambda e: f"参数 {e.get('loc')[-1]} 长度必须大于 {e.limit_value}", "value_error.any_str.max_length": lambda e: f"参数 {e.get('loc')[-1]} 长度必须小于 {e.limit_value}", "value_error.any_str.regex": lambda e: f"参数 {e.get('loc')[-1]} 格式不正确", "value_error.any_str.url": lambda e: f"参数 {e.get('loc')[-1]} 不是有效的 URL", "value_error.any_str.email": lambda e: f"参数 {e.get('loc')[-1]} 不是有效的邮箱地址", "value_error.any_str.ipv4": lambda e: f"参数 {e.get('loc')[-1]} 不是有效的 IPv4 地址", "value_error.any_str.ipv6": lambda e: f"参数 {e.get('loc')[-1]} 不是有效的 IPv6 地址", "value_error.any_str.uuid": lambda e: f"参数 {e.get('loc')[-1]} 不是有效的 UUID", "value_error.any_str.lower": lambda e: f"参数 {e.get('loc')[-1]} 必须为小写", "value_error.any_str.upper": lambda e: f"参数 {e.get('loc')[-1]} 必须为大写", "value_error.any_str.strip": lambda e: f"参数 {e.get('loc')[-1]} 不能包含空格", "type_error.none.not_allowed": lambda e: f"参数 {e.get('loc')[-1]} 不能为 None", "value_error.number.not_finite": lambda e: f"参数 {e.get('loc')[-1]} 必须为有限数字", "value_error.number.not_nan": lambda e: f"参数 {e.get('loc')[-1]} 不能为 NaN", "value_error.number.not_inf": lambda e: f"参数 {e.get('loc')[-1]} 不能为无穷大", "value_error.number.not_gt": lambda e: f"参数 {e.get('loc')[-1]} 必须大于 {e.limit_value}", "value_error.number.not_ge": lambda e: f"参数 {e.get('loc')[-1]} 必须大于等于 {e.limit_value}", "value_error.number.not_lt": lambda e: f"参数 {e.get('loc')[-1]} 必须小于 {e.limit_value}", "value_error.number.not_le": lambda e: f"参数 {e.get('loc')[-1]} 必须小于等于 {e.limit_value}", "value_error.number.not_eq": lambda e: f"参数 {e.get('loc')[-1]} 必须等于 {e.limit_value}", "value_error.number.not_ne": lambda e: f"参数 {e.get('loc')[-1]} 不能等于 {e.limit_value}", } def display_validation_error(e: RequestValidationError) -> str: """用于在控制台输出数据格式验证失败的异常.""" err = e.errors()[0] loc = err.get("loc") err_type = err["type"] if loc and err_type in ERROR_CODE_MAPPING: try: return ERROR_CODE_MAPPING[err_type](err) except Exception: logger.opt(exception=True).error("数据格式验证失败") return "参数验证失败" def handler_validation_error( request: Request, e: RequestValidationError ) -> ErrorJSONResponse: """处理数据格式验证失败的异常.""" _ = request return ErrorJSONResponse( status_code=422, msg="Unprocessable Entity", data={ "error_code": 422, "error_msg": display_validation_error(e), "details": e.errors(), }, ) def handle_generic_error(request: Request, e: Exception) -> JSONResponse: """处理通用异常""" _ = request # 如果被此方法捕获, 则说明该异常未被主动捕获, 属于未知异常, 需要输出详细调用栈信息. logger.error(repr(e), exc_info=True) return ErrorJSONResponse( status_code=500, code=-1, msg="Internal Server Error", data={"error_code": -1, "error_message": "Internal Server Error"}, ) def handle_xyz_not_found(request: Request, e: XYZNotFoundError) -> JSONResponse: """处理所有 XYZNotFoundException 异常.""" _ = request logger.exception(e) # NOTE: 为了兼容前端, 此处 status_code 为 200 return ErrorJSONResponse( code=e.status_code, status_code=200, msg=e.name, data={"error_code": e.error_code, "error_message": e.error_message}, ) def handle_xyz_error(request: Request, e: XYZException) -> JSONResponse: """处理所有 XYZException 异常.""" _ = request logger.exception(e) return ErrorJSONResponse( code=e.status_code, status_code=e.status_code, msg=e.name, data={"error_code": e.error_code, "error_message": e.error_message}, ) def init_app(app: "Application"): app.add_exception_handler(Exception, handle_generic_error) app.add_exception_handler(XYZNotFoundError, handle_xyz_not_found) app.add_exception_handler(XYZException, handle_xyz_error) app.add_exception_handler(XYZValidationError, handler_validation_error) app.add_exception_handler(RequestValidationError, handler_validation_error)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\exceptions.py
from pathlib import Path from typing import TYPE_CHECKING, Optional from fastapi_babel import _ from xyz_max_hmi_server import mixin if TYPE_CHECKING: from xyz_max_hmi_server.entity.order import LiteOrder from xyz_max_hmi_server.entity.task import LiteTask class XYZException(Exception): """异常基类""" status_code: int = 500 error_code: int = 10000 name: str = "Internal Server Error" def __init__( # noqa: D107 self, error_message: Optional[str] = None, status_code: Optional[int] = None, ): self.error_message = error_message if status_code is not None: self.status_code = status_code def __str__(self): # noqa: D105 return f"[{self.error_code}] {self.error_message}" def __repr__(self): # noqa: D105 return f"[{self.__class__.__name__}] {self.__str__()}" class WCSException(XYZException, mixin.OrderInfoEventMessageMixin): """WCS API 异常""" status_code = 200 error_code = 10100 name = "WCS API Error" class MAXException(XYZException, mixin.OrderInfoEventMessageMixin): """MAX API 异常""" status_code = 200 error_code = 10200 name = "MAX API Error" class XYZTaskError(XYZException): """任务错误""" status_code = 200 error_code: int = 10300 name = "Task Error" def __init__( # noqa: D107 self, task_id: Optional[str] = None, error_message: Optional[str] = None ): if error_message is None: self.error_message = _("任务 '{0}' 发生错误.").format(task_id) else: self.error_message = error_message self.task_id = task_id @property def task(self) -> Optional["LiteTask"]: from xyz_max_hmi_server.modules.manager.task_manager import TaskManager return TaskManager().get_task_by_id(self.task_id) class XYZOrderError(XYZException): """订单错误""" status_code = 200 error_code: int = 10400 name = "Order Error" def __init__( # noqa: D107 self, order_id: Optional[str] = None, error_message: Optional[str] = None, ): if error_message is None: self.error_message = _("订单 '{0}' 发生错误.").format(order_id) else: self.error_message = error_message self.order_id = order_id @property def task(self) -> Optional["LiteOrder"]: from xyz_max_hmi_server.modules.manager.order_manager import ( OrderManager, ) return OrderManager().get_by_order_id(self.order_id) class XYZOrderNotAllowDeleteError(XYZOrderError): """订单不允许删除""" error_code: int = 10401 name = "Order Not Allow Delete Error" def __init__(self, order_id: str): self.error_message = _("订单 '{0}' 不允许删除, 订单的任务正常执行中.").format(order_id) self.order_id = order_id class XYZConfigError(XYZException): """配置文件错误""" error_code: int = 11000 name = "Configuration Error" class XYZConfigParseError(XYZConfigError): """配置文件解析错误""" error_code: int = 11001 name = "Configuration Parse Error" def __init__(self, filename: str, path: Path): self.error_message = ( f"Failed to parse configuration file({filename}) in {path}." ) class XYZConfigValueError(XYZConfigError): """配置文件值错误""" error_code: int = 11002 name = "Configuration Value Error" def __init__(self, filename: str, path: Path, key: str, value: str): self.error_message = f"Invalid value({value}) for key({key}) in configuration file({filename}) in {path}." class XYZNotFoundError(XYZException, mixin.OrderInfoEventMessageMixin): """资源未找到错误""" status_code = 404 error_code: int = 12000 name = "Resource Not Found" class XYZValidationError( XYZException, mixin.OrderInfoEventMessageMixin, ): """验证错误""" status_code = 422 error_code: int = 13000 name = "Validation Error" def __init__( self, error_message: Optional[str] = None, body: Optional[dict] = None ): self.error_message = error_message self.raw_errors = [error_message] self.body = body class XYZCyberError(XYZException): """Cyber错误""" status_code = 200 error_code: int = 14000 name = "Cyber Error" class XYZCyberDigitalError(XYZCyberError): """Cyber数字服务器错误""" error_code: int = 14001 name = "Cyber Digital Server Error" class XYZCyberRobotSignalError(XYZCyberError): """Cyber机器人信号错误""" error_code: int = 14002 name = "Cyber Robot Signal Error" class XYZCyberVPError(XYZCyberError): """Cyber VP错误""" error_code: int = 14003 name = "Cyber VP Error" class XYZCyberRobotServerError(XYZCyberError): """Cyber 机器人服务错误""" error_code: int = 14004 name = "Cyber Robot Server Error" class XYZGrpcError(XYZException): """Grpc错误""" status_code = 200 error_code: int = 15000 name = "Grpc Error" class XYZNotFoundGrpcServiceError(XYZGrpcError): """未找到Grpc服务错误""" error_code: int = 15001 name = "Not Found Grpc Service Error" def __init__(self, service_name: str): # noqa: D107 self.error_message = f"未找到Grpc服务: {service_name}"
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\globals.py
"""全局对象""" import time from . import enums from .modules.cycle.current import current_cycle class WCSStatus: def __init__(self): self.status = enums.WCSConnectionStatus.DISCONNECTED self.last_timestame = 0 def get(self) -> dict: return { "status": self.status, "status_name": self.status.name.lower(), "timestamp": self.last_timestamp, } def set_connected(self): self.status = enums.WCSConnectionStatus.CONNECTED self.last_timestamp = int(time.time() * 1000) def set_disconnected(self): self.status = enums.WCSConnectionStatus.DISCONNECTED self.last_timestamp = int(time.time() * 1000) class SystemStatus: """系统状态类 Attributes: status(enums.SystemStatus): 系统状态 Methods: set_running: 设置系统运行中 set_ready: 设置系统就绪 set_error: 设置系统错误 set_stopped: 设置系统停止 """ def __init__(self) -> None: self.status = enums.SystemStatus.STOPPED def set_running(self): self.status = enums.SystemStatus.RUNNING def set_ready(self): self.status = enums.SystemStatus.READY def set_error(self): self.status = enums.SystemStatus.ERROR def set_stopped(self): self.status = enums.SystemStatus.STOPPED wcs_status = WCSStatus() system_status = SystemStatus() __all__ = ["current_cycle", "wcs_status", "system_status"]
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\io_config.py
"""I/O 设备地址读取模块""" import json from typing import Dict, List from xyz_max_hmi_server.config import settings from xyz_max_hmi_server.utils.signleton import Singleton class IOConfig(metaclass=Singleton): def __init__(self): self.config_file_path = ( settings.project_dir / "robot_configs/io_devices_config.json" ) self.config = self._read_config() # 记录文件修改时间 self.last_modified_time = self.get_modified_time() def get_modified_time(self): """获取文件修改时间""" return self.config_file_path.stat().st_mtime def _read_config(self) -> dict: """读取配置文件""" with open(self.config_file_path) as f: return json.load(f) def get_address(self, device_id: int) -> Dict: """获取设备地址. Args: device_id: 设备ID """ if self.last_modified_time != self.get_modified_time(): self.config = self._read_config() self.last_modified_time = self.get_modified_time() # TODO: 待确定 self.config["devices"][str(device_id)] return self.config[device_id] def get_devices(self) -> List[Dict]: """获取所有设备""" if self.last_modified_time != self.get_modified_time(): self.config = self._read_config() self.last_modified_time = self.get_modified_time() results = [] for _id, item in self.config["devices"].items(): results.append( { "id": int(_id), "name": item["name"], } ) return results
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\log.py
import logging import os import sys from pathlib import Path from pprint import pformat from types import FrameType from typing import cast from loguru import logger from loguru._defaults import LOGURU_FORMAT def get_log_path() -> Path: # TODO: 临时,后续需要修改为读取 Studio 注册表,获取日志存储目录 return Path.home() / "xyz_log/xyz_max_hmi/server" class InterceptHandler(logging.Handler): def emit(self, record: logging.LogRecord) -> None: # pragma: no cover # NOTE: ignore proactor_events loop debug logs if record.module == "proactor_events": return # Get corresponding Loguru level if it exists try: level = logger.level(record.levelname).name except ValueError: level = str(record.levelno) # Find caller from where originated the logged message frame, depth = logging.currentframe(), 2 while frame.f_code.co_filename == logging.__file__: # noqa: WPS609 frame = cast(FrameType, frame.f_back) depth += 1 logger.opt(depth=depth, exception=record.exc_info).log( level, record.getMessage(), ) def format_record(record: dict) -> str: """Custom format for loguru loggers. Uses pformat for log any data like request/response body during debug. Works with logging if loguru handler it. Example: >>> payload = [{"users":[{"name": "Nick", "age": 87, "is_active": True}, {"name": "Alex", "age": 27, "is_active": True}], "count": 2}] >>> logger.bind(payload=payload).debug("users payload") >>> [ { 'count': 2, >>> 'users': [ {'age': 87, 'is_active': True, 'name': 'Nick'}, >>> {'age': 27, 'is_active': True, 'name': 'Alex'}]}] """ format_string = str(LOGURU_FORMAT) if record["extra"].get("payload") is not None: record["extra"]["payload"] = pformat( record["extra"]["payload"], indent=4, compact=True, width=88 ) format_string += "\n<level>{extra[payload]}</level>" format_string += "{exception}\n" return format_string def init_logging(level: int = logging.INFO) -> None: logger.remove() intercept_handler = InterceptHandler() intercept_handler.level = level logging.basicConfig(handlers=[intercept_handler], level=level, force=True) for name in logging.root.manager.loggerDict: _logger = logging.getLogger(name) if name.startswith("uvicorn."): # change handler for default uvicorn logger _logger.handlers = [] # uvicorn -> default # uvicorn.access -> access LOGGER_NAMES = ("uvicorn", "uvicorn.access") logging.basicConfig() logging.getLogger("sqlalchemy.engine").setLevel(level) for name in LOGGER_NAMES: _logger = logging.getLogger(name) _logger.handlers = [intercept_handler] log_path = get_log_path() logger.add( sys.stderr, level=level, enqueue=True, filter=lambda record: ignore_log_in_console(record) and ignore_wcs_mock_server(record) and not filter_sqlalchemy(record), ) logger.add( log_path / "all/all.log", retention="60 days", rotation="00:00", enqueue=True, filter=lambda record: ignore_iocp_proactor_events(record) and not filter_long_polling(record) and record["level"].name != "DEBUG" and not filter_listener(record) and ignore_wcs_mock_server(record) and not filter_sqlalchemy(record), ) logger.add( log_path / "pipe/pipe.log", retention="60 days", rotation="00:00", filter=lambda record: "pipe" in record.get("name", ""), # type: ignore enqueue=True, ) logger.add( log_path / "wcs_adaptor/wcs_adaptor.log", retention="60 days", rotation="00:00", filter=filter_wcs_adaptor, # type: ignore enqueue=True, ) logger.add( log_path / "debug/debug.log", retention="14 days", rotation="00:00", filter=lambda record: record["level"].name == "DEBUG", # type: ignore enqueue=True, ) logger.add( log_path / "error/error.log", retention="14 days", rotation="00:00", enqueue=True, filter=lambda record: record["level"].name == "ERROR", # type: ignore ) # 存储长轮询接口的日志 logger.add( log_path / "long_polling/long_polling.log", retention="7 days", rotation="00:00", enqueue=True, filter=filter_long_polling, ) # 存储监听器的日志 logger.add( log_path / "listener/listener.log", retention="7 days", rotation="00:00", enqueue=True, filter=filter_listener, ) # 存储 WCS Mock Server 的日志 logger.add( log_path / "wcs_mockserver/wcs_mockserver.log", retention="7 days", rotation="00:00", filter=lambda record: not ignore_wcs_mock_server(record), ) # 存储 sqlalchemy 的日志 logger.add( log_path / "sqlalchemy/sqlalchemy.log", retention="7 days", rotation="00:00", filter=filter_sqlalchemy, ) # NOTE: Deprecated logger.add( log_path / "max/api/api.log", retention="1 days", rotation="00:00", filter=lambda _: False, enqueue=True, ) logger.add( log_path / "wcs/request/request.log", retention="1 days", rotation="00:00", filter=lambda _: False, enqueue=True, ) logger.add( log_path / "wcs/api/api.log", retention="1 days", rotation="00:00", filter=lambda _: False, enqueue=True, ) def _show_record(record) -> bool: print(record) return True def filter_wcs_adaptor(record) -> bool: return ( "/api/wcs" in record.get("message", "") or "/api/max" in record.get("message", "") or record.get("name", "").startswith("wcs_adaptor") ) def filter_listener(record) -> bool: return record["name"] == "xyz_max_hmi_server.modules.monitor.listener" def ignore_iocp_proactor_events(record) -> bool: return ( "iocp" not in record["message"] and "proactor" not in record["message"] ) def filter_long_polling(record) -> bool: """过滤长轮询接口的日志""" return ( "/api/max/get_task_info" in record["message"] or "/api/max/get_next_task" in record["message"] or "/api/max/get_order_info" in record["message"] or "/api/max/mcp/get_unplanned_order" in record["message"] ) def filter_sqlalchemy(record) -> bool: """过滤 sqlalchemy 的日志""" return record["name"].startswith("sqlalchemy.engine") def ignore_log_in_console(record) -> bool: """忽略部分日志在控制台输出 1. 忽略 proactor_events loop debug 日志 2. 忽略 DEBUG 级别日志 3. 忽略监听日志 4. 忽略轮询接口的日志 """ if "iocp" in record["message"] or record["message"].startswith( "proactor_events loop debug" ): return False if ( record["level"].name == "DEBUG" and os.environ.get("MAX_HMI_ENV") != "dev" ): return False if record["name"] == "xyz_max_hmi_server.modules.monitor.listener": if record["function"] == "f": return False if record["function"] == "run": return False if ( "/api/max/get_task_info" in record["message"] or "/api/max/get_next_task" in record["message"] or "/api/max/get_order_info" in record["message"] or "/api/max/mcp/get_unplanned_order" in record["message"] ): return False return True def ignore_wcs_mock_server(record) -> bool: return record["thread"].name != "WCSMockServer"
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\mixin.py
from typing import Optional from xyz_max_hmi_server import enums class EventMessageMixin: """事件消息混入类""" event_type: Optional[enums.EventType] = None def __init__(self, event_type: enums.EventType): self.event_type = event_type def set_msg_event(self, event: enums.EventType): """设置消息事件. Args: event(EventType): 事件枚举值. """ self.event_type = event return self def disable_msg_event(self): """禁用消息事件 Examples: >>> raise XYZException().disable_msg_event() """ self.event_type = None return self class OrderInfoEventMessageMixin(EventMessageMixin): """订单信息事件消息混入类""" def __init__(self): super().__init__(enums.EventType.ORDER_LOG)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\mock_wcs.py
"""模拟 WCS 服务. 从所有的工作流类中提取 WCS 接口路径,生成 API。 """ from threading import Thread import uvicorn from fastapi import FastAPI, Request from loguru import logger from xyz_max_hmi_server import settings from xyz_max_hmi_server.modules.workflow.workflow import WORKFLOW_CLASSES PATHS = [] def collect_path() -> list: """收集路径""" paths = [] for clazz in WORKFLOW_CLASSES: paths.extend(extract_path_from_workflow_class(clazz)) return list(set(paths)) def extract_path_from_workflow_class(clazz: object) -> list: """从工作流类中提取路径""" paths = [] # 读取 clazz 的类变量 clazz_vars = clazz.__dict__ for key in clazz_vars: if not key.startswith("api_"): continue value = clazz_vars[key] if isinstance(value, str): if value.startswith("/"): paths.append(value) else: paths.append("/" + value) return paths def gen_api(app: FastAPI, path: str): """生成API""" @app.post(path) @app.get(path) async def api(request: Request): logger.info( "{path} - {method} - {body}", path=path, method=request.method, body=await request.body(), ) return {"path": path} def _start_server(): app = FastAPI() paths = collect_path() for path in paths: gen_api(app, path) uvicorn.run(app, port=settings.wcs.port) PATHS.extend(paths) def start_mock_server(): """启动模拟 WCS 服务""" t = Thread(target=_start_server, name="WCSMockServer") t.daemon = True t.start() logger.info(f"WCS 模拟服务已启动, PORT: {settings.wcs.port}")
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\monkey.py
""" 猴子补丁 """ import json import re from datetime import date, datetime _OLD_JSON_ENCODER = json.JSONEncoder _OLD_JSON_DECODER = json.JSONDecoder class JsonEncoder(_OLD_JSON_ENCODER): """ 重写json.JSONEncoder,用于处理 datetime/date 类型 Example: >>> import json >>> from datetime import datetime, date >>> json.dumps({"datetime": datetime.now(), "date": date.today()}) """ def default(self, obj): if isinstance(obj, datetime): return obj.strftime("%Y-%m-%d %H:%M:%S") elif isinstance(obj, date): return obj.strftime("%Y-%m-%d") else: return _OLD_JSON_ENCODER.default(self, obj) class JsonDecoder(_OLD_JSON_DECODER): """ 重写json.JSONDecoder,用于处理 datetime/date 类型 """ def __init__(self, *args, **kwargs): super().__init__(object_hook=self.object_hook, *args, **kwargs) def object_hook(self, obj): for key, value in obj.items(): # 使用正则表达式判断是否为日期时间格式 if isinstance(value, str) and re.match( r"^\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}$", value ): try: obj[key] = datetime.strptime(value, "%Y-%m-%d %H:%M:%S") except ValueError: pass # 使用正则表达式判断是否为日期格式 elif isinstance(value, str) and re.match( r"^\d{4}-\d{1,2}-\d{1,2}$", value ): try: obj[key] = datetime.strptime(value, "%Y-%m-%d") except ValueError: pass return obj def monkey_patch(): """ 猴子补丁 """ json._default_encoder = JsonEncoder( # type: ignore skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, )
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\responses.py
from typing import Optional from fastapi.responses import JSONResponse, StreamingResponse from starlette.responses import ContentStream def make_std_json_repsonse( code: int, msg: str, data: Optional[dict] = None ) -> JSONResponse: """生成JSON格式的响应数据.""" return JSONResponse( status_code=code, content={"code": code, "msg": msg, "data": data}, ) class STDJSONResponse(JSONResponse): """标准的JSON响应数据.""" def __init__( self, code: int = 0, msg: str = "success", data: Optional[dict] = None, status_code: int = 200, ) -> None: """初始化.""" super().__init__( status_code=status_code, content={"code": code, "msg": msg, "data": data}, ) class ErrorJSONResponse(STDJSONResponse): """错误的JSON响应数据.""" def __init__( self, code: int = -1, msg: str = "error", data: Optional[dict] = None, status_code: int = 200, ) -> None: """初始化.""" self.is_error_happened = True super().__init__( code=code, msg=msg, data=data, status_code=status_code, ) class XLSXResponse(StreamingResponse): """XLSX响应数据.""" def __init__( self, content: ContentStream, filename: str, status_code: int = 200, headers: Optional[dict] = None, ) -> None: """初始化.""" super().__init__( content=content, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", status_code=status_code, headers=headers, ) self.filename = filename self.headers["Access-Control-Allow-Headers"] = "*" self.headers["Access-Control-Expose-Headers"] = "Content-Disposition" self.headers["Content-Disposition"] = f"attachment; filename={filename}"
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\route.py
import json from typing import Callable from fastapi import Request, Response from fastapi.exceptions import RequestValidationError from fastapi.routing import APIRoute from loguru import logger from xyz_max_hmi_server.exceptions import XYZException class EnhancedAPIRoute(APIRoute): """APIRoute 增强,报错时会打印堆栈信息及运行时的值 使用 loguru.catch 捕获异常并输出堆栈信息 """ def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def route_handler(request: Request) -> Response: try: if request.method != "GET, HEAD": content_type = request.headers.get("content-type") if content_type is None: content_type = request.headers.get("Content-Type") if content_type and "json" in content_type: try: json_data = await request.json() except json.decoder.JSONDecodeError: json_data = await request.body() logger.debug( "{} - Request: {}", request.url.path, json_data, ) resp = await original_route_handler(request) if resp.headers["content-type"] == "application/json": logger.debug( "{} - Response: {}", request.url.path, json.loads(resp.body), ) return resp except XYZException as e: logger.warning(e.error_message) raise e except RequestValidationError as e: logger.warning(e) raise e except Exception as e: logger.exception(e) raise e return route_handler
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\router.py
from enum import Enum from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union from fastapi import APIRouter, params from fastapi.datastructures import Default from fastapi.types import DecoratedCallable from fastapi.utils import generate_unique_id from starlette import routing from starlette.responses import JSONResponse, Response from starlette.routing import BaseRoute # noqa from starlette.routing import Mount as Mount from starlette.types import ASGIApp from .route import EnhancedAPIRoute as APIRoute class EnhancedAPIRouter(APIRouter): def __init__( self, *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: super().__init__( prefix=prefix, tags=tags, dependencies=dependencies, default_response_class=default_response_class, responses=responses, callbacks=callbacks, routes=routes, redirect_slashes=redirect_slashes, default=default, dependency_overrides_provider=dependency_overrides_provider, route_class=route_class, on_startup=on_startup, on_shutdown=on_shutdown, deprecated=deprecated, include_in_schema=include_in_schema, generate_unique_id_function=generate_unique_id_function, ) def api_route( self, path: str, *, include_in_schema: bool = True, **kwargs: Any ) -> Callable[[DecoratedCallable], DecoratedCallable]: """增加一个路由,同时增加一个以 / 结尾的路由,用于兼容以 / 结尾的请求. Ref: https://github.com/tiangolo/fastapi/issues/2060#issuecomment-834868906 """ if path.endswith("/"): path = path[:-1] add_path = super().api_route( path, include_in_schema=include_in_schema, **kwargs ) alternate_path = path + "/" add_alternate_path = super().api_route( alternate_path, include_in_schema=False, **kwargs ) def decorator(func: DecoratedCallable) -> DecoratedCallable: add_alternate_path(func) return add_path(func) return decorator
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\test_server.py
"""用于测试时的Server""" import asyncio from typing import List, Optional import uvicorn class UvicornTestServer(uvicorn.Server): """Uvicorn test server Usage: @pytest.fixture async def start_stop_server(): server = UvicornTestServer() await server.up() yield await server.down() """ def __init__( self, app, host: str = "127.0.0.1", port: int = 7077, ): """Create a Uvicorn test server Args: app (FastAPI, optional): the FastAPI app. Defaults to main.app. host (str, optional): the host ip. Defaults to '127.0.0.1'. port (int, optional): the port. Defaults to PORT. """ # app.sio.eio.start_service_task = False self._startup_done = asyncio.Event() super().__init__(config=uvicorn.Config(app, host=host, port=port)) async def startup(self, sockets: Optional[List] = None) -> None: """Override uvicorn startup""" await super().startup(sockets=sockets) # type: ignore self.config.setup_event_loop() self._startup_done.set() async def up(self) -> None: """Start up server asynchronously""" self._serve_task = asyncio.create_task(self.serve()) await self._startup_done.wait() async def down(self) -> None: """Shut down server asynchronously""" self.should_exit = True await self._serve_task
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\version.py
__version__ = "1.6.2"
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\__init__.py
import os import sys from pathlib import Path # FIXME: 仅从 studio-max/bin 目录启动时,才能正确设置 MAX_HMI_STUDIO_MAX_DIR # 所以,这里应该在 bin/hmi_server.py 中设置 if "MAX_HMI_STUDIO_MAX_DIR" not in os.environ: current_file_path = Path(__file__).parent.resolve() os.environ["MAX_HMI_STUDIO_MAX_DIR"] = current_file_path.parents[ 3 ].as_posix() # NOTE: 临时解决方案,后续需要修改 # 假设 xyz_max_hmi_server 是安装在 xyz_studio_max/lib/python/dist-packages/xyz_max_hmi_server for arg in sys.argv: if arg == "--studio-max-dir": try: dir = sys.argv[sys.argv.index(arg) + 1] except IndexError: raise RuntimeError("MAX HMI Studio dir not specified") from None if not os.path.exists(dir): raise FileNotFoundError(f"MAX HMI Studio dir not exists: {dir}") os.environ["MAX_HMI_STUDIO_MAX_DIR"] = dir break p = ( Path(os.environ["MAX_HMI_STUDIO_MAX_DIR"]) / "lib/python/dist-packages" ).as_posix() if p not in sys.path: sys.path.insert(0, p) third_party_path = ( Path(os.environ["MAX_HMI_STUDIO_MAX_DIR"]) / "lib/python/dist-packages/xyz_max_hmi_server/third_party_packages" ).as_posix() if third_party_path not in sys.path: sys.path.insert(0, third_party_path) from .monkey import monkey_patch monkey_patch() if os.name == "posix": from setproctitle import setproctitle as __setproctitle # 设置进程名 __setproctitle("xyz_max_hmi_server") from fastapi import Body as Body, Depends as Depends from .app import ( Application as Application, cached_app as cached_app, create_app as create_app, ) from .config import settings as settings from .db.session import ( db as db, get_db as get_db, provide_session as provide_session, start_session as start_session, ) from .entity.order import LiteOrder as LiteOrder from .entity.sku import SKUInfo as SKUInfo from .entity.task import LiteTask as LiteTask from .globals import system_status as system_status, wcs_status as wcs_status from .log import logger as logger from .modules.cycle import current_cycle as current_cycle from .modules.error_map import ErrorMap as ErrorMap from .modules.global_variable import g as g from .modules.grpc.client.max import MaxClient as MaxClient from .modules.grpc.client.robot_driver import ( RobotDriverClient as RobotDriverClient, ) from .modules.manager import ( OrderManager as OrderManager, TaskManager as TaskManager, WorkspaceManager as WorkspaceManager, ) from .modules.message_pusher import MessagePusher as MessagePusher from .modules.monitor import monitor as monitor from .modules.notify import notify as notify from .modules.plc import plc_manager as plc_manager from .responses import ( STDJSONResponse as STDJSONResponse, make_std_json_repsonse as make_std_json_repsonse, ) from .route import APIRoute as APIRoute, EnhancedAPIRoute as EnhancedAPIRoute from .router import ( APIRouter as APIRouter, EnhancedAPIRouter as EnhancedAPIRouter, ) from .schemas.base import List as List, Page as Page, Std as Std from .utils import db_util as db_util from .utils.i18n import _ as _, gettext as gettext from .version import __version__ as __version__
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\__main__.py
import os import re import sys from pathlib import Path current_file_path = Path(__file__).parent.resolve() os.environ["MAX_HMI_STUDIO_MAX_DIR"] = current_file_path.parents[3].as_posix() sys.path.insert( 0, os.environ["MAX_HMI_STUDIO_MAX_DIR"] + "/lib/python/dist-packages", ) sys.path.insert( 0, os.environ["MAX_HMI_STUDIO_MAX_DIR"] + "/lib/python/dist-packages/xyz_max_hmi_server/third_party_packages", ) from xyz_max_hmi_server.cmdline import main if __name__ == "__main__": sys.argv[0] = re.sub(r"(-script\.pyw|\.exe)?$", "", sys.argv[0]) sys.exit(main())
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\api.py
from fastapi import APIRouter from xyz_max_hmi_server.api.endpoints import registry from .endpoints import ( base, data, error_records, io, manager, order_log, pipe, plc, robot, robot_driver, setting, subapp, task_batch, task_results, topic, vp, ) api_router = APIRouter() api_router.include_router(base.router) api_router.include_router( error_records.router, prefix="/error_records", tags=["异常记录"] ) api_router.include_router( task_results.router, prefix="/task_results", tags=["历史任务"] ) api_router.include_router(manager.router, prefix="/manager", tags=["订单和任务管理"]) api_router.include_router(pipe.router, prefix="/ws", tags=["Websocket 通信"]) api_router.include_router(order_log.router, prefix="/order_log", tags=["订单日志"]) api_router.include_router(topic.router, prefix="/topic", tags=["Topic"]) api_router.include_router(vp.router, prefix="/vp", tags=["VP"]) api_router.include_router(setting.router, prefix="/setting", tags=["系统设置"]) api_router.include_router(plc.router, prefix="/plc", tags=["PLC"]) # Deprecated: 2023-06-20, Version: 1.2.3 api_router.include_router( robot_driver.router, prefix="/robot_driver", tags=["机械臂驱动"], deprecated=True, ) api_router.include_router(io.router, prefix="/io", tags=["IO设备"]) api_router.include_router( task_batch.router, prefix="/task_batch", tags=["任务批次"] ) api_router.include_router(registry.router, prefix="/registry", tags=["注册中心"]) api_router.include_router(data.router, prefix="/data", tags=["数据统计"]) api_router.include_router(robot.router, prefix="/robot", tags=["Robot"]) api_router.include_router(subapp.router, prefix="/subapp", tags=["子应用"])
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\deps.py
from xyz_max_hmi_server.exceptions import XYZException from xyz_max_hmi_server.modules.manager import OrderManager, TaskManager def get_task_manager(): tm = TaskManager._get_subinstance() if tm is None: raise XYZException("TaskManager is not initialized.") return tm def get_order_manager(): om = OrderManager._get_subinstance() if om is None: raise XYZException("OrderManager is not initialized.") return om
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\base.py
from pydantic import BaseModel from xyz_max_hmi_server import EnhancedAPIRouter, enums, system_status from xyz_max_hmi_server.schemas.base import Std router = EnhancedAPIRouter() class SystemStatusSchema(BaseModel): # noqa: D101 status: enums.SystemStatus @router.get("/status", summary="获取系统状态", response_model=Std[SystemStatusSchema]) async def get_system_status(): """获取系统状态 该接口用于获取系统状态,返回值为枚举类型,具体值如下: 0: 就绪 1: 运行中 99: 异常/停止 """ return { "status": system_status.status, "message": system_status.status.name.lower(), }
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\data.py
"""数据相关的接口.""" from datetime import datetime from typing import Optional from loguru import logger from xyz_max_hmi_server import EnhancedAPIRouter, crud, enums from xyz_max_hmi_server.exceptions import XYZException from xyz_max_hmi_server.schemas.base import Std router = EnhancedAPIRouter() @router.get("/cycle", name="获取节拍数据", response_model=Std) def cycle( start_time: Optional[datetime] = None, end_time: Optional[datetime] = None ): """获取节拍数据, 完成的抓放总数和总耗时.""" # 统计历史任务的数据 total_completed_count = crud.task_result.get_total_completed_count( start_time, end_time ) total_elapsed_time = crud.task_result.get_total_elapsed_time( start_time, end_time ) # 统计正在执行中的数据 task = crud.task.first(is_ready=True, by_priority=True) if task and task.task_status != enums.TaskStatus.RECEIVED: total_completed_count += task.done_num if task.start_time is None: logger.warning("任务开始时间为空") else: total_elapsed_time += (datetime.now() - task.start_time).seconds # type: ignore return { "total_completed_count": total_completed_count, "total_elapsed_time": total_elapsed_time, }
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\dpt.py
from xyz_max_hmi_server import EnhancedAPIRouter from xyz_max_hmi_server.exceptions import XYZException from xyz_max_hmi_server.schemas.base import Std router = EnhancedAPIRouter() @router.post("/add_box", summary="添加箱子", response_model=Std) def add_box(): """添加箱子.""" raise XYZException(error_message="正在开发中", status_code=400) @router.post("/remove_box", summary="移除箱子", response_model=Std) def remove_box(): """移除箱子.""" raise XYZException(error_message="正在开发中", status_code=400)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\error_records.py
import io import time from typing import List from urllib.parse import quote import pandas as pd from fastapi.encoders import jsonable_encoder from fastapi.responses import StreamingResponse from fastapi_filter.base.filter import FilterDepends from sqlalchemy.orm import Query from xyz_max_hmi_server import EnhancedAPIRouter as APIRouter, _, crud from xyz_max_hmi_server.db.session import db from xyz_max_hmi_server.exceptions import XYZNotFoundError from xyz_max_hmi_server.schemas.base import Page, Std from xyz_max_hmi_server.schemas.error_records import ( ErrorRecord, ErrorRecordFilter, ) from xyz_max_hmi_server.utils.db_util import paginate router = APIRouter() @router.get("/", name="查询多个异常记录", response_model=Page[ErrorRecord]) def list_error_records( error_filter: ErrorRecordFilter = FilterDepends(ErrorRecordFilter), ): """获取多个异常记录""" query = crud.error_records.get_query(db.session) query = error_filter.filter(query) query = error_filter.sort(query) return paginate(query) @router.get("/download", name="下载异常记录") def download_error_records( error_filter: ErrorRecordFilter = FilterDepends(ErrorRecordFilter), ): """下载异常记录""" query = crud.error_records.get_query(db.session) query = error_filter.filter(query) query = error_filter.sort(query) if isinstance(query, Query): records: List[ErrorRecord] = query.all() else: raise TypeError("query应为sqlalchemy.orm.query.Query类型") headers = { "id": _("ID"), "error_code": _("异常码"), "error_msg": _("异常消息"), "error_source": _("异常来源"), "tip": _("操作提示"), "task": _("任务快照"), "create_time": _("创建时间"), } df = pd.DataFrame.from_records( [jsonable_encoder(record) for record in records] ) if df.empty: # 如果没有数据, to_csv 时保留表头 df = pd.DataFrame(columns=list(headers.values())) else: for k, v in headers.items(): df.rename(columns={k: v}, inplace=True) # 删除 update_time 字段 df.drop(columns=["update_time"], inplace=True) # 转换时间格式 df[_("创建时间")] = pd.to_datetime(df[_("创建时间")]).dt.strftime( "%Y-%m-%d %H:%M:%S" ) # 按照 异常码, 异常消息, 异常来源, 异常提示, 任务快照, 创建时间 编排 df = df[headers.values()] text = df.to_csv(index=False, encoding="utf-8") fp = io.BytesIO(text.encode(encoding="utf-8")) filename = "{filename}-{datetime}.csv".format( filename=quote(_("异常记录")), datetime=time.strftime("%Y%m%d%H%M%S", time.localtime()), ) return StreamingResponse( fp, headers={ "Content-Type": "application/octet-stream", "Content-Disposition": f"attachment; filename={filename}", "Access-Control-Allow-Headers": "*", "Access-Control-Expose-Headers": "Content-Disposition", }, media_type="text/csv", ) # wb = xw.Workbook(output, {"in_memory": True}) # wsh = wb.add_worksheet("sheet1") # headers = ["异常码", "异常消息", "异常来源", "异常提示", "任务快照", "创建时间"] # for i, header in enumerate(headers): # wsh.write(0, i, header) # for i, record in enumerate(records): # j = i + 1 # wsh.write(j, 0, record.error_code) # wsh.write(j, 1, record.error_msg) # wsh.write(j, 2, record.error_source and record.error_source.value) # wsh.write(j, 3, record.tip) # wsh.write(j, 4, json.dumps(record.task)) # wsh.write(j, 5, record.create_time) # # set title format # wsh.set_row(0, 20, wb.add_format({"bold": True, "align": "center"})) # # set format # wsh.set_column( # 5, 5, 20, wb.add_format({"num_format": "yyyy-mm-dd hh:mm:ss"}) # ) # wb.close() # output.seek(0) # return XLSXResponse( # content=output, # filename=f"error_records_{int(time.time())}.xlsx", # ) @router.get("/{id}", name="查询单个异常记录", response_model=Std[ErrorRecord]) def get_error_record(id: int): """获取异常记录""" if error_record := crud.error_records.get(id, session=db.session): return error_record raise XYZNotFoundError("异常记录(id: {id})不存在".format(id=id))
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\io.py
from pydantic import BaseModel, Field from xyz_max_hmi_server import EnhancedAPIRouter from xyz_max_hmi_server.exceptions import XYZException, XYZNotFoundError from xyz_max_hmi_server.io_config import IOConfig from xyz_max_hmi_server.schemas.base import List, _list router = EnhancedAPIRouter() class IODeviceSchema(BaseModel): id: str = Field(..., description="设备ID") name: str = Field(..., description="设备名称") @router.get( "/device", summary="获取IO设备列表", response_model=List[IODeviceSchema], ) def get_io_devices(): """获取 I/O 设备列表. 如果 I/O 列表为空,则报错. """ try: results = IOConfig().get_devices() if not results: raise XYZException("I/O 设备列表为空, 请先配置 I/O 设备。") return _list(results) except FileNotFoundError: raise XYZNotFoundError("I/O 配置文件不存在。")
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\order_log.py
from fastapi import Query from fastapi.encoders import jsonable_encoder from xyz_max_hmi_server import EnhancedAPIRouter as APIRouter from xyz_max_hmi_server.modules.message_pusher.cache import order_log_cache from xyz_max_hmi_server.modules.message_pusher.models import OrderLog from xyz_max_hmi_server.modules.message_pusher.push import MessagePusher from xyz_max_hmi_server.schemas.base import List, Std, _list router = APIRouter() __mp = MessagePusher() @router.post("/", response_model=Std, summary="添加订单日志") @router.post("/send_order_log", response_model=Std, summary="添加订单日志") def add_order_log(order_log: OrderLog): """添加订单日志""" data = order_log.dict() __mp.order.send(jsonable_encoder(data)) return {} @router.get("/", response_model=List[OrderLog], summary="获取订单日志") def get_order_log(max_lines: int = Query(1000, ge=1, le=2000)): """获取最近的订单日志信息""" return _list(order_log_cache.get_last(max_lines))
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\pipe.py
import json from fastapi import Query, WebSocket, WebSocketDisconnect, status from loguru import logger from xyz_max_hmi_server import EnhancedAPIRouter as APIRouter from xyz_max_hmi_server.modules.manager import WebsocketManager from xyz_max_hmi_server.schemas.pipe import Request, Response from xyz_max_hmi_server.signals import pipe router = APIRouter() websocket_manager = WebsocketManager() @router.websocket("/") async def websocket_endpoint( websocket: WebSocket, token: str = Query(...), ): """This endpoint will be called when the client connects to the websocket.""" await websocket.accept() await websocket_manager.add_or_replace(websocket, token) logger.info( "Client connected to websocket, id: '{}'", websocket_manager.get_id(websocket), ) logger.info("Current websocket count: {}", websocket_manager.count()) while True: try: data = await websocket.receive_json() logger.info( "ws_id: {}, data: {}", websocket_manager.get_id(websocket), data ) except WebSocketDisconnect: logger.info( "Client disconnected from websocket, id: '{}'", websocket_manager.get_id(websocket), ) break except json.decoder.JSONDecodeError: logger.error("Invalid json format") await websocket.send_json( Response( code=-1, msg="Invalid json format", ).dict() ) await websocket.close( code=status.WS_1003_UNSUPPORTED_DATA, reason="Invalid json format", ) break try: request = Request(**data) except Exception as e: logger.opt(exception=e).error("解析请求数据失败") await websocket.send_json( Response( code=-1, msg="Invalid request", ).dict() ) await websocket.close( code=status.WS_1007_INVALID_FRAME_PAYLOAD_DATA, reason="Invalid request", ) break else: signal = pipe.get_signal_by_event(request.event) signal.send(websocket, request=request) websocket_manager.remove(websocket)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\plc.py
from typing import Literal from fastapi import Body from xyz_max_hmi_server import EnhancedAPIRouter, enums, plc_manager from xyz_max_hmi_server.schemas.base import Std from xyz_max_hmi_server.schemas.plc import LightSchema from xyz_max_hmi_server.schemas.robot import ( ControlRobotSchema, RobotModeSchema, RobotStatusSchema, ) router = EnhancedAPIRouter() @router.post("/buzzer", summary="控制蜂鸣器", response_model=Std) def control_buzzer(action: Literal["open", "close"] = Body(..., embed=True)): """控制蜂鸣器""" getattr(plc_manager.buzzer, action)() return {} @router.post("/grating", summary="控制光栅", response_model=Std) def control_grating(action: Literal["open", "close"] = Body(..., embed=True)): """控制光栅""" getattr(plc_manager.grating, action)() return {} @router.post("/robot", summary="控制机器人", response_model=Std) def control_robot(control_robot_schema: ControlRobotSchema): """控制机器人""" getattr(plc_manager.robot, control_robot_schema.action.value)() return {} @router.get( "/robot/status", summary="获取机器人状态", response_model=Std[RobotStatusSchema] ) def get_robot_status(): """获取机器人状态""" return {"status": plc_manager.robot.get_status()} @router.get( "/robot/mode", summary="获取机器人模式", response_model=Std[RobotModeSchema] ) def get_robot_mode(): """获取机器人模式""" if plc_manager.robot.is_auto_mode(): return {"mode": enums.RobotMode.AUTO} return {"mode": enums.RobotMode.MANUAL} @router.get("/light", summary="获取三色灯状态", response_model=Std[LightSchema]) def get_light_status(): """获取三色灯状态""" return plc_manager.light.get_status()
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\registry.py
from typing import Dict from pydantic import BaseModel from xyz_max_hmi_server import EnhancedAPIRouter from xyz_max_hmi_server.exceptions import XYZException from xyz_max_hmi_server.modules.grpc.registry import SERVICES, registry from xyz_max_hmi_server.schemas.base import Std router = EnhancedAPIRouter() class ServiceSchema(BaseModel): # noqa: D101 host: str port: int @router.get( "/services", summary="获取所有服务", response_model=Std[Dict[str, ServiceSchema]] ) def get_services(): """获取所有服务""" services = {} for service_name, service in registry.list().items(): services[service_name] = { "host": service.host, "port": service.port, } return services @router.get( "/service/{name}", summary="获取服务", response_model=Std[ServiceSchema] ) def get_service(name: SERVICES): """获取服务""" service = registry.find(name) return { "host": service.host, "port": service.port, }
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\robot.py
from xyz_max_hmi_server import EnhancedAPIRouter from xyz_max_hmi_server.modules.grpc.client.max import MaxClient from xyz_max_hmi_server.schemas.base import List, Std, _list router = EnhancedAPIRouter() @router.post("/restart", summary="重启机械臂", response_model=Std) def restart_robot(is_simulation: bool = False): """重启机械臂""" MaxClient().restart_robot(is_simulation=is_simulation) return {} @router.post("/stop", summary="停止机械臂", response_model=Std) def stop_robot(): """停止机械臂""" MaxClient().stop_robot() return {} @router.get("/status", summary="获取机械臂状态", response_model=List[dict]) def get_robot_status(): """获取机械臂状态""" client = MaxClient() data = client.get_robot_status() return _list(data)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\robot_driver.py
from dataclasses import dataclass from typing import cast from fastapi import Depends from xyz_max_hmi_server import EnhancedAPIRouter, enums from xyz_max_hmi_server.modules.cyber import Cyber from xyz_max_hmi_server.modules.cyber.client.robot_driver import ( RobotDriverCyberClient, ) from xyz_max_hmi_server.schemas.base import Std router = EnhancedAPIRouter() robot_driver_client = cast(RobotDriverCyberClient, None) def get_client(): global robot_driver_client # TODO: client name 必须固定 # 所以,考虑将 client name 写死在 CyberClient 中 if robot_driver_client: return robot_driver_client robot_driver_client = ( Cyber() .get_or_create_node(enums.CyberNodeName.RobotDriver) .get_or_create_client( "RobotServerServiceManager", RobotDriverCyberClient ) ) return robot_driver_client @dataclass class ResponseSchema: status: enums.RobotDriverStatus status_name: str class Config: schema_extra = { "example": { "status": 2, "status_name": "CONNECTED", } } @router.post("/start", response_model=Std[ResponseSchema]) def start(client: RobotDriverCyberClient = Depends(get_client)): """连接机械驱动""" if client.get_status() == enums.RobotDriverStatus.CONNECTED: return ResponseSchema( status=enums.RobotDriverStatus.CONNECTED, status_name=enums.RobotDriverStatus.CONNECTED.name.lower(), ) client.start() status = client.get_status() return ResponseSchema( status=status, status_name=enums.RobotDriverStatus(status).name.lower(), ) @router.post("/stop", response_model=Std[ResponseSchema]) def stop(client: RobotDriverCyberClient = Depends(get_client)): """断开机械驱动""" client.stop() status = client.get_status() return ResponseSchema( status=status, status_name=enums.RobotDriverStatus(status).name.lower(), ) @router.get("/status", response_model=Std[ResponseSchema]) def status(client: RobotDriverCyberClient = Depends(get_client)): """获取机械驱动状态""" status = client.get_status() return ResponseSchema( status=status, status_name=enums.RobotDriverStatus(status).name.lower(), )
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\setting.py
from fastapi import Body, File, UploadFile from fastapi.responses import FileResponse from xyz_max_hmi_server import EnhancedAPIRouter, enums from xyz_max_hmi_server.config import settings from xyz_max_hmi_server.exceptions import XYZException, XYZNotFoundError from xyz_max_hmi_server.schemas.base import Std router = EnhancedAPIRouter() @router.get("/logo", summary="获取logo", response_class=FileResponse) async def get_logo(): """获取 logo""" if (settings.workdir / "statics/images/logo.png").exists(): return FileResponse(settings.workdir / "statics/images/logo.png") raise XYZNotFoundError("文件不存在") @router.post("/logo", summary="上传logo", response_model=Std) async def upload_logo(logo: UploadFile = File(...)): """上传 logo, 文件大小不能超过2M""" if logo.content_type not in ("image/png", "image/jpeg"): raise XYZException("文件类型不支持", status_code=415) file_path = settings.workdir / "statics/images/logo.png" if not file_path.parent.exists(): file_path.parent.mkdir(parents=True) with open(file_path, "wb") as f: content = await logo.read() if len(content) > 1024 * 1024 * 2: raise XYZException("文件大小不能超过2M", status_code=413) f.write(content) return {} @router.get("/lang", summary="获取语言", response_model=Std) async def get_language(): """获取语言""" return {"lang": settings.system.language.name.lower()} @router.post("/lang", summary="设置语言", response_model=Std) async def set_language( lang: enums.LanguageType = Body(..., embed=True) # noqa: B008 ): """设置语言""" from xyz_max_hmi_server.babel import babel settings.system.language = lang babel.locale = lang.name.lower() return {}
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\subapp.py
from xyz_max_hmi_server import EnhancedAPIRouter from xyz_max_hmi_server.schemas.base import Std from xyz_max_hmi_server.utils import subapp router = EnhancedAPIRouter() @router.get("/reload", summary="重载 Adaptor", response_model=Std[dict]) def reload(): """重载 Adaptor""" subapp.reload() return {}
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\task_batch.py
"""批次相关接口""" import collections from fastapi import Query from fastapi.encoders import jsonable_encoder from xyz_max_hmi_server import EnhancedAPIRouter as APIRouter, crud from xyz_max_hmi_server.exceptions import XYZNotFoundError from xyz_max_hmi_server.schemas.base import List, Std, _list from xyz_max_hmi_server.schemas.task_batch import TaskBatch router = APIRouter() @router.get("/get_batch_id", name="获取批次号", response_model=Std[TaskBatch]) def get_batch_id(task_id: str = Query(..., title="任务编号")): """通过任务编号获取批次编号""" record = crud.task_batch.get_batch(task_id) if not record: raise XYZNotFoundError("未找到对应批次号") return jsonable_encoder(record) @router.get( "/list_batchs_and_task_count", name="列出所有批次号以及对应的任务数量", response_model=List[dict], ) def list_batchs_and_task_count(): """列出所有批次号以及对应的任务数量""" results = collections.OrderedDict() records = crud.task_batch.all() for record in records: if record.batch_id not in results: results[record.batch_id] = 0 results[record.batch_id] += 1 return _list([{"batch_id": k, "task_count": v} for k, v in results.items()]) @router.get("/{batch_id}", name="查看批次", response_model=Std[dict]) def get_batch(batch_id: str): """查看批次详情""" count = crud.task_batch.count(batch_id) if count == 0: task_ids = [] else: task_ids = crud.task_batch.get_task_ids(batch_id) return {"batch_id": batch_id, "task_count": count, "task_ids": task_ids} @router.get("/", name="列出批次记录", response_model=List[TaskBatch]) def list_batchs(): """列出所有批次记录""" records = crud.task_batch.all() results = [jsonable_encoder(record) for record in records] return _list(results)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\task_results.py
"""历史任务""" import io import time from typing import List from urllib.parse import quote import pandas as pd from fastapi.encoders import jsonable_encoder from fastapi.responses import FileResponse, StreamingResponse from fastapi_filter.base.filter import FilterDepends from fastapi_sqlalchemy import db from sqlalchemy.orm import Query from xyz_max_hmi_server import EnhancedAPIRouter as APIRouter, _, crud from xyz_max_hmi_server.entity.task_result import TaskResult from xyz_max_hmi_server.exceptions import XYZNotFoundError from xyz_max_hmi_server.schemas.base import Page, Std from xyz_max_hmi_server.schemas.task_result import TaskFilter from xyz_max_hmi_server.utils.db_util import paginate router = APIRouter() @router.get( "/", name="查询多个任务执行结果", response_model=Page[TaskResult], ) def get_task_results( task_filter: TaskFilter = FilterDepends(TaskFilter), ): """获取多个任务结果""" query = crud.task_result.get_query(db.session) query = task_filter.filter(query) query = task_filter.sort(query) return paginate(query) @router.get("/download", name="下载任务执行结果", response_class=FileResponse) def download_task_result( task_filter: TaskFilter = FilterDepends(TaskFilter), ): """下载历史任务文件.""" query = crud.task_result.get_query(db.session) query = task_filter.filter(query) query = task_filter.sort(query) if isinstance(query, Query): records: List[TaskResult] = query.all() else: raise TypeError("query应为sqlalchemy.orm.query.Query类型") headers = { "id": _("ID"), "task_id": _("任务ID"), "order_id": _("订单ID"), "task_type": _("任务类型"), "task_status": _("任务状态"), "sku_info": _("物料信息"), "done_num": _("完成数量"), "target_num": _("目标数量"), "to_ws": _("放置位"), "from_ws": _("抓取位"), "start_time": _("开始时间"), "end_time": _("结束时间"), "create_time": _("创建时间"), } df = pd.DataFrame.from_records( [jsonable_encoder(record) for record in records] ) if df.empty: df = pd.DataFrame(columns=list(headers.values())) else: for k, v in headers.items(): if k in df.columns: df.rename(columns={k: v}, inplace=True) else: df.drop(columns=[k], inplace=True) df = df[headers.values()] text = df.to_csv(index=False, encoding="utf-8") fp = io.BytesIO(text.encode(encoding="utf-8")) filename = "{filename}-{datetime}.csv".format( filename=quote(_("任务执行结果")), datetime=time.strftime("%Y%m%d%H%M%S", time.localtime()), ) return StreamingResponse( fp, headers={ "Content-Type": "application/octet-stream", "Content-Disposition": f"attachment; filename={filename}", "Access-Control-Allow-Headers": "*", "Access-Control-Expose-Headers": "Content-Disposition", }, media_type="text/csv", ) @router.get("/{id}", name="查询任务执行结果详情", response_model=Std[TaskResult]) def get_task_result(id: int): """获取任务结果""" if task_result := crud.task_result.get(id, session=db.session): return task_result raise XYZNotFoundError("任务结果(id: {id})不存在".format(id=id))
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\topic.py
from xyz_max_hmi_server import EnhancedAPIRouter from xyz_max_hmi_server.modules.cyber import utils as cyber_utils from xyz_max_hmi_server.schemas.base import List, _list from xyz_max_hmi_server.schemas.pipe import TopicInfo from xyz_max_hmi_server.utils.message2jsonschema import message2jsonschema router = EnhancedAPIRouter() @router.get("/", response_model=List[TopicInfo], summary="获取所有已注册的topic") def get_topics(): """获取所有已激活的topic""" topics = cyber_utils.get_channels(1) data = [] for topic in topics: clazz = cyber_utils.get_msgtype(topic, 0) if clazz is None: continue jsonschema = message2jsonschema(clazz) data.append(TopicInfo(topic_name=topic, schema=jsonschema)) return _list(data)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\vp.py
from typing import Optional from fastapi import Body from xyz_max_hmi_server import APIRouter from xyz_max_hmi_server.schemas.base import Std from xyz_max_hmi_server.utils.vp import vp_utils router = APIRouter() @router.post("/run", summary="运行 VP 流图", response_model=Std) def run_vp(name: Optional[str] = Body(None, embed=True, title="流图名称")): """运行 VP 流图 Args: name(str or None): Default: None, 流图名称, 即相对的流图文件路径,例如: "tasks/test.task", 如果为 None, 则运行当前流图 """ if name: vp_utils.run_by_name(name) else: vp_utils.run() return {} @router.post("/stop", summary="停止 VP 流图", response_model=Std) def stop_vp(name: Optional[str] = Body(None, embed=True, title="流图名称")): """停止 VP 流图 Args: name(str or None): Default: None, 流图名称, 即相对的流图文件路径,例如: "tasks/test.task", 如果为 None, 则停止当前流图 """ if name: vp_utils.stop_by_name(name) else: vp_utils.stop() return {} @router.post("/pause", summary="暂停 VP 流图", response_model=Std) def pause_vp(): """暂停 VP 流图""" vp_utils.pause() return {} @router.get("/status", summary="获取 VP 状态", response_model=Std[dict]) def get_vp_status(): """获取 VP 状态""" return vp_utils.get_all_status()
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\manager\order_manager.py
from typing import Union from xyz_max_hmi_server import Depends, EnhancedAPIRouter as APIRouter from xyz_max_hmi_server.api.deps import get_order_manager from xyz_max_hmi_server.entity.order import LiteOrder from xyz_max_hmi_server.exceptions import XYZException from xyz_max_hmi_server.modules.manager import OrderManager from xyz_max_hmi_server.schemas.base import List, Std, _list router = APIRouter() @router.get("/", response_model=List[dict], name="获取订单列表") def get_orders(om: OrderManager = Depends(get_order_manager)): return _list(om.orders) @router.get("/first", response_model=Std[Union[dict, None]], name="获取第一个订单") def get_first_order(om: OrderManager = Depends(get_order_manager)): return om.first() @router.get("/{order_id}", response_model=Std[dict], name="获取订单") def get_order(order_id: str, om: OrderManager = Depends(get_order_manager)): order = om.get_order_or_404(order_id) return order @router.post("/giveup_current_order", response_model=Std[dict], name="放弃当前订单") def giveup_current_order( om: OrderManager[LiteOrder] = Depends(get_order_manager), ): """放弃当前订单, 即放弃队列中的第一个订单""" order = om.first() if order is None: raise XYZException("No order in queue.") order.terminate() return {"order_id": order.order_id}
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\manager\task_manager.py
from typing import NewType from xyz_max_hmi_server import Depends, EnhancedAPIRouter as APIRouter from xyz_max_hmi_server.api.deps import get_order_manager, get_task_manager from xyz_max_hmi_server.entity.order import LiteOrder from xyz_max_hmi_server.entity.task import LiteTask from xyz_max_hmi_server.exceptions import XYZException from xyz_max_hmi_server.modules.manager import OrderManager, TaskManager from xyz_max_hmi_server.schemas.base import List, Std, _list router = APIRouter() T = NewType("T", TaskManager[LiteTask]) @router.get("/", response_model=List[dict], name="获取任务列表") def get_tasks(tm: T = Depends(get_task_manager)): if tm is None: raise XYZException("TaskManager is not initialized.") # PERF:(YuhangWu): 优化格式,预期:tm.tasks return _list(tm.tasks) @router.get("/first", response_model=Std[dict], name="获取第一个任务") def get_first_task(tm: T = Depends(get_task_manager)): return tm.first_or_404() @router.get("/{task_id}", response_model=Std[dict], name="获取任务") def get_task(task_id: str, tm: T = Depends(get_task_manager)): task = tm.get_task_or_404(task_id) return task # NOTE: 该接口原逻辑是用于放弃当前任务 # 1.4.0 版本之后,统一了订单与任务的概念,因此该接口的逻辑应该是放弃当前订单 # 接口路由保留,但是接口逻辑修改为放弃当前订单 @router.post("/giveup_current_task", response_model=Std[dict], name="放弃当前任务") def giveup_current_task( om: OrderManager[LiteOrder] = Depends(get_order_manager), ): """ 放弃当前任务,即放弃队列中的第一个任务 versionchanged:: 1.4.0 该接口原逻辑是用于放弃当前任务,1.4.0 版本之后,统一了订单与任务的概念,因此该接口的逻辑应该是放弃当前订单 """ order = om.first() if order is None: raise XYZException("No order in queue.") order.terminate() return {"order_id": order.order_id}
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\api\endpoints\manager\__init__.py
from xyz_max_hmi_server import EnhancedAPIRouter as APIRouter, crud from xyz_max_hmi_server.schemas.base import Std from .order_manager import router as order_manager_router from .task_manager import router as task_manager_router router = APIRouter() router.include_router(order_manager_router, prefix="/order") router.include_router(task_manager_router, prefix="/task") @router.post("/clear", summary="清空任务/订单列表", response_model=Std) def clear_task_and_order(): """清空所有的订单和任务. **该接口会清空所有的订单和任务,慎用!** 对于控序混码,还会清空当前队列中所有控序混码订单的全部规划记录 删除控序订单对应的规划记录 delete from t_cmcp_planning_result where key in ( select key from t_order where order_type = 'CONTROLLED_SEQ_MCP' ) """ crud.task.remove_all() crud.task_batch.remove_all() crud.order.remove_all() crud.pallet.remove_all() crud.workspace.remove_all() crud.arrival_sequence.remove_all() return {}
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\base.py
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union from pydantic import BaseModel from sqlalchemy.engine.result import Result from sqlalchemy.orm import Query, Session from sqlalchemy.sql.selectable import Select from xyz_max_hmi_server.db.base_class import Base from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.utils.utils import ( jsonable_custom_encoder as jsonable_encoder, ) ModelType = TypeVar("ModelType", bound=Base) # type: ignore CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): def __init__(self, model: Type[ModelType]): """ CRUD object with default methods to Create, Read, Update, Delete (CRUD). **Parameters** * `model`: A SQLAlchemy model class * `schema`: A Pydantic model (schema) class """ self.model = model def get_query(self, session: Session) -> Query: """Get query from session""" return session.query(self.model) @provide_session def get( self, id: Any, session: Session = NEW_SESSION ) -> Optional[ModelType]: return session.query(self.model).filter(self.model.id == id).first() @provide_session def all(self, session: Session = NEW_SESSION) -> List[ModelType]: """获取所有""" return session.query(self.model).all() @provide_session def total(self, session: Session = NEW_SESSION) -> int: """获取总数""" return session.query(self.model).count() @provide_session def get_multi( self, *, skip: int = 0, limit: int = 100, session: Session = NEW_SESSION ) -> List[ModelType]: return session.query(self.model).offset(skip).limit(limit).all() @provide_session def create( self, *, obj_in: CreateSchemaType, session: Session = NEW_SESSION, auto_commit: bool = False, auto_flush: bool = True, auto_refresh: bool = True, # Deprecated ) -> ModelType: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data) # type: ignore session.add(db_obj) if auto_flush: session.flush() if auto_commit: session.commit() return db_obj @provide_session def update( self, *, db_obj: ModelType, obj_in: Union[UpdateSchemaType, Dict[str, Any]], session: Session = NEW_SESSION, auto_commit: bool = False, auto_flush: bool = True, auto_refresh: bool = True, # Deprecated ) -> ModelType: obj_data = jsonable_encoder(db_obj) if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) update_data = jsonable_encoder(update_data) for field in obj_data: if field in update_data: setattr(db_obj, field, update_data[field]) session.add(db_obj) if auto_flush: session.flush() if auto_commit: session.commit() return db_obj @provide_session def remove( self, *, id: int, session: Session = NEW_SESSION ) -> Optional[ModelType]: obj = session.query(self.model).get(id) if obj: session.delete(obj) return obj @provide_session def remove_all(self, *, session: Session = NEW_SESSION) -> None: session.query(self.model).delete() @provide_session def execute( self, query: Union[Query, Select], session: Session = NEW_SESSION ) -> Result: return session.execute(query)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_arrival_sequence.py
from xyz_max_hmi_server.models.arrival_sequence import ArrivalSequenceModel from xyz_max_hmi_server.schemas.arrival_sequence import ( ArrivalSequenceCreateSchema, ArrivalSequenceUpdateSchema, ) from .base import CRUDBase class CRUDArrivalSequence( CRUDBase[ ArrivalSequenceModel, ArrivalSequenceCreateSchema, ArrivalSequenceUpdateSchema, ] ): """CRUD for ArrivalSequence.""" pass arrival_sequence = CRUDArrivalSequence(ArrivalSequenceModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_cmcp_planning_result.py
from typing import Optional from sqlalchemy.orm.session import Session from xyz_max_hmi_server import enums from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.entity.cmcp_planning_result import CMCPPlanningResult from xyz_max_hmi_server.exceptions import XYZNotFoundError from xyz_max_hmi_server.models.cmcp_planning_result import ( CMCPPlanningResultModel, ) from xyz_max_hmi_server.schemas.cmcp_planning_result import ( CMCPPlanningResultCreateSchema, CMCPPlanningResultUpdateSchema, ) from .base import CRUDBase class CRUDCMCPPlanningResult( CRUDBase[ CMCPPlanningResultModel, CMCPPlanningResultCreateSchema, CMCPPlanningResultUpdateSchema, ] ): @provide_session def get_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> Optional[CMCPPlanningResultModel]: """根据订单ID获取对应的CMCPPlanningResult.""" return ( session.query(self.model) .filter(self.model.order_id == order_id) .order_by(self.model.id.desc()) .first() ) @provide_session def get_by_order_id_and_status( self, order_id: str, status: enums.CMCPPlanningStatus, session: Session = NEW_SESSION, ) -> Optional[CMCPPlanningResultModel]: """根据订单ID和状态获取对应的CMCPPlanningResult.""" return ( session.query(self.model) .filter( self.model.order_id == order_id, self.model.status == status ) .order_by(self.model.id.desc()) .first() ) @provide_session def get_unplaned_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> Optional[CMCPPlanningResultModel]: """根据订单ID获取对应的CMCPPlanningResult.""" if result := self.get_pending_by_order_id(order_id, session): return result if result := self.get_planning_by_order_id(order_id, session): return result return None @provide_session def get_by_order_id_and_key( self, order_id: str, key: str, session: Session = NEW_SESSION ) -> Optional[CMCPPlanningResultModel]: """根据订单ID和key获取对应的CMCPPlanningResult.""" return ( session.query(self.model) .filter(self.model.order_id == order_id, self.model.key == key) .first() ) @provide_session def get_planning_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> Optional[CMCPPlanningResultModel]: """根据订单ID获取对应的CMCPPlanningResult.""" return self.get_by_order_id_and_status( order_id, enums.CMCPPlanningStatus.PLANNING, session=session, ) @provide_session def get_pending_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> Optional[CMCPPlanningResultModel]: """根据订单ID获取对应的CMCPPlanningResult.""" return self.get_by_order_id_and_status( order_id, enums.CMCPPlanningStatus.PENDING, session=session, ) @provide_session def set_status( self, id: int, status: enums.CMCPPlanningStatus, session: Session = NEW_SESSION, ) -> None: """根据订单ID设置CMCPPlanningResult的状态.""" record = self.get(id, session=session) if record: record.status = status # type: ignore @provide_session def set_error_by_key( self, key: str, error_msg: str, session: Session = NEW_SESSION, ): """设置规划结果的错误信息.""" session.query(self.model).filter(self.model.key == key).update( { self.model.status: enums.CMCPPlanningStatus.FAILURE, self.model.error_msg: error_msg, } ) @provide_session def set_all_status( self, order_id: str, status: enums.CMCPPlanningStatus, session: Session = NEW_SESSION, ) -> None: """根据订单ID设置CMCPPlanningResult的状态.""" session.query(self.model).filter( self.model.order_id == order_id ).update( { self.model.status: status, } ) @provide_session def remove_by_order_id( self, order_id: str, session: Session = NEW_SESSION, ) -> None: """根据订单ID删除CMCPPlanningResult.""" session.query(self.model).filter( self.model.order_id == order_id ).delete() @provide_session def count_failed_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> int: """统计订单ID对应的CMCPPlanningResult中失败的数量.""" return ( session.query(self.model) .filter( self.model.order_id == order_id, self.model.status == enums.CMCPPlanningStatus.FAILURE, ) .count() ) @provide_session def count_total_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> int: """统计订单ID对应的CMCPPlanningResult中总数.""" return ( session.query(self.model) .filter(self.model.order_id == order_id) .count() ) @provide_session def allow_create( self, order_id: str, session: Session = NEW_SESSION ) -> bool: """检查是否允许创建CMCPPlanningResult.""" return self.count_total_by_order_id( order_id, session=session, ) == self.count_failed_by_order_id( order_id, session=session, ) @provide_session def has_success( self, order_id: str, session: Session = NEW_SESSION ) -> bool: """检查是否存在已成功的规划结果.""" return ( session.query(self.model) .filter( self.model.order_id == order_id, self.model.status == enums.CMCPPlanningStatus.SUCCESS, ) .count() > 0 ) cmcp_planning_result = CRUDCMCPPlanningResult(CMCPPlanningResultModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_cycle.py
from typing import Optional from sqlalchemy.orm import Session from xyz_max_hmi_server.crud.base import CRUDBase from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.models.cycle import CycleModel from xyz_max_hmi_server.schemas.cycle import ( CycleCreateSchema, CycleUpdateSchema, ) class CRUDCycle(CRUDBase[CycleModel, CycleCreateSchema, CycleUpdateSchema]): @provide_session def push(self, id: str, data: dict, session: Session = NEW_SESSION) -> None: """将数据写入到数据库中.""" cycle = CycleModel(id=id, data=data) # type: ignore session.add(cycle) @provide_session def pop(self, session: Session = NEW_SESSION) -> Optional[CycleModel]: """从数据库中获取最新的数据.""" cycle = self.peak(session=session) if cycle: session.delete(cycle) return cycle return None @provide_session def set_persisted( self, id: str, file_path: str, session: Session = NEW_SESSION ) -> None: """设置为已持久化到磁盘.""" cycle = session.query(self.model).filter(self.model.id == id).first() if cycle: cycle.is_persisted = True cycle.file_path = file_path session.add(cycle) @provide_session def get_persisted(self, session: Session = NEW_SESSION) -> CycleModel: """获取已持久化到磁盘的数据.""" cycle = ( session.query(self.model) .filter(self.model.is_persisted == True) .order_by(self.model.create_time.desc()) .first() ) return cycle @provide_session def get_unpersisted(self, session: Session = NEW_SESSION) -> CycleModel: """获取未持久化到磁盘的数据.""" cycle = ( session.query(self.model) .filter(self.model.is_persisted == False) .order_by(self.model.create_time.desc()) .first() ) return cycle cycle = CRUDCycle(CycleModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_error_records.py
from sqlalchemy.orm import Session from xyz_max_hmi_server.crud.base import NEW_SESSION, CRUDBase, provide_session from xyz_max_hmi_server.models.error_records import ErrorRecordsModel from xyz_max_hmi_server.schemas.error_records import ( ErrorRecordCreate, ErrorRecordUpdate, ) class ErrorRecord( CRUDBase[ErrorRecordsModel, ErrorRecordCreate, ErrorRecordUpdate] ): @provide_session def delete_all(self, session: "Session" = NEW_SESSION) -> None: """删除所有订单""" session.query(self.model).delete() error_records = ErrorRecord(ErrorRecordsModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_order.py
from typing import List, Optional from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from xyz_max_hmi_server import enums from xyz_max_hmi_server.crud.base import CRUDBase from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.exceptions import XYZException, XYZNotFoundError from xyz_max_hmi_server.models.order import OrderModel from xyz_max_hmi_server.schemas.order import OrderCreate, OrderUpdate class CRUDOrder(CRUDBase[OrderModel, OrderCreate, OrderUpdate]): """订单CRUD类""" @provide_session def first( self, session: Session = NEW_SESSION, ) -> Optional[OrderModel]: """根据订单ID获取订单对象""" return session.query(self.model).order_by(self.model.id.asc()).first() @provide_session def first_by_status( self, status: enums.OrderStatus, session: Session = NEW_SESSION, ) -> Optional[OrderModel]: return ( session.query(self.model) .filter(self.model.order_status == status) .order_by(self.model.id.asc()) .first() ) @provide_session def get_by_order_id( self, order_id: str, session: "Session" = NEW_SESSION ) -> Optional[OrderModel]: """根据订单ID获取订单对象 Args: order_id(str): 订单ID Returns: OrderModel: 订单对象 """ return ( session.query(self.model) .filter(self.model.order_id == order_id) .first() ) @provide_session def get_orders_by_type( self, order_type: enums.OrderType, session: "Session" = NEW_SESSION, ) -> List[OrderModel]: """根据订单类型获取订单列表 Args: order_type(enums.OrderType): 订单类型 Returns: list: 订单列表 """ return ( session.query(self.model) .filter(self.model.order_type == order_type) .all() ) @provide_session def delete_all(self, session: "Session" = NEW_SESSION) -> None: """删除所有订单""" try: session.query(self.model).delete() except IntegrityError as err: session.rollback() raise XYZException("删除订单失败, 因为存在关联任务") from err # @provide_session # def get_and_remove_by_order_id( # self, order_id: str, session: "Session" = NEW_SESSION # ) -> Optional[OrderModel]: # """根据订单ID获取订单对象并删除 # Args: # order_id(str): 订单ID # Returns: # OrderModel: 订单对象 # """ # order = self.get_by_order_id(order_id=order_id, session=session) # if order: # self.remove_by_order_id(order_id=order_id, session=session) # return order @provide_session def remove_by_order_id( self, order_id: str, session: "Session" = NEW_SESSION ) -> None: """根据订单ID删除订单对象 Args: order_id(str): 订单ID """ ( session.query(self.model) .filter(self.model.order_id == order_id) .delete() ) order = CRUDOrder(OrderModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_order_result.py
from typing import List from sqlalchemy.orm import Session from xyz_max_hmi_server.crud.base import CRUDBase from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.models.order_result import OrderResultModel from xyz_max_hmi_server.schemas.order_result import ( OrderResultCreate, OrderResultUpdate, ) class CRUDOrderResult( CRUDBase[OrderResultModel, OrderResultCreate, OrderResultUpdate] ): @provide_session def get_order_result_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> List[OrderResultModel]: """通过订单号获取订单结果.""" return ( session.query(self.model) .filter(self.model.order_id == order_id) .all() ) @provide_session def delete_all(self, session: Session = NEW_SESSION) -> None: """删除所有任务结果""" session.query(self.model).delete() order_result = CRUDOrderResult(OrderResultModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_pallet.py
from typing import List, Optional from sqlalchemy.orm import Session from sqlalchemy.sql import or_ from xyz_max_hmi_server.crud.base import CRUDBase from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.models.pallet import PalletModel from xyz_max_hmi_server.schemas.pallet import PalletCreate, PalletUpdate class CRUDPallet(CRUDBase[PalletModel, PalletCreate, PalletUpdate]): @provide_session def is_exists(self, pallet_id: str, session: Session = NEW_SESSION) -> bool: return bool( session.query(self.model) .filter(self.model.pallet_id == pallet_id) .first() ) @provide_session def get_by_pallet_id( self, pallet_id: str, session: Session = NEW_SESSION ) -> Optional[PalletModel]: return ( session.query(self.model) .filter(self.model.pallet_id == pallet_id) .first() ) @provide_session def get_next_pallet_by_ws_id( self, workspace_id: str, session: Session = NEW_SESSION ) -> Optional[PalletModel]: # TODO: 新增一个 seq 字段,用于排序 return ( session.query(self.model) .filter(self.model.workspace_id == workspace_id) .order_by(self.model.create_time.asc()) .first() ) @provide_session def remove_by_pallet_id( self, pallet_id: str, session: Session = NEW_SESSION ): session.query(self.model).filter( self.model.pallet_id == pallet_id ).delete() @provide_session def remove_by_workspace_id( self, workspace_id: str, session: Session = NEW_SESSION ): session.query(self.model).filter( self.model.workspace_id == workspace_id ).delete() @provide_session def remove_invalid_pallets( self, workspace_id: str, session: Session = NEW_SESSION ): session.query(self.model).filter( self.model.workspace_id == workspace_id, or_( self.model.pickable_quantity == 0, self.model.placeable_quantity == 0, ), ).delete() @provide_session def list_by_workspace_id( self, workspace_id: str, session: Session ) -> List[PalletModel]: return ( session.query(self.model) .filter(self.model.workspace_id == workspace_id) .all() ) @provide_session def set_pickable_quantity( self, session: Session, pallet_id: str, pickable_quantity: int ) -> None: session.query(self.model).filter( self.model.pallet_id == pallet_id ).update({"pickable_quantity": pickable_quantity}) @provide_session def set_placeable_quantity( self, session: Session, pallet_id: str, placeable_quantity: int ) -> None: session.query(self.model).filter( self.model.pallet_id == pallet_id ).update({"placeable_quantity": placeable_quantity}) @provide_session def delete_all(self, session: Session = NEW_SESSION) -> None: session.query(self.model).delete() return pallet = CRUDPallet(PalletModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_task.py
from typing import List, Optional # noqa: D100 from sqlalchemy import func from sqlalchemy.orm import Session from xyz_max_hmi_server import enums from xyz_max_hmi_server.crud.base import CRUDBase from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.models.task import TaskModel from xyz_max_hmi_server.schemas.task import TaskCreate, TaskUpdate class CRUDTask(CRUDBase[TaskModel, TaskCreate, TaskUpdate]): # noqa: D101 @provide_session def get_by_task_id( self, task_id: str, session: "Session" = NEW_SESSION ) -> Optional[TaskModel]: """根据任务编号获取任务""" return ( session.query(self.model) .filter(self.model.task_id == task_id) .first() ) @provide_session def get_tasks_by_order_id( self, order_id: str, session: "Session" = NEW_SESSION ) -> List[TaskModel]: """根据订单编号获取任务列表""" return ( session.query(self.model) .filter(self.model.order_id == order_id) .order_by(self.model.id.asc()) .all() ) @provide_session def first( self, is_ready: bool, by_priority: bool, session: "Session" = NEW_SESSION, ) -> Optional[TaskModel]: """获取第一个任务 Args: is_ready: 是否只获取非接收状态的任务 by_priority: 是否按优先级排序 session: 数据库会话 Returns: Optional[TaskModel] -- 任务 """ q = session.query(self.model) if is_ready: q = q.filter(self.model.task_status != enums.TaskStatus.RECEIVED) order_by = [] if by_priority: order_by.append(self.model.priority.desc()) order_by.append(self.model.id.asc()) return q.order_by(*order_by).first() @provide_session def first_by_order_id_and_status( self, status: enums.TaskStatus, order_id: str, session: "Session" = NEW_SESSION, ) -> Optional[TaskModel]: """根据订单编号和状态获取第一个任务, 按创建时间升序""" return ( session.query(self.model) .filter( self.model.order_id == order_id, self.model.task_status == status, ) .order_by(self.model.id.asc()) .first() ) # @provide_session # def first_not_received( # self, session: "Session" = NEW_SESSION # ) -> Optional[TaskModel]: # """获取第一个为非接收状态的任务, 按创建时间升序""" # return ( # session.query(self.model) # .filter(self.model.task_status != enums.TaskStatus.RECEIVED) # .order_by(self.model.id.asc()) # .first() # ) @provide_session def get_by_index( self, idx: int = 0, session: "Session" = NEW_SESSION ) -> Optional[TaskModel]: """根据索引获取任务""" return ( session.query(self.model) .order_by(self.model.id.asc()) .offset(idx) .first() ) def remove_by_task_id( self, task_id: str, session: "Session" = NEW_SESSION ) -> None: """根据任务编号删除任务""" session.query(self.model).filter(self.model.task_id == task_id).delete() @provide_session def get_and_remove_by_task_id( self, task_id: str, session: "Session" = NEW_SESSION, ) -> Optional[TaskModel]: """根据任务编号获取并删除任务""" record = session.query(self.model).filter(self.model.task_id == task_id) if task := record.first(): record.delete() return task return None @provide_session def remove_by_order_id( self, order_id: str, exclude: Optional[List[str]] = None, session: "Session" = NEW_SESSION, ) -> None: """根据订单编号删除任务""" if exclude is None: exclude = [] session.query(self.model).filter( self.model.order_id == order_id, self.model.task_id.notin_(exclude), ).delete() @provide_session def delete_all( self, session: "Session" = NEW_SESSION, ) -> None: """删除所有任务""" session.query(self.model).delete() @provide_session def count(self, session: "Session" = NEW_SESSION): """获取任务数量""" return session.query(self.model).count() @provide_session def count_tasks_by_order_id_and_status( self, order_id: str, status: enums.TaskStatus, session: "Session" = NEW_SESSION, ) -> int: """根据订单编号和状态获取任务数量""" return ( session.query(self.model) .filter( self.model.order_id == order_id, self.model.task_status == status, ) .count() ) @provide_session def count_tasks_by_order_id( self, order_id: str, session: "Session" = NEW_SESSION, ) -> int: """根据订单编号获取任务数量""" return ( session.query(self.model) .filter(self.model.order_id == order_id) .count() ) @provide_session def count_target_num( self, order_id: Optional[str] = None, status: Optional[enums.TaskStatus] = None, session: "Session" = NEW_SESSION, ) -> int: """对目标数量进行求和""" filters = [] if order_id: filters.append(self.model.order_id == order_id) if status: filters.append(self.model.task_status == status) result = ( session.query(self.model) .filter(*filters) .with_entities(func.sum(self.model.target_num)) .scalar() ) if result is None: return 0 return result @provide_session def count_not_recieved_status_tasks( self, session: "Session" = NEW_SESSION, ) -> int: """获取非接收状态的任务数量""" return ( session.query(self.model) .filter(self.model.task_status != enums.TaskStatus.RECEIVED) .count() ) @provide_session def delete_not_received( self, session: "Session" = NEW_SESSION, ) -> None: """删除非接收状态的任务""" session.query(self.model).filter( self.model.task_status != enums.TaskStatus.RECEIVED ).delete() @provide_session def all_not_received( self, session: "Session" = NEW_SESSION, ) -> List[TaskModel]: """获取所有非接收状态的任务""" return ( session.query(self.model) .filter(self.model.task_status != enums.TaskStatus.RECEIVED) .all() ) @provide_session def is_not_received( self, task_id: str, session: "Session" = NEW_SESSION, ) -> bool: """判断任务是否为非接收状态""" query = ( session.query(self.model) .filter(self.model.task_id == task_id) .first() ) if query: return query.task_status != enums.TaskStatus.RECEIVED return False @provide_session def is_exists_by_task_id( self, task_id: str, session: "Session" = NEW_SESSION ) -> bool: """判断任务是否存在""" return ( session.query(self.model) .filter(self.model.task_id == task_id) .count() > 0 ) def get_top_priority( self, session: "Session" = NEW_SESSION, ) -> int: """获取最高优先级 如果没有任务, 则返回 0 Returns: int -- 最高优先级 """ record = ( session.query(self.model) .order_by(self.model.priority.desc()) .first() ) if record: return record.priority else: return 0 task = CRUDTask(TaskModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_task_batch.py
from typing import List, Optional from sqlalchemy.orm.session import Session from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.models import TaskBatchModel from xyz_max_hmi_server.schemas.task_batch import ( TaskBatchCreate, TaskBatchUpdate, ) from .base import CRUDBase class CRUDTaskBatch(CRUDBase[TaskBatchModel, TaskBatchCreate, TaskBatchUpdate]): @provide_session def get_batch( self, task_id: str, session: Session = NEW_SESSION ) -> Optional[TaskBatchModel]: return session.query(self.model).filter_by(task_id=task_id).first() @provide_session def get_batch_id( self, task_id: str, session: Session = NEW_SESSION ) -> Optional[str]: """获取批次编号""" return ( session.query(self.model.batch_id) .filter_by(task_id=task_id) .scalar() ) @provide_session def count(self, batch_id: str, session: Session = NEW_SESSION) -> int: return session.query(self.model).filter_by(batch_id=batch_id).count() @provide_session def get_first_task_id( self, batch_id: str, session: Session = NEW_SESSION ) -> Optional[str]: """根据批次号,获取该批次对应的第一个任务编号""" return ( session.query(self.model.task_id) .filter_by(batch_id=batch_id) .order_by(self.model.id) .scalar() ) @provide_session def get_task_ids( self, batch_id: str, session: Session = NEW_SESSION ) -> List[str]: """根据批次号,获取该批次对应的所有任务编号""" records = ( session.query(self.model.task_id).filter_by(batch_id=batch_id).all() ) return [record.task_id for record in records] # type: ignore @provide_session def remove_by_task_id_and_batch_id( self, batch_id: str, task_id: str, session: Session = NEW_SESSION ) -> None: """删除一条记录""" session.query(self.model).filter_by( batch_id=batch_id, task_id=task_id ).delete() task_batch = CRUDTaskBatch(TaskBatchModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_task_result.py
from datetime import datetime from typing import List, Optional from sqlalchemy import func from sqlalchemy.orm import Session from xyz_max_hmi_server import enums from xyz_max_hmi_server.crud.base import CRUDBase from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.models.task_result import TaskResultModel from xyz_max_hmi_server.schemas.task_result import ( TaskResultCreate, TaskResultUpdate, ) class CRUDTaskResult( CRUDBase[TaskResultModel, TaskResultCreate, TaskResultUpdate] ): @provide_session def get_task_result_by_task_id( self, task_id: str, session: Session = NEW_SESSION ) -> List[TaskResultModel]: """根据任务id获取任务结果""" return ( session.query(self.model) .filter(self.model.task_id == task_id) .all() ) @provide_session def count_tasks_by_order_id( self, order_id: str, session: Session = NEW_SESSION ) -> int: """根据订单id获取任务数量""" return ( session.query(self.model) .filter(self.model.order_id == order_id) .count() ) @provide_session def count_target_num( self, order_id: Optional[str] = None, status: Optional[enums.TaskStatus] = None, session: "Session" = NEW_SESSION, ) -> int: """对目标数量进行求和""" filters = [] if order_id: filters.append(self.model.order_id == order_id) if status: filters.append(self.model.task_status == status) result = ( session.query(self.model) .filter(*filters) .with_entities(func.sum(self.model.target_num)) .scalar() ) if result is None: return 0 return result @provide_session def get_total_completed_count( self, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, session: Session = NEW_SESSION, ) -> int: """求和已完成的数量""" q = session.query(self.model).with_entities( func.sum(self.model.done_num) ) if start_time: q = q.filter(self.model.start_time >= start_time) else: q = q.filter(self.model.start_time.isnot(None)) if end_time: q = q.filter(self.model.end_time <= end_time) else: q = q.filter(self.model.end_time.isnot(None)) result = q.scalar() if result is None: return 0 return result @provide_session def get_total_elapsed_time( self, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, session: Session = NEW_SESSION, ) -> int: """获取总耗时 SQL: SELECT SUM(TIMESTAMPDIFF(SECOND, start_time, end_time)) AS total_elapsed_time FROM t_task_result WHERE end_time IS NOT NULL AND start_time IS NOT NULL """ q = session.query(self.model).with_entities( # NOTE: sqlite3 不支持 TIMESTAMPDIFF func.sum( func.strftime( "%s", self.model.end_time, ) - func.strftime( "%s", self.model.start_time, ) ) ) if start_time: q = q.filter(self.model.start_time >= start_time) else: q = q.filter(self.model.start_time.isnot(None)) if end_time: q = q.filter(self.model.end_time <= end_time) else: q = q.filter(self.model.end_time.isnot(None)) result = q.scalar() if result is None: return 0 return result @provide_session def delete_all(self, session: Session = NEW_SESSION) -> None: """删除所有任务结果""" session.query(self.model).delete() task_result = CRUDTaskResult(TaskResultModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\crud_workspace.py
from typing import Optional from sqlalchemy.orm import Session from xyz_max_hmi_server.crud.base import CRUDBase from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session from xyz_max_hmi_server.models.workspace import WorkspaceModel from xyz_max_hmi_server.schemas.workspace import ( WorkspaceCreate, WorkspaceUpdate, ) class CRUDWorkspace(CRUDBase[WorkspaceModel, WorkspaceCreate, WorkspaceUpdate]): @provide_session def get_by_ws_id( self, ws_id: str, session: Session = NEW_SESSION ) -> Optional[WorkspaceModel]: return ( session.query(self.model).filter(self.model.ws_id == ws_id).first() ) @provide_session def remove_by_ws_id( self, ws_id: str, session: Session = NEW_SESSION ) -> None: session.query(self.model).filter(self.model.ws_id == ws_id).delete() @provide_session def is_exists(self, ws_id: str, session: Session = NEW_SESSION) -> bool: return bool( session.query(self.model).filter(self.model.ws_id == ws_id).first() ) @provide_session def set_ready( self, ws_id: str, is_ready: bool, session: Session = NEW_SESSION ) -> None: session.query(self.model).filter(self.model.ws_id == ws_id).update( {self.model.is_ready: is_ready} ) @provide_session def is_ready(self, ws_id: str, session: Session = NEW_SESSION) -> bool: return bool( session.query(self.model.is_ready) .filter(self.model.ws_id == ws_id) .scalar() ) @provide_session def delete_all(self, session: Session = NEW_SESSION) -> None: session.query(self.model).delete() @provide_session def set_current_pallet_id( self, pallet_id: Optional[str], ws_id: str, session: Session = NEW_SESSION, ) -> None: session.query(self.model).filter(self.model.ws_id == ws_id).update( {self.model.current_pallet_id: pallet_id} ) workspace = CRUDWorkspace(WorkspaceModel)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\crud\__init__.py
from .crud_arrival_sequence import arrival_sequence from .crud_cmcp_planning_result import cmcp_planning_result from .crud_cycle import cycle from .crud_error_records import error_records from .crud_order import order from .crud_order_result import order_result from .crud_pallet import pallet from .crud_task import task from .crud_task_batch import task_batch from .crud_task_result import task_result from .crud_workspace import workspace __all__ = [ "arrival_sequence", "task", "order", "task_result", "task_batch", "order_result", "workspace", "error_records", "cycle", "cmcp_planning_result", "pallet", ]
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\db\base.py
from xyz_max_hmi_server.db.base_class import Base from xyz_max_hmi_server.models.error_records import ErrorRecordsModel from xyz_max_hmi_server.models.order import OrderModel from xyz_max_hmi_server.models.order_result import OrderResultModel from xyz_max_hmi_server.models.task import TaskModel from xyz_max_hmi_server.models.task_result import TaskResultModel from xyz_max_hmi_server.models.workspace import WorkspaceModel __all__ = [ "Base", "ErrorRecordsModel", "OrderModel", "OrderResultModel", "TaskModel", "TaskResultModel", "WorkspaceModel", ]
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\db\base_class.py
from datetime import datetime import sqlalchemy as sa from sqlalchemy.orm import as_declarative @as_declarative() class Base: """Base class for all models.""" id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) create_time = sa.Column(sa.DateTime, default=datetime.now) update_time = sa.Column( sa.DateTime, default=datetime.now, onupdate=datetime.now ) __abstract__ = True __table_args__ = {"mysql_engine": "InnoDB"}
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\db\session.py
import sqlite3 from contextlib import contextmanager from functools import wraps from inspect import signature from typing import Callable, Generator, Type, TypeVar, cast from fastapi_sqlalchemy import db from fastapi_sqlalchemy.middleware import _session from sqlalchemy import create_engine from sqlalchemy.orm import Session, sessionmaker from typing_extensions import ParamSpec from xyz_max_hmi_server.config import settings SessionLocal = None # NOTICE: 延迟初始化 SessionLocal # 在使用 cli 时,无需使用数据库,因此不需要初始化 # 仅在调用 get_db 或 session 等相关函数时,才会初始化 def _session_factory() -> Type[Session]: global SessionLocal if SessionLocal is None: if settings.db.sqlalchemy_database_uri.startswith("sqlite"): engine = create_engine( settings.db.real_database_uri, pool_pre_ping=True, connect_args={ "check_same_thread": False, "detect_types": sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES, }, ) else: engine = create_engine( settings.db.sqlalchemy_database_uri, pool_pre_ping=True, ) SessionLocal = sessionmaker( autocommit=False, autoflush=False, bind=engine ) return SessionLocal # type: ignore # 简化操作,在接口内直接使用 db.session 即可 # 在接口外则需要使用上下文管理器,如: # with db(): # db.session.query(...) db = db def get_db(): """Get db session.""" session = _session_factory()() try: yield session finally: session.close() @contextmanager def start_session() -> Generator[Session, None, None]: # def start_session(): """Contextmanager that will create and teardown a session.""" session = _session_factory()() try: yield session session.commit() except Exception: session.rollback() raise finally: session.close() PS = ParamSpec("PS") RT = TypeVar("RT") def find_session_idx(func: Callable[PS, RT]) -> int: """Find session index in function call parameter.""" func_params = signature(func).parameters try: # func_params is an ordered dict -- this is the "recommended" way of getting the position session_args_idx = tuple(func_params).index("session") except ValueError: raise ValueError( f"Function {func.__qualname__} has no `session` argument" ) from None return session_args_idx def provide_session(func: Callable[PS, RT]) -> Callable[PS, RT]: """ Function decorator that provides a session if it isn't provided. If you want to reuse a session or run the function as part of a database transaction, you pass it to the function, if not this wrapper will create one and close it for you. """ session_args_idx = find_session_idx(func) @wraps(func) def wrapper(*args, **kwargs) -> RT: for arg in args: if isinstance(arg, Session): return func(*args, **kwargs) # type: ignore session = kwargs.get("session", None) if session == NEW_SESSION: if session := _session.get(): kwargs["session"] = session return func(*args, **kwargs) # type: ignore else: with start_session() as session: kwargs["session"] = session return func(*args, **kwargs) # type: ignore elif "session" in kwargs or session_args_idx < len(args): return func(*args, **kwargs) # type: ignore else: with start_session() as session: return func(*args, session=session, **kwargs) # type: ignore return wrapper # type: ignore # A fake session to use in functions decorated by provide_session. This allows # the 'session' argument to be of type Session instead of Session | None, # making it easier to type hint the function body without dealing with the None # case that can never happen at runtime. NEW_SESSION: Session = cast(Session, None)
0
xyz_max_hmi_server
repos\xyz_max_hmi_server\entity\cmcp_planning_result.py
from datetime import datetime from typing import List, Optional from pydantic import BaseModel, Field from xyz_max_hmi_server import enums from xyz_max_hmi_server.entity.sku import SKUInfo class Result(BaseModel): sku_info: SKUInfo from_ws: str = Field(..., title="抓取位工作空间编号", alias="from") to_ws: str = Field(..., title="放置位工作空间编号", alias="to") pallet_idx: int = Field(..., title="托盘编号") serial_num: int = Field(..., title="序号") customized_data: dict = Field(default_factory=dict, title="自定义数据") class Config: allow_population_by_field_name = True class CMCPPlanningResult(BaseModel): id: int order_id: str status: enums.CMCPPlanningStatus error_msg: Optional[str] results: Optional[List[Result]] start_time: Optional[datetime] end_time: Optional[datetime] create_time: Optional[datetime] update_time: Optional[datetime] class Config: orm_mode = True
0
README.md exists but content is empty.
Downloads last month
30