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 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\order.py | # Copyright (c) XYZ Robotics Inc. - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Author: Yuhang Wu <[email protected]>, 2022/8/31 下午3:15
import importlib
import warnings
from datetime import datetime
from typing import (
Callable,
Dict,
Generic,
List,
Optional,
Type,
TypeVar,
Union,
cast,
)
from fastapi.encoders import jsonable_encoder
from fastapi_sqlalchemy import db
from fastapi_sqlalchemy.exceptions import (
MissingSessionError,
SessionNotInitialisedError,
)
from pydantic import Field, root_validator, validator
from sqlalchemy.orm import Session
from typing_extensions import Final
from xyz_max_hmi_server import crud, enums, services
from xyz_max_hmi_server.db.session import (
NEW_SESSION,
provide_session,
start_session,
)
from xyz_max_hmi_server.entity.cmcp_planning_result import CMCPPlanningResult
from xyz_max_hmi_server.entity.pre_task import PreTask
from xyz_max_hmi_server.entity.task import LiteTask
from xyz_max_hmi_server.exceptions import (
XYZException,
XYZNotFoundError,
XYZOrderError,
XYZOrderNotAllowDeleteError,
XYZTaskError,
XYZValidationError,
)
from xyz_max_hmi_server.models.task import TaskModel
from xyz_max_hmi_server.schemas.order import OrderUpdate
from xyz_max_hmi_server.schemas.task import TaskCreate
from xyz_max_hmi_server.signals import (
order_abort,
order_add_task,
order_done,
order_ended,
order_start,
)
from xyz_max_hmi_server.utils.generic_model import GenericModel
T = TypeVar("T", bound=LiteTask, covariant=True)
def refresh(func):
"""用于刷新任务状态的装饰器
如果被装饰方法,没有显示的传入 session 参数,即修改的数据立即生效,
否则需要手动调用 session.commit() 方法
"""
def wrapper(self: "LiteOrder", *args, **kwargs):
r = func(self, *args, **kwargs)
session = kwargs.get("session", NEW_SESSION)
self._refresh(session=session)
return r
return wrapper
class LiteOrder(GenericModel, Generic[T]):
"""订单类
Attributes:
order_id(str): 订单ID.
tasks(List[Task]): 任务列表.
start_time(datetime): 订单开始时间.
end_time(datetime): 订单结束时间.
error_code(int): 错误码.
error_msg(str): 错误信息.
_not_mutation_fields(List[Field]): 不允许变更的字段列表.
"""
order_id: str = Field(description="订单号", allow_mutation=False)
order_type: enums.OrderType = Field(
default=enums.OrderType.SINGLE_DEPAL,
title="订单类型",
description="订单类型",
)
order_status: enums.OrderStatus = Field(
default=enums.OrderStatus.PENDING, description="订单状态"
)
start_time: Optional[datetime] = Field(
default=None, description="开始时间", allow_mutation=False
)
end_time: Optional[datetime] = Field(
default=None, description="结束时间", allow_mutation=False
)
create_time: datetime = Field(
default_factory=datetime.now,
description="创建时间",
allow_mutation=False,
)
customized_data: Dict = Field(default_factory=dict, description="自定义字典")
error_code: Optional[int] = Field(default=None, description="异常码")
error_msg: Optional[str] = Field(default=None, description="异常信息")
# 用于保存 allow_mutation=False 的字段名.
_not_mutation_fields: set = set()
# 允许变更的字段值的方法名与信号映射关系.
_allow_mutation_methods = {
"start": order_start,
"finish": order_done,
"end": order_ended,
"terminate": order_abort,
"add": order_add_task,
}
class Config: # noqa: D106
validate_assignment = True
orm_mode = True
@property
def tasks(self) -> List[T]:
"""任务列表."""
try:
# WARN: 如果直接使用下方代码,可能引发
# Instance <TaskModel at 0x7f2fb4266550> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: https://sqlalche.me/e/14/bhk3)
records = crud.task.get_tasks_by_order_id(
self.order_id, session=db.session
)
return [self._deserialize(record) for record in records]
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
records = crud.task.get_tasks_by_order_id(
self.order_id, session
)
return [self._deserialize(record) for record in records]
@provide_session
def get_tasks(self, session: Session = NEW_SESSION) -> List[T]:
"""获取任务列表, 提供 session 参数,仅作用于当前事务.
Args:
session(Session): 数据库会话.
Returns:
List[Task]: 任务列表.
"""
records = crud.task.get_tasks_by_order_id(
self.order_id, session=session
)
return [self._deserialize(record) for record in records]
@root_validator()
def fill_not_mutation_fields(cls, values) -> Dict:
"""填充不可修改的字段."""
for _, field_info in cls.__dict__["__fields__"].items():
if field_info.field_info.allow_mutation is False:
cls._not_mutation_fields.add(field_info)
return values
@validator("customized_data", pre=True)
def validate_customized_data(cls, value: Optional[Dict]) -> Dict:
"""校验自定义数据."""
return {} if value is None else value
@provide_session
def _refresh(self, session: Session):
"""将当前任务刷新到数据库中."""
order = crud.order.get_by_order_id(
order_id=self.order_id, session=session
)
if order is not None:
kw = jsonable_encoder(self)
obj = OrderUpdate(
**kw, raw_data=kw, class_name=self.__class__.__name__
)
crud.order.update(
db_obj=order,
obj_in=obj,
session=session,
auto_commit=False,
auto_flush=True,
)
# WARNING: Covariant type variable connot be used in parameter type
# https://github.com/python/mypy/issues/7049
@provide_session
def add(self, task: T, session: Session = NEW_SESSION) -> None: # type: ignore
"""添加任务.
Args:
task(LiteTask): 任务对象.
"""
import warnings
from xyz_max_hmi_server.modules.manager.task_manager import TaskManager
warnings.warn(
"`Order.add` 方法已被废弃, 请使用 `TaskManager().append` 方法代替.",
DeprecationWarning,
stacklevel=2,
)
if TaskManager().is_exists(task, session=session):
raise XYZTaskError(
error_message=f"任务 '{task.task_id}' 已存在",
task_id=task.task_id,
)
kw = jsonable_encoder(task)
kw["order_id"] = self.order_id
crud.task.create(
obj_in=TaskCreate(
task_id=task.task_id,
order_id=self.order_id,
task_status=task.task_status,
task_type=task.task_type,
target_num=task.target_num,
class_name=task.__class__.__name__,
customized_data=task.customized_data,
raw_data=kw,
),
session=session,
)
task.set_order_id(self.order_id, session=session)
@property
def done_num(self) -> int:
"""获取已完成任务数量.
Returns:
int: 已完成任务数量.
"""
try:
count = crud.task.count_tasks_by_order_id_and_status(
self.order_id, enums.TaskStatus.FINISHED, session=db.session
)
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
count = crud.task.count_tasks_by_order_id_and_status(
self.order_id, enums.TaskStatus.FINISHED, session=session
)
return count
@property
def end_num(self) -> int:
"""获取已完成任务数量.
Returns:
int: 已完成任务数量.
"""
try:
count = crud.task.count_tasks_by_order_id_and_status(
self.order_id, enums.TaskStatus.ENDED, session=db.session
)
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
count = crud.task.count_tasks_by_order_id_and_status(
self.order_id, enums.TaskStatus.ENDED, session=session
)
return count
@property
def complete_num(self) -> int:
"""获取已完成的任务数量.
队列中状态为已完成的任务 + 结果表中相关联的任务数量
"""
try:
count = crud.task.count_tasks_by_order_id_and_status(
self.order_id, enums.TaskStatus.FINISHED, session=db.session
) + crud.task_result.count_tasks_by_order_id(
self.order_id, session=db.session
)
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
count = crud.task.count_tasks_by_order_id_and_status(
self.order_id, enums.TaskStatus.FINISHED, session=session
) + crud.task_result.count_tasks_by_order_id(
self.order_id, session=session
)
return count
@property
def total_num(self) -> int:
"""获取任务总数(task_manager 中的任务数 + 结果表中相关联的任务数量).
Returns:
int: 任务总数.
"""
try:
count = crud.task.count_tasks_by_order_id(
self.order_id
) + crud.task_result.count_tasks_by_order_id(self.order_id)
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
count = crud.task.count_tasks_by_order_id(
self.order_id
) + crud.task_result.count_tasks_by_order_id(
self.order_id, session=session
)
return count
@property
def total_boxes_count(self) -> int:
"""获取需要完成的箱子数量.
获取订单下所有任务中的目标箱数并求和.
由于 target_num 可能为 -1, 所以当 target_num 为 -1 时, 返回 -1.
Returns:
int: 任务总箱数, -1 表示无限.
"""
tasks = self.get_tasks()
for task in tasks:
if task.target_num < 0:
return -1
return crud.task.count_target_num(
order_id=self.order_id
) + crud.task_result.count_target_num(order_id=self.order_id)
@property
def completed_boxes_count(self) -> int:
"""获取已完成的箱子数量.
获取订单下所有任务中已完成的箱子数量并求和.
"""
count = crud.task.count_target_num(
order_id=self.order_id, status=enums.TaskStatus.FINISHED
) + crud.task_result.count_target_num(order_id=self.order_id)
return count
@provide_session
def get_task_by_id(
self, task_id: str, session: Session = NEW_SESSION
) -> Optional[T]:
"""根据任务ID获取任务对象.
Args:
task_id(str): 任务ID.
session(Session): 数据库会话.
Returns:
Task: 任务对象, 不存在时返回None.
"""
record = crud.task.get_by_task_id(task_id=task_id, session=session)
if record:
return self._deserialize(record)
return None
@provide_session
def get_task_or_404(self, v: str, session: Session = NEW_SESSION) -> T:
"""根据task_id获取任务.
Args:
v(str): 任务ID.
Returns:
Task: 任务对象.
"""
if isinstance(v, str):
task = self.get_task_by_id(v)
else:
raise TypeError("v must be a string or integer.")
if task is None:
raise XYZNotFoundError(error_message=str(v))
return task
@refresh
def start(self, session: Session = NEW_SESSION) -> None:
"""订单开始."""
self.order_status = enums.OrderStatus.STARTED
self.start_time = datetime.now()
@refresh
def finish(
self,
auto_remove: bool = True,
auto_complete: bool = False,
session: Session = NEW_SESSION,
) -> None:
"""完成订单并出从manager中移除.
Args:
auto_remove(bool): 默认True, 是否从manager中移除.
"""
self.order_status = enums.OrderStatus.FINISHED
self.end_time = datetime.now()
@refresh
def end(
self, auto_remove: bool = True, session: Session = NEW_SESSION
) -> None:
"""设置订单已结束.
Args:
auto_remove(bool): 是否从manager中移除当前订单.
Raises:
XYZOrder
"""
# 检查队列中是否还有该订单的任务, 如果有, 则不允许结束订单.
if (
auto_remove
and crud.task.count_tasks_by_order_id(
self.order_id, session=session
)
> 0
):
raise XYZOrderNotAllowDeleteError(self.order_id)
self.order_status = enums.OrderStatus.ENDED
self.end_time = datetime.now()
@refresh
def terminate(
self,
error: Union[XYZException, str, None] = None,
auto_remove: bool = True,
session: Session = NEW_SESSION,
) -> None:
"""终止订单并从manager中移除.
终止订单将会将订单状态设置为终止状态, 并将订单从 order_manager 中移除,
如果订单中的任务存在 task_manager 中, 也会将任务从 task_manager 中移除.
Args:
error(XYZException or str, Optional): WCSError及子类异常对象.
auto_remove(bool): 默认True, 是否从manager移除.
"""
if error is None:
error = XYZException("被上游终止.")
elif isinstance(error, str):
error = XYZException(error)
self.error_code = error.error_code
self.error_msg = error.error_message
self.end_time = datetime.now()
self.order_status = enums.OrderStatus.TERMINATED
def is_pending(self) -> bool:
return self.order_status == enums.OrderStatus.PENDING
def is_started(self) -> bool:
return self.order_status == enums.OrderStatus.STARTED
def is_finished(self) -> bool:
"""判断订单是否已完成.
Returns:
bool: 订单是否已完成.
"""
return self.order_status == enums.OrderStatus.FINISHED
def is_ended(self) -> bool:
"""判断订单是否已结束."""
return self.order_status == enums.OrderStatus.ENDED
def is_terminated(self) -> bool:
"""判断订单是否终止."""
return self.order_status == enums.OrderStatus.TERMINATED
@provide_session
def flush(self, session: Session = NEW_SESSION) -> None:
"""将数据库中的数据刷新到当前对象中."""
warnings.warn("flush 方法已被废弃, 请使用 reload 方法代替.", DeprecationWarning)
record = crud.order.get_by_order_id(
order_id=self.order_id, session=session
)
if record:
self.__dict__.update(record.__dict__)
return None
@provide_session
def reload(self, session: Session = NEW_SESSION) -> None:
"""将数据库中的数据刷新到当前对象中."""
record = crud.order.get_by_order_id(
order_id=self.order_id, session=session
)
if record:
self.__dict__.update(record.__dict__)
return None
@provide_session
def save(self, session: Session = NEW_SESSION) -> None:
"""将数据刷新到数据库."""
self._refresh(session=session)
def send_signal(self, signal) -> Callable:
"""用于发送信号的装饰器"""
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
# NOTE: signal 仅接收一个位置参数,
# 如果需要将参数传递给信号,必须通过 k-v 的形式声明参数
signal.send(self, **kwargs)
return result
return wrapper
return decorator
def ignore_mutation(self, func) -> Callable:
"""暂时屏蔽 allow_mutation=False 的限制."""
def wrapper(*args, **kwargs):
# 记录变更前的状态
before_status = {}
for field in self._not_mutation_fields:
before_status[field] = field.field_info.allow_mutation
field.field_info.allow_mutation = True
result = func(*args, **kwargs)
# 恢复原来的状态
for field, status in before_status.items():
field.field_info.allow_mutation = status
return result
return wrapper
def __getattribute__(self, item):
# 当调用这些方法时, 会触发相对应的信号.
# 当调用这些方法时,暂时屏蔽 allow_mutation=False 的限制.
ignore_mutation = object.__getattribute__(self, "ignore_mutation")
send_signal = object.__getattribute__(self, "send_signal")
method = object.__getattribute__(self, item)
_allow_mutation_methods = object.__getattribute__(
self, "_allow_mutation_methods"
)
if item in _allow_mutation_methods:
return ignore_mutation(
send_signal(_allow_mutation_methods[item])(method)
)
return super().__getattribute__(item)
def encoder(self, *args, **kwargs) -> dict:
"""将对象转换为字典.
内部调用 jsonable_encoder 方法.
其中 datetime/date 类型会被转换为字符串.
Returns:
dict: 字典.
"""
return jsonable_encoder(self, *args, **kwargs)
def _get_task_class(self, order_model: TaskModel) -> Type[T]:
"""获取订单类."""
module = importlib.import_module("wcs_adaptor.entity.task")
clazz: Type[T] = getattr(module, cast(str, order_model.class_name))
return clazz
def _deserialize(self, order_model: TaskModel) -> T:
"""反序序列化 sa 模型为任务对象."""
# from wcs_adaptor.entity import Order
clazz = self._get_task_class(order_model)
return clazz.parse_obj(order_model.raw_data)
class Order(LiteOrder, Generic[T]):
"""Generic Order"""
class MCDOrder(Order, Generic[T]):
"""Mixed Case Depalletting Order"""
order_type: Final[enums.OrderType] = Field(
default=enums.OrderType.MCD,
title="订单类型",
description="订单类型",
)
class MCPOrder(LiteOrder, Generic[T]):
"""Mixed Case Palletizing Order"""
pre_tasks: List[PreTask] = Field(
default_factory=list,
title="预处理任务列表",
description="用于控序混码规划",
alias="order_items",
)
class Config:
allow_population_by_field_name = True
class RMCPOrder(MCPOrder, Generic[T]):
"""Random Mixed Case Palletizing Order"""
order_type: Final[enums.OrderType] = Field(
default=enums.OrderType.RANDOM_SEQ_MCP,
title="订单类型",
description="订单类型",
)
@refresh
def finish(
self,
auto_remove: bool = True,
auto_complete: bool = False,
session: Session = NEW_SESSION,
) -> None:
"""完成订单并出从manager中移除.
如果是来自于控序混码订单的转换
arrival_sequence 中还有未完成的箱子则不允许完成订单
Args:
auto_remove(bool): 默认True, 是否从manager中移除.
auto_complete(bool): 默认False, 是否自动完成.
session(Session): 数据库会话.
"""
if (
self.is_from_cmcp()
and services.arrival_sequence.has_uncompleted_item(
order_id=self.order_id, session=session
)
):
return
return super().finish(auto_remove, auto_complete, session=session)
@provide_session
def end(
self, auto_remove: bool = True, session: Session = NEW_SESSION
) -> None:
"""设置订单已结束.
Args:
auto_remove(bool): 是否从manager中移除当前订单.
session(Session): 数据库会话.
"""
services.arrival_sequence.clear_by_order_id(
order_id=self.order_id,
session=session,
)
return super().end(auto_remove, session)
@provide_session
def terminate(
self,
error: Union[XYZException, str, None] = None,
auto_remove: bool = True,
session: Session = NEW_SESSION,
) -> None:
services.arrival_sequence.clear_by_order_id(
order_id=self.order_id,
session=session,
)
return super().terminate(error, auto_remove, session)
@property
def total_num(self) -> int:
"""获取任务总数(task_manager 中的任务数 + 结果表中相关联的任务数量).
Returns:
int: 任务总数.
"""
if self.is_from_cmcp():
return services.arrival_sequence.count_by_order_id(
order_id=self.order_id
)
return super().total_num
def is_from_cmcp(self) -> bool:
"""是否来自于控序混码订单的转换"""
return self.customized_data.get("__from_cmcp", False)
class CMCPOrder(MCPOrder, Generic[T]):
"""Controlled Mixed Case Palletizing Order"""
global_barcode_direction: int = Field(default=-1, title="全局条码方向")
time_budget: int = Field(
default=-1,
title="最大规划时间",
description="最大规划时间,单位:秒, -1 表示不限制, 直到规划完成",
)
place_pallet_budget: int = Field(
default=-1,
title="最多放置托盘数",
description="最多放置托盘数, -1 表示不限制",
)
supply_pallet_budget: int = Field(
default=-1,
title="最多来料托盘数",
description="最多来料托盘数, -1 表示不限制",
)
planning_result_key: str = Field(
default="",
title="规划结果的唯一标识",
description="规划结果的唯一标识, 用于区分不同的规划结果",
)
fix_order: bool = Field(default=False, title="是否校验顺序")
@validator("pre_tasks")
def validate_pre_tasks(cls, v: List[PreTask]) -> List[PreTask]:
"""验证 pre_tasks 是否有效.
1. 校验物料编号的唯一性.
"""
from xyz_max_hmi_server import _
s = set()
for task in v:
if task.sku_info is None:
raise XYZValidationError(_("物料编号不能为空."))
if task.sku_info.sku_id in s:
raise XYZValidationError(
_("物料编号 '{0}' 重复.").format(task.sku_info.sku_id)
)
s.add(task.sku_info.sku_id)
return v
@refresh
def start_planning(self):
"""开始规划"""
self.order_status = enums.OrderStatus.PLANNING
@refresh
def end_planning(self):
"""结束规划"""
self.order_status = enums.OrderStatus.PLANNED
def is_planning(self) -> bool:
"""判断是否正在规划"""
return self.order_status == enums.OrderStatus.PLANNING
@property
def planning_result(self) -> Optional[CMCPPlanningResult]:
"""规划结果(仅获取成功的规划结果)"""
warnings.warn(
"planning_result 方法已被废弃, 请使用 get_planning_result 方法代替.",
DeprecationWarning,
stacklevel=2,
)
try:
record = crud.cmcp_planning_result.get_by_order_id_and_status(
self.order_id,
enums.CMCPPlanningStatus.SUCCESS,
session=db.session,
)
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
record = crud.cmcp_planning_result.get_by_order_id_and_status(
self.order_id,
enums.CMCPPlanningStatus.SUCCESS,
session=session,
)
if record is None:
return None
return CMCPPlanningResult.from_orm(record)
@provide_session
def get_planning_result(
self, session: Session = NEW_SESSION
) -> Optional[CMCPPlanningResult]:
"""获取规划结果"""
try:
record = crud.cmcp_planning_result.get_by_order_id(
self.order_id,
session=db.session,
)
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
record = crud.cmcp_planning_result.get_by_order_id(
self.order_id,
session=session,
)
if record is None:
return None
return CMCPPlanningResult.from_orm(record)
@provide_session
def has_success_planning_result(
self, session: Session = NEW_SESSION
) -> bool:
"""是否存在成功的规划结果"""
try:
is_exists = crud.cmcp_planning_result.has_success(
self.order_id,
session=session,
)
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
is_exists = crud.cmcp_planning_result.has_success(
self.order_id,
session=session,
)
return is_exists
@provide_session
def has_cmcp_task(self, session: Session = NEW_SESSION) -> bool:
"""是否存在控序混码任务"""
try:
r = (
crud.task.get_query(session=session)
.filter(
crud.task.model.task_type
== enums.TaskType.CONTROLLED_SEQ_MCP,
)
.exists()
)
is_exists = session.query(r).scalar()
return is_exists
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
r = (
crud.task.get_query(session=session)
.filter(
crud.task.model.task_type
== enums.TaskType.CONTROLLED_SEQ_MCP,
)
.exists()
)
is_exists = session.query(r).scalar()
return is_exists
@provide_session
def is_converting_to_rmcp(self, session: Session = NEW_SESSION) -> bool:
"""是否正在转换为无序混码订单"""
try:
r = (
crud.task.get_query(session=session)
.filter(
crud.task.model.task_type == enums.TaskType.RANDOM_SEQ_MCP,
)
.exists()
)
is_exists = session.query(r).scalar()
return is_exists
except (MissingSessionError, SessionNotInitialisedError):
with start_session() as session:
r = (
crud.task.get_query(session=session)
.filter(
crud.task.model.task_type
== enums.TaskType.RANDOM_SEQ_MCP,
)
.exists()
)
is_exists = session.query(r).scalar()
return is_exists
@property
def total_num(self):
"""获取任务总数(task_manager 中的任务数 + 结果表中相关联的任务数量).
Returns:
int: 任务总数.
"""
if self.is_converting_to_rmcp():
return services.arrival_sequence.count_by_order_id(
order_id=self.order_id
)
return super().total_num
@provide_session
def end(
self, auto_remove: bool = True, session: Session = NEW_SESSION
) -> None:
services.arrival_sequence.clear_by_order_id(
order_id=self.order_id,
session=session,
)
return super().end(auto_remove, session)
@provide_session
def terminate(
self,
error: Union[XYZException, str, None] = None,
auto_remove: bool = True,
session: Session = NEW_SESSION,
) -> None:
services.arrival_sequence.clear_by_order_id(
order_id=self.order_id,
session=session,
)
return super().terminate(error, auto_remove, session)
@provide_session
def to_rmcp(self, session: Session = NEW_SESSION) -> RMCPOrder:
"""转换为无序混码订单"""
old_order = jsonable_encoder(self)
self.customized_data["__old_order"] = old_order
self.customized_data["__from_cmcp"] = True
return RMCPOrder(
order_id=self.order_id,
order_type=enums.OrderType.RANDOM_SEQ_MCP,
order_status=self.order_status,
start_time=self.start_time,
end_time=self.end_time,
create_time=self.create_time,
customized_data=self.customized_data,
error_code=self.error_code,
error_msg=self.error_msg,
)
class RockyDualUnloadingOrder(Order, Generic[T]):
"""装卸车双臂拆垛订单"""
order_type: Final[enums.OrderType] = Field(
default=enums.OrderType.ROCKYDUAL_TRUCK_UNLOADING,
title="订单类型",
description="订单类型",
)
class RockyDualLoadingOrder(Order, Generic[T]):
"""装卸车双臂码垛订单"""
order_type: Final[enums.OrderType] = Field(
default=enums.OrderType.ROCKYDUAL_TRUCK_LOADING,
title="订单类型",
description="订单类型",
)
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\pallet.py | from pydantic import BaseModel
from sqlalchemy.orm import Session
from xyz_max_hmi_server import crud
from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session
from xyz_max_hmi_server.entity.workspace import Workspace
class Pallet(BaseModel):
"""托盘."""
pallet_id: str
workspace_id: str
pickable_quantity: int
placeable_quantity: int
@property
def workspace(self) -> Workspace:
"""获取托盘所在的工作空间.
Returns:
Workspace: 工作空间实例.
Raises:
XYZNotFoundError: 工作空间不存在.
"""
from xyz_max_hmi_server.modules.manager.workspace_manager import (
WorkspaceManager,
)
return WorkspaceManager().get_workspace_or_404(self.workspace_id)
def is_empty(self) -> bool:
"""判断托盘是否为空."""
return self.pickable_quantity == 0
def is_full(self) -> bool:
"""判断托盘是否已满."""
return self.placeable_quantity == 0
@provide_session
def dec_pickable_quantity(
self, quantity: int = 1, session: Session = NEW_SESSION
) -> None:
"""减少可取数量.
Args:
quantity (int, optional): 减少的数量. Defaults to 1.
"""
crud.pallet.set_pickable_quantity(
session, self.pallet_id, self.pickable_quantity - quantity
)
self.pickable_quantity -= quantity
@provide_session
def inc_pickable_quantity(
self, quantity: int = 1, session: Session = NEW_SESSION
) -> None:
"""增加可取数量.
Args:
quantity (int, optional): 增加的数量. Defaults to 1.
"""
crud.pallet.set_pickable_quantity(
session, self.pallet_id, self.pickable_quantity + quantity
)
self.pickable_quantity += quantity
@provide_session
def dec_placeable_quantity(
self, quantity: int = 1, session: Session = NEW_SESSION
) -> None:
"""减少可放数量.
Args:
quantity (int, optional): 减少的数量. Defaults to 1.
"""
crud.pallet.set_placeable_quantity(
session, self.pallet_id, self.placeable_quantity - quantity
)
self.placeable_quantity -= quantity
@provide_session
def inc_placeable_quantity(
self, quantity: int = 1, session: Session = NEW_SESSION
) -> None:
"""增加可放数量.
Args:
quantity (int, optional): 增加的数量. Defaults to 1.
"""
crud.pallet.set_placeable_quantity(
session, self.pallet_id, self.placeable_quantity + quantity
)
self.placeable_quantity += quantity
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\pre_task.py | from typing import List, Optional
from pydantic import BaseModel, Field, validator
from xyz_max_hmi_server import enums
from xyz_max_hmi_server.entity.sku import SKUInfo
from xyz_max_hmi_server.utils.i18n import gettext as _
class PreTask(BaseModel):
"""预处理任务, 用于控序混码规划"""
order_id: Optional[str] = Field(default=None, description="订单ID")
task_type: enums.TaskType = Field(..., description="任务类型")
target_num: Optional[int] = Field(default=None, description="任务数量")
from_options: List[str] = Field(
default=None,
description="可使用的抓取位",
alias="from",
)
to_options: List[str] = Field(
default=None,
description="可使用的放置位",
alias="to",
)
sku_info: Optional[SKUInfo] = Field(default=None, description="SKU信息")
@validator("from_options", "to_options", pre=True)
def validate_options(cls, v):
if isinstance(v, str):
return [v]
elif isinstance(v, list):
return v
raise ValueError(_("'from_options' 和 'to_options' 必须为字符串或字符串列表."))
@validator("target_num")
def validate_target_num(cls, num: int) -> int:
"""验证target_num是否有效.
Args:
num: 任务数量.
Returns:
int: 任务数量.
"""
if num == 0:
raise ValueError("'target_num' 不能为0.")
if num < -1:
raise ValueError("'target_num' 不能小于-1.")
return num
class Config: # noqa: D106
validate_assignment = True
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\sku.py | # Copyright (c) XYZ Robotics Inc. - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Author: Yuhang Wu <[email protected]>, 2022/9/22 上午8:58
from typing import Dict, List, Literal, Optional
from pydantic import BaseModel, Field, root_validator
from typing_extensions import Self
class Position(BaseModel):
x: float
y: float
z: float
class Orientation(BaseModel):
x: float
y: float
z: float
w: float
@root_validator()
def validate_orientation(cls, values: Dict[str, float]):
"""四元组校验"""
x = values["x"]
y = values["y"]
z = values["z"]
w = values["w"]
if abs(x**2 + y**2 + z**2 + w**2 - 1) < 0.001:
return values
raise ValueError("Orientation is not a quaternion")
class Pose(BaseModel):
position: Position
orientation: Orientation
class SKUInfo(BaseModel):
"""物料信息."""
sku_id: str = Field(title="物料ID")
sku_type: Optional[Literal["box", "tote"]] = Field(
default="box", title="物料类型"
)
sku_num: Optional[int] = None
length: float = Field(title="长度", gt=0.0)
width: float = Field(title="宽度", gt=0.0)
height: float = Field(title="高度", gt=0.0)
weight: float = Field(title="重量", gt=0.0)
weight_unit: Literal["kg", "g"] = Field(default="kg", title="重量单位")
length_unit: Literal["mm", "cm", "m"] = Field(default="mm", title="长度单位")
barcode_direction: int = Field(default=0, title="条码方向", ge=0, le=4)
load_bearing: float = Field(default=-1, title="承重, -1 表示不限制", ge=-1)
direction_options: List[str] = Field(
default=["Ori", "RotZ"],
title="方向选项",
description="方向选项, Ori: 保持原方向, RotZ: 旋转90度",
)
pose: Optional[Pose] = Field(
default=None,
title="物料的位置和姿态",
description="物料的位置和姿态, 如果为 None, 则表示不关心物料的位置和姿态",
)
@property
def id(self) -> str:
"""物料ID."""
return self.sku_id
@property
def type(self) -> Optional[Literal["box", "tote"]]:
"""物料类型."""
return self.sku_type
# @validator("weight_unit")
# def validate_weight_unit(cls, v: Literal["kg", "g"]) -> Literal["kg", "g"]:
# """根据项目类型填充默认的重量单位.
#
# 拆码垛: kg
# 分拣站: g
# """
# if settings.system.project_type == enums.ProjectType.DPT:
# return "kg"
# elif settings.system.project_type == enums.ProjectType.PP:
# return "g"
# else:
# warnings.warn(
# f"Unknown project type: {settings.system.project_type}"
# )
# return v
@root_validator(pre=True)
def fill_default(cls, values: dict) -> dict:
"""填充默认值."""
if "id" in values:
values["sku_id"] = values.pop("id")
if "type" in values:
values["sku_type"] = values.pop("type")
if "num" in values:
values["sku_num"] = values.pop("num")
return values
@root_validator
def convert_unit(cls, values: dict) -> dict:
"""将单位转换为内部使用的单位."""
if values["length_unit"] == "mm":
values["length"] /= 1000
values["width"] /= 1000
values["height"] /= 1000
values["length_unit"] = "m"
elif values["length_unit"] == "cm":
values["length"] /= 100
values["width"] /= 100
values["height"] /= 100
values["length_unit"] = "m"
if values["weight_unit"] == "g":
# FIXME:当 weight 未校验通过时, 将导致 KeyError
values["weight"] /= 1000
values["weight_unit"] = "kg"
return values
def dict(self, *args, **kwargs):
# HACK: dict 时将单位转换为外部使用的单位
result = super(SKUInfo, self.to_m().to_kg()).dict(*args, **kwargs)
# HACK: 与 sku_id, sku_type, sku_num 作用一致, 仅为了兼容旧版本
if "sku_id" in result:
result["id"] = result["sku_id"]
if "sku_type" in result:
result["type"] = result["sku_type"]
if "sku_num" in result:
result["num"] = result["sku_num"]
return result
def to_m(self) -> Self:
"""将mm转换为m."""
if self.length_unit == "mm":
return self.copy(
update={
"length": self.length / 1000,
"width": self.width / 1000,
"height": self.height / 1000,
"length_unit": "m",
}
)
elif self.length_unit == "cm":
return self.copy(
update={
"length": self.length / 100,
"width": self.width / 100,
"height": self.height / 100,
"length_unit": "m",
}
)
return self
def to_mm(self) -> Self:
"""将m转换为mm."""
if self.length_unit == "m":
return self.copy(
update={
"length": self.length * 1000,
"width": self.width * 1000,
"height": self.height * 1000,
"length_unit": "mm",
}
)
elif self.length_unit == "cm":
return self.copy(
update={
"length": self.length * 10,
"width": self.width * 10,
"height": self.height * 10,
"length_unit": "mm",
}
)
return self
def to_cm(self) -> Self:
"""将m转换为cm."""
if self.length_unit == "m":
return self.copy(
update={
"length": self.length * 100,
"width": self.width * 100,
"height": self.height * 100,
"length_unit": "cm",
}
)
elif self.length_unit == "mm":
return self.copy(
update={
"length": self.length / 10,
"width": self.width / 10,
"height": self.height / 10,
"length_unit": "cm",
}
)
return self
def to_g(self) -> Self:
"""将kg转换为g."""
if self.weight_unit == "kg":
return self.copy(
update={
"weight": self.weight * 1000,
"weight_unit": "g",
}
)
return self
def to_kg(self) -> Self:
"""将g转换为kg."""
if self.weight_unit == "g":
return self.copy(
update={
"weight": self.weight / 1000,
"weight_unit": "kg",
}
)
return self
def __eq__(self, other: Optional[Self]) -> bool:
if other is None:
return False
if not isinstance(other, SKUInfo):
return False
a = self.to_kg().to_mm()
b = other.to_kg().to_mm()
if (
round(a.length, 5) == round(b.length, 5)
and round(a.width, 5) == round(b.width, 5)
and round(a.height, 5) == round(b.height, 5)
and round(a.weight, 5) == round(b.weight, 5)
):
return True
return False
class Config:
# frozen = True # 是否允许hash
allow_population_by_field_name = True
schema_extra = {
"example": {
"id": "",
"type": "box",
"num": 5,
"sku_id": "",
"sku_type": "box",
"sku_num": 5,
"length": 1,
"width": 1,
"height": 1,
"weight": 0.005,
"weight_unit": "kg",
"length_unit": "m",
"barcode_direction": 0,
"load_bearing": -1,
"direction_options": ["Ori", "RotZ"],
"pose": {
"position": {"x": 0, "y": 0, "z": 0},
"orientation": {"x": 0, "y": 0, "z": 0, "w": 0},
},
},
}
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\task.py | # -*- coding: utf-8 -*-
# Copyright (c) XYZ Robotics Inc. - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Author: Yuhang Wu <[email protected]>, 2022/8/31 下午3:12
import uuid
from datetime import datetime
from typing import TYPE_CHECKING, Dict, Final, List, Optional, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, Field, root_validator, validator
from sqlalchemy.orm.session import Session
from typing_extensions import Self
from xyz_max_hmi_server import crud, enums
from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session
from xyz_max_hmi_server.entity.pre_task import PreTask
from xyz_max_hmi_server.entity.sku import SKUInfo
from xyz_max_hmi_server.exceptions import XYZException, XYZValidationError
from xyz_max_hmi_server.schemas.task import TaskUpdate
from xyz_max_hmi_server.signals import (
task_abort,
task_done,
task_ended,
task_pick,
task_ready,
task_reset,
task_start,
)
if TYPE_CHECKING:
from xyz_max_hmi_server.entity.order import LiteOrder
def refresh(func):
"""
用于刷新任务状态的装饰器
如果被装饰方法,没有显示的传入 session 参数,即修改的数据立即生效,
否则需要手动调用 session.commit() 方法
"""
def wrapper(self: "LiteTask", *args, **kwargs):
r = func(self, *args, **kwargs)
session = kwargs.get("session", NEW_SESSION)
self._refresh(session=session)
return r
return wrapper
class LiteTask(BaseModel):
"""简化版任务抽象类.
Warnings:
task_id、order_id、done_num、create_time、start_time、end_time
以上字段在初始化后不可直接修改, 比如下方的代码是被禁止的:
task.done_num = 10
Attributes:
task_id: 任务ID
order_id: 订单ID
sku_info: 物料信息
target_num: 目标数量
done_num: 已完成数量
customized_data: 自定义数据
create_time: 创建时间
start_time: 开始时间
end_time: 结束时间
error_code: 错误码
error_msg: 错误信息
"""
task_id: str = Field(description="任务ID", allow_mutation=False)
task_status: enums.TaskStatus = Field(
default=enums.TaskStatus.RECEIVED,
title="任务状态",
allow_mutation=False,
)
task_type: enums.TaskType = Field(title="任务类型", allow_mutation=False)
order_id: Optional[str] = Field(default=None, description="订单ID")
sku_info: Optional[SKUInfo] = Field(default=None, description="sku信息")
done_num: int = Field(
default=0, description="已完成的数量", ge=0, allow_mutation=False
)
target_num: int = Field(description="预估数量")
customized_data: Dict = Field(default_factory=dict, description="自定义字典")
start_time: Optional[datetime] = Field(
default=None, description="开始时间", allow_mutation=False
)
end_time: Optional[datetime] = Field(
default=None, description="结束时间", allow_mutation=False
)
create_time: datetime = Field(
default_factory=datetime.now,
description="创建时间",
allow_mutation=False,
)
error_code: Optional[int] = Field(default=None, description="异常码")
error_msg: Optional[str] = Field(default=None, description="异常信息")
# 用于保存 allow_mutation=False 的字段名.
_not_mutation_fields = set()
# 允许修改的方法和信号映射表
_allow_mutation_methods = {
"ready": task_ready,
"start": task_start,
"finish": task_done,
"terminate": task_abort,
"end": task_ended,
"report_pick_num": task_pick,
"reset": task_reset,
}
class Config:
validate_assignment = True
orm_mode = True
allow_population_by_field_name = True # 允许通过字段名进行赋值
# TODO: 将数据库 Model 绑定到 LiteTask 上
@property
def db_model(self):
raise NotImplementedError
@db_model.setter
def db_model(self, model):
raise NotImplementedError
@validator("target_num")
def check_target_num(cls, value):
"""检查目标数量是否合法.
target_num == -1 时表示无限制.
target_num > 0 时表示限制数量.
"""
if value == 0 or value < -1:
raise XYZValidationError("target_num is incorrect.")
return value
@root_validator()
def fill_not_mutation_fields(cls, values):
"""填充不可修改的字段."""
for _, field_info in cls.__dict__["__fields__"].items():
if field_info.field_info.allow_mutation is False:
cls._not_mutation_fields.add(field_info)
return values
@validator("customized_data", pre=True)
def validate_customized_data(cls, value: Optional[Dict]) -> Dict:
"""校验自定义数据."""
return {} if value is None else value
@classmethod
def parse_pre_task(cls, pre_task: PreTask, **kwargs) -> Self:
"""将预任务转换为任务."""
data = pre_task.dict()
data.update(kwargs)
if "task_id" not in kwargs:
data["task_id"] = str(uuid.uuid4())
return cls.parse_obj(data)
@provide_session
def _refresh(self, session: Session = NEW_SESSION):
"""将当前任务刷新到数据库中."""
task = crud.task.get_by_task_id(task_id=self.task_id, session=session)
if task is not None:
kwargs = self.dict()
sku = kwargs.pop("sku_info", None)
if isinstance(sku, BaseModel):
sku = sku.dict()
kwargs["sku_info"] = sku
kwargs["raw_data"] = jsonable_encoder(self)
obj = TaskUpdate.parse_obj(kwargs)
crud.task.update(
db_obj=task,
obj_in=obj,
session=session,
auto_commit=False,
auto_refresh=False,
)
@property
def order(self) -> Optional["LiteOrder"]:
"""获取当前任务所属的订单."""
from xyz_max_hmi_server.modules.manager import OrderManager
om = OrderManager._get_subinstance() # type: ignore
if om and self.order_id:
return om.get_by_order_id(order_id=self.order_id)
return None
@refresh
def set_order_id(self, order_id: str, session: Session = NEW_SESSION):
self.order_id = order_id
@refresh
def report_pick_num(
self,
num: int = 1,
auto_complete: bool = True,
auto_remove: bool = True,
session: Session = NEW_SESSION,
) -> None:
"""报告本次已抓取的数量.
默认情况下, 当已完成数量等于理论数量时, 此任务将自动调用 finish 方法.
可根据 auto_complete 参数来决定是否自动调用 finish 方法.
Args:
num(int): 数量, 默认为1.
auto_complete(bool): 是否自动完成, 默认为True.
auto_remove(bool): 当 `auto_complete` 为 True 时有效, 用于决定是否将任务从队列中自动移除, 默认为 True.
session: 数据库会话, 默认为新会话.
"""
self.done_num += num
def is_received(self) -> bool:
"""是否已接收."""
return self.task_status == enums.TaskStatus.RECEIVED
def is_pending(self) -> bool:
return self.task_status == enums.TaskStatus.PENDING
def is_started(self) -> bool:
return self.task_status == enums.TaskStatus.STARTED
def is_finished(self) -> bool:
"""判断当前任务是否已完成.
Examples:
if task.is_finished():
print("ok")
else:
print("failed")
Returns:
bool: True已完成, False未完成
"""
return self.task_status == enums.TaskStatus.FINISHED
def is_ended(self) -> bool:
"""判断当前任务状态是否为已结束."""
return self.task_status == enums.TaskStatus.ENDED
def is_terminated(self) -> bool:
"""判断当前任务状态是否为已终止."""
return self.task_status == enums.TaskStatus.TERMINATED
def is_removed(self) -> bool:
"""判断当前任务状态是否为已移除."""
from xyz_max_hmi_server.modules.manager import TaskManager
tm = TaskManager._get_subinstance()
if tm is None:
raise XYZException("task manager not found")
return not tm.is_exists(self)
@refresh
def ready(
self,
session: Session = NEW_SESSION,
) -> None:
"""标记任务为已准备好."""
if self.task_status == enums.TaskStatus.PENDING:
return
self.task_status = enums.TaskStatus.PENDING
@refresh
def start(self, session: Session = NEW_SESSION) -> None:
"""开始任务."""
if self.task_status == enums.TaskStatus.STARTED:
return
self.task_status = enums.TaskStatus.STARTED
self.start_time = datetime.now()
@refresh
def finish(
self,
auto_remove: bool = True,
auto_complete: bool = True,
session: Session = NEW_SESSION,
) -> None:
"""标记该任务已完成并从manager中移除任务.
Args:
auto_remove(bool): 是否从manager中移除当前任务.
session: 数据库会话, 默认为新会话.
"""
if self.task_status == enums.TaskStatus.FINISHED:
return
self.task_status = enums.TaskStatus.FINISHED
@refresh
def end(
self,
auto_remove: bool = True,
auto_complete: bool = True,
session: Session = NEW_SESSION,
) -> None:
"""标记该任务已结束并从manager中移除任务.
Args:
auto_remove(bool): 是否从manager中移除当前任务.
session(Session): 数据库会话, 默认为新会话.
"""
if self.task_status == enums.TaskStatus.ENDED:
return
self.task_status = enums.TaskStatus.ENDED
self.end_time = datetime.now()
@refresh
def terminate(
self,
error: Union[str, XYZException, None] = None,
auto_remove: bool = True,
session: Session = NEW_SESSION,
) -> None:
"""终止任务并从manager中移除任务.
Args:
error(WCSError): WCSError及子类异常对象.
auto_remove(bool): 是否从manager中移除当前任务.
"""
if error is None:
error = XYZException("task terminated.")
elif isinstance(error, str):
error = XYZException(error)
else:
raise XYZException("error must be str or XYZException.")
self.error_code = error.error_code
self.error_msg = error.error_message
self.end_time = datetime.now()
self.task_status = enums.TaskStatus.TERMINATED
@refresh
def reset(self, session: Session = NEW_SESSION) -> None:
"""重置任务状态."""
self.task_status = enums.TaskStatus.PENDING
self.done_num = 0
self.error_code = 0
self.error_msg = ""
self.start_time = None
self.end_time = None
@provide_session
def reload(self, session: Session = NEW_SESSION) -> None:
"""从数据库中重新加载数据."""
record = crud.task.get_by_task_id(self.task_id, session=session)
if record is None:
raise XYZException("task not found.")
data = record.raw_data
new_obj = self.__class__(**data) # type: ignore
for key, val in new_obj.__dict__.items():
self.__dict__[key] = val
@provide_session
def save(self, session: Session = NEW_SESSION) -> None:
"""将数据刷新到数据库."""
self._refresh(session=session)
def send_signal(self, signal):
"""用于发送信号的装饰器"""
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
signal.send(self, **kwargs)
return result
return wrapper
return decorator
def ignore_mutation(self, func):
"""暂时屏蔽 allow_mutation=False 的限制."""
def wrapper(*args, **kwargs):
# 记录变更前的状态
before_status = {}
for field in self._not_mutation_fields:
before_status[field] = field.field_info.allow_mutation
field.field_info.allow_mutation = True
result = func(*args, **kwargs)
# 恢复原来的状态
for field, status in before_status.items():
field.field_info.allow_mutation = status
return result
return wrapper
def __getattribute__(self, item):
# 当调用这些方法时, 会触发相对应的信号.
# 当调用这些方法时,暂时屏蔽 allow_mutation=False 的限制.
ignore_mutation = object.__getattribute__(self, "ignore_mutation")
send_signal = object.__getattribute__(self, "send_signal")
method = object.__getattribute__(self, item)
_allow_mutation_methods = object.__getattribute__(
self, "_allow_mutation_methods"
)
if item in _allow_mutation_methods:
method = ignore_mutation(method)
return send_signal(_allow_mutation_methods[item])(method)
return super().__getattribute__(item)
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\task_result.py | from xyz_max_hmi_server.schemas.task_result import TaskResultInDBBase
class TaskResult(TaskResultInDBBase):
class Config:
orm_mode = True
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\workspace.py | # -*- coding: utf-8 -*-
# Copyright (c) XYZ Robotics Inc. - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Author: Yuhang Wu <[email protected]>, 2022/9/20 下午6:01
from typing import TYPE_CHECKING, List, Optional
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from xyz_max_hmi_server import crud
from xyz_max_hmi_server.db.session import NEW_SESSION, provide_session
from xyz_max_hmi_server.exceptions import XYZNotFoundError, XYZValidationError
from xyz_max_hmi_server.schemas.pallet import PalletCreate
if TYPE_CHECKING:
from xyz_max_hmi_server.entity.pallet import Pallet
def refresh(func):
"""
用于刷新任务状态的装饰器
如果被装饰方法,没有显示的传入 session 参数,即修改的数据立即生效,
否则需要手动调用 session.commit() 方法
"""
def wrapper(self: "BaseWorkspace", *args, **kwargs):
r = func(self, *args, **kwargs)
session = kwargs.get("session", NEW_SESSION)
self._refresh(session=session)
return r
return wrapper
class BaseWorkspace(BaseModel):
"""工作空间.
Attributes:
ws_id (str): 工作空间ID.
is_ready (bool): 是否就绪, 默认已就绪.
is_new_pallet (bool): 是否为新托盘, 默认为True.
Methods:
ready(): 设置工作空间状态为已就绪.
not_ready(): 设置工作空间状态为未就绪.
"""
ws_id: str
is_ready: bool = True
is_new_pallet: Optional[bool] = True
current_pallet_id: Optional[str] = None
class Config:
orm_mode = True
@provide_session
def _refresh(self, session: Session):
"""将当前任务刷新到数据库中."""
result = crud.workspace.get_by_ws_id(ws_id=self.ws_id, session=session)
if result is None:
raise XYZNotFoundError(f"工作空间 {self.ws_id} 不存在")
crud.workspace.update(
db_obj=result,
obj_in=self.dict(exclude_unset=True),
session=session,
auto_commit=False,
auto_refresh=False,
)
@refresh
def ready(
self, is_new_pallet: bool = True, session: Session = NEW_SESSION
) -> None:
"""设置工作空间状态为已就绪.
Args:
is_new_pallet (bool): 是否为新托盘, 默认为True.
"""
self.is_ready = True
self.is_new_pallet = is_new_pallet
@refresh
def not_ready(self, session: Session = NEW_SESSION) -> None:
"""设置工作空间状态为未就绪."""
self.is_ready = False
@refresh
def new_pallet(self, session: Session = NEW_SESSION) -> None:
"""设置工作空间状态为新托盘."""
self.is_new_pallet = True
@refresh
def not_new_pallet(self, session: Session = NEW_SESSION) -> None:
"""设置工作空间状态为非新托盘."""
self.is_new_pallet = False
@provide_session
def save(self, session: Session = NEW_SESSION) -> None:
"""将数据刷新到数据库."""
self._refresh(session=session)
class Workspace(BaseWorkspace):
@provide_session
def get_pallets(self, session: Session = NEW_SESSION) -> List["Pallet"]:
"""获取工作空间中的托盘."""
from xyz_max_hmi_server.entity.pallet import Pallet
records = crud.pallet.list_by_workspace_id(self.ws_id, session)
return [
Pallet.parse_obj(jsonable_encoder(record)) for record in records
]
@provide_session
def add_pallet(
self, pallet: "Pallet", session: Session = NEW_SESSION
) -> None:
"""添加托盘."""
crud.pallet.create(
obj_in=PalletCreate(
pallet_id=pallet.pallet_id,
workspace_id=self.ws_id,
pickable_quantity=pallet.pickable_quantity,
placeable_quantity=pallet.placeable_quantity,
),
session=session,
)
@provide_session
def remove_pallet(
self, pallet: "Pallet", session: Session = NEW_SESSION
) -> None:
"""移除托盘."""
crud.pallet.remove_by_pallet_id(pallet.pallet_id, session=session)
# 托盘已放入工作空间
@provide_session
def pallet_in(
self, pallet: "Pallet", session: Session = NEW_SESSION
) -> None:
"""托盘已放入工作空间."""
if not crud.pallet.is_exists(pallet.pallet_id, session=session):
self.add_pallet(pallet, session=session)
crud.workspace.set_current_pallet_id(
pallet.pallet_id, self.ws_id, session=session
)
self.current_pallet_id = pallet.pallet_id
@provide_session
def pallet_out(self, session: Session = NEW_SESSION) -> None:
"""将当前托盘从工作空间移除."""
crud.workspace.set_current_pallet_id(None, self.ws_id, session=session)
# 删除托盘
if self.current_pallet_id is not None:
crud.pallet.remove_by_pallet_id(
self.current_pallet_id, session=session
)
self.current_pallet_id = None
@provide_session
def use_next_pallet(
self,
ready: bool = True,
new_pallet: bool = True,
session: Session = NEW_SESSION,
) -> None:
"""使用下一个托盘, 移除当前托盘, 并将下一个托盘设置为当前托盘.
设置工作空间状态为已就绪, 并设置当前托盘为新托盘.
"""
self.pallet_out(session=session)
record = crud.pallet.get_next_pallet_by_ws_id(
self.ws_id, session=session
)
if record is None:
raise XYZNotFoundError(f"工作空间 '{self.ws_id}' 没有可用的托盘")
if record.pallet_id is None:
raise XYZValidationError("托盘ID为空")
pallet_id = record.pallet_id
if not isinstance(pallet_id, str):
raise XYZValidationError("托盘ID不是字符串")
self.current_pallet_id = str(pallet_id)
crud.workspace.set_current_pallet_id(
pallet_id, self.ws_id, session=session
)
if ready:
self.ready(session=session)
if new_pallet:
self.new_pallet(session=session)
@provide_session
def get_current_pallet(
self, session: Session = NEW_SESSION
) -> Optional["Pallet"]:
"""获取当前工作空间中的托盘."""
from xyz_max_hmi_server.entity.pallet import Pallet
current_pallet_id = self.current_pallet_id
if current_pallet_id is None:
return None
pallet_in_db = crud.pallet.get_by_pallet_id(
current_pallet_id, session=session
)
if pallet_in_db is None:
return None
return Pallet.parse_obj(jsonable_encoder(pallet_in_db))
@provide_session
def remove_invalid_pallets(self, session: Session = NEW_SESSION) -> None:
"""移除无效的托盘."""
crud.pallet.remove_invalid_pallets(self.ws_id, session=session)
@provide_session
def clear(self, session: Session = NEW_SESSION) -> None:
"""清空工作空间."""
crud.pallet.remove_by_workspace_id(self.ws_id, session=session)
self.current_pallet_id = None
self.is_ready = False
self.is_new_pallet = False
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\entity\__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) XYZ Robotics Inc. - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Author: Yuhang Wu <[email protected]>, 2022/8/31 下午3:12
from .order import LiteOrder
from .pallet import Pallet
from .pre_task import PreTask
from .sku import SKUInfo
from .task import LiteTask
from .workspace import BaseWorkspace, Workspace
__all__ = [
"LiteOrder",
"LiteTask",
"PreTask",
"SKUInfo",
"Pallet",
"BaseWorkspace",
"Workspace",
]
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\middlewares\cors.py | from fastapi.middleware.cors import CORSMiddleware
def init_app(app):
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
return app
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\middlewares\pagination.py | import typing as t
from fastapi_pagination import add_pagination
if t.TYPE_CHECKING:
from xyz_max_hmi_server.app import Application
def init_app(app: "Application") -> "Application":
add_pagination(app)
return app
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\middlewares\sqlalchemy.py | import typing as t
from fastapi_sqlalchemy import DBSessionMiddleware as _DBSessionMiddleware, db
from loguru import logger
from starlette.middleware.base import RequestResponseEndpoint
from starlette.requests import Request
if t.TYPE_CHECKING:
from xyz_max_hmi_server.app import Application
class DBSessionMiddleware(_DBSessionMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
):
with db(commit_on_exit=self.commit_on_exit):
response = await call_next(request)
if (
hasattr(request.state, "is_error_happened")
and request.state.is_error_happened
):
db.session.rollback()
else:
try:
db.session.commit()
except Exception as e:
logger.error(f"数据库提交失败: {e}")
pass
return response
def init_app(app: "Application", db_url: str) -> "Application":
"""注册中间件"""
app.add_middleware(DBSessionMiddleware, db_url=db_url)
return app
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\middlewares\__init__.py | from . import cors, pagination, sqlalchemy
__all__ = ["sqlalchemy", "pagination", "cors"]
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\env.py | # from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from xyz_max_hmi_server.config import settings
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
# if config.config_file_name is not None:
# fileConfig(config.config_file_name)
# 读取 settings 中的数据库连接
# FIXME: 生成迁移文件时必须指定项目目录下的数据库文件, 否则无法生成迁移文件
# 如果修改了绝对路径, 又将导致执行测试用例时无法连接数据库
# config.set_main_option("sqlalchemy.url", settings.db.real_database_uri)
config.set_main_option("sqlalchemy.url", settings.db.sqlalchemy_database_uri)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from xyz_max_hmi_server.db.base import Base
target_metadata = Base.metadata # type: ignore
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section), # type: ignore
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
render_as_batch=True,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\script.py.mako | """${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\01_f1f3a26e3212_init_commit.py | """init commit
Revision ID: f1f3a26e3212
Revises:
Create Date: 2023-01-10 13:54:57.304980
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.sql import func
# NOTE: func.now() to replace sa.text("now()") for sqlite
# revision identifiers, used by Alembic.
revision = "f1f3a26e3212"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"t_error_records",
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column(
"error_code", sa.String(length=20), nullable=True, comment="异常状态码"
),
sa.Column("error_msg", sa.Text(), nullable=True, comment="异常消息"),
sa.Column(
"error_source",
sa.Enum("VP", "VISION", name="errorsources"),
nullable=True,
comment="异常来源",
),
sa.Column("tip", sa.Text(), nullable=True, comment="异常提示"),
sa.Column("task", sa.JSON(), nullable=True, comment="任务快照"),
sa.Column(
"create_time",
sa.DateTime(),
server_default=func.now(),
nullable=True,
comment="创建时间",
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_t_error_records_create_time"),
"t_error_records",
["create_time"],
unique=False,
)
op.create_table(
"t_order",
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column(
"order_id", sa.String(length=255), nullable=False, comment="订单编号"
),
sa.Column(
"order_status",
sa.Enum(
"PENDING",
"STARTED",
"FINISHED",
"ERROR",
"TERMINATED",
"ENDED",
name="orderstatus",
),
nullable=False,
comment="订单状态",
),
sa.Column("raw_data", sa.JSON(), nullable=True, comment="原始数据"),
sa.Column(
"create_time",
sa.DateTime(),
server_default=func.now(),
nullable=True,
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_t_order_create_time"),
"t_order",
["create_time"],
unique=False,
)
op.create_index(
op.f("ix_t_order_order_id"), "t_order", ["order_id"], unique=True
)
op.create_table(
"t_order_result",
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column(
"order_id", sa.String(length=50), nullable=False, comment="订单号"
),
sa.Column(
"order_status",
sa.Enum(
"PENDING",
"STARTED",
"FINISHED",
"ERROR",
"TERMINATED",
"ENDED",
name="orderstatus",
),
nullable=True,
comment="订单状态",
),
sa.Column("customized_data", sa.JSON(), nullable=True, comment="自定义数据"),
sa.Column("start_time", sa.DateTime(), nullable=True, comment="开始时间"),
sa.Column("end_time", sa.DateTime(), nullable=True, comment="结束时间"),
sa.Column(
"create_time",
sa.DateTime(),
server_default=func.now(),
nullable=True,
comment="创建时间",
),
sa.Column("error_code", sa.Integer(), nullable=True, comment="异常码"),
sa.Column(
"error_msg", sa.String(length=255), nullable=True, comment="异常信息"
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"idx_order_id", "t_order_result", ["order_id", "id"], unique=True
)
op.create_index(
op.f("ix_t_order_result_create_time"),
"t_order_result",
["create_time"],
unique=False,
)
op.create_table(
"t_task_result",
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column(
"task_id", sa.String(length=50), nullable=True, comment="任务ID"
),
sa.Column(
"order_id", sa.String(length=50), nullable=True, comment="订单ID"
),
sa.Column(
"task_type",
sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MULTI_DEPAL",
"MULTI_PAL_ONLINE",
"MULTI_PAL_OFFLINE",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
nullable=True,
comment="任务类型",
),
sa.Column(
"task_status",
sa.Enum(
"RECEIVED",
"PENDING",
"STARTED",
"FINISHED",
"ERROR",
"TERMINATED",
"ENDED",
name="taskstatus",
),
nullable=True,
comment="任务状态",
),
sa.Column("sku_info", sa.JSON(), nullable=True, comment="sku的信息"),
sa.Column("target_num", sa.Integer(), nullable=True, comment="需要执行的数量"),
sa.Column("done_num", sa.Integer(), nullable=True, comment="已完成的数量"),
sa.Column(
"from_ws", sa.String(length=50), nullable=True, comment="抓取位ID"
),
sa.Column(
"to_ws", sa.String(length=50), nullable=True, comment="放置位ID"
),
sa.Column("customized_data", sa.JSON(), nullable=True, comment="自定义数据"),
sa.Column("start_time", sa.DateTime(), nullable=True, comment="开始时间"),
sa.Column("end_time", sa.DateTime(), nullable=True, comment="结束时间"),
sa.Column(
"create_time",
sa.DateTime(),
server_default=func.now(),
nullable=True,
comment="创建时间",
),
sa.Column("error_code", sa.Integer(), nullable=True, comment="异常码"),
sa.Column(
"error_msg", sa.String(length=255), nullable=True, comment="异常信息"
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"idx_task_id_order_id",
"t_task_result",
["task_id", "order_id"],
unique=False,
)
op.create_index(
op.f("ix_t_task_result_create_time"),
"t_task_result",
["create_time"],
unique=False,
)
op.create_table(
"t_workspace",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("create_time", sa.DateTime(), nullable=True),
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column(
"ws_id", sa.String(length=32), nullable=True, comment="工作空间ID"
),
sa.Column("is_ready", sa.Boolean(), nullable=True, comment="是否就绪"),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_t_workspace_ws_id"), "t_workspace", ["ws_id"], unique=True
)
op.create_table(
"t_task",
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column(
"task_id", sa.String(length=255), nullable=False, comment="任务编号"
),
sa.Column(
"task_status",
sa.Enum(
"RECEIVED",
"PENDING",
"STARTED",
"FINISHED",
"ERROR",
"TERMINATED",
"ENDED",
name="taskstatus",
),
nullable=False,
comment="任务状态",
),
sa.Column(
"task_type",
sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MULTI_DEPAL",
"MULTI_PAL_ONLINE",
"MULTI_PAL_OFFLINE",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
nullable=False,
comment="任务类型",
),
sa.Column("order_id", sa.String(length=255), nullable=True),
sa.Column("sku_info", sa.JSON(), nullable=True, comment="sku的信息"),
sa.Column("target_num", sa.Integer(), nullable=True, comment="需要执行的数量"),
sa.Column("done_num", sa.Integer(), nullable=True, comment="已完成的数量"),
sa.Column("customized_data", sa.JSON(), nullable=True, comment="自定义数据"),
sa.Column("start_time", sa.DateTime(), nullable=True, comment="开始时间"),
sa.Column("end_time", sa.DateTime(), nullable=True, comment="结束时间"),
sa.Column("raw_data", sa.JSON(), nullable=True, comment="额外数据"),
sa.Column(
"create_time",
sa.DateTime(),
server_default=func.now(),
nullable=True,
),
sa.ForeignKeyConstraint(
["order_id"],
["t_order.order_id"],
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("order_id", "task_id", name="uix_task_id_order_id"),
)
op.create_index("idx_task_status", "t_task", ["task_status"], unique=False)
op.create_index(
op.f("ix_t_task_create_time"), "t_task", ["create_time"], unique=False
)
op.create_index(
op.f("ix_t_task_task_id"), "t_task", ["task_id"], unique=False
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_t_task_task_id"), table_name="t_task")
op.drop_index(op.f("ix_t_task_create_time"), table_name="t_task")
op.drop_index("idx_task_status", table_name="t_task")
op.drop_table("t_task")
op.drop_index(op.f("ix_t_workspace_ws_id"), table_name="t_workspace")
op.drop_table("t_workspace")
op.drop_index(
op.f("ix_t_task_result_create_time"), table_name="t_task_result"
)
op.drop_index("idx_task_id_order_id", table_name="t_task_result")
op.drop_table("t_task_result")
op.drop_index(
op.f("ix_t_order_result_create_time"), table_name="t_order_result"
)
op.drop_index("idx_order_id", table_name="t_order_result")
op.drop_table("t_order_result")
op.drop_index(op.f("ix_t_order_order_id"), table_name="t_order")
op.drop_index(op.f("ix_t_order_create_time"), table_name="t_order")
op.drop_table("t_order")
op.drop_index(
op.f("ix_t_error_records_create_time"), table_name="t_error_records"
)
op.drop_table("t_error_records")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\02_b2a98a1384b7_add_cycle_table.py | """add cycle table
Revision ID: b2a98a1384b7
Revises: f1f3a26e3212
Create Date: 2023-05-25 16:29:45.346611
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "b2a98a1384b7"
down_revision = "f1f3a26e3212"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"t_cycle",
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("id", sa.String(50), nullable=False, comment="节拍数据唯一ID"),
sa.Column("data", sa.JSON(), nullable=False, comment="节拍数据"),
sa.Column(
"create_time",
sa.DateTime(),
server_default=sa.text("(CURRENT_TIMESTAMP)"),
nullable=True,
comment="创建时间",
),
sa.PrimaryKeyConstraint("id"),
mysql_engine="InnoDB",
)
op.create_index(
op.f("ix_t_cycle_create_time"),
"t_cycle",
["create_time"],
unique=False,
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_t_cycle_create_time"), table_name="t_cycle")
op.drop_table("t_cycle")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\03_01545379df6b_add_column.py | """t_task 表新增 class_name 字段.
Revision ID: 01545379df6b
Revises: b2a98a1384b7
Create Date: 2023-07-19 16:57:47.031409
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "01545379df6b"
down_revision = "b2a98a1384b7"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_task", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"class_name",
sa.String(length=255),
nullable=True,
comment="任务类名",
)
)
batch_op.alter_column(
"task_type",
existing_type=sa.VARCHAR(length=17),
type_=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
existing_nullable=False,
)
with op.batch_alter_table("t_task_result", schema=None) as batch_op:
batch_op.alter_column(
"task_type",
existing_type=sa.VARCHAR(length=17),
type_=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
existing_nullable=True,
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_task_result", schema=None) as batch_op:
batch_op.alter_column(
"task_type",
existing_type=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
type_=sa.VARCHAR(length=17),
existing_nullable=True,
)
with op.batch_alter_table("t_task", schema=None) as batch_op:
batch_op.alter_column(
"task_type",
existing_type=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
type_=sa.VARCHAR(length=17),
existing_nullable=False,
)
batch_op.drop_column("class_name")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\04_1abea9c92276_add_column.py | """t_order 表新增 class_name 字段.
Revision ID: 1abea9c92276
Revises: 01545379df6b
Create Date: 2023-07-20 09:34:54.729293
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "1abea9c92276"
down_revision = "01545379df6b"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"class_name",
sa.String(length=255),
nullable=True,
comment="类名",
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.drop_column("class_name")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\05_a4bc4d5c0ee5_add_table_t_cmcp_planning_result.py | """新增表 t_cmcp_planning_result
Revision ID: a4bc4d5c0ee5
Revises: 1abea9c92276
Create Date: 2023-07-20 14:15:39.290944
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "a4bc4d5c0ee5"
down_revision = "1abea9c92276"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"t_cmcp_planning_result",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("create_time", sa.DateTime(), nullable=True),
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column(
"order_id", sa.String(length=50), nullable=False, comment="订单号"
),
sa.Column(
"status",
sa.Enum(
"PENDING",
"PLANNING",
"SUCCESS",
"FAILURE",
name="cmcpplanningstatus",
),
nullable=True,
comment="状态",
),
sa.Column(
"error_msg", sa.String(length=100), nullable=True, comment="错误信息"
),
sa.Column("results", sa.JSON(), nullable=True, comment="结果"),
sa.Column("start_time", sa.DateTime(), nullable=True, comment="开始时间"),
sa.Column("end_time", sa.DateTime(), nullable=True, comment="结束时间"),
sa.PrimaryKeyConstraint("id"),
mysql_engine="InnoDB",
)
with op.batch_alter_table(
"t_cmcp_planning_result", schema=None
) as batch_op:
batch_op.create_index(
batch_op.f("ix_t_cmcp_planning_result_order_id"),
["order_id"],
unique=False,
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table(
"t_cmcp_planning_result", schema=None
) as batch_op:
batch_op.drop_index(batch_op.f("ix_t_cmcp_planning_result_order_id"))
op.drop_table("t_cmcp_planning_result")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\06_d78672fe2a71_add_column_is_new_pallet.py | """新增列 is_new_pallet
Revision ID: d78672fe2a71
Revises: a4bc4d5c0ee5
Create Date: 2023-07-28 17:52:23.848255
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "d78672fe2a71"
down_revision = "a4bc4d5c0ee5"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_workspace", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"is_new_pallet", sa.Boolean(), nullable=True, comment="是否为新托盘"
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_workspace", schema=None) as batch_op:
batch_op.drop_column("is_new_pallet")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\07_4837ccbd2cbd_add_column_class_name.py | """t_workspace add column class_name
Revision ID: 4837ccbd2cbd
Revises: d78672fe2a71
Create Date: 2023-07-28 18:21:20.382223
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "4837ccbd2cbd"
down_revision = "d78672fe2a71"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_workspace", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"class_name",
sa.String(length=32),
nullable=True,
comment="工作空间类名",
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_workspace", schema=None) as batch_op:
batch_op.drop_column("class_name")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\08_2a40ec86aa30_add_column_for_cycle_table.py | """新增 t_cycle 表的 is_persisted 和 file_path 字段
Revision ID: 2a40ec86aa30
Revises: 4837ccbd2cbd
Create Date: 2023-08-17 15:20:40.429078
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "2a40ec86aa30"
down_revision = "4837ccbd2cbd"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_cycle", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"is_persisted",
sa.Boolean(),
nullable=True,
comment="是否已持久化",
)
)
batch_op.add_column(
sa.Column(
"file_path",
sa.String(length=255),
nullable=True,
comment="节拍数据文件路径",
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_cycle", schema=None) as batch_op:
batch_op.drop_column("file_path")
batch_op.drop_column("is_persisted")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\09_d9f1a78bcc3f_add_order_type.py | """新增订单类型字段
Revision ID: d9f1a78bcc3f
Revises: 2a40ec86aa30
Create Date: 2023-08-22 09:15:49.816266
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "d9f1a78bcc3f"
down_revision = "2a40ec86aa30"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"order_type",
sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"RANDOM_SEQ_MCP",
"CONTROLLED_SEQ_MCP",
"PP_DEFAULT",
"PP_CYCLE",
name="ordertype",
),
nullable=True,
comment="订单类型",
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.drop_column("order_type")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\10_af0f46273e0e_remove_index.py | """移除 t_order_result 表的 idx_order_id 索引
Revision ID: af0f46273e0e
Revises: d9f1a78bcc3f
Create Date: 2023-08-23 16:28:07.352827
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "af0f46273e0e"
down_revision = "d9f1a78bcc3f"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_order_result", schema=None) as batch_op:
batch_op.drop_index("idx_order_id")
batch_op.create_index(
batch_op.f("ix_t_order_result_order_id"),
["order_id"],
unique=False,
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_order_result", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_t_order_result_order_id"))
batch_op.create_index("idx_order_id", ["order_id", "id"], unique=False)
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\11_745f026b3db8_add_pallet_table.py | """add pallet table
Revision ID: 745f026b3db8
Revises: af0f46273e0e
Create Date: 2023-09-09 14:48:53.316440
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "745f026b3db8"
down_revision = "af0f46273e0e"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"t_pallet",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("create_time", sa.DateTime(), nullable=True),
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column(
"pallet_id",
sa.String(length=255),
nullable=True,
comment="托盘编号",
),
sa.Column(
"workspace_id",
sa.String(length=255),
nullable=True,
comment="工作区编号",
),
sa.Column(
"pickable_quantity",
sa.Integer(),
nullable=True,
comment="可抓取的数量",
),
sa.Column(
"placeable_quantity",
sa.Integer(),
nullable=True,
comment="可放置的数量",
),
sa.PrimaryKeyConstraint("id"),
mysql_engine="InnoDB",
)
with op.batch_alter_table("t_pallet", schema=None) as batch_op:
batch_op.create_index(
batch_op.f("ix_t_pallet_pallet_id"), ["pallet_id"], unique=False
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_pallet", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_t_pallet_pallet_id"))
op.drop_table("t_pallet")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\12_f22877c2b9f5_planning_result_key.py | """订单规划结果表增加key字段
Revision ID: f22877c2b9f5
Revises: af0f46273e0e
Create Date: 2023-09-04 14:29:46.799955
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "f22877c2b9f5"
down_revision = "745f026b3db8"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table(
"t_cmcp_planning_result", schema=None
) as batch_op:
batch_op.add_column(
sa.Column(
"key", sa.String(length=50), nullable=True, comment="唯一标识"
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table(
"t_cmcp_planning_result", schema=None
) as batch_op:
batch_op.drop_column("key")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\13_771fd0c26a5a_add_unique_key.py | """规划结果表增加唯一索引
Revision ID: 771fd0c26a5a
Revises: f22877c2b9f5
Create Date: 2023-09-06 15:46:26.000829
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "771fd0c26a5a"
down_revision = "f22877c2b9f5"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table(
"t_cmcp_planning_result", schema=None
) as batch_op:
batch_op.create_index(
batch_op.f("ix_t_cmcp_planning_result_key"), ["key"], unique=True
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table(
"t_cmcp_planning_result", schema=None
) as batch_op:
batch_op.drop_index(batch_op.f("ix_t_cmcp_planning_result_key"))
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\14_307db6a158e9_add_column_current_pallet_id.py | """t_workspace add column current_pallet_id
Revision ID: 307db6a158e9
Revises: 771fd0c26a5a
Create Date: 2023-09-11 13:41:25.615484
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "307db6a158e9"
down_revision = "771fd0c26a5a"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_workspace", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"current_pallet_id",
sa.String(length=32),
nullable=True,
comment="当前托盘ID",
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_workspace", schema=None) as batch_op:
batch_op.drop_column("current_pallet_id")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\15_01a4b13a78b7_add_table_t_task_batch.py | """add table t_task_batch
Revision ID: 01a4b13a78b7
Revises: 307db6a158e9
Create Date: 2023-09-15 16:47:52.016209
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "01a4b13a78b7"
down_revision = "307db6a158e9"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"t_task_batch",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("create_time", sa.DateTime(), nullable=True),
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("batch_id", sa.String(50), nullable=True, comment="批次ID"),
sa.Column("task_id", sa.String(50), nullable=True, comment="任务ID"),
sa.PrimaryKeyConstraint("id"),
mysql_engine="InnoDB",
)
with op.batch_alter_table("t_task_batch", schema=None) as batch_op:
batch_op.create_index(
batch_op.f("ix_t_task_batch_batch_id"), ["batch_id"], unique=False
)
batch_op.create_index(
batch_op.f("ix_t_task_batch_task_id"), ["task_id"], unique=False
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_task_batch", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_t_task_batch_task_id"))
batch_op.drop_index(batch_op.f("ix_t_task_batch_batch_id"))
op.drop_table("t_task_batch")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\16_8d9923282189_add_table_g.py | """add table global_variable
Revision ID: 8d9923282189
Revises: 01a4b13a78b7
Create Date: 2023-10-21 11:24:49.662108
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "8d9923282189"
down_revision = "01a4b13a78b7"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"t_global_variable",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("create_time", sa.DateTime(), nullable=True),
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column("key", sa.String(length=255), nullable=False, comment="变量名"),
sa.Column(
"binary_value", sa.LargeBinary(), nullable=True, comment="二进制值"
),
sa.Column(
"serialize_method",
sa.String(length=255),
nullable=True,
comment="序列化方法",
),
sa.PrimaryKeyConstraint("id"),
mysql_engine="InnoDB",
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("t_global_variable")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\17_378af6183812_add_priority_column_to_order_and_task.py | """Add priority column to t_order and t_task
Revision ID: 378af6183812
Revises: 8d9923282189
Create Date: 2023-11-16 10:46:36.886791
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "378af6183812"
down_revision = "8d9923282189"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"priority",
sa.Integer(),
nullable=False,
server_default="MIN(0)",
comment="优先级",
)
)
with op.batch_alter_table("t_task", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"priority",
sa.Integer(),
nullable=False,
server_default="MIN(0)",
comment="优先级",
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_task", schema=None) as batch_op:
batch_op.drop_column("priority")
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.drop_column("priority")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\18_bd084fe1744d_add_table_t_arrival_sequence.py | """Create a new table "t_arrival_sequence" and modify column types for "t_order", "t_task", and "t_task_result".
Revision ID: bd084fe1744d
Revises: 378af6183812
Create Date: 2023-12-07 10:48:53.200836
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "bd084fe1744d"
down_revision = "378af6183812"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"t_arrival_sequence",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("create_time", sa.DateTime(), nullable=True),
sa.Column("update_time", sa.DateTime(), nullable=True),
sa.Column(
"order_id", sa.String(length=50), nullable=False, comment="订单号"
),
sa.Column(
"expect_box_size", sa.JSON(), nullable=False, comment="预期箱子的尺寸"
),
sa.Column(
"actual_box_size", sa.JSON(), nullable=True, comment="实际箱子的尺寸"
),
sa.Column("checked", sa.Boolean(), nullable=False, comment="是否已经检查"),
sa.Column("is_match", sa.Boolean(), nullable=False, comment="是否匹配"),
sa.Column("is_complete", sa.Boolean(), nullable=False, comment="是否完成"),
sa.PrimaryKeyConstraint("id"),
mysql_engine="InnoDB",
)
with op.batch_alter_table("t_arrival_sequence", schema=None) as batch_op:
batch_op.create_index(
batch_op.f("ix_t_arrival_sequence_order_id"),
["order_id"],
unique=False,
)
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.alter_column(
"order_type",
existing_type=sa.VARCHAR(length=18),
type_=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"RANDOM_SEQ_MCP",
"CONTROLLED_SEQ_MCP",
"ROCKYDUAL_TRUCK_UNLOADING",
"ROCKYDUAL_TRUCK_LOADING",
"PP_DEFAULT",
"PP_CYCLE",
name="ordertype",
),
existing_nullable=True,
)
with op.batch_alter_table("t_task", schema=None) as batch_op:
batch_op.alter_column(
"task_type",
existing_type=sa.VARCHAR(length=18),
type_=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"ROCKYDUAL_TRUCK_UNLOADING",
"ROCKYDUAL_TRUCK_LOADING",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
existing_nullable=False,
)
with op.batch_alter_table("t_task_result", schema=None) as batch_op:
batch_op.alter_column(
"task_type",
existing_type=sa.VARCHAR(length=18),
type_=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"ROCKYDUAL_TRUCK_UNLOADING",
"ROCKYDUAL_TRUCK_LOADING",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
existing_nullable=True,
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_task_result", schema=None) as batch_op:
batch_op.alter_column(
"task_type",
existing_type=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"ROCKYDUAL_TRUCK_UNLOADING",
"ROCKYDUAL_TRUCK_LOADING",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
type_=sa.VARCHAR(length=18),
existing_nullable=True,
)
with op.batch_alter_table("t_task", schema=None) as batch_op:
batch_op.alter_column(
"task_type",
existing_type=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"MULTI_DEPAL",
"RANDOM_SEQ_MCP",
"MULTI_PAL_ONLINE",
"CONTROLLED_SEQ_MCP",
"MULTI_PAL_OFFLINE",
"ROCKYDUAL_TRUCK_UNLOADING",
"ROCKYDUAL_TRUCK_LOADING",
"PP_DEFAULT",
"PP_CYCLE",
name="tasktype",
),
type_=sa.VARCHAR(length=18),
existing_nullable=False,
)
with op.batch_alter_table("t_order", schema=None) as batch_op:
batch_op.alter_column(
"order_type",
existing_type=sa.Enum(
"SINGLE_DEPAL",
"SINGLE_PAL",
"MCD",
"RANDOM_SEQ_MCP",
"CONTROLLED_SEQ_MCP",
"ROCKYDUAL_TRUCK_UNLOADING",
"ROCKYDUAL_TRUCK_LOADING",
"PP_DEFAULT",
"PP_CYCLE",
name="ordertype",
),
type_=sa.VARCHAR(length=18),
existing_nullable=True,
)
with op.batch_alter_table("t_arrival_sequence", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_t_arrival_sequence_order_id"))
op.drop_table("t_arrival_sequence")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\migrations\versions\19_021c40a6a602_add_extra_column_to_t_arrival_sequence.py | """Add extra column to t_arrival_sequence
Revision ID: 021c40a6a602
Revises: bd084fe1744d
Create Date: 2023-12-12 10:04:48.536632
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "021c40a6a602"
down_revision = "bd084fe1744d"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_arrival_sequence", schema=None) as batch_op:
batch_op.add_column(
sa.Column("extra", sa.JSON(), nullable=True, comment="额外信息")
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("t_arrival_sequence", schema=None) as batch_op:
batch_op.drop_column("extra")
# ### end Alembic commands ###
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\models\arrival_sequence.py | """物料的来料顺序表"""
import sqlalchemy as sa
from xyz_max_hmi_server.db.base_class import Base
class ArrivalSequenceModel(Base): # type: ignore
"""物料的来料顺序表"""
__tablename__ = "t_arrival_sequence"
order_id = sa.Column(
sa.String(50), nullable=False, index=True, comment="订单号"
)
expect_box_size = sa.Column(sa.JSON, nullable=False, comment="预期箱子的尺寸")
actual_box_size = sa.Column(sa.JSON, nullable=True, comment="实际箱子的尺寸")
checked = sa.Column(
sa.Boolean, nullable=False, default=False, comment="是否已经检查"
)
is_match = sa.Column(
sa.Boolean, nullable=False, default=False, comment="是否匹配"
)
is_complete = sa.Column(
sa.Boolean, nullable=False, default=False, comment="是否完成"
)
extra = sa.Column(sa.JSON, nullable=True, comment="额外信息")
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\models\cmcp_planning_result.py | import sqlalchemy as sa
from xyz_max_hmi_server import enums
from xyz_max_hmi_server.db.base_class import Base
class CMCPPlanningResultModel(Base): # type: ignore
__tablename__ = "t_cmcp_planning_result"
order_id = sa.Column(
sa.String(50), nullable=False, index=True, comment="订单号"
)
key = sa.Column(
sa.String(50),
nullable=True,
index=True,
unique=True,
comment="唯一标识",
)
status = sa.Column(sa.Enum(enums.CMCPPlanningStatus), comment="状态")
error_msg = sa.Column(sa.String(100), nullable=True, comment="错误信息")
results = sa.Column(sa.JSON, nullable=True, comment="结果")
start_time = sa.Column(sa.DateTime, nullable=True, comment="开始时间")
end_time = sa.Column(sa.DateTime, nullable=True, comment="结束时间")
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\models\cycle.py | import sqlalchemy as sa
from sqlalchemy.sql import func
from xyz_max_hmi_server.db.base_class import Base
class CycleModel(Base): # type: ignore
__tablename__ = "t_cycle"
id = sa.Column(sa.String(50), primary_key=True, comment="节拍数据唯一ID")
data = sa.Column(sa.JSON, nullable=False, comment="节拍数据")
is_persisted = sa.Column(
sa.Boolean,
default=False,
comment="是否已持久化",
)
file_path = sa.Column(sa.String(255), comment="节拍数据文件路径")
create_time = sa.Column(
sa.DateTime, server_default=func.now(), index=True, comment="创建时间"
)
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\models\error_records.py | import sqlalchemy as sa
from sqlalchemy.sql import func
from xyz_max_hmi_server import enums
from xyz_max_hmi_server.db.base_class import Base
class ErrorRecordsModel(Base): # type: ignore
__tablename__ = "t_error_records"
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
error_code = sa.Column(sa.String(20), nullable=True, comment="异常状态码")
error_msg = sa.Column(sa.Text, nullable=True, comment="异常消息")
error_source = sa.Column(sa.Enum(enums.ErrorSources), comment="异常来源")
tip = sa.Column(sa.Text, nullable=True, comment="异常提示")
task = sa.Column(sa.JSON, nullable=True, comment="任务快照")
create_time = sa.Column(
sa.DateTime, server_default=func.now(), index=True, comment="创建时间"
)
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\models\global_variable.py | """临时变量表模型"""
import sqlalchemy as sa
from xyz_max_hmi_server.db.base_class import Base
class GlobalVariableModel(Base): # type: ignore
__tablename__ = "t_global_variable"
key = sa.Column(sa.String(255), comment="变量名", nullable=False)
binary_value = sa.Column(sa.LargeBinary, comment="二进制值")
serialize_method = sa.Column(sa.String(255), comment="序列化方法")
# val_type = sa.Column(sa.String(255), comment="类型")
# value = sa.Column(sa.TEXT, comment="值")
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\models\order.py | import sqlalchemy as sa
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from xyz_max_hmi_server import enums
from xyz_max_hmi_server.db.base_class import Base
class OrderModel(Base): # type: ignore
__tablename__ = "t_order"
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
order_id = sa.Column(
sa.String(255),
comment="订单编号",
index=True,
unique=True,
nullable=False,
)
order_status = sa.Column(
sa.Enum(enums.OrderStatus), comment="订单状态", nullable=False
)
order_type = sa.Column(
sa.Enum(enums.OrderType), comment="订单类型", nullable=True
)
tasks = relationship(
"TaskModel", back_populates="order", cascade="all, delete-orphan"
)
priority = sa.Column(sa.Integer, default=0, comment="优先级", nullable=False)
raw_data = sa.Column(sa.JSON, comment="原始数据")
class_name = sa.Column(sa.String(255), comment="类名")
create_time = sa.Column(sa.DateTime, server_default=func.now(), index=True)
| 0 |
xyz_max_hmi_server | repos\xyz_max_hmi_server\models\order_result.py | import sqlalchemy as sa
from sqlalchemy.sql import func
from xyz_max_hmi_server import enums
from xyz_max_hmi_server.db.base_class import Base
class OrderResultModel(Base): # type: ignore
"""
订单结果表
"""
__tablename__ = "t_order_result"
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
order_id = sa.Column(
sa.String(50), nullable=False, index=True, unique=False, comment="订单号"
)
order_status = sa.Column(sa.Enum(enums.OrderStatus), comment="订单状态")
customized_data = sa.Column(sa.JSON, comment="自定义数据")
start_time = sa.Column(sa.DateTime, comment="开始时间")
end_time = sa.Column(sa.DateTime, comment="结束时间")
create_time = sa.Column(
sa.DateTime, index=True, server_default=func.now(), comment="创建时间"
)
error_code = sa.Column(sa.Integer, default=None, comment="异常码")
error_msg = sa.Column(sa.String(255), default=None, comment="异常信息")
| 0 |