From 81313e61b02af36496488907dfa5f4331a0fe297 Mon Sep 17 00:00:00 2001 From: lidg Date: Fri, 6 Nov 2026 15:49:33 +0800 Subject: [PATCH] =?UTF-8?q?feat(production):=20=E4=BF=AE=E6=94=B9=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=B5=81=E7=A8=8B=E5=8D=A1=E6=AD=BB=E6=B5=81=E7=A8=8B?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.ini | 17 +- config/configmanager.cpp | 19 + config/configmanager.h | 5 + db/schema.sql | 46 +- ...-11-05-active-run-order-deletion-design.md | 91 +++ .../specs/2026-11-06-connected-plc-ready.md | 15 + .../2026-11-06-disable-action-timeouts.md | 14 + ...2026-11-06-orphan-photo-feedback-unlock.md | 19 + .../specs/2026-11-06-plc-flow-fixes.md | 46 ++ .../specs/2026-11-06-vision-lock-lifecycle.md | 22 + .../2026-11-06-vision-preflight-stall.md | 17 + modbus/modbusaddress.cpp | 2 + modbus/modbusaddress.h | 2 + pages/dashboardpage.cpp | 84 ++- pages/dashboardpage.h | 3 + repositories/productionrepository.cpp | 62 +- repositories/productionrepository.h | 2 + services/deviceservice.cpp | 32 +- services/deviceservice.h | 1 + services/orderservice.cpp | 34 +- services/productionservice.cpp | 641 ++++++++++++------ services/productionservice.h | 21 + services/productionworker.cpp | 12 +- services/productionworker.h | 3 +- 24 files changed, 949 insertions(+), 261 deletions(-) create mode 100644 docs/superpowers/specs/2026-11-05-active-run-order-deletion-design.md create mode 100644 docs/superpowers/specs/2026-11-06-connected-plc-ready.md create mode 100644 docs/superpowers/specs/2026-11-06-disable-action-timeouts.md create mode 100644 docs/superpowers/specs/2026-11-06-orphan-photo-feedback-unlock.md create mode 100644 docs/superpowers/specs/2026-11-06-plc-flow-fixes.md create mode 100644 docs/superpowers/specs/2026-11-06-vision-lock-lifecycle.md create mode 100644 docs/superpowers/specs/2026-11-06-vision-preflight-stall.md diff --git a/config.ini b/config.ini index cb29ac9..19e1c3c 100644 --- a/config.ini +++ b/config.ini @@ -47,6 +47,10 @@ frontUnloadCommand=802 frontUnloadFeedback=809 flipCommand=840 flipFeedback=842 + +flipCommand2=841 +flipFeedback2=843 + backLoadCommand=806 backLoadFeedback=813 backUnloadCommand=805 @@ -55,8 +59,8 @@ rackPlaceCommand=801 rackPlaceFeedback=808 inspectionMode=814 -photoMoveCoil=850 -photoMoveCoilFeedback=851 +photoMoveCoil=846 +photoMoveCoilFeedback=844 comparisonPickCoil=852 @@ -82,6 +86,13 @@ errorResult=3 simulationResult=1 timeoutWarningMs=8000 stateTimeoutMs=10000 +; Legacy per-stage limits: mechanical action timeouts are disabled. +; stateTimeoutMs still applies to vision PLC stages. +; readyTimeoutMs=10000 +; photoMoveTimeoutMs=10000 +; handlingTimeoutMs=10000 +; flipTimeoutMs=10000 +; inspectionTimeoutMs=10000 maxRecoveryRetries=1 simulationStepMs=500 usePlcErrorCode=false @@ -92,7 +103,7 @@ productionEnabled=true [vision] ; Recognition switch only; the M850/M851 photo-position stage always precedes RackPick. -enabled=true +enabled=false contractConfirmed=true photoPoseReadyConfirmed=true executablePath=E:/QTCode/VisionGuide/VisionGuide_Qt/source/build-ssp-integration/bin/VisionGuide.exe diff --git a/config/configmanager.cpp b/config/configmanager.cpp index acd27a0..c0c4e46 100644 --- a/config/configmanager.cpp +++ b/config/configmanager.cpp @@ -118,6 +118,8 @@ bool ConfigManager::load(const QString &filePath) settings.value("modbus/frontUnloadCommand", addresses.frontUnloadCommand).toInt(); addresses.flipCommand = settings.value("modbus/flipCommand", addresses.flipCommand).toInt(); + addresses.flipCommand2 = + settings.value("modbus/flipCommand2", addresses.flipCommand2).toInt(); addresses.backLoadCommand = settings.value("modbus/backLoadCommand", addresses.backLoadCommand).toInt(); addresses.backUnloadCommand = @@ -134,6 +136,8 @@ bool ConfigManager::load(const QString &filePath) settings.value("modbus/frontUnloadFeedback", addresses.frontUnloadFeedback).toInt(); addresses.flipFeedback = settings.value("modbus/flipFeedback", addresses.flipFeedback).toInt(); + addresses.flipFeedback2 = + settings.value("modbus/flipFeedback2", addresses.flipFeedback2).toInt(); addresses.backLoadFeedback = settings.value("modbus/backLoadFeedback", addresses.backLoadFeedback).toInt(); addresses.backUnloadFeedback = @@ -177,6 +181,16 @@ bool ConfigManager::load(const QString &filePath) m_productionConfig.stateTimeoutMs = settings.value("production/stateTimeoutMs", m_productionConfig.stateTimeoutMs).toInt(); + m_productionConfig.readyTimeoutMs = settings.value( + "production/readyTimeoutMs", m_productionConfig.stateTimeoutMs).toInt(); + m_productionConfig.photoMoveTimeoutMs = settings.value( + "production/photoMoveTimeoutMs", m_productionConfig.stateTimeoutMs).toInt(); + m_productionConfig.handlingTimeoutMs = settings.value( + "production/handlingTimeoutMs", m_productionConfig.stateTimeoutMs).toInt(); + m_productionConfig.flipTimeoutMs = settings.value( + "production/flipTimeoutMs", m_productionConfig.stateTimeoutMs).toInt(); + m_productionConfig.inspectionTimeoutMs = settings.value( + "production/inspectionTimeoutMs", m_productionConfig.stateTimeoutMs).toInt(); m_productionConfig.maxRecoveryRetries = settings.value("production/maxRecoveryRetries", m_productionConfig.maxRecoveryRetries).toInt(); @@ -298,6 +312,11 @@ bool ConfigManager::validate(QString *error) const } if (m_productionConfig.timeoutWarningMs <= 0 || m_productionConfig.stateTimeoutMs <= 0 + || m_productionConfig.readyTimeoutMs <= 0 + || m_productionConfig.photoMoveTimeoutMs <= 0 + || m_productionConfig.handlingTimeoutMs <= 0 + || m_productionConfig.flipTimeoutMs <= 0 + || m_productionConfig.inspectionTimeoutMs <= 0 || m_productionConfig.timeoutWarningMs >= m_productionConfig.stateTimeoutMs || m_productionConfig.maxRecoveryRetries < 0 || m_productionConfig.simulationStepMs <= 0) { diff --git a/config/configmanager.h b/config/configmanager.h index 028bad4..20bae5e 100644 --- a/config/configmanager.h +++ b/config/configmanager.h @@ -43,6 +43,11 @@ struct ProductionConfig int simulationResult = 1; int timeoutWarningMs = 8000; int stateTimeoutMs = 10000; + int readyTimeoutMs = 10000; + int photoMoveTimeoutMs = 10000; + int handlingTimeoutMs = 10000; + int flipTimeoutMs = 10000; + int inspectionTimeoutMs = 10000; int maxRecoveryRetries = 1; int simulationStepMs = 500; bool usePlcErrorCode = false; diff --git a/db/schema.sql b/db/schema.sql index 1f5d7fe..0972751 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -119,7 +119,7 @@ create table if not exists schema_version ( ); insert into schema_version (id, version, description) -values (1, 7, 'Quality query indexes') +values (1, 10, 'Support reverse flip production checkpoints') on conflict (id) do update set version = excluded.version, description = excluded.description, @@ -151,6 +151,7 @@ create table if not exists production_runs ( 'RUNNING', 'PAUSED', 'RECOVERY', + 'STOPPING', 'ERROR', 'COMPLETED', 'STOPPED' @@ -169,7 +170,7 @@ create table if not exists production_runs ( create unique index if not exists ux_production_runs_active_order on production_runs(order_id) -where run_state in ('RUNNING', 'PAUSED', 'RECOVERY'); +where run_state in ('RUNNING', 'PAUSED', 'RECOVERY', 'STOPPING'); create index if not exists ix_production_runs_order_id on production_runs(order_id); @@ -177,6 +178,38 @@ on production_runs(order_id); create index if not exists ix_production_runs_workpiece_id on production_runs(current_workpiece_id); +-- Existing databases were created before STOPPING became a persisted run state. +do $$ +declare + target_table regclass := 'production_runs'::regclass; +begin + if exists ( + select 1 from pg_indexes + where schemaname = current_schema() + and indexname = 'ux_production_runs_active_order' + and indexdef not like '%STOPPING%' + ) then + drop index ux_production_runs_active_order; + create unique index ux_production_runs_active_order + on production_runs(order_id) + where run_state in ('RUNNING', 'PAUSED', 'RECOVERY', 'STOPPING'); + end if; + if exists ( + select 1 from pg_constraint + where conrelid = target_table + and conname = 'ck_production_run_state' + and pg_get_constraintdef(oid) not like '%STOPPING%' + ) then + alter table production_runs drop constraint ck_production_run_state; + alter table production_runs add constraint ck_production_run_state + check (run_state in ( + 'RUNNING', 'PAUSED', 'RECOVERY', 'STOPPING', + 'ERROR', 'COMPLETED', 'STOPPED' + )); + end if; +end; +$$ language plpgsql; + -- Independent action recovery checkpoints (PostgreSQL 9.5 compatible). -- Keep NULL phases for historical rows: NULL does not mean NOT_SENT. do $$ @@ -266,7 +299,7 @@ begin select * from (values ('ck_production_runs_action_type', - 'action_type is null or action_type in (''PHOTO_MOVE'', ''VISION'', ''RACK_PICK'', ''FRONT_LOAD'', ''INSPECT'', ''FRONT_UNLOAD'', ''FLIP'', ''BACK_LOAD'', ''BACK_UNLOAD'', ''RACK_PLACE'')'), + 'action_type is null or action_type in (''PHOTO_MOVE'', ''VISION'', ''RACK_PICK'', ''FRONT_LOAD'', ''INSPECT'', ''FRONT_UNLOAD'', ''FLIP'', ''BACK_LOAD'', ''BACK_UNLOAD'', ''REVERSE_FLIP'', ''RACK_PLACE'')'), ('ck_production_runs_action_phase', 'action_phase is null or action_phase in (''NOT_SENT'', ''SENDING'', ''COMMAND_CONFIRMED'', ''FEEDBACK_RECEIVED'', ''SIGNALS_CLEARED'', ''STEP_COMMITTED'', ''RESULT_WRITING'', ''RESULT_CONFIRMED'', ''MODE_WRITING'', ''MODE_CONFIRMED'')'), ('ck_production_runs_manual_decision', @@ -275,6 +308,13 @@ begin ('ck_production_runs_action_lock_version', 'action_lock_version >= 0') ) as constraints_to_add(constraint_name, check_expression) loop + if rule.constraint_name = 'ck_production_runs_action_type' and exists ( + select 1 from pg_constraint + where conrelid = target_table and conname = rule.constraint_name + and pg_get_constraintdef(oid) not like '%REVERSE_FLIP%' + ) then + alter table production_runs drop constraint ck_production_runs_action_type; + end if; if not exists ( select 1 from pg_constraint where conrelid = target_table diff --git a/docs/superpowers/specs/2026-11-05-active-run-order-deletion-design.md b/docs/superpowers/specs/2026-11-05-active-run-order-deletion-design.md new file mode 100644 index 0000000..d57a0d1 --- /dev/null +++ b/docs/superpowers/specs/2026-11-05-active-run-order-deletion-design.md @@ -0,0 +1,91 @@ +# 生产状态与订单绑定修复 + +## 目标 + +修复生产线程仍持有旧订单、订单管理却删除该订单并切换到新订单,最终导致 +`ProductionService::m_orderId` 与控制面板 `currentOrderId` 不一致的问题。 + +## 行为规则 + +- `NOT_START` 或 `CANCELED` 订单没有活动生产运行时,保持现有行为,允许删除。 +- 订单存在 `RUNNING`、`PAUSED`、`RECOVERY` 或 `STOPPING` 的 `production_runs` 记录时,拒绝删除。 +- 拒绝信息明确提示:请先在控制面板终止订单,终止完成后再删除。 +- 人工终止后,订单状态为 `FINISHED` 且最新生产运行状态为 `STOPPED`;没有测量记录时允许删除。 +- 正常生产完成、最新运行状态为 `COMPLETED` 的 `FINISHED` 订单继续禁止删除。 +- 保留 `ProductionService::stopOrder()` 的订单 ID 一致性校验,防止误终止其他订单。 + +## 实现 + +`OrderService::deleteOrder()` 在现有事务中通过 `findOrderForUpdate()` 读取并锁定 +目标订单,锁持续到提交或回滚。该锁与 `production_runs.order_id` 外键检查配合,避免 +“检查后、删除前”并发创建活动运行的竞态。 + +在 `ProductionRepository` 增加按订单 ID 查询并锁定全部生产运行状态的接口。 +查询使用 `FOR UPDATE`,既锁定已有运行记录,也返回最新运行状态和是否存在活动运行; +接口通过返回值与输出参数区分查询失败和查询成功。订单行锁阻止并发插入新运行, +运行记录锁阻止并发把历史运行切换为活动状态。 + +`OrderService::deleteOrder()` 在删除工件和运行记录前根据锁定结果处理: + +- 存在活动运行:回滚,返回“订单存在活动生产任务,请先在控制面板终止订单,终止完成后再删除”。 +- 查询失败:回滚并原样返回数据库错误,不显示终止提示。 +- `NOT_START`、`CANCELED` 且不存在活动运行:继续现有删除流程。 +- `FINISHED`、最新运行为 `STOPPED` 且不存在测量记录:继续现有删除流程。 +- 其他 `FINISHED` 订单:回滚,返回现有“已完成订单不能删除”提示。 + +## 生产状态同步 + +`ProductionService::Snapshot` 一次发布初始化结果、运行 ID、订单 ID、状态、错误和 +是否必须继续终止。控制面板在初始化完成前禁用生产操作,失败后提供重新检查入口。 +恢复查询先在局部变量中验证订单、工件及托盘,再绑定运行上下文。无活动运行时进入 Idle; +有活动运行时进入 Paused 或 ManualConfirm;多个活动运行拒绝自动选择。 + +界面把候选订单 `selectedOrderId` 与服务绑定的订单分开。活动运行期间,定时刷新始终 +读取绑定订单,即使数据库出现其他未完成订单也不切换。终止请求携带用户确认的 +runId 和 orderId,服务校验两者后才处理。 + +启动事务锁定订单,创建运行记录、将订单设为 RUNNING,并写入状态历史和操作日志。 +提交后才发布 Preparing、发起 PLC 检查。检查失败时保留当前运行,按恢复流程处理。 + +终止先持久化 STOPPING,再在数据库事务之外清理设备握手。清理成功后,订单结束、 +运行 STOPPED、状态历史与操作日志在同一事务内提交;失败则保持绑定并允许重试终止, +禁止恢复生产。成功后先清空运行、订单、工件、位置等上下文,再发布 Idle。 +正常完成也采用同一事务收尾,但运行状态为 COMPLETED。 + +数据库提交应答丢失时,不假定提交成功或失败;禁用操作并提供重新检查入口,重新读取 +数据库决定状态。UPDATE 影响行数不是 1 时返回失败,不再将不存在的运行视为更新成功。 + +## 数据库部署 + +新建数据库使用 `db/schema.sql`。已有数据库在生产停止期间执行 +`db/migrations/2026-11-05-production-stopping.sql`。该事务添加 STOPPING 约束支持, +重建包含 STOPPING 的活动订单唯一索引,并更新版本至 9。若旧数据存在重复活动运行, +迁移失败并回滚,需先人工核对记录。应用不会自动修改业务数据库。 + +## 验证 + +1. `NOT_START`、`CANCELED` 或异常遗留的 `FINISHED` 订单关联 `RUNNING`、`PAUSED`、`RECOVERY` 或 `STOPPING` 运行时, + 删除必须失败并返回指定终止提示;订单、工件和运行记录均保持不变。 +2. 没有活动运行的 `NOT_START`、`CANCELED` 订单仍然可以删除。 +3. 人工终止后的 `FINISHED + STOPPED` 订单:无测量记录时可删除;有测量记录时拒绝并保留追溯数据。 +4. 正常完成的 `FINISHED + COMPLETED` 订单始终拒绝删除。`ERROR` 不视为人工终止。 +5. 数据库查询失败时删除回滚,并返回原始数据库错误。 +6. PostgreSQL 并发验证:删除事务锁定订单后,并发创建运行必须等待;删除提交后, + 创建运行因外键不存在而失败,不能在保护检查与删除之间成为活动运行。 +7. PostgreSQL 并发验证:已有非活动运行在删除检查后尝试切换到活动状态时必须等待, + 不能在保护检查与删除之间改变删除结论。 +8. 端到端验证“启动或恢复订单 -> 控制面板终止 -> 运行变为 `STOPPED` -> 删除订单”成功。 +9. 构建项目,确认新增仓储接口及调用无编译错误。 + +## 自动化回归 + +- `tests/recovery_flow`:初始化失败及重试、STOPPING 恢复、旧身份拒绝、事务回滚、 + 提交应答丢失、Idle 快照清理、终止后删除并启动新订单、订单删除矩阵。 +- `tests/recovery_ui`:初始化操作门禁、重试释放按钮、定时刷新保持绑定订单、确认上下文。 + Windows Qt 5.14 的 QMessageBox 不支持 offscreen 后端;测试使用原生 windows 后端, + 通过 WA_DontShowOnScreen 隐藏测试窗口。 +- `tests/vision_production`:既有视觉、检查点及恢复回归。 +- `tests/recovery_postgres`:独立 PostgreSQL 9.5 实例上的约束、STOPPING 唯一性、影响行数。 + +自动化测试使用隔离数据库或模拟设备,不替代现场 PLC 联调。 + diff --git a/docs/superpowers/specs/2026-11-06-connected-plc-ready.md b/docs/superpowers/specs/2026-11-06-connected-plc-ready.md new file mode 100644 index 0000000..2c71d1e --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-connected-plc-ready.md @@ -0,0 +1,15 @@ +# PLC 连接即就绪 + +用户要求屏蔽 PLC、机器人就绪门槛。采用固定规则,不增加配置开关:完整状态读取成功且 PLC +连接有效时,plcReady 为 true;不再读取 M100。M101 保留采集用于显示,但不再限制启动、 +恢复和后续动作。通信失败、无有效状态时仍不可推进生产。用户临时注释的门禁、急停等检查 +保持现状,本次只修改就绪规则。 + +实施及验证:先用真实 PostgreSQL 与本机 FakePlc 复现 M100/M101 均为 0 时等待超时; +修改状态归一化与等待分支,移除无用 requireReady 参数;验证两个信号均为 0 时完整生产、 +暂停继续及超时恢复正常,状态读取失败不能发送动作,最后编译应用。不操作现场 PLC。 + +验证结果:原实现已复现两个就绪位为 0 时进入 TimeoutPaused;修改后所选端到端回归 +13 项通过(含初始化及清理),随后补充断连场景与不再读取 M100 的断言,专项 5 项通过。 +生产恢复回归 45 项通过,完整应用编译通过。用户临时屏蔽的门禁检查对应 3 项测试未纳入本轮运行。 +验证程序位于 `tmp/build-state-app/ssp.exe`;现场正在运行的 Qt Creator 构建目录需重新编译并重启生效。 diff --git a/docs/superpowers/specs/2026-11-06-disable-action-timeouts.md b/docs/superpowers/specs/2026-11-06-disable-action-timeouts.md new file mode 100644 index 0000000..a36f2aa --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-disable-action-timeouts.md @@ -0,0 +1,14 @@ +# 关闭动作超时 + +用户已确认取消动作超时。删除 tick 中等待就绪与机械动作的超时暂停分支,以及无调用的 +timeoutForState 方法。反馈轮询与动作检查点保留,未收到反馈时保持当前动作,不重复下发。 +人工暂停仍等待当前动作完成,终止订单仍可中断等待。PLC 通信超时和视觉识别超时保持原逻辑。 +原分阶段超时配置保留兼容读取,但不再限制机械动作;stateTimeoutMs 仍用于视觉 PLC 阶段。 + +验证:先复现超过原时长进入 TimeoutPaused,再验证延迟反馈仍可完成生产、暂停继续、 +人工恢复和终止删除后启动下一单。保留用户临时注释的门禁等检查,不执行相关门禁测试。 +仅使用独立测试数据库和本机 FakePlc,不操作现场 PLC,不提交 Git。 + +验证结果:修改前拍照延迟反馈测试复现 TimeoutPaused;修改后 10 类动作在原时限 200 ms +之外继续等待至少 700 ms,保持轮询且未重复发命令,反馈到达后完成订单。端到端回归 +22 项、生产恢复回归 45 项通过(均含初始化与清理),完整应用编译通过。 diff --git a/docs/superpowers/specs/2026-11-06-orphan-photo-feedback-unlock.md b/docs/superpowers/specs/2026-11-06-orphan-photo-feedback-unlock.md new file mode 100644 index 0000000..8d4e204 --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-orphan-photo-feedback-unlock.md @@ -0,0 +1,19 @@ +# 孤立视觉锁的残留拍照反馈清理 + +用户确认现场拍照命令 M846、到位反馈 M844,M844 是完成后置位且允许上位机清零的 +握手反馈。现场 M846=0、M844=1、取料命令/反馈均为 0,无活动运行记录。 +用户已批准修改:孤立锁恢复允许这种反馈残留进入人工确认,确认后清反馈并读回,再解锁。 + +只对 Idle 下的孤立锁放宽“拍照反馈必须为 0”的诊断条件;拍照命令为 1、取料任一信号 +为 1、通讯失败仍拒绝。活动订单恢复规则不变。诊断和提交均读取当前信号,提交后、 +写入前及读回后核对恢复代次/停止状态与数据库是否出现活动任务。未经人工提交不写 PLC。 +只清配置中的拍照反馈位,不发动作命令;清理未确认或读回非零则保留 pending=true。 +成功后清恢复文件和内存锁,发布状态快照,不启动任何订单。提示按实际配置显示地址及数值。 + +测试用真实 PG9.5 与本机 FakePlc 覆盖 M846/M844 成功、取消、命令/取料非零、 +写入超时、读回反馈重新置位、确认期间状态改变及正常全零解锁。现场不自动清信号或启动订单。 + +验证结果:原实现无法对 M844=1 弹出确认,测试已复现。修复后端到端 21 项、生产恢复 +45 项通过(含初始化与清理),包含解锁读回期间退出、空闲时无效终止请求两个异步场景。 +空闲退出使恢复回调失效,保留未完成的锁;无效终止不再破坏正在进行的恢复。 +实际 Qt Creator 构建目录已编译成功,现场遗留锁仍由操作者在新程序内确认后清理。 diff --git a/docs/superpowers/specs/2026-11-06-plc-flow-fixes.md b/docs/superpowers/specs/2026-11-06-plc-flow-fixes.md new file mode 100644 index 0000000..f945fdb --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-plc-flow-fixes.md @@ -0,0 +1,46 @@ +# PLC 联机流程修复 + +后续变更:用户于 2026-11-06 要求取消 PLC/机器人就绪位门槛,当前规则见 +`2026-11-06-connected-plc-ready.md`。下述就绪要求及验证结果为该变更之前的记录。 + +## 已确认范围 + +用户根据上一轮分析授权修改。采用局部修复,不改 PLC 地址或视觉识别关闭时的拍照位前置协议。 +真实设备点表和动作耗时需现场确认,不能用本机模拟结果代替。 + +## 修改方案 + +1. `REVERSE_FLIP` 同时加入 schema、实际数据库迁移和运行时约束校验;新增迁移可从版本 8/9 升至 10, + 包含 STOPPING 检查约束与活动订单唯一索引。旧约束在启动时明确提示执行新迁移,避免运行到中途才失败。 +2. 通讯有效、急停未触发、安全门全部关闭、可选 PLC 错误码无故障,使用同一个检查函数。 + 启动前验证这些条件;进入等待就绪后再等待 PLC/机器人 ready。恢复及新动作发送前还要求 ready。 + 已在途动作的轮询、完成反馈持久化和清理不要求 ready 始终为 1,因为运行中 ready 可能为 0。 +3. 等待就绪、拍照移动、取放、正反翻转、检测分别可设置超时,未配置时使用原有 stateTimeoutMs。 + 等待就绪超时进入 TimeoutPaused,保留运行上下文、停止调度并显示未就绪原因;条件满足后可恢复。 + 动作超时仍保留 PLC 握手及检查点,不自动重发动作。实际超时值不凭空放大。 +4. 显示反向翻面中文状态和恢复动作名称。 + +## 验证 + +- 使用真实 PostgreSQL 9.5 与本机 FakePlc 的 TCP 通讯,在 `simulation=false` 下执行: + 镀前单件/连续两件、镀后单件、暂停继续、超时恢复、终止删除后启动新订单。 +- 门打开时启动及恢复均不得写入生产控制;在途机器人不就绪不能阻止已完成动作的握手清理。 + 已复现并修复恢复异步读取期间开门后仍写检测模式的问题,写模式前再次检查安全状态。 +- 等待就绪超时及恢复、分阶段超时覆盖/回退/无效值,以及慢反馈不被旧统一超时误判。 +- PostgreSQL 检查点写入接受 REVERSE_FLIP,旧约束被拒绝并明确提示迁移。 +- 隔离数据库验证升级、重复迁移及完整 schema;回归原有流程、界面、视觉及设备握手测试并编译应用。 + +验证结果:端到端 15 项、生产恢复 45 项、视觉生产 34 项、恢复界面 19 项、PostgreSQL 16 项、 +设备握手 7 项,合计 136 项 QtTest 结果通过(含各套件初始化与清理);完整应用编译通过。 + +## 部署 + +已有数据库执行 `db/migrations/2026-11-06-production-plc-flow.sql`,不必再单独执行版本 9 迁移。 +部署前确保生产已停止;迁移在同一事务内提交,锁等待上限 5 秒,失败全部回滚。 +程序仍读取 exe 旁的 config.ini;现有地址保持不变。可选超时键示例在项目 config.ini 中注释列出, +现场确认后填写到实际运行的配置。数据库迁移不会主动发出任何 PLC 操作。 + +2026-11-06 已将本机 `127.0.0.1:5432/ssp` 从版本 8 升至 10。升级前确认应用未运行、 +无活动任务,并保存结构备份 `tmp/ssp-schema-before-plc-flow-v10.sql`;事务内再次检查无活动生产。 +升级后核实 REVERSE_FLIP 约束及包含 STOPPING 的唯一索引生效,订单、工件、运行及检测记录数量 +均保持为 0。其他部署环境仍需执行上述迁移。 diff --git a/docs/superpowers/specs/2026-11-06-vision-lock-lifecycle.md b/docs/superpowers/specs/2026-11-06-vision-lock-lifecycle.md new file mode 100644 index 0000000..d1617f3 --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-vision-lock-lifecycle.md @@ -0,0 +1,22 @@ +# 视觉锁与订单生命周期修复 + +用户通过界面终止/删除后重建订单仍无法启动。现场数据库已无 production_runs,新订单 +为 NOT_START,但 exe 旁视觉恢复文件 pending=true、run_id/workpiece_id=0。视觉锁独立于 +订单保存,旧终止流程未清除此锁,退出又会把它写回;界面未明确展示遗留锁原因。 + +修改范围: +- 终止时清理当前动作、拍照和取料握手,清零并读回确认 M852;失败保持可重试终止状态。 +- PLC 清理成功后保存 pending=false,再结束运行并复位视觉内存状态;活动任务正常退出同样清理。 +- 状态快照携带视觉恢复标志,空闲时有遗留锁显示明确原因和“解除视觉遗留锁”入口。 +- 历史 pending=true 不因订单删除被直接忽略,仍经现有 PLC 握手检查与人工确认解除。 + 空闲状态继承的孤立锁在退出时保留,不隐式复位设备或解锁。 +- 视觉处理内部如果处于暂停/待核对却外部仍在运行状态,应明确进入人工确认,不能静默等待。 + +验证:真实 PG9.5 + 本机 FakePlc,拍照/视觉阶段终止或退出,删除重建、重启后启动新单; +终止信号清理失败不得解锁;孤立文件恢复仅解锁而不启动订单;界面禁用原因与恢复按钮同步。 +保留用户就绪屏蔽、动作无限等待、公共安全检查临时注释,不自动提交,不操作现场 PLC。 + +结果:修改前视觉终止/退出留下恢复锁的测试失败,修复后端到端 13 项、界面 20 项、 +生产恢复 45 项、视觉生产 34 项、设备握手 7 项通过,合计 119 项 QtTest 结果(含初始化/清理)。 +实际 Qt Creator 构建目录已编译成功。现场旧恢复文件保持不变,可通过“解除视觉遗留锁” +读取握手并人工确认后解除;业务库和现场 PLC 未被测试改写。 diff --git a/docs/superpowers/specs/2026-11-06-vision-preflight-stall.md b/docs/superpowers/specs/2026-11-06-vision-preflight-stall.md new file mode 100644 index 0000000..c0aa101 --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-vision-preflight-stall.md @@ -0,0 +1,17 @@ +# 视觉准备阻塞修复 + +现场 enabled=false,但运行停在 VISION/NOT_SENT,安全门汇总为 false。公共安全检查 +被用户临时注释,而 visionCurrent 仍单独检查安全门和急停,导致普通取料模式写入前直接 +返回,反复准备而不推进。 + +用户随后明确要求相机不判断公共安全条件。最终修改:visionCurrent 不再独立判断安全门 +和急停,由生产流程 checkRecoverySafety 统一负责;保留 PLC 状态有效、连接、动作上下文、 +停止标志及异步回调代次校验。prepareVision 对无效上下文明确报错,防止再次静默循环。 +用户临时注释的公共安全检查保持原样,本次没有恢复这些检查。 + +验证:公共检查当前被注释时,安全门/急停反馈不会单独阻断视觉关闭后的普通取料; +视觉关闭、视觉开启但无进程连接均能完成生产。保留暂停、恢复、终止及失效上下文回归。 +只使用本机 FakePlc 与独立测试数据库,不操作现场 PLC,不提交 Git。 + +验证结果:最终策略在旧实现上复现被 ManualConfirm 阻断,修改后端到端 12 项、视觉生产 +回归 34 项通过(含初始化与清理),完整应用编译成功。未执行要求公共门禁生效的旧用例。 diff --git a/modbus/modbusaddress.cpp b/modbus/modbusaddress.cpp index 0f07f3c..d801642 100644 --- a/modbus/modbusaddress.cpp +++ b/modbus/modbusaddress.cpp @@ -35,6 +35,7 @@ bool ModbusAddressMap::isValid(QString *error) const << qMakePair(QString("inspectionCommand"), inspectionCommand) << qMakePair(QString("frontUnloadCommand"), frontUnloadCommand) << qMakePair(QString("flipCommand"), flipCommand) + << qMakePair(QString("flipCommand2"), flipCommand2) << qMakePair(QString("backLoadCommand"), backLoadCommand) << qMakePair(QString("backUnloadCommand"), backUnloadCommand) << qMakePair(QString("rackPlaceCommand"), rackPlaceCommand) @@ -43,6 +44,7 @@ bool ModbusAddressMap::isValid(QString *error) const << qMakePair(QString("inspectionFeedback"), inspectionFeedback) << qMakePair(QString("frontUnloadFeedback"), frontUnloadFeedback) << qMakePair(QString("flipFeedback"), flipFeedback) + << qMakePair(QString("flipFeedback2"), flipFeedback2) << qMakePair(QString("backLoadFeedback"), backLoadFeedback) << qMakePair(QString("backUnloadFeedback"), backUnloadFeedback) << qMakePair(QString("rackPlaceFeedback"), rackPlaceFeedback); diff --git a/modbus/modbusaddress.h b/modbus/modbusaddress.h index 8bb54e2..2c39fbb 100644 --- a/modbus/modbusaddress.h +++ b/modbus/modbusaddress.h @@ -32,6 +32,7 @@ struct ModbusAddressMap int inspectionCommand = 302; int frontUnloadCommand = 802; int flipCommand = 804; + int flipCommand2 = 841; int backLoadCommand = 806; int backUnloadCommand = 805; int rackPlaceCommand = 801; @@ -41,6 +42,7 @@ struct ModbusAddressMap int inspectionFeedback = 312; int frontUnloadFeedback = 809; int flipFeedback = 811; + int flipFeedback2 = 843; int backLoadFeedback = 813; int backUnloadFeedback = 812; int rackPlaceFeedback = 808; diff --git a/pages/dashboardpage.cpp b/pages/dashboardpage.cpp index 34fcd3c..f877cf6 100644 --- a/pages/dashboardpage.cpp +++ b/pages/dashboardpage.cpp @@ -48,6 +48,7 @@ QString displayState(const QString &state) if (state == "FRONT_CHECKING") return "正面检测"; if (state == "FRONT_UNLOADING") return "正面下料"; if (state == "FLIPPING") return "翻面"; + if (state == "REVERSE_FLIPPING") return "反向翻面"; if (state == "BACK_LOADING") return "反面上料"; if (state == "BACK_CHECKING") return "反面检测"; if (state == "BACK_UNLOADING") return "反面下料"; @@ -80,6 +81,7 @@ QString displayRecoveryAction(const QString &action) if (action == "INSPECT") return "检测"; if (action == "FRONT_UNLOAD") return "正面下料"; if (action == "FLIP") return "翻面"; + if (action == "REVERSE_FLIP") return "反向翻面"; if (action == "BACK_LOAD") return "反面上料"; if (action == "BACK_UNLOAD") return "反面下料"; if (action == "RACK_PLACE") return "料架放料"; @@ -287,8 +289,8 @@ DashboardPage::DashboardPage(QWidget *parent) this, &DashboardPage::clearAlarm); connect(markNgButton, &QPushButton::clicked, this, &DashboardPage::markWorkpieceNg); - connect(productionWorker, &ProductionWorker::stateChanged, - this, &DashboardPage::onProductionStateChanged); + connect(productionWorker, &ProductionWorker::snapshotChanged, + this, &DashboardPage::onProductionSnapshot); connect(productionWorker, &ProductionWorker::currentWorkpieceChanged, this, &DashboardPage::onCurrentWorkpieceChanged); connect(productionWorker, &ProductionWorker::currentWorkpieceSnapshotChanged, @@ -424,6 +426,7 @@ void DashboardPage::updateRackSize() void DashboardPage::startProduction() { + if (!productionSnapshot.initialized) return; if (recoveryBusy || visionRecoveryRequired) return; if (productionState == ProductionService::Paused) { if (!currentOrderResumable) return; @@ -449,7 +452,7 @@ void DashboardPage::startProduction() ui->startButton->setEnabled(false); if (!QMetaObject::invokeMethod( productionWorker, "requestStart", Qt::QueuedConnection, - Q_ARG(int, currentOrderId))) { + Q_ARG(int, selectedOrderId))) { updateRecoveryButtons(); QMessageBox::warning(this, "启动生产", "提交生产启动请求失败。"); @@ -466,11 +469,17 @@ void DashboardPage::pauseProduction() void DashboardPage::stopProduction() { + if (!productionSnapshot.initialized) return; + const bool active = productionState != ProductionService::Idle + && productionState != ProductionService::Completed; + const int confirmedRunId = active ? productionSnapshot.runId : 0; + const int confirmedOrderId = active ? productionSnapshot.orderId : selectedOrderId; if (!stopButton->isEnabled() || !confirmControlOperation("终止订单", "将当前订单标记为已完成,保留实际加工数量及记录,剩余工件不再执行。此操作不是机器人急停。")) return; if (recoveryDialog) recoveryDialog->reject(); QMetaObject::invokeMethod(productionWorker, "requestStopOrder", - Qt::QueuedConnection, Q_ARG(int, currentOrderId)); + Qt::QueuedConnection, Q_ARG(int, confirmedRunId), + Q_ARG(int, confirmedOrderId)); } void DashboardPage::clearAlarm() @@ -490,7 +499,12 @@ QString DashboardPage::controlOperationContext(QString *identity) const ProductionRunSnapshot run; if (currentOrderId > 0 && !OrderService::instance().findOrder(currentOrderId, &order, &error)) return QString(); - if (!ProductionRepository().findActiveRun(&run, &error)) return QString(); + const bool active = productionState != ProductionService::Idle + && productionState != ProductionService::Completed; + if (active && productionSnapshot.runId > 0) { + if (!ProductionRepository().findRun(productionSnapshot.runId, &run, &error)) + return QString(); + } else if (!ProductionRepository().findActiveRun(&run, &error)) return QString(); if (run.id > 0 && run.orderId != currentOrderId) return QString(); Workpiece piece; @@ -575,6 +589,19 @@ bool DashboardPage::confirmControlOperation(const QString &title, const QString return true; } +void DashboardPage::onProductionSnapshot(const ProductionService::Snapshot &snapshot) +{ + productionSnapshot = snapshot; + visionRecoveryRequired = snapshot.visionRecoveryRequired; + onProductionStateChanged(snapshot.state, snapshot.stateName); + if (!snapshot.initialized) { + ui->actionLabel->setText(snapshot.error.isEmpty() + ? "正在检查上次生产状态..." : "初始化失败:" + snapshot.error); + } else if (!snapshot.error.isEmpty()) { + ui->actionLabel->setText("生产状态:" + snapshot.error); + } +} + void DashboardPage::onProductionStateChanged(ProductionService::State state, const QString &name) { @@ -670,6 +697,11 @@ void DashboardPage::onRecoveryCompleted(const QString &mode) void DashboardPage::recoverProduction() { if (recoveryBusy || !ui->recoveryButton->isEnabled()) return; + if (!productionSnapshot.initialized) { + onRecoveryBusyChanged(true); + QMetaObject::invokeMethod(productionWorker, "requestRestore", Qt::QueuedConnection); + return; + } if (!confirmControlOperation("恢复/重试", "先读取设备及动作记录,检查能否安全恢复;状态不明确时再由人工选择。本次确认不保证立即继续生产。")) return; onRecoveryBusyChanged(true); ui->actionLabel->setText("正在检查设备状态和动作记录..."); @@ -819,6 +851,16 @@ void DashboardPage::markWorkpieceNg() void DashboardPage::updateRecoveryButtons() { + if (!productionSnapshot.initialized) { + ui->startButton->setEnabled(false); + ui->pauseButton->setEnabled(false); + stopButton->setEnabled(false); + ui->clearAlarmButton->setEnabled(false); + markNgButton->setEnabled(false); + ui->recoveryButton->setEnabled(!productionSnapshot.error.isEmpty() && !recoveryBusy); + ui->recoveryButton->setText("重新检查生产状态"); + return; + } const ProductionService::State state = productionState; const bool recoveryRequired = state == ProductionService::TimeoutPaused || state == ProductionService::ManualConfirm @@ -833,18 +875,24 @@ void DashboardPage::updateRecoveryButtons() && currentOrderResumable)) && !visionRecoveryRequired && !recoveryBusy; ui->startButton->setEnabled(canStart); + ui->startButton->setToolTip(visionRecoveryRequired + ? "上次视觉任务尚未清理,请先解除视觉遗留锁或恢复/终止当前任务" : QString()); ui->startButton->setText(state == ProductionService::Paused ? "继续" : "启动"); ui->recoveryButton->setVisible(true); - ui->recoveryButton->setEnabled(recoveryRequired && !terminating && !recoveryBusy); - ui->recoveryButton->setText(recoveryBusy ? "恢复检查中..." : "恢复/重试"); + ui->recoveryButton->setEnabled(recoveryRequired && !terminating && !recoveryBusy + && !productionSnapshot.terminationRequired); + ui->recoveryButton->setText(recoveryBusy ? "恢复检查中..." + : state == ProductionService::Idle && visionRecoveryRequired + ? "解除视觉遗留锁" : "恢复/重试"); ui->pauseButton->setEnabled(running && !recoveryRequired && state != ProductionService::Paused && !recoveryBusy && !terminating); ui->clearAlarmButton->setEnabled(!recoveryBusy && !terminating); markNgButton->setVisible(recoveryRequired && productionWorkpiece.id > 0 && !visionRecoveryRequired); - markNgButton->setEnabled(!recoveryBusy && !terminating); + markNgButton->setEnabled(!recoveryBusy && !terminating + && !productionSnapshot.terminationRequired); stopButton->setVisible(true); stopButton->setEnabled(currentOrderId > 0 && !terminating); stopButton->setText(terminating ? "终止中..." : "终止"); @@ -1071,16 +1119,21 @@ void DashboardPage::loadCurrentOrder() { QString error; Order order; - ProductionRunSnapshot run; - const bool loaded = ProductionRepository().findActiveRun(&run, &error) - && (run.id > 0 - ? OrderService::instance().findOrder(run.orderId, &order, &error) - : OrderService::instance().findUnfinishedOrder(&order, &error)); + const bool active = productionSnapshot.orderId > 0 + && productionState != ProductionService::Idle + && productionState != ProductionService::Completed; + const bool loaded = active + ? OrderService::instance().findOrder(productionSnapshot.orderId, &order, &error) + : OrderService::instance().findUnfinishedOrder(&order, &error); if (!loaded) { - currentOrderId = 0; + currentOrderId = active ? productionSnapshot.orderId : 0; + selectedOrderId = 0; currentOrderStartable = false; currentOrderResumable = false; - ui->orderLabel->setText("当前订单:读取失败"); + ui->orderLabel->setText(active + ? QString("当前生产订单 %1:记录缺失或读取失败,请核对").arg(currentOrderId) + : QString("当前订单:读取失败")); + updateRecoveryButtons(); updateProductionStats(); updateRackSummary(); emit logRequested("操作日志", "控制面板", "加载订单", @@ -1089,6 +1142,7 @@ void DashboardPage::loadCurrentOrder() } currentOrderId = order.id; + selectedOrderId = active ? 0 : order.id; currentOrderStartable = false; currentOrderResumable = false; if (order.id <= 0) { diff --git a/pages/dashboardpage.h b/pages/dashboardpage.h index 5ae90c4..f458261 100644 --- a/pages/dashboardpage.h +++ b/pages/dashboardpage.h @@ -44,6 +44,7 @@ signals: const QString &content, const QString &status); private slots: + void onProductionSnapshot(const ProductionService::Snapshot &snapshot); void startProduction(); void pauseProduction(); void stopProduction(); @@ -103,6 +104,8 @@ private: QThread *productionThread; ProductionWorker *productionWorker; ProductionService::State productionState; + ProductionService::Snapshot productionSnapshot; + int selectedOrderId = 0; int currentOrderId; bool currentOrderStartable; bool currentOrderResumable; diff --git a/repositories/productionrepository.cpp b/repositories/productionrepository.cpp index 3581d29..ad6ab99 100644 --- a/repositories/productionrepository.cpp +++ b/repositories/productionrepository.cpp @@ -41,9 +41,9 @@ int ProductionRepository::createRun(int orderId, const QString &productionState, QSqlQuery query(DatabaseManager::instance().database()); query.prepare("insert into production_runs " - "(order_id, production_state, process_step, inspection_mode, " + "(order_id, run_state, production_state, process_step, inspection_mode, " "start_tray_no, start_slot_no, plan_num) " - "values (:order_id, :production_state, :process_step, " + "values (:order_id, 'RUNNING', :production_state, :process_step, " ":inspection_mode, :start_tray_no, :start_slot_no, :plan_num) " "returning id"); query.bindValue(":order_id", orderId); @@ -96,6 +96,10 @@ bool ProductionRepository::updateRun(int runId, const QString &runState, setError(query, error); return false; } + if (query.numRowsAffected() != 1) { + if (error) *error = "生产运行记录不存在或已改变,请重新核对"; + return false; + } return true; } @@ -118,6 +122,10 @@ bool ProductionRepository::finishRun(int runId, const QString &runState, setError(query, error); return false; } + if (query.numRowsAffected() != 1) { + if (error) *error = "生产运行记录不存在或已改变,请重新核对"; + return false; + } return true; } @@ -131,7 +139,7 @@ bool ProductionRepository::heartbeatRun(int runId, QString *error) query.prepare("update production_runs set " "last_heartbeat_at = now(), updated_at = now() " "where id = :id " - "and run_state in ('RUNNING', 'PAUSED', 'RECOVERY')"); + "and run_state in ('RUNNING', 'PAUSED', 'RECOVERY', 'STOPPING')"); query.bindValue(":id", runId); if (!query.exec()) { setError(query, error); @@ -148,8 +156,8 @@ bool ProductionRepository::findActiveRun(ProductionRunSnapshot *run, QString *er QSqlQuery query(DatabaseManager::instance().database()); query.prepare("select * from production_runs " - "where run_state in ('RUNNING', 'PAUSED', 'RECOVERY') " - "order by id desc limit 1"); + "where run_state in ('RUNNING', 'PAUSED', 'RECOVERY', 'STOPPING') " + "order by id desc limit 2"); if (!query.exec()) { setError(query, error); return false; @@ -183,6 +191,10 @@ bool ProductionRepository::findActiveRun(ProductionRunSnapshot *run, QString *er run->action.manualDecision = query.value("manual_decision").toString(); run->action.manualOperator = query.value("manual_operator").toString(); run->action.manualDecidedAt = query.value("manual_decided_at").toDateTime(); + if (query.next()) { + if (error) *error = "发现多个活动生产任务,请先核对运行记录,不能自动选择订单"; + return false; + } return true; } @@ -221,6 +233,40 @@ bool ProductionRepository::findRun(int runId, ProductionRunSnapshot *run, QStrin return true; } +bool ProductionRepository::lockOrderRuns(int orderId, QString *latestRunState, + bool *hasActiveRun, QString *error) +{ + if (!latestRunState || !hasActiveRun || !ensureOpen(error)) { + return false; + } + + latestRunState->clear(); + *hasActiveRun = false; + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select run_state from production_runs " + "where order_id = :order_id order by id desc for update"); + query.bindValue(":order_id", orderId); + if (!query.exec()) { + setError(query, error); + return false; + } + + bool first = true; + while (query.next()) { + const QString runState = query.value(0).toString(); + if (first) { + *latestRunState = runState; + first = false; + } + if (runState == "RUNNING" || runState == "PAUSED" + || runState == "RECOVERY" || runState == "STOPPING") { + *hasActiveRun = true; + } + } + return true; +} + bool ProductionRepository::checkActionSchema(QString *error) { if (!ensureOpen(error)) return false; @@ -271,7 +317,7 @@ bool ProductionRepository::checkActionSchema(QString *error) return false; } const QMap expectedChecks = { - {"ck_production_runs_action_type", "CHECK (action_type IS NULL OR action_type = ANY ARRAY['PHOTO_MOVE','VISION','RACK_PICK','FRONT_LOAD','INSPECT','FRONT_UNLOAD','FLIP','BACK_LOAD','BACK_UNLOAD','RACK_PLACE'])"}, + {"ck_production_runs_action_type", "CHECK (action_type IS NULL OR action_type = ANY ARRAY['PHOTO_MOVE','VISION','RACK_PICK','FRONT_LOAD','INSPECT','FRONT_UNLOAD','FLIP','BACK_LOAD','BACK_UNLOAD','REVERSE_FLIP','RACK_PLACE'])"}, {"ck_production_runs_action_phase", "CHECK (action_phase IS NULL OR action_phase = ANY ARRAY['NOT_SENT','SENDING','COMMAND_CONFIRMED','FEEDBACK_RECEIVED','SIGNALS_CLEARED','STEP_COMMITTED','RESULT_WRITING','RESULT_CONFIRMED','MODE_WRITING','MODE_CONFIRMED'])"}, {"ck_production_runs_manual_decision", "CHECK (manual_decision IS NULL OR manual_decision = ANY ARRAY['ACTION_COMPLETED','ACTION_NOT_EXECUTED','RETRY_VISION','NORMAL_PICK'])"}, {"ck_production_runs_action_attempt", "CHECK (action_attempt >= 0)"}, @@ -290,7 +336,9 @@ bool ProductionRepository::checkActionSchema(QString *error) const QString name = query.value(0).toString(); if (!expectedChecks.contains(name)) continue; if (normalizedCheck(query.value(1).toString()) != normalizedCheck(expectedChecks.value(name))) { - if (error) *error = "动作恢复约束定义不匹配:" + name; + if (error) *error = name == "ck_production_runs_action_type" + ? "动作类型约束不匹配,请先执行 db/migrations/2026-11-06-production-plc-flow.sql" + : "动作恢复约束定义不匹配:" + name; return false; } ++checked; diff --git a/repositories/productionrepository.h b/repositories/productionrepository.h index 0ba50ad..238d5c0 100644 --- a/repositories/productionrepository.h +++ b/repositories/productionrepository.h @@ -68,6 +68,8 @@ public: bool heartbeatRun(int runId, QString *error = nullptr); bool findActiveRun(ProductionRunSnapshot *run, QString *error = nullptr); bool findRun(int runId, ProductionRunSnapshot *run, QString *error = nullptr); + bool lockOrderRuns(int orderId, QString *latestRunState, + bool *hasActiveRun, QString *error = nullptr); bool checkActionSchema(QString *error = nullptr); bool saveActionCheckpoint(int runId, int orderId, int workpieceId, ProductionActionCheckpoint *action, diff --git a/services/deviceservice.cpp b/services/deviceservice.cpp index b1490c7..7333ee4 100644 --- a/services/deviceservice.cpp +++ b/services/deviceservice.cpp @@ -42,6 +42,10 @@ bool actionAddresses(DeviceService::ProductionAction action, *commandAddress = addresses.flipCommand; *feedbackAddress = addresses.flipFeedback; return true; + case DeviceService::ReverseFlip: + *commandAddress = addresses.flipCommand2; + *feedbackAddress = addresses.flipFeedback2; + return true; case DeviceService::BackLoad: *commandAddress = addresses.backLoadCommand; *feedbackAddress = addresses.backLoadFeedback; @@ -148,7 +152,7 @@ void DeviceService::requestStatus(const StatusCallback &callback) } DeviceStatus status; status.plcConnected = true; - readStatusStep(0, status); + readStatusStep(1, status); } void DeviceService::finishStatusRequest(bool success, @@ -157,6 +161,8 @@ void DeviceService::finishStatusRequest(bool success, { DeviceStatus finalStatus = status; finalStatus.statusValid = success; + // PLC communication establishes readiness; M100 is not a production interlock. + finalStatus.plcReady = success && finalStatus.plcConnected; if (success) { finalStatus.safetyDoorClosed = finalStatus.safetyDoorClosed && finalStatus.safetyDoor1Closed @@ -204,7 +210,6 @@ void DeviceService::readStatusStep(int index, const DeviceStatus &status) DeviceStatus nextStatus = status; switch (index) { - case 0: nextStatus.plcReady = value != 0; break; case 1: nextStatus.robotReady = value != 0; break; case 2: nextStatus.safetyDoorClosed = value != 0; break; case 3: nextStatus.emergencyStop = value != 0; break; @@ -226,12 +231,6 @@ void DeviceService::readStatusStep(int index, const DeviceStatus &status) const ModbusAddressMap &addresses = m_modbus->config().addressMap; switch (index) { - case 0: - m_modbus->readCoil(addresses.plcReady, - [next](bool ok, bool value, const QString &error) { - next(ok, value ? 1 : 0, error); - }); - break; case 1: m_modbus->readCoil(addresses.robotReady, [next](bool ok, bool value, const QString &error) { @@ -452,9 +451,13 @@ void DeviceService::terminate(const OperationCallback &callback) m_terminationSignalIndex = 0; m_pollTimer->stop(); + const VisionConfig vision = ConfigManager::instance().visionConfig(); + const ModbusAddressMap &addresses = m_modbus->config().addressMap; const QList> currentSignals = QList>() << qMakePair(m_productionCommandAddress, - m_productionFeedbackAddress); + m_productionFeedbackAddress) + << qMakePair(vision.photoMoveCoil, vision.photoMoveCoilFeedback) + << qMakePair(addresses.rackPickCommand, addresses.rackPickFeedback); for (const QPair &signalPair : currentSignals) { if (signalPair.first >= 0 && signalPair.second >= 0 && !m_terminationSignals.contains(signalPair)) { @@ -481,7 +484,16 @@ void DeviceService::clearNextTerminationSignal() return; } if (m_terminationSignalIndex >= m_terminationSignals.size()) { - finishTermination(true, QString()); + const int address = ConfigManager::instance().visionConfig().comparisonPickCoil; + m_modbus->writeCoil(address, false, + [this, address](bool written, const QString &error) { + if (!written) { finishTermination(false, error); return; } + m_modbus->readCoil(address, + [this](bool read, bool value, const QString &readError) { + finishTermination(read && !value, + !read ? readError : value ? "M852 未复位,不能完成终止" : QString()); + }); + }); return; } diff --git a/services/deviceservice.h b/services/deviceservice.h index 1493e5b..4ef8e4f 100644 --- a/services/deviceservice.h +++ b/services/deviceservice.h @@ -66,6 +66,7 @@ public: Inspect, FrontUnload, Flip, + ReverseFlip, BackLoad, BackUnload, RackPlace diff --git a/services/orderservice.cpp b/services/orderservice.cpp index f31f1a7..d650c72 100644 --- a/services/orderservice.cpp +++ b/services/orderservice.cpp @@ -3,6 +3,7 @@ #include "../db/databasemanager.h" #include "../repositories/logrepository.h" #include "../repositories/orderrepository.h" +#include "../repositories/productionrepository.h" #include "../repositories/trayrepository.h" #include "../repositories/workpiecerepository.h" @@ -307,7 +308,7 @@ bool OrderService::generateWorkpiecesAndAssign(int orderId, QString *error) continue; } - const QList slots = + const QList traySlots = trayRepository.listSlots(tray.id, &transactionError); if (!transactionError.isEmpty()) { database.rollback(); @@ -317,7 +318,7 @@ bool OrderService::generateWorkpiecesAndAssign(int orderId, QString *error) return false; } - for (const TraySlot &slot : slots) { + for (const TraySlot &slot : traySlots) { const int position = (slot.rowNo - 1) * 7 + slot.columnNo; if (trayIndex == startTrayIndex && position < order.startSlotNo) { continue; @@ -493,21 +494,44 @@ bool OrderService::deleteOrder(int id, QString *error) OrderRepository repository; Order order; - if (!repository.findOrder(id, &order, &transactionError)) { + if (!repository.findOrderForUpdate(id, &order, &transactionError)) { database.rollback(); if (error) { *error = transactionError; } return false; } - if (order.status == "FINISHED" || order.status == "COMPLETED") { + + QString latestRunState; + bool hasActiveRun = false; + if (!ProductionRepository().lockOrderRuns( + id, &latestRunState, &hasActiveRun, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (hasActiveRun) { + database.rollback(); + if (error) { + *error = "订单存在活动生产任务,请先在控制面板终止订单,终止完成后再删除"; + } + return false; + } + + const bool manuallyStopped = order.status == "FINISHED" + && latestRunState == "STOPPED"; + if (order.status == "COMPLETED" + || (order.status == "FINISHED" && !manuallyStopped)) { database.rollback(); if (error) { *error = "已完成订单不能删除"; } return false; } - if (order.status != "NOT_START" && order.status != "CANCELED") { + if (order.status != "NOT_START" && order.status != "CANCELED" + && !manuallyStopped) { database.rollback(); if (error) { *error = "当前订单不能直接删除,请先在控制面板安全终止订单"; diff --git a/services/productionservice.cpp b/services/productionservice.cpp index 20984dc..34445d8 100644 --- a/services/productionservice.cpp +++ b/services/productionservice.cpp @@ -2,6 +2,8 @@ #include "../config/configmanager.h" #include "../repositories/productionrepository.h" +#include "../repositories/orderrepository.h" +#include "../repositories/logrepository.h" #include "../db/databasemanager.h" #include "orderservice.h" #include "trayservice.h" @@ -84,6 +86,26 @@ ProductionService::State ProductionService::state() const return m_state; } +ProductionService::Snapshot ProductionService::snapshot() const +{ + Snapshot result; + result.initialized = m_initialized; + result.runId = m_runId; + result.orderId = m_orderId; + result.state = m_state; + result.stateName = stateName(); + result.terminationRequired = m_terminationRequired; + result.visionRecoveryRequired = m_visionNeedsReconcile; + result.error = m_lastError; + return result; +} + +void ProductionService::publishState() +{ + emit snapshotChanged(snapshot()); + emit stateChanged(m_state, stateName()); +} + ProductionService::~ProductionService() { m_timer->stop(); @@ -122,6 +144,7 @@ QString ProductionService::stateNameForState(State state) const case BackLoading: return "BACK_LOADING"; case BackChecking: return "BACK_CHECKING"; case BackUnloading: return "BACK_UNLOADING"; + case ReverseFlipping: return "REVERSE_FLIPPING"; case RackPlacing: return "RACK_PLACING"; case Judging: return "JUDGING"; case Unloading: return "UNLOADING"; @@ -218,8 +241,7 @@ bool ProductionService::visionCurrent(quint64 generation) const return generation == m_visionGeneration && !m_visionSuspended && !stopRequested() && isActive() && m_currentWorkpiece.id == m_visionWorkpieceId && m_currentTrayNo == m_visionTrayNo - && m_deviceStatusValid && m_deviceStatus.plcConnected - && m_deviceStatus.safetyDoorClosed && !m_deviceStatus.emergencyStop; + && m_deviceStatusValid && m_deviceStatus.plcConnected; } void ProductionService::reportVision(const QString &phase, const QString &message, bool invalidated) @@ -276,6 +298,13 @@ void ProductionService::prepareVision() m_visionCommitStarted = false; m_visionEnabled = config.enabled && !m_forceNormalPick; m_visionIoPending = false; + if (!visionCurrent(m_visionGeneration)) { + QString reason = "当前视觉取料上下文已失效"; + if (!m_deviceStatusValid) reason = "PLC 状态未采集成功"; + else if (!m_deviceStatus.plcConnected) reason = "PLC 连接已断开"; + visionFault("无法准备取料:" + reason); + return; + } // Persist before R60/M852 can be written so a crash cannot erase an in-flight result. if (!saveVisionRecoveryState(true, &error)) { visionFault(error); @@ -515,6 +544,7 @@ void ProductionService::visionFault(const QString &reason) bool ProductionService::start(int orderId, QString *error) { + if (!m_initialized && !restoreActiveRun(error)) return false; if (!ProductionRepository().checkActionSchema(error)) return false; const VisionConfig vision = ConfigManager::instance().visionConfig(); if (m_visionNeedsReconcile || (!ConfigManager::instance().simulationMode() && !vision.isValid(error))) { @@ -530,19 +560,51 @@ bool ProductionService::start(int orderId, QString *error) } if (m_state != Idle && m_state != Completed) { if (error) { - *error = "Production service is already active"; + *error = QString("无法启动订单 %1:订单 %2 当前状态为 %3,请先恢复或终止当前任务") + .arg(orderId).arg(m_orderId).arg(stateName()); } return false; } + DatabaseManager &database = DatabaseManager::instance(); + if (!database.transaction(error)) return false; Order order; - if (!OrderService::instance().findOrder(orderId, &order, error)) { + ProductionRunSnapshot activeRun; + if (!OrderRepository().findOrderForUpdate(orderId, &order, error) + || !ProductionRepository().findActiveRun(&activeRun, error)) { + database.rollback(); return false; } - if (order.status != "NOT_START") { - if (error) { - *error = "Only not-started orders can start production"; - } + if (order.status != "NOT_START" || activeRun.id > 0) { + database.rollback(); + if (error) *error = "订单状态已改变或存在待恢复的生产任务,请重新核对"; + return false; + } + + const int newRunId = ProductionRepository().createRun( + orderId, "PREPARING", "PREPARING", order.inspectionMode, + order.startTrayNo, order.startSlotNo, order.planNum, error); + LogRecord log; + log.type = "操作日志"; + log.module = "订单管理"; + log.action = "开始订单"; + log.content = "开始订单:" + order.no; + log.status = "成功"; + if (newRunId <= 0 + || !OrderRepository().updateOrderLifecycle(orderId, "RUNNING", + QDateTime::currentDateTime(), QDateTime(), error) + || !ProductionRepository().insertStateHistory(newRunId, orderId, 0, + stateName(), "PREPARING", "PREPARING", "SYSTEM", "START", QString(), error) + || !LogRepository().insertLog(log, error)) { + database.rollback(); + return false; + } + if (!database.commit(error)) { + database.rollback(); + m_initialized = false; + m_state = ManualConfirm; + m_lastError = "启动事务提交结果不确定,请重新检查生产状态"; + publishState(); return false; } @@ -563,6 +625,9 @@ bool ProductionService::start(int orderId, QString *error) } m_orderId = orderId; + m_runId = newRunId; + m_persistenceUncertain = false; + m_terminationRequired = false; m_checkpoint = ProductionActionCheckpoint(); m_restoredRun = false; m_targetReady = false; @@ -577,21 +642,10 @@ bool ProductionService::start(int orderId, QString *error) m_starting = true; m_plcStarted = false; - QString persistenceError; - m_runId = ProductionRepository().createRun( - m_orderId, "PREPARING", "PREPARING", order.inspectionMode, - order.startTrayNo, order.startSlotNo, order.planNum, - &persistenceError); - if (m_runId <= 0) { - m_orderId = 0; - m_starting = false; - if (error) { - *error = "Failed to create production run: " + persistenceError; - } - return false; - } - - if (!setState(Preparing)) { if (error) *error = m_lastError; return false; } + m_state = Preparing; + m_stateTimer.restart(); + publishState(); + publishVisionControl(); m_deviceService->startPolling(); const int interval = ProductionTickIntervalMs; @@ -633,13 +687,6 @@ bool ProductionService::start(int orderId, QString *error) } m_plcStarted = true; - QString orderError; - if (!OrderService::instance().startOrder( - m_orderId, &orderError)) { - fail(orderError); - return; - } - m_starting = false; tick(); }); @@ -809,33 +856,43 @@ bool ProductionService::stopOrder(int orderId, QString *error) return false; } if (!OrderService::instance().terminateOrder(orderId, error)) return false; - emit stateChanged(m_state, stateName()); + publishState(); return true; } +bool ProductionService::stopConfirmedOrder(int runId, int orderId, QString *error) +{ + const bool active = m_state != Idle && m_state != Completed; + if (!m_initialized || runId != (active ? m_runId : 0) + || (active && orderId != m_orderId)) { + if (error) *error = "生产任务已改变或尚未完成初始化,请重新确认终止"; + return false; + } + return stopOrder(orderId, error); +} + bool ProductionService::stop(QString *error, bool finishOrder) { - m_forceNormalPick = false; - ++m_actionGeneration; - ++m_recoveryGeneration; - finishRecoveryCheck(); - if (m_state == Terminating) { - return true; - } + if (m_state == Terminating) return true; if (m_state == Idle || m_state == Completed) { if (error) { *error = "Production service is not running"; } return false; } + m_forceNormalPick = false; + ++m_actionGeneration; + ++m_recoveryGeneration; + finishRecoveryCheck(); invalidateVision("操作员已终止生产"); + m_terminationRequired = true; m_lastError = "Production stopped by operator"; m_timer->stop(); if (!setState(Terminating)) { // Stop may still clean the PLC, but no stale database snapshot may be written. m_state = Terminating; - emit stateChanged(m_state, stateName()); + publishState(); } auto failTermination = [this](const QString &terminationError) { @@ -853,6 +910,11 @@ bool ProductionService::stop(QString *error, bool finishOrder) finishShutdown(false, m_lastError); }; + if (m_restoredRun) { + DeviceService::ProductionAction action; + if (productionActionForState(m_timeoutState, &action)) + m_deviceService->adoptProductionAction(action); + } m_deviceService->terminate( [this, failTermination, finishOrder](bool cleaned, const QString &cleanupError) { if (!cleaned) { @@ -860,50 +922,38 @@ bool ProductionService::stop(QString *error, bool finishOrder) return; } - QString orderError; - Order order; - if (!OrderService::instance().findOrder( - m_orderId, &order, &orderError)) { - failTermination(orderError); - return; - } - if (finishOrder && order.status != "FINISHED" - && !OrderService::instance().terminateOrder(m_orderId, &orderError)) { - failTermination(orderError); - return; - } - if (!finishOrder && order.status == "RUNNING" - && !OrderService::instance().pauseOrder( - m_orderId, &orderError)) { - failTermination(orderError); - return; - } - - if (!finishOrder && (order.status == "NOT_START" - || order.status == "RUNNING" || order.status == "PAUSED") - && !OrderService::instance().cancelOrder( - m_orderId, &orderError)) { - failTermination(orderError); - return; - } - QString persistenceError; - if (m_runId > 0 - && !ProductionRepository().finishRun( - m_runId, "STOPPED", m_lastError, - &persistenceError)) { + if (!saveVisionRecoveryState(false, &persistenceError) + || !finalizeRun(false, finishOrder, &persistenceError)) { failTermination(persistenceError); return; } - persistRecoveryAction("STOP", m_lastError); m_persistenceUncertain = false; m_runId = 0; - if (!setState(Idle)) { failTermination(m_lastError); return; } m_orderId = 0; m_currentWorkpiece = Workpiece(); + m_checkpoint = ProductionActionCheckpoint(); + m_currentTrayNo = 0; + m_currentSlotNo = 0; + m_timeoutState = Idle; + m_terminationRequired = false; + m_lastError.clear(); + m_actionPending = false; + m_actionStarting = false; + m_actionPollPending = false; + m_actionCompleted = false; + m_restoredRun = false; m_starting = false; m_plcStarted = false; + m_visionNeedsReconcile = false; + m_visionSuspended = false; + m_visionIoPending = false; + m_visionCommitStarted = false; + m_visionStage = VisionStage::Idle; + m_targetReady = false; + m_visionRequest = QJsonObject(); + m_visionResult = QJsonObject(); clearProcessTimer(); emit currentWorkpieceChanged(0, QString()); emit currentWorkpieceSnapshotChanged(m_currentWorkpiece); @@ -912,6 +962,8 @@ bool ProductionService::stop(QString *error, bool finishOrder) if (m_externalStopRequested) { m_externalStopRequested->store(false); } + setState(Idle); + reportVision("待机", "终止清理完成,可以启动新订单"); finishShutdown(true, QString()); }); return true; @@ -919,6 +971,7 @@ bool ProductionService::stop(QString *error, bool finishOrder) void ProductionService::shutdown(const DeviceService::OperationCallback &callback) { + const bool orphanVisionLock = m_state == Idle && m_visionNeedsReconcile; invalidateVision("生产线程正在退出"); if (m_shutdownRequested) { if (callback) { @@ -929,7 +982,14 @@ void ProductionService::shutdown(const DeviceService::OperationCallback &callbac m_shutdownRequested = true; m_shutdownCallback = callback; - if (m_state != Idle && m_state != Completed) { + if (orphanVisionLock) { + finishRecoveryCheck(); + m_timer->stop(); + finishShutdown(true, QString()); + return; + } + if (m_state != Idle && m_state != Completed + && (m_initialized || m_runId > 0)) { QString stopError; if (!stop(&stopError)) { finishShutdown(false, stopError); @@ -944,6 +1004,17 @@ void ProductionService::shutdown(const DeviceService::OperationCallback &callbac finishShutdown(false, cleanupError); return; } + QString error; + if (!saveVisionRecoveryState(false, &error)) { + finishShutdown(false, error); + return; + } + m_visionNeedsReconcile = false; + m_visionSuspended = false; + m_visionIoPending = false; + m_visionCommitStarted = false; + m_visionStage = VisionStage::Idle; + m_targetReady = false; setState(Idle); finishShutdown(true, QString()); }); @@ -971,10 +1042,23 @@ bool ProductionService::clearAlarm(QString *error) bool ProductionService::restoreActiveRun(QString *error) { - if (!ProductionRepository().checkActionSchema(error)) return false; - if (m_state != Idle) { - return true; + if (m_initialized) { publishState(); return true; } + QString restoreError; + const bool success = restoreRun(&restoreError); + m_initialized = success; + if (!success) { + m_timer->stop(); + m_lastError = restoreError; + m_state = ManualConfirm; + if (error) *error = restoreError; } + publishState(); + return success; +} + +bool ProductionService::restoreRun(QString *error) +{ + if (!ProductionRepository().checkActionSchema(error)) return false; ProductionRunSnapshot run; QString persistenceError; @@ -985,37 +1069,46 @@ bool ProductionService::restoreActiveRun(QString *error) return false; } if (run.id <= 0) { + m_runId = 0; + m_orderId = 0; + m_currentWorkpiece = Workpiece(); + m_checkpoint = ProductionActionCheckpoint(); + m_currentTrayNo = 0; + m_currentSlotNo = 0; + m_starting = false; + m_plcStarted = false; + m_actionPending = false; + clearProcessTimer(); + m_lastError.clear(); + m_persistenceUncertain = false; + m_terminationRequired = false; + m_state = Idle; + if (m_visionNeedsReconcile) + m_lastError = "存在上次任务的视觉遗留锁,请点击“解除视觉遗留锁”核对后解锁,无需删除新订单"; return true; } - m_runId = run.id; - m_orderId = run.orderId; - m_inspectionMode = run.inspectionMode; - m_recoveryRetryCount = run.recoveryRetryCount; - m_lastError = run.lastError; - + Order order; + if (!OrderRepository().findOrder(run.orderId, &order, error)) return false; + Workpiece workpiece; + int trayNo = 0; + int slotNo = 0; if (run.currentWorkpieceId > 0) { QString workpieceError; if (!WorkpieceService::instance().findWorkpiece( - run.currentWorkpieceId, &m_currentWorkpiece, &workpieceError)) { + run.currentWorkpieceId, &workpiece, &workpieceError)) { if (error) { *error = workpieceError; } return false; } - if (m_currentWorkpiece.orderId != run.orderId - || m_currentWorkpiece.processStep != run.processStep - || m_currentWorkpiece.state != "PROCESSING") { - m_persistenceUncertain = true; - m_state = ManualConfirm; - m_timer->stop(); + if (workpiece.orderId != run.orderId + || workpiece.processStep != run.processStep + || workpiece.state != "PROCESSING") { if (error) *error = "恢复快照与工件身份/工序不一致,请核对数据库记录"; - emit stateChanged(m_state, stateName()); return false; } - emit currentWorkpieceChanged(m_currentWorkpiece.id, - m_currentWorkpiece.barcode); - m_currentSlotNo = m_currentWorkpiece.trayPos; + slotNo = workpiece.trayPos; const QList trays = TrayService::instance().listTrays( &workpieceError); if (!workpieceError.isEmpty()) { @@ -1023,27 +1116,45 @@ bool ProductionService::restoreActiveRun(QString *error) return false; } for (int index = 0; index < trays.size(); ++index) { - if (trays.at(index).id == m_currentWorkpiece.trayId) { - m_currentTrayNo = index + 1; + if (trays.at(index).id == workpiece.trayId) { + trayNo = index + 1; break; } } - if (m_currentTrayNo <= 0 || m_currentSlotNo < 1 - || m_currentSlotNo > 49) { + if (trayNo <= 0 || slotNo < 1 || slotNo > 49) { if (error) *error = "恢复记录中的托盘或工位无法映射到 PLC"; return false; } - emit currentWorkpieceSnapshotChanged(m_currentWorkpiece); - emit currentPositionChanged(m_currentTrayNo, m_currentSlotNo); - startProcessTimer(m_currentWorkpiece.processStep); - emitProcessElapsed(); } + m_runId = run.id; + m_orderId = run.orderId; + m_inspectionMode = run.inspectionMode; + m_recoveryRetryCount = run.recoveryRetryCount; + m_lastError = run.lastError; + m_currentWorkpiece = workpiece; + m_currentTrayNo = trayNo; + m_currentSlotNo = slotNo; + m_persistenceUncertain = false; m_checkpoint = run.action; m_restoredRun = true; m_targetReady = false; m_timeoutState = m_currentWorkpiece.id > 0 ? stateForProcessStep(m_currentWorkpiece.processStep) : Preparing; + // Preserve interrupted termination across restart, including old partial closures. + m_terminationRequired = run.runState == "STOPPING" + || run.productionState == "TERMINATING" + || order.status == "FINISHED" || order.status == "CANCELED"; + if (m_terminationRequired) { + m_state = ManualConfirm; + m_lastError = "上次终止尚未完成,请核对设备后重试终止订单"; + } else { + m_state = run.runState == "PAUSED" ? Paused : ManualConfirm; + } + emit currentWorkpieceChanged(workpiece.id, workpiece.barcode); + emit currentWorkpieceSnapshotChanged(workpiece); + emit currentPositionChanged(trayNo, slotNo); + if (workpiece.id > 0) startProcessTimer(workpiece.processStep); const bool unstartedPick = m_timeoutState == RackPicking && (m_checkpoint.phase == "NOT_SENT" || m_checkpoint.phase == "STEP_COMMITTED"); if (m_timeoutState == VisionProcessing || unstartedPick) { @@ -1052,12 +1163,6 @@ bool ProductionService::restoreActiveRun(QString *error) m_visionStage = VisionStage::Fault; m_recoveryAlarmCode = "VISION"; } - if (run.runState == "PAUSED") { - if (!setState(Paused)) { if (error) *error = m_lastError; return false; } - } else if (!setState(ManualConfirm)) { - if (error) *error = m_lastError; - return false; - } m_heartbeatTimer.restart(); m_timer->stop(); if (run.runState != "PAUSED") @@ -1071,7 +1176,15 @@ bool ProductionService::restoreActiveRun(QString *error) bool ProductionService::loadRecoverySnapshot(QString *error) { if (!ProductionRepository().checkActionSchema(error)) return false; - if (m_recoveryIdleUnlock) return true; + if (m_recoveryIdleUnlock) { + ProductionRunSnapshot activeRun; + if (!ProductionRepository().findActiveRun(&activeRun, error)) return false; + if (activeRun.id > 0) { + if (error) *error = "出现活动生产任务,不能按孤立视觉锁解锁,请重新检查生产状态"; + return false; + } + return true; + } ProductionRunSnapshot run; Order order; if (!ProductionRepository().findRun(m_runId, &run, error) @@ -1135,6 +1248,10 @@ void ProductionService::finishRecoveryCheck(const QString &error) bool ProductionService::recover(QString *error) { + if (m_terminationRequired) { + if (error) *error = "上次终止尚未完成,请重试终止,不能恢复生产"; + return false; + } if (m_recoveryCheckPending) { if (error) *error = "正在恢复,请等待当前操作结束"; return false; @@ -1382,14 +1499,22 @@ void ProductionService::checkVisionRecovery(const QJsonObject &decision) m_deviceService->inspectProductionAction(DeviceService::PhotoMoveAction, [this, generation, decision](bool photoRead, const ProductionActionStatus &photo, const QString &photoError) { if (generation != m_recoveryGeneration || stopRequested()) return; - if (!photoRead || photo.command || photo.feedback) { - finishRecoveryCheck(photoRead ? "M850/M851尚未复位,请先核对拍照位动作" : photoError); return; + const VisionConfig config = ConfigManager::instance().visionConfig(); + const QString photoSignals = QString("拍照命令 M%1=%2,到位反馈 M%3=%4") + .arg(config.photoMoveCoil).arg(int(photo.command)) + .arg(config.photoMoveCoilFeedback).arg(int(photo.feedback)); + if (!photoRead || photo.command || (photo.feedback && !m_recoveryIdleUnlock)) { + finishRecoveryCheck(photoRead ? photoSignals + ";拍照位握手未复位,请先核对动作" : photoError); return; } m_deviceService->inspectProductionAction(DeviceService::RackPick, - [this, generation, decision](bool read, const ProductionActionStatus &status, const QString &readError) { + [this, generation, decision, photo, photoSignals](bool read, const ProductionActionStatus &status, const QString &readError) { if (generation != m_recoveryGeneration || stopRequested()) return; + const ModbusAddressMap addresses = ConfigManager::instance().modbusConfig().addressMap; + const QString pickSignals = QString("取料命令 M%1=%2,取料反馈 M%3=%4") + .arg(addresses.rackPickCommand).arg(int(status.command)) + .arg(addresses.rackPickFeedback).arg(int(status.feedback)); if (!read || status.command || status.feedback) { - finishRecoveryCheck(read ? "RackPick信号非零,禁止重测或改取料模式" : readError); return; + finishRecoveryCheck(read ? pickSignals + ";禁止重测或改取料模式" : readError); return; } const bool visionCheckpoint = m_checkpoint.type == "VISION" && m_checkpoint.nextStep == "RACK_PICKING" @@ -1412,7 +1537,9 @@ void ProductionService::checkVisionRecovery(const QJsonObject &decision) } if (decision.isEmpty()) { requestManualDecision(VisionProcessing, status, - m_recoveryIdleUnlock ? "仅解除已终止任务的视觉遗留锁,不恢复订单" + m_recoveryIdleUnlock ? photoSignals + ";" + pickSignals + + (photo.feedback ? "。确认机器人停止、旧动作已结束后,清除到位反馈并读回确认,再解除遗留锁;不恢复订单" + : "。仅解除已终止任务的视觉遗留锁,不恢复订单") : historicalVision ? "历史记录没有视觉检查点,必须现场确认机器人仍在拍照位且RackPick尚未执行;确认后才建立新检查点" : "现场确认机器人仍在拍照位且RackPick尚未执行,再选择处理方式", @@ -1426,13 +1553,63 @@ void ProductionService::checkVisionRecovery(const QJsonObject &decision) m_deviceService->cancelVisionRequests("人工恢复作废旧视觉写入"); m_targetReady = false; if (m_recoveryIdleUnlock) { - if (!saveVisionRecoveryState(false, &error)) { finishRecoveryCheck(error); return; } - m_visionNeedsReconcile = false; - m_visionSuspended = false; - m_visionStage = VisionStage::Idle; - reportVision("视觉锁已解除", "订单保持终止状态", true); - publishVisionControl(); - finishRecoveryCheck(); + const auto verifyAndUnlock = [this, generation]() { + m_deviceService->inspectProductionAction(DeviceService::PhotoMoveAction, + [this, generation](bool read, const ProductionActionStatus &photo, const QString &readError) { + if (generation != m_recoveryGeneration || stopRequested()) return; + const VisionConfig config = ConfigManager::instance().visionConfig(); + if (!read || photo.command || photo.feedback) { + finishRecoveryCheck(!read ? readError : QString("解锁读回失败:M%1=%2,M%3=%4,保留视觉锁") + .arg(config.photoMoveCoil).arg(int(photo.command)) + .arg(config.photoMoveCoilFeedback).arg(int(photo.feedback))); + return; + } + m_deviceService->inspectProductionAction(DeviceService::RackPick, + [this, generation](bool read, const ProductionActionStatus &pick, const QString &readError) { + if (generation != m_recoveryGeneration || stopRequested()) return; + QString error; + if (!read || pick.command || pick.feedback) { + const auto addresses = ConfigManager::instance().modbusConfig().addressMap; + finishRecoveryCheck(!read ? readError : QString("取料状态已改变:M%1=%2,M%3=%4,保留视觉锁") + .arg(addresses.rackPickCommand).arg(int(pick.command)) + .arg(addresses.rackPickFeedback).arg(int(pick.feedback))); + return; + } + if (!checkRecoverySafety(&error) || !loadRecoverySnapshot(&error) + || !saveVisionRecoveryState(false, &error)) { + finishRecoveryCheck(error); return; + } + m_visionNeedsReconcile = false; + m_visionSuspended = false; + m_visionStage = VisionStage::Idle; + m_lastError.clear(); + reportVision("视觉锁已解除", "旧任务已清理,可启动未开始订单", true); + publishState(); + publishVisionControl(); + finishRecoveryCheck(); + }); + }); + }; + if (!photo.feedback) { verifyAndUnlock(); return; } + m_visionIoPending = true; + m_deviceService->writeVisionSignal(DeviceService::PhotoMoveFeedback, false, + [this, generation, verifyAndUnlock](VisionWriteOutcome outcome, const QString &writeError) { + if (generation != m_recoveryGeneration || stopRequested()) return; + m_visionIoPending = false; + if (outcome != VisionWriteOutcome::Confirmed) { + finishRecoveryCheck(QString("清除 M%1 到位反馈未确认,保留视觉锁:%2") + .arg(ConfigManager::instance().visionConfig().photoMoveCoilFeedback).arg(writeError)); + return; + } + verifyAndUnlock(); + }, [this, generation]() { + if (generation != m_recoveryGeneration || stopRequested()) return false; + QString error; + if (checkRecoverySafety(&error) && loadRecoverySnapshot(&error)) return true; + m_visionIoPending = false; + finishRecoveryCheck(error); + return false; + }); return; } if (!saveVisionRecoveryState(true, &error)) { finishRecoveryCheck(error); return; } @@ -1457,6 +1634,11 @@ void ProductionService::checkVisionRecovery(const QJsonObject &decision) void ProductionService::resumeRecoveredState(State state) { + QString safetyError; + if (!checkRecoverySafety(&safetyError)) { + finishRecoveryCheck(safetyError); + return; + } const quint64 generation = m_recoveryGeneration; m_deviceService->setInspectionMode(m_inspectionMode, [this, generation, state](bool success, const QString &modeError) { @@ -1488,7 +1670,7 @@ void ProductionService::resumeRecoveredState(State state) m_pauseAfterCurrentAction = false; m_state = target; m_stateTimer.restart(); - emit stateChanged(m_state, stateName()); + publishState(); publishVisionControl(); m_recoveryAlarmCode.clear(); m_plcStarted = true; @@ -1506,6 +1688,10 @@ void ProductionService::resumeRecoveredState(State state) bool ProductionService::markCurrentWorkpieceNg(QString *error) { + if (m_terminationRequired) { + if (error) *error = "终止尚未完成,请重试终止,不能继续处理工件"; + return false; + } if (m_checkpoint.type != "RACK_PLACE" || m_checkpoint.phase != "SIGNALS_CLEARED" || m_recoveryCheckPending || m_actionStarting || m_actionPollPending) { if (error) *error = "必须先通过恢复/重试确认工件已放回料架,不能跳过未完成动作"; @@ -1562,6 +1748,7 @@ QString ProductionService::actionTypeForState(State state) const case Flipping: return "FLIP"; case BackLoading: return "BACK_LOAD"; case BackUnloading: return "BACK_UNLOAD"; + case ReverseFlipping: return "REVERSE_FLIP"; case RackPlacing: return "RACK_PLACE"; default: return QString(); } @@ -1579,7 +1766,9 @@ QString ProductionService::nextStepForState(State state) const case Flipping: return "BACK_LOADING"; case BackLoading: return "BACK_CHECKING"; case BackChecking: return "BACK_UNLOADING"; - case BackUnloading: return "RACK_PLACING"; + case BackUnloading: return m_inspectionMode == "BEFORE_PLATING" + ? "REVERSE_FLIPPING" : "RACK_PLACING"; + case ReverseFlipping: return "RACK_PLACING"; case RackPlacing: return "COMPLETE"; default: return QString(); } @@ -1684,7 +1873,7 @@ bool ProductionService::setState(State state) m_timer->stop(); pauseProcessTimer(); m_state = state == ManualConfirm ? ManualConfirm : Error; - emit stateChanged(m_state, stateName()); + publishState(); return false; } if (m_state == state) return true; @@ -1711,14 +1900,14 @@ bool ProductionService::setState(State state) m_persistenceUncertain = true; m_lastError = "保存生产状态失败:" + persistenceError; m_state = state == ManualConfirm ? ManualConfirm : Error; - emit stateChanged(m_state, stateName()); + publishState(); emit productionError(m_lastError); return false; } } m_state = state; m_stateTimer.restart(); - emit stateChanged(m_state, stateName()); + publishState(); publishVisionControl(); return true; } @@ -2002,7 +2191,10 @@ bool ProductionService::processVisionAction(bool *completed, QString *error) *completed = true; return true; } - if (m_visionNeedsReconcile || m_visionSuspended) return true; + if (m_visionNeedsReconcile || m_visionSuspended) { + if (error) *error = "视觉动作尚未解除恢复锁,请先恢复/重试或终止当前订单"; + return false; + } if (m_visionStage == VisionStage::Idle) { prepareVision(); return true; @@ -2200,6 +2392,7 @@ bool ProductionService::productionActionForState( case Flipping: *action = DeviceService::Flip; return true; case BackLoading: *action = DeviceService::BackLoad; return true; case BackUnloading: *action = DeviceService::BackUnload; return true; + case ReverseFlipping: *action = DeviceService::ReverseFlip; return true; case RackPlacing: *action = DeviceService::RackPlace; return true; default: return false; } @@ -2338,37 +2531,19 @@ bool ProductionService::checkRecoverySafety(QString *error) const } return false; } - if (!m_deviceStatus.plcReady) { - if (error) { - *error = "PLC is not ready"; - } - return false; - } - if (!m_deviceStatus.robotReady) { - if (error) { - *error = "Robot is not ready"; - } - return false; - } - if (!m_deviceStatus.safetyDoorClosed) { - if (error) { - *error = "Safety door is open"; - } - return false; - } - if (m_deviceStatus.emergencyStop) { - if (error) { - *error = "Emergency stop is active"; - } - return false; - } - if (ConfigManager::instance().productionConfig().usePlcErrorCode - && m_deviceStatus.errorCode > 0) { - if (error) { - *error = QString("PLC error code: %1").arg(m_deviceStatus.errorCode); - } - return false; - } +// if (m_deviceStatus.emergencyStop) { +// if (error) *error = "Emergency stop is active"; +// return false; +// } +// if (!m_deviceStatus.safetyDoorClosed) { +// if (error) *error = "Safety door is open"; +// return false; +// } +// if (ConfigManager::instance().productionConfig().usePlcErrorCode +// && m_deviceStatus.errorCode > 0) { +// if (error) *error = QString("PLC error code: %1").arg(m_deviceStatus.errorCode); +// return false; +// } return true; } @@ -2434,25 +2609,85 @@ bool ProductionService::finishCurrentWorkpiece(const QString &state, return true; } +bool ProductionService::finalizeRun(bool completed, bool finishOrder, QString *error) +{ + DatabaseManager &database = DatabaseManager::instance(); + if (!database.transaction(error)) return false; + OrderRepository orders; + ProductionRepository runs; + Order order; + ProductionRunSnapshot run; + QString latestState; + bool hasActiveRun = false; + if (!orders.findOrderForUpdate(m_orderId, &order, error) + || !runs.lockOrderRuns(m_orderId, &latestState, &hasActiveRun, error) + || !runs.findRun(m_runId, &run, error)) { + database.rollback(); + return false; + } + if (run.orderId != m_orderId || run.runState == "COMPLETED" + || run.runState == "STOPPED") { + database.rollback(); + if (error) *error = "生产运行记录已改变,不能结束当前订单"; + return false; + } + if (completed) { + if (!orders.refreshProgress(m_orderId, error) + || !orders.findOrder(m_orderId, &order, error)) { + database.rollback(); + return false; + } + if ((order.status != "RUNNING" && order.status != "PAUSED") + || order.qualified + order.unqualified < order.planNum) { + database.rollback(); + if (error) *error = "订单尚未全部完成,不能结束生产"; + return false; + } + } + const QString targetStatus = completed || finishOrder ? "FINISHED" : "CANCELED"; + LogRecord log; + log.type = "操作日志"; + log.module = "订单管理"; + log.action = completed ? "完成订单" : (finishOrder ? "终止订单(剩余工件不再执行)" : "取消订单"); + log.content = log.action + ":" + order.no; + log.status = "成功"; + if (!orders.updateOrderLifecycle(m_orderId, targetStatus, order.beginTime, + QDateTime::currentDateTime(), error) + || !runs.updateRun(m_runId, completed ? "COMPLETED" : "STOPPED", + completed ? "COMPLETED" : "IDLE", m_currentWorkpiece.processStep, + m_currentWorkpiece.id, QString(), m_recoveryRetryCount, m_lastError, error) + || !runs.finishRun(m_runId, completed ? "COMPLETED" : "STOPPED", m_lastError, error) + || !runs.insertStateHistory(m_runId, m_orderId, m_currentWorkpiece.id, + stateName(), completed ? "COMPLETED" : "IDLE", m_currentWorkpiece.processStep, + completed ? "SYSTEM" : "OPERATOR", completed ? "COMPLETE" : "STOP", m_lastError, error) + || !LogRepository().insertLog(log, error)) { + database.rollback(); + return false; + } + if (!database.commit(error)) { + database.rollback(); + m_persistenceUncertain = true; + m_initialized = false; + return false; + } + return true; +} + bool ProductionService::finishOrder(QString *error) { - if (!OrderService::instance().completeOrder(m_orderId, error)) { - return false; - } - - QString persistenceError; - if (m_runId > 0 - && !ProductionRepository().finishRun( - m_runId, "COMPLETED", QString(), &persistenceError)) { - if (error) { - *error = persistenceError; - } - return false; - } - + if (!finalizeRun(true, true, error)) return false; + const int finishedOrderId = m_orderId; m_timer->stop(); - if (!setState(Completed)) { if (error) *error = m_lastError; return false; } - emit productionFinished(m_orderId); + m_runId = 0; + m_orderId = 0; + m_currentWorkpiece = Workpiece(); + m_checkpoint = ProductionActionCheckpoint(); + m_currentTrayNo = 0; + m_currentSlotNo = 0; + m_lastError.clear(); + clearProcessTimer(); + setState(Completed); + emit productionFinished(finishedOrderId); return true; } @@ -2483,7 +2718,7 @@ void ProductionService::tick() pauseProcessTimer(); m_lastError = persistenceError; m_state = Error; - emit stateChanged(m_state, stateName()); + publishState(); emit productionError(persistenceError); publishVisionControl(); return; @@ -2505,30 +2740,10 @@ void ProductionService::tick() m_heartbeatTimer.restart(); } - if (m_state == RecoveryChecking) { - QString recoveryError; - if (!checkRecoverySafety(&recoveryError)) { - m_lastError = recoveryError; - return; - } - } else { - if (!m_deviceStatus.plcConnected) { - fail("PLC is disconnected"); - return; - } - if (m_deviceStatus.emergencyStop) { - fail("Emergency stop is active"); - return; - } - if (!m_deviceStatus.safetyDoorClosed) { - fail("Safety door is open"); - return; - } - if (ConfigManager::instance().productionConfig().usePlcErrorCode - && m_deviceStatus.errorCode > 0) { - fail(QString("PLC error code: %1").arg(m_deviceStatus.errorCode)); - return; - } + QString safetyError; + if (!checkRecoverySafety(&safetyError)) { + fail(safetyError); + return; } if (m_state == Preparing) { @@ -2539,21 +2754,8 @@ void ProductionService::tick() return; } - DeviceService::ProductionAction timedAction; - if (productionActionForState(m_state, &timedAction) - && m_stateTimer.isValid() - && m_stateTimer.elapsed() > ConfigManager::instance().productionConfig().stateTimeoutMs) { - m_timeoutState = m_state; - m_lastError = "当前独立动作超时,请核对后恢复/重试"; - m_timer->stop(); - pauseProcessTimer(); - setState(TimeoutPaused); - emit timeoutRecoveryRequired(stateNameForState(m_timeoutState), m_lastError); - return; - } - if (m_state == WaitingDeviceReady) { - if (m_deviceStatus.plcReady && m_deviceStatus.robotReady) { + if (m_deviceStatusValid && m_deviceStatus.plcConnected) { QString error; State nextState = stateForProcessStep( m_currentWorkpiece.processStep); @@ -2696,7 +2898,13 @@ bool ProductionService::processProductionStep(State state, QString *error) return true; } case BackUnloading: - return executeCurrentAction(DeviceService::BackUnload, + return executeCurrentAction( + DeviceService::BackUnload, + m_inspectionMode == "BEFORE_PLATING" ? "REVERSE_FLIPPING" : "RACK_PLACING", + m_inspectionMode == "BEFORE_PLATING" ? ReverseFlipping : RackPlacing, + error); + case ReverseFlipping: + return executeCurrentAction(DeviceService::ReverseFlip, "RACK_PLACING", RackPlacing, error); case RackPlacing: { bool completed = false; @@ -2750,7 +2958,8 @@ bool ProductionService::isTimedState(State state) const || state == Loading || state == FrontChecking || state == FrontUnloading || state == Flipping || state == BackLoading || state == BackChecking - || state == BackUnloading || state == RackPlacing + || state == BackUnloading || state == ReverseFlipping + || state == RackPlacing || state == Judging; } @@ -2770,6 +2979,7 @@ QString ProductionService::processStepForState(State state) const case BackLoading: return "BACK_LOADING"; case BackChecking: return "BACK_CHECKING"; case BackUnloading: return "BACK_UNLOADING"; + case ReverseFlipping: return "REVERSE_FLIPPING"; case RackPlacing: return "RACK_PLACING"; case Judging: return "JUDGING"; default: return QString(); @@ -2792,6 +3002,7 @@ ProductionService::State ProductionService::stateForProcessStep( if (processStep == "BACK_LOADING") return BackLoading; if (processStep == "BACK_CHECKING") return BackChecking; if (processStep == "BACK_UNLOADING") return BackUnloading; + if (processStep == "REVERSE_FLIPPING") return ReverseFlipping; if (processStep == "RACK_PLACING") return RackPlacing; if (processStep == "JUDGING") return Judging; return Idle; @@ -2799,6 +3010,7 @@ ProductionService::State ProductionService::stateForProcessStep( QString ProductionService::runStateForState(State state) const { + if (m_terminationRequired && state != Idle && state != Completed) return "STOPPING"; switch (state) { case Paused: return "PAUSED"; @@ -2835,6 +3047,7 @@ ProductionService::State ProductionService::stateFromName(const QString &name) c if (name == "BACK_LOADING") return BackLoading; if (name == "BACK_CHECKING") return BackChecking; if (name == "BACK_UNLOADING") return BackUnloading; + if (name == "REVERSE_FLIPPING") return ReverseFlipping; if (name == "RACK_PLACING") return RackPlacing; if (name == "JUDGING") return Judging; if (name == "UNLOADING") return Unloading; diff --git a/services/productionservice.h b/services/productionservice.h index bc77374..e846d1f 100644 --- a/services/productionservice.h +++ b/services/productionservice.h @@ -34,6 +34,7 @@ public: BackLoading, BackChecking, BackUnloading, + ReverseFlipping, RackPlacing, Judging, Unloading, @@ -49,6 +50,18 @@ public: }; Q_ENUM(State) + struct Snapshot { + bool initialized = false; + int runId = 0; + int orderId = 0; + State state = Idle; + QString stateName; + bool terminationRequired = false; + bool visionRecoveryRequired = false; + QString error; + }; + Snapshot snapshot() const; + static ProductionService &instance(); State state() const; @@ -64,6 +77,7 @@ public: bool resume(QString *error = nullptr); bool stop(QString *error = nullptr, bool finishOrder = false); bool stopOrder(int orderId, QString *error = nullptr); + bool stopConfirmedOrder(int runId, int orderId, QString *error = nullptr); bool clearAlarm(QString *error = nullptr); bool recover(QString *error = nullptr); bool submitRecoveryDecision(const QJsonObject &decision, QString *error = nullptr); @@ -79,6 +93,7 @@ public slots: void publishVisionSnapshot(); signals: + void snapshotChanged(const ProductionService::Snapshot &snapshot); void stateChanged(ProductionService::State state, const QString &name); void deviceStatusChanged(const DeviceStatus &status); void deviceCommunicationError(const QString &error); @@ -130,6 +145,8 @@ private: ProductionService &operator=(const ProductionService &) = delete; bool setState(State state); + void publishState(); + bool restoreRun(QString *error); QString actionTypeForState(State state) const; QString nextStepForState(State state) const; bool ensureActionCheckpoint(State state, QString *error); @@ -152,6 +169,7 @@ private: bool finishCurrentWorkpiece(const QString &state, const QString &processStep, QString *error); bool finishOrder(QString *error); + bool finalizeRun(bool completed, bool finishOrder, QString *error); void tickSimulation(); void tickProduction(); bool processProductionStep(State state, QString *error); @@ -203,6 +221,8 @@ private: QElapsedTimer m_processTimer; QElapsedTimer m_heartbeatTimer; State m_state; + bool m_initialized = false; + bool m_terminationRequired = false; State m_timeoutState; int m_runId; int m_orderId; @@ -271,6 +291,7 @@ private: }; Q_DECLARE_METATYPE(ProductionService::State) +Q_DECLARE_METATYPE(ProductionService::Snapshot) Q_DECLARE_METATYPE(Workpiece) #endif // PRODUCTIONSERVICE_H diff --git a/services/productionworker.cpp b/services/productionworker.cpp index ef4cc8b..c70b70f 100644 --- a/services/productionworker.cpp +++ b/services/productionworker.cpp @@ -5,6 +5,7 @@ ProductionWorker::ProductionWorker(QObject *parent) , m_service(nullptr) , m_stopRequested(false) { + qRegisterMetaType("ProductionService::Snapshot"); } void ProductionWorker::ensureService() @@ -14,6 +15,8 @@ void ProductionWorker::ensureService() } m_service = new ProductionService(this); + connect(m_service, &ProductionService::snapshotChanged, + this, &ProductionWorker::snapshotChanged); m_service->setExternalStopFlag(&m_stopRequested); connect(m_service, &ProductionService::visionMeasureRequested, this, &ProductionWorker::visionMeasureRequested); connect(m_service, &ProductionService::visionCancelRequested, this, &ProductionWorker::visionCancelRequested); @@ -109,11 +112,11 @@ void ProductionWorker::requestStop() reportFailure(m_service->stop(&error), error); } -void ProductionWorker::requestStopOrder(int orderId) +void ProductionWorker::requestStopOrder(int runId, int orderId) { ensureService(); QString error; - reportFailure(m_service->stopOrder(orderId, &error), error); + reportFailure(m_service->stopConfirmedOrder(runId, orderId, &error), error); } void ProductionWorker::requestClearAlarm() @@ -127,7 +130,9 @@ void ProductionWorker::requestRecover() { ensureService(); QString error; - reportFailure(m_service->recover(&error), error); + const bool success = m_service->snapshot().initialized + ? m_service->recover(&error) : m_service->restoreActiveRun(&error); + reportFailure(success, error); } void ProductionWorker::requestRecoveryDecision(const QJsonObject &decision) @@ -149,6 +154,7 @@ void ProductionWorker::requestRestore() ensureService(); QString error; reportFailure(m_service->restoreActiveRun(&error), error); + emit recoveryBusyChanged(false); } void ProductionWorker::requestShutdown() diff --git a/services/productionworker.h b/services/productionworker.h index d21a0b5..368eadf 100644 --- a/services/productionworker.h +++ b/services/productionworker.h @@ -19,7 +19,7 @@ public slots: void requestPause(); void requestResume(); void requestStop(); - void requestStopOrder(int orderId); + void requestStopOrder(int runId, int orderId); void requestClearAlarm(); void requestRecover(); void requestRecoveryDecision(const QJsonObject &decision); @@ -31,6 +31,7 @@ public slots: void requestVisionSnapshot(); signals: + void snapshotChanged(const ProductionService::Snapshot &snapshot); void stateChanged(ProductionService::State state, const QString &name); void deviceStatusChanged(const DeviceStatus &status); void deviceCommunicationError(const QString &error);