diff --git a/config.ini b/config.ini index e13dc57..4c25f47 100644 --- a/config.ini +++ b/config.ini @@ -14,7 +14,6 @@ serverAddress=1 timeoutMs=1000 retryCount=1 pollIntervalMs=1000 -commandPulseMs=100 feedbackTimeoutMs=2000 reconnectDelayMs=200 reconnectAttempts=2 @@ -33,6 +32,25 @@ emergencyStop=103 currentStep=200 checkResult=201 errorCode=202 +rackPickCommand=300 +rackPickFeedback=310 +frontLoadCommand=301 +frontLoadFeedback=311 +inspectionCommand=302 +inspectionFeedback=312 +frontUnloadCommand=303 +frontUnloadFeedback=313 +flipCommand=304 +flipFeedback=314 +backLoadCommand=305 +backLoadFeedback=315 +backUnloadCommand=306 +backUnloadFeedback=316 +rackPlaceCommand=307 +rackPlaceFeedback=317 +inspectionMode=320 +trayNumber=400 +slotNumber=401 [production] loadStep=1 diff --git a/config/configmanager.cpp b/config/configmanager.cpp index a7a184b..6437df1 100644 --- a/config/configmanager.cpp +++ b/config/configmanager.cpp @@ -38,7 +38,6 @@ bool ConfigManager::load(const QString &filePath) m_modbusConfig.timeoutMs = settings.value("modbus/timeoutMs", m_modbusConfig.timeoutMs).toInt(); m_modbusConfig.retryCount = settings.value("modbus/retryCount", m_modbusConfig.retryCount).toInt(); m_modbusConfig.pollIntervalMs = settings.value("modbus/pollIntervalMs", m_modbusConfig.pollIntervalMs).toInt(); - m_modbusConfig.commandPulseMs = settings.value("modbus/commandPulseMs", m_modbusConfig.commandPulseMs).toInt(); m_modbusConfig.feedbackTimeoutMs = settings.value("modbus/feedbackTimeoutMs", m_modbusConfig.feedbackTimeoutMs).toInt(); m_modbusConfig.reconnectDelayMs = settings.value("modbus/reconnectDelayMs", m_modbusConfig.reconnectDelayMs).toInt(); m_modbusConfig.reconnectAttempts = settings.value("modbus/reconnectAttempts", m_modbusConfig.reconnectAttempts).toInt(); @@ -59,6 +58,44 @@ bool ConfigManager::load(const QString &filePath) addresses.currentStep = settings.value("modbus/currentStep", addresses.currentStep).toInt(); addresses.checkResult = settings.value("modbus/checkResult", addresses.checkResult).toInt(); addresses.errorCode = settings.value("modbus/errorCode", addresses.errorCode).toInt(); + addresses.rackPickCommand = + settings.value("modbus/rackPickCommand", addresses.rackPickCommand).toInt(); + addresses.frontLoadCommand = + settings.value("modbus/frontLoadCommand", addresses.frontLoadCommand).toInt(); + addresses.inspectionCommand = + settings.value("modbus/inspectionCommand", addresses.inspectionCommand).toInt(); + addresses.frontUnloadCommand = + settings.value("modbus/frontUnloadCommand", addresses.frontUnloadCommand).toInt(); + addresses.flipCommand = + settings.value("modbus/flipCommand", addresses.flipCommand).toInt(); + addresses.backLoadCommand = + settings.value("modbus/backLoadCommand", addresses.backLoadCommand).toInt(); + addresses.backUnloadCommand = + settings.value("modbus/backUnloadCommand", addresses.backUnloadCommand).toInt(); + addresses.rackPlaceCommand = + settings.value("modbus/rackPlaceCommand", addresses.rackPlaceCommand).toInt(); + addresses.rackPickFeedback = + settings.value("modbus/rackPickFeedback", addresses.rackPickFeedback).toInt(); + addresses.frontLoadFeedback = + settings.value("modbus/frontLoadFeedback", addresses.frontLoadFeedback).toInt(); + addresses.inspectionFeedback = + settings.value("modbus/inspectionFeedback", addresses.inspectionFeedback).toInt(); + addresses.frontUnloadFeedback = + settings.value("modbus/frontUnloadFeedback", addresses.frontUnloadFeedback).toInt(); + addresses.flipFeedback = + settings.value("modbus/flipFeedback", addresses.flipFeedback).toInt(); + addresses.backLoadFeedback = + settings.value("modbus/backLoadFeedback", addresses.backLoadFeedback).toInt(); + addresses.backUnloadFeedback = + settings.value("modbus/backUnloadFeedback", addresses.backUnloadFeedback).toInt(); + addresses.rackPlaceFeedback = + settings.value("modbus/rackPlaceFeedback", addresses.rackPlaceFeedback).toInt(); + addresses.inspectionMode = + settings.value("modbus/inspectionMode", addresses.inspectionMode).toInt(); + addresses.trayNumber = + settings.value("modbus/trayNumber", addresses.trayNumber).toInt(); + addresses.slotNumber = + settings.value("modbus/slotNumber", addresses.slotNumber).toInt(); m_productionConfig.loadStep = settings.value("production/loadStep", m_productionConfig.loadStep).toInt(); @@ -146,8 +183,7 @@ bool ConfigManager::validate(QString *error) const if (m_modbusConfig.pollIntervalMs <= 0) { errors.append("Modbus pollIntervalMs must be greater than 0"); } - if (m_modbusConfig.commandPulseMs <= 0 - || m_modbusConfig.feedbackTimeoutMs <= 0 + if (m_modbusConfig.feedbackTimeoutMs <= 0 || m_modbusConfig.reconnectDelayMs < 0 || m_modbusConfig.reconnectAttempts < 0) { errors.append("Modbus timing or retry settings are invalid"); diff --git a/db/databasemanager.cpp b/db/databasemanager.cpp index 26ac226..71fd161 100644 --- a/db/databasemanager.cpp +++ b/db/databasemanager.cpp @@ -1,6 +1,8 @@ #include "databasemanager.h" +#include #include +#include DatabaseManager &DatabaseManager::instance() { @@ -28,11 +30,12 @@ DbConfig DatabaseManager::config() const bool DatabaseManager::open(QString *error) { + const QString name = connectionName(); QSqlDatabase db; - if (QSqlDatabase::contains(m_config.connectionName)) { - db = QSqlDatabase::database(m_config.connectionName); + if (QSqlDatabase::contains(name)) { + db = QSqlDatabase::database(name); } else { - db = QSqlDatabase::addDatabase(m_config.driverName, m_config.connectionName); + db = QSqlDatabase::addDatabase(m_config.driverName, name); } if (db.isOpen()) { @@ -59,35 +62,37 @@ bool DatabaseManager::open(QString *error) void DatabaseManager::close() { - const QString connectionName = m_config.connectionName; - if (!QSqlDatabase::contains(connectionName)) { + const QString name = connectionName(); + if (!QSqlDatabase::contains(name)) { return; } { - QSqlDatabase db = QSqlDatabase::database(connectionName, false); + QSqlDatabase db = QSqlDatabase::database(name, false); if (db.isValid() && db.isOpen()) { db.close(); } } - QSqlDatabase::removeDatabase(connectionName); + QSqlDatabase::removeDatabase(name); } bool DatabaseManager::isOpen() const { - if (!QSqlDatabase::contains(m_config.connectionName)) { + const QString name = connectionName(); + if (!QSqlDatabase::contains(name)) { return false; } - return QSqlDatabase::database(m_config.connectionName, false).isOpen(); + return QSqlDatabase::database(name, false).isOpen(); } QSqlDatabase DatabaseManager::database() const { - if (!QSqlDatabase::contains(m_config.connectionName)) { + const QString name = connectionName(); + if (!QSqlDatabase::contains(name)) { return QSqlDatabase(); } - return QSqlDatabase::database(m_config.connectionName); + return QSqlDatabase::database(name); } QString DatabaseManager::lastErrorText() const @@ -136,3 +141,14 @@ bool DatabaseManager::rollback(QString *error) } return true; } + +QString DatabaseManager::connectionName() const +{ + if (QThread::currentThread() == QCoreApplication::instance()->thread()) { + return m_config.connectionName; + } + + return QString("%1_%2") + .arg(m_config.connectionName) + .arg(reinterpret_cast(QThread::currentThreadId()), 0, 16); +} diff --git a/db/databasemanager.h b/db/databasemanager.h index 69350b7..c37aa08 100644 --- a/db/databasemanager.h +++ b/db/databasemanager.h @@ -29,6 +29,8 @@ private: DatabaseManager(const DatabaseManager &) = delete; DatabaseManager &operator=(const DatabaseManager &) = delete; + QString connectionName() const; + DbConfig m_config; QString m_lastErrorText; }; diff --git a/db/schema.sql b/db/schema.sql index 3fd5f5b..12128b0 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -8,11 +8,22 @@ create table if not exists orders ( qualified integer not null default 0, unqualified integer not null default 0, status varchar(32) not null default 'NOT_START', + inspection_mode varchar(32) not null default 'BEFORE_PLATING', + start_tray_no integer not null default 1, + start_slot_no integer not null default 1, begin_time timestamp, end_time timestamp, remark text, created_at timestamp not null default now(), - updated_at timestamp not null default now() + updated_at timestamp not null default now(), + constraint ck_orders_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')), + constraint ck_orders_plan_num + check (plan_num > 0), + constraint ck_orders_start_tray_no + check (start_tray_no > 0), + constraint ck_orders_start_slot_no + check (start_slot_no between 1 and 49) ); create table if not exists trays ( @@ -45,6 +56,10 @@ create table if not exists workpieces ( updated_at timestamp not null default now() ); +create unique index if not exists ux_workpieces_tray_position +on workpieces(tray_id, tray_pos) +where tray_id is not null and tray_pos > 0; + create table if not exists tray_slots ( id bigserial primary key, tray_id bigint not null references trays(id) on delete cascade, @@ -55,6 +70,10 @@ create table if not exists tray_slots ( unique (tray_id, row_no, column_no) ); +create unique index if not exists ux_tray_slots_workpiece +on tray_slots(workpiece_id) +where workpiece_id is not null; + create table if not exists devices ( id bigserial primary key, code varchar(64) not null unique, @@ -85,6 +104,11 @@ values ('TRAY-6', 2, 3, true, 34, 'PRESENT') on conflict (rack_row, rack_column) do nothing; +-- Only one unfinished order may exist at a time. +create unique index if not exists ux_orders_single_unfinished +on orders ((1)) +where status in ('NOT_START', 'RUNNING', 'PAUSED'); + -- Database schema version create table if not exists schema_version ( id smallint primary key default 1, @@ -95,7 +119,7 @@ create table if not exists schema_version ( ); insert into schema_version (id, version, description) -values (1, 3, 'Production records, alarm closed-loop and final inspection tables') +values (1, 6, 'Inspection modes, order range, and production allocation constraints') on conflict (id) do update set version = excluded.version, description = excluded.description, @@ -109,6 +133,10 @@ create table if not exists production_runs ( run_state varchar(32) not null default 'RUNNING', production_state varchar(64) not null, process_step varchar(64), + inspection_mode varchar(32) not null default 'BEFORE_PLATING', + start_tray_no integer not null default 1, + start_slot_no integer not null default 1, + plan_num integer not null default 0, timeout_state varchar(64), recovery_retry_count integer not null default 0, last_error text, @@ -128,7 +156,15 @@ create table if not exists production_runs ( 'STOPPED' )), constraint ck_production_retry_count - check (recovery_retry_count >= 0) + check (recovery_retry_count >= 0), + constraint ck_production_runs_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')), + constraint ck_production_runs_start_tray_no + check (start_tray_no > 0), + constraint ck_production_runs_start_slot_no + check (start_slot_no between 1 and 49), + constraint ck_production_runs_plan_num + check (plan_num >= 0) ); create unique index if not exists ux_production_runs_active_order @@ -181,6 +217,7 @@ create table if not exists inspection_records ( order_id bigint references orders(id) on delete set null, workpiece_id bigint not null references workpieces(id), inspection_side varchar(16) not null, + inspection_mode varchar(32) not null default 'BEFORE_PLATING', attempt_no integer not null default 1, raw_result integer, result_state varchar(16) not null, @@ -194,6 +231,8 @@ create table if not exists inspection_records ( created_at timestamp not null default now(), constraint ck_inspection_side check (inspection_side in ('FRONT', 'BACK', 'FINAL')), + constraint ck_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')), constraint ck_inspection_attempt check (attempt_no > 0), constraint ck_inspection_result_state @@ -241,6 +280,7 @@ create table if not exists workpiece_process_records ( order_id bigint references orders(id) on delete set null, workpiece_id bigint not null references workpieces(id), process_step varchar(64) not null, + inspection_mode varchar(32) not null default 'BEFORE_PLATING', attempt_no integer not null default 1, process_state varchar(16) not null default 'RUNNING', result_state varchar(16), @@ -253,6 +293,8 @@ create table if not exists workpiece_process_records ( created_at timestamp not null default now(), constraint ck_process_record_attempt check (attempt_no > 0), + constraint ck_process_record_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')), constraint ck_process_record_state check (process_state in ('RUNNING', 'COMPLETED', 'FAILED', 'SKIPPED')), constraint ck_process_record_result @@ -276,6 +318,239 @@ on workpiece_process_records(process_step); create index if not exists ix_process_records_started_at on workpiece_process_records(started_at); +-- Inspection mode migration for existing databases +do $$ +begin + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'orders' + and column_name = 'inspection_mode' + ) then + alter table public.orders + add column inspection_mode varchar(32) + not null default 'BEFORE_PLATING'; + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'orders' + and constraint_name = 'ck_orders_inspection_mode' + ) then + alter table public.orders + add constraint ck_orders_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')); + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'orders' + and constraint_name = 'ck_orders_plan_num' + ) then + alter table public.orders + add constraint ck_orders_plan_num + check (plan_num > 0); + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'orders' + and column_name = 'start_tray_no' + ) then + alter table public.orders + add column start_tray_no integer + not null default 1; + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'orders' + and column_name = 'start_slot_no' + ) then + alter table public.orders + add column start_slot_no integer + not null default 1; + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'orders' + and constraint_name = 'ck_orders_start_tray_no' + ) then + alter table public.orders + add constraint ck_orders_start_tray_no + check (start_tray_no > 0); + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'orders' + and constraint_name = 'ck_orders_start_slot_no' + ) then + alter table public.orders + add constraint ck_orders_start_slot_no + check (start_slot_no between 1 and 49); + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'production_runs' + and column_name = 'inspection_mode' + ) then + alter table public.production_runs + add column inspection_mode varchar(32) + not null default 'BEFORE_PLATING'; + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'production_runs' + and constraint_name = 'ck_production_runs_inspection_mode' + ) then + alter table public.production_runs + add constraint ck_production_runs_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')); + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'production_runs' + and column_name = 'start_tray_no' + ) then + alter table public.production_runs + add column start_tray_no integer + not null default 1; + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'production_runs' + and column_name = 'start_slot_no' + ) then + alter table public.production_runs + add column start_slot_no integer + not null default 1; + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'production_runs' + and constraint_name = 'ck_production_runs_start_tray_no' + ) then + alter table public.production_runs + add constraint ck_production_runs_start_tray_no + check (start_tray_no > 0); + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'production_runs' + and constraint_name = 'ck_production_runs_start_slot_no' + ) then + alter table public.production_runs + add constraint ck_production_runs_start_slot_no + check (start_slot_no between 1 and 49); + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'production_runs' + and column_name = 'plan_num' + ) then + alter table public.production_runs + add column plan_num integer + not null default 0; + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'production_runs' + and constraint_name = 'ck_production_runs_plan_num' + ) then + alter table public.production_runs + add constraint ck_production_runs_plan_num + check (plan_num >= 0); + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'workpiece_process_records' + and column_name = 'inspection_mode' + ) then + alter table public.workpiece_process_records + add column inspection_mode varchar(32) + not null default 'BEFORE_PLATING'; + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'workpiece_process_records' + and constraint_name = 'ck_process_record_inspection_mode' + ) then + alter table public.workpiece_process_records + add constraint ck_process_record_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')); + end if; + + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'inspection_records' + and column_name = 'inspection_mode' + ) then + alter table public.inspection_records + add column inspection_mode varchar(32) + not null default 'BEFORE_PLATING'; + end if; + + if not exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'inspection_records' + and constraint_name = 'ck_inspection_mode' + ) then + alter table public.inspection_records + add constraint ck_inspection_mode + check (inspection_mode in ('BEFORE_PLATING', 'AFTER_PLATING')); + end if; +end +$$; + -- Alarm definitions create table if not exists alarm_definitions ( id bigserial primary key, diff --git a/modbus/modbusaddress.cpp b/modbus/modbusaddress.cpp index 03a7107..0c5058e 100644 --- a/modbus/modbusaddress.cpp +++ b/modbus/modbusaddress.cpp @@ -2,6 +2,7 @@ #include #include +#include namespace { @@ -29,8 +30,28 @@ bool ModbusAddressMap::isValid(QString *error) const << qMakePair(QString("emergencyStop"), emergencyStop) << qMakePair(QString("currentStep"), currentStep) << qMakePair(QString("checkResult"), checkResult) - << qMakePair(QString("errorCode"), errorCode); + << qMakePair(QString("errorCode"), errorCode) + << qMakePair(QString("rackPickCommand"), rackPickCommand) + << qMakePair(QString("frontLoadCommand"), frontLoadCommand) + << qMakePair(QString("inspectionCommand"), inspectionCommand) + << qMakePair(QString("frontUnloadCommand"), frontUnloadCommand) + << qMakePair(QString("flipCommand"), flipCommand) + << qMakePair(QString("backLoadCommand"), backLoadCommand) + << qMakePair(QString("backUnloadCommand"), backUnloadCommand) + << qMakePair(QString("rackPlaceCommand"), rackPlaceCommand) + << qMakePair(QString("rackPickFeedback"), rackPickFeedback) + << qMakePair(QString("frontLoadFeedback"), frontLoadFeedback) + << qMakePair(QString("inspectionFeedback"), inspectionFeedback) + << qMakePair(QString("frontUnloadFeedback"), frontUnloadFeedback) + << qMakePair(QString("flipFeedback"), flipFeedback) + << qMakePair(QString("backLoadFeedback"), backLoadFeedback) + << qMakePair(QString("backUnloadFeedback"), backUnloadFeedback) + << qMakePair(QString("rackPlaceFeedback"), rackPlaceFeedback) + << qMakePair(QString("inspectionMode"), inspectionMode) + << qMakePair(QString("trayNumber"), trayNumber) + << qMakePair(QString("slotNumber"), slotNumber); + QSet usedAddresses; for (const QPair &item : addresses) { if (!isValidAddress(item.second)) { if (error) { @@ -38,6 +59,14 @@ bool ModbusAddressMap::isValid(QString *error) const } return false; } + if (usedAddresses.contains(item.second)) { + if (error) { + *error = QString("Modbus address is duplicated: %1") + .arg(item.first); + } + return false; + } + usedAddresses.insert(item.second); } return true; diff --git a/modbus/modbusaddress.h b/modbus/modbusaddress.h index e9725c3..d814d69 100644 --- a/modbus/modbusaddress.h +++ b/modbus/modbusaddress.h @@ -24,6 +24,28 @@ struct ModbusAddressMap int checkResult = 201; int errorCode = 202; + int rackPickCommand = 300; + int frontLoadCommand = 301; + int inspectionCommand = 302; + int frontUnloadCommand = 303; + int flipCommand = 304; + int backLoadCommand = 305; + int backUnloadCommand = 306; + int rackPlaceCommand = 307; + + int rackPickFeedback = 310; + int frontLoadFeedback = 311; + int inspectionFeedback = 312; + int frontUnloadFeedback = 313; + int flipFeedback = 314; + int backLoadFeedback = 315; + int backUnloadFeedback = 316; + int rackPlaceFeedback = 317; + + int inspectionMode = 320; + int trayNumber = 400; + int slotNumber = 401; + bool isValid(QString *error = nullptr) const; }; diff --git a/modbus/modbusconfig.cpp b/modbus/modbusconfig.cpp index 30293e5..76c3a06 100644 --- a/modbus/modbusconfig.cpp +++ b/modbus/modbusconfig.cpp @@ -9,7 +9,6 @@ ModbusConfig ModbusConfig::defaultConfig() config.timeoutMs = 1000; config.retryCount = 1; config.pollIntervalMs = 1000; - config.commandPulseMs = 100; config.feedbackTimeoutMs = 2000; config.reconnectDelayMs = 200; config.reconnectAttempts = 2; diff --git a/modbus/modbusconfig.h b/modbus/modbusconfig.h index d87219f..6d9261d 100644 --- a/modbus/modbusconfig.h +++ b/modbus/modbusconfig.h @@ -13,7 +13,6 @@ struct ModbusConfig int timeoutMs; int retryCount; int pollIntervalMs; - int commandPulseMs; int feedbackTimeoutMs; int reconnectDelayMs; int reconnectAttempts; diff --git a/models/order.h b/models/order.h index 50afef8..73a4bec 100644 --- a/models/order.h +++ b/models/order.h @@ -15,6 +15,9 @@ struct Order int qualified = 0; int unqualified = 0; QString status; + QString inspectionMode = "BEFORE_PLATING"; + int startTrayNo = 1; + int startSlotNo = 1; QDateTime beginTime; QDateTime endTime; QString remark; diff --git a/pages/dashboardpage.cpp b/pages/dashboardpage.cpp index a5d7dc7..2cd4bee 100644 --- a/pages/dashboardpage.cpp +++ b/pages/dashboardpage.cpp @@ -18,10 +18,12 @@ #include #include #include +#include #include #include #include #include +#include #include DashboardPage::DashboardPage(QWidget *parent) @@ -41,9 +43,18 @@ DashboardPage::DashboardPage(QWidget *parent) , processTable(new QTableWidget(processBox)) , processRefreshTimer(new QTimer(this)) , currentProcessElapsedMs(0) + , productionThread(new QThread(this)) + , productionWorker(new ProductionWorker) + , productionState(ProductionService::Idle) + , productionTrayNo(0) + , productionSlotNo(0) { ui->setupUi(this); + productionWorker->moveToThread(productionThread); + connect(productionThread, &QThread::finished, + productionWorker, &QObject::deleteLater); + const QList values = QList() << ui->planValue << ui->pendingValue << ui->frontValue << ui->backValue << ui->okValue << ui->ngValue; @@ -155,29 +166,30 @@ DashboardPage::DashboardPage(QWidget *parent) connect(orderCombo, QOverload::of(&QComboBox::currentIndexChanged), this, &DashboardPage::onOrderChanged); - ProductionService &production = ProductionService::instance(); - connect(&production, &ProductionService::stateChanged, + connect(productionWorker, &ProductionWorker::stateChanged, this, &DashboardPage::onProductionStateChanged); - connect(&production, &ProductionService::currentWorkpieceChanged, + connect(productionWorker, &ProductionWorker::currentWorkpieceChanged, this, &DashboardPage::onCurrentWorkpieceChanged); - connect(&production, &ProductionService::productionError, + connect(productionWorker, &ProductionWorker::currentWorkpieceSnapshotChanged, + this, &DashboardPage::onCurrentWorkpieceSnapshotChanged); + connect(productionWorker, &ProductionWorker::currentPositionChanged, + this, &DashboardPage::onCurrentPositionChanged); + connect(productionWorker, &ProductionWorker::productionError, this, &DashboardPage::onProductionError); - connect(&production, &ProductionService::productionFinished, + connect(productionWorker, &ProductionWorker::productionFinished, this, &DashboardPage::onProductionFinished); - connect(&production, &ProductionService::processElapsedChanged, + connect(productionWorker, &ProductionWorker::processElapsedChanged, this, &DashboardPage::onProcessElapsedChanged); - connect(&production, &ProductionService::timeoutRecoveryRequired, + connect(productionWorker, &ProductionWorker::timeoutRecoveryRequired, this, &DashboardPage::onTimeoutRecoveryRequired); - connect(&production, &ProductionService::recoveryCompleted, + connect(productionWorker, &ProductionWorker::recoveryCompleted, this, &DashboardPage::onRecoveryCompleted); connect(&DeviceService::instance(), &DeviceService::statusChanged, this, &DashboardPage::onDeviceStatusChanged); - QString restoreError; - if (!production.restoreActiveRun(&restoreError)) { - emit logRequested("Alarm log", "Production", "Restore production", - restoreError, "Failed"); - } + productionThread->start(); + QMetaObject::invokeMethod(productionWorker, "requestRestore", + Qt::QueuedConnection); loadOrderOptions(); DeviceService::instance().startPolling(); @@ -190,6 +202,10 @@ DashboardPage::DashboardPage(QWidget *parent) DashboardPage::~DashboardPage() { + if (productionThread->isRunning()) { + productionThread->quit(); + productionThread->wait(); + } delete ui; } @@ -251,46 +267,32 @@ void DashboardPage::startProduction() return; } - QString error; - const bool success = ProductionService::instance().state() - == ProductionService::Paused - ? ProductionService::instance().resume(&error) - : ProductionService::instance().start(selectedOrderId, &error); - if (!success) { - QMessageBox::warning(this, "Start production failed", error); - emit logRequested("Operation log", "Dashboard", "Start production", - error, "Failed"); + if (productionState == ProductionService::Paused) { + QMetaObject::invokeMethod(productionWorker, "requestResume", + Qt::QueuedConnection); + } else { + QMetaObject::invokeMethod( + productionWorker, "requestStart", Qt::QueuedConnection, + Q_ARG(int, selectedOrderId)); } } void DashboardPage::pauseProduction() { - QString error; - if (!ProductionService::instance().pause(&error)) { - QMessageBox::warning(this, "Pause production failed", error); - emit logRequested("Operation log", "Dashboard", "Pause production", - error, "Failed"); - } + QMetaObject::invokeMethod(productionWorker, "requestPause", + Qt::QueuedConnection); } void DashboardPage::stopProduction() { - QString error; - if (!ProductionService::instance().stop(&error)) { - QMessageBox::warning(this, "Stop production failed", error); - emit logRequested("Operation log", "Dashboard", "Stop production", - error, "Failed"); - } + QMetaObject::invokeMethod(productionWorker, "requestStop", + Qt::QueuedConnection); } void DashboardPage::resetProduction() { - QString error; - if (!ProductionService::instance().reset(&error)) { - QMessageBox::warning(this, "Reset production failed", error); - emit logRequested("Operation log", "Dashboard", "Reset production", - error, "Failed"); - } + QMetaObject::invokeMethod(productionWorker, "requestReset", + Qt::QueuedConnection); } void DashboardPage::clearAlarm() @@ -318,12 +320,11 @@ void DashboardPage::onOrderChanged(int) updateOrderSummary(); } -void DashboardPage::onProductionStateChanged(ProductionService::State, +void DashboardPage::onProductionStateChanged(ProductionService::State state, const QString &name) { + productionState = state; ui->actionLabel->setText("Production state: " + name); - const ProductionService::State state = ProductionService::instance().state(); - Q_UNUSED(state); updateRecoveryButtons(); emit systemStateChanged(name); emit currentStepChanged(name); @@ -336,6 +337,7 @@ void DashboardPage::onCurrentWorkpieceChanged(int workpieceId, { if (workpieceId <= 0) { ui->workpieceLabel->setText("Current workpiece: -"); + ui->trayLabel->setText("Current tray: -"); currentProcessElapsedMs = 0; } else { ui->workpieceLabel->setText( @@ -346,6 +348,23 @@ void DashboardPage::onCurrentWorkpieceChanged(int workpieceId, updateProductionStats(); } +void DashboardPage::onCurrentWorkpieceSnapshotChanged( + const Workpiece &workpiece) +{ + productionWorkpiece = workpiece; + refreshProcessRecords(); + updateProductionStats(); +} + +void DashboardPage::onCurrentPositionChanged(int trayNo, int slotNo) +{ + productionTrayNo = trayNo; + productionSlotNo = slotNo; + ui->trayLabel->setText(trayNo > 0 + ? QString("Current tray: %1 / slot: %2").arg(trayNo).arg(slotNo) + : "Current tray: -"); +} + void DashboardPage::onProductionError(const QString &error) { ui->actionLabel->setText("Production error: " + error); @@ -387,9 +406,7 @@ void DashboardPage::onRecoveryCompleted(const QString &mode) void DashboardPage::recoverProduction() { - ProductionService &production = ProductionService::instance(); - QString error; - if (production.state() == ProductionService::ManualConfirm + if (productionState == ProductionService::ManualConfirm && QMessageBox::question( this, "Continue production", "Continue only after confirming the equipment and current PLC step are safe?", @@ -398,22 +415,14 @@ void DashboardPage::recoverProduction() return; } - const bool success = production.recover(&error); - if (!success) { - QMessageBox::warning(this, "Recovery failed", error); - emit logRequested("Operation log", "Production", "Manual recovery", - error, "Failed"); - } + QMetaObject::invokeMethod(productionWorker, "requestRecover", + Qt::QueuedConnection); } void DashboardPage::retryRecovery() { - QString error; - if (!ProductionService::instance().retry(&error)) { - QMessageBox::warning(this, "Retry failed", error); - emit logRequested("Alarm log", "Production", "Retry production step", - error, "Failed"); - } + QMetaObject::invokeMethod(productionWorker, "requestRetry", + Qt::QueuedConnection); } void DashboardPage::markWorkpieceNg() @@ -426,17 +435,13 @@ void DashboardPage::markWorkpieceNg() return; } - QString error; - if (!ProductionService::instance().markCurrentWorkpieceNg(&error)) { - QMessageBox::warning(this, "Mark NG failed", error); - emit logRequested("Alarm log", "Production", "Mark workpiece NG", - error, "Failed"); - } + QMetaObject::invokeMethod(productionWorker, "requestMarkNg", + Qt::QueuedConnection); } void DashboardPage::updateRecoveryButtons() { - const ProductionService::State state = ProductionService::instance().state(); + const ProductionService::State state = productionState; const bool recoveryRequired = state == ProductionService::TimeoutPaused || state == ProductionService::ManualConfirm; const bool running = state != ProductionService::Idle @@ -444,8 +449,7 @@ void DashboardPage::updateRecoveryButtons() recoverButton->setVisible(recoveryRequired); retryButton->setVisible(recoveryRequired); markNgButton->setVisible(recoveryRequired - && ProductionService::instance() - .currentWorkpiece().id > 0); + && productionWorkpiece.id > 0); stopButton->setVisible(running); recoverButton->setText(state == ProductionService::ManualConfirm ? "Continue" : "Recover"); @@ -467,7 +471,7 @@ QString DashboardPage::formatDuration(int elapsedMs) void DashboardPage::refreshProcessRecords() { - const Workpiece workpiece = ProductionService::instance().currentWorkpiece(); + const Workpiece workpiece = productionWorkpiece; if (workpiece.id <= 0) { currentProcessLabel->setText("-"); processElapsedLabel->setText(formatDuration(0)); @@ -527,7 +531,7 @@ void DashboardPage::refreshProcessRecords() void DashboardPage::updateCurrentProcessDuration(int elapsedMs) { - const Workpiece workpiece = ProductionService::instance().currentWorkpiece(); + const Workpiece workpiece = productionWorkpiece; if (workpiece.id <= 0) { return; } diff --git a/pages/dashboardpage.h b/pages/dashboardpage.h index 41d0bab..40f8c2a 100644 --- a/pages/dashboardpage.h +++ b/pages/dashboardpage.h @@ -1,7 +1,7 @@ #ifndef DASHBOARDPAGE_H #define DASHBOARDPAGE_H -#include "../services/productionservice.h" +#include "../services/productionworker.h" #include #include @@ -13,6 +13,7 @@ class QResizeEvent; class QLabel; class QPushButton; class QTimer; +class QThread; namespace Ui { class DashboardPage; } @@ -42,6 +43,8 @@ private slots: void onProductionStateChanged(ProductionService::State state, const QString &name); void onCurrentWorkpieceChanged(int workpieceId, const QString &barcode); + void onCurrentWorkpieceSnapshotChanged(const Workpiece &workpiece); + void onCurrentPositionChanged(int trayNo, int slotNo); void onProductionError(const QString &error); void onProductionFinished(int orderId); void onDeviceStatusChanged(const DeviceStatus &status); @@ -81,6 +84,12 @@ private: QTableWidget *processTable; QTimer *processRefreshTimer; int currentProcessElapsedMs; + QThread *productionThread; + ProductionWorker *productionWorker; + ProductionService::State productionState; + Workpiece productionWorkpiece; + int productionTrayNo; + int productionSlotNo; }; #endif // DASHBOARDPAGE_H diff --git a/pages/orderpage.cpp b/pages/orderpage.cpp index 29920c0..855a417 100644 --- a/pages/orderpage.cpp +++ b/pages/orderpage.cpp @@ -2,6 +2,7 @@ #include "ui_orderpage.h" #include +#include #include #include #include @@ -27,10 +28,16 @@ OrderPage::OrderPage(QWidget *parent) ui->toolbarLayout->insertWidget(5, generateButton); QTableWidget *table = ui->orderTable; - table->setColumnCount(11); + table->setColumnCount(14); table->setHorizontalHeaderLabels(QStringList() << "订单编号" << "生产号" << "图纸号" << "批次号" << "计划" << "OK" << "NG" << "状态" << "开始时间" << "结束时间" << "备注"); + table->setHorizontalHeaderItem(8, new QTableWidgetItem("Mode")); + table->setHorizontalHeaderItem(9, new QTableWidgetItem("Start tray")); + table->setHorizontalHeaderItem(10, new QTableWidgetItem("Start slot")); + table->setHorizontalHeaderItem(11, new QTableWidgetItem("Begin")); + table->setHorizontalHeaderItem(12, new QTableWidgetItem("End")); + table->setHorizontalHeaderItem(13, new QTableWidgetItem("Remark")); table->horizontalHeader()->setStretchLastSection(true); table->verticalHeader()->setVisible(false); table->setEditTriggers(QAbstractItemView::NoEditTriggers); @@ -88,6 +95,9 @@ void OrderPage::fillOrderTable(const QList &orders) << QString::number(order.qualified) << QString::number(order.unqualified) << order.status + << order.inspectionMode + << QString::number(order.startTrayNo) + << QString::number(order.startSlotNo) << beginTime << endTime << order.remark; @@ -123,9 +133,16 @@ void OrderPage::createOrder() QLineEdit *productionNoEdit = new QLineEdit(&dialog); QLineEdit *drawingNoEdit = new QLineEdit(&dialog); QLineEdit *batchNoEdit = new QLineEdit(&dialog); + QComboBox *modeCombo = new QComboBox(&dialog); + QSpinBox *startTraySpin = new QSpinBox(&dialog); + QSpinBox *startSlotSpin = new QSpinBox(&dialog); QSpinBox *planNumSpin = new QSpinBox(&dialog); QTextEdit *remarkEdit = new QTextEdit(&dialog); + modeCombo->addItem("BEFORE_PLATING", "BEFORE_PLATING"); + modeCombo->addItem("AFTER_PLATING", "AFTER_PLATING"); + startTraySpin->setRange(1, 999); + startSlotSpin->setRange(1, 49); planNumSpin->setRange(1, 999999); planNumSpin->setValue(49); remarkEdit->setFixedHeight(70); @@ -138,6 +155,10 @@ void OrderPage::createOrder() formLayout->addRow("计划数量:", planNumSpin); formLayout->addRow("备注:", remarkEdit); + formLayout->addRow("Inspection mode:", modeCombo); + formLayout->addRow("Start tray:", startTraySpin); + formLayout->addRow("Start slot:", startSlotSpin); + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); QVBoxLayout *layout = new QVBoxLayout(&dialog); @@ -156,6 +177,9 @@ void OrderPage::createOrder() order.productionNo = productionNoEdit->text().trimmed(); order.drawingNo = drawingNoEdit->text().trimmed(); order.batchNo = batchNoEdit->text().trimmed(); + order.inspectionMode = modeCombo->currentData().toString(); + order.startTrayNo = startTraySpin->value(); + order.startSlotNo = startSlotSpin->value(); order.planNum = planNumSpin->value(); order.status = "NOT_START"; order.remark = remarkEdit->toPlainText().trimmed(); diff --git a/pages/rackpage.cpp b/pages/rackpage.cpp index 0606246..2565dd4 100644 --- a/pages/rackpage.cpp +++ b/pages/rackpage.cpp @@ -144,6 +144,7 @@ void RackPage::updateTrayButtons() SquareTrayButton *button = rackTrayButtons.at(index); if (index >= trays.size()) { button->setTrayInfo(0, QString(), 0, "无数据", false); + button->setPlanned(false); button->setChecked(false); continue; } @@ -151,6 +152,21 @@ void RackPage::updateTrayButtons() const Tray &tray = trays.at(index); button->setTrayInfo(tray.id, tray.code, tray.loadedCount, tray.status, tray.present); + bool planned = false; + QString error; + const QList traySlots = + TrayService::instance().listSlots(tray.id, &error); + if (error.isEmpty()) { + for (const TraySlot &slot : traySlots) { + if (slot.state == "PENDING" || slot.state == "PROCESSING" + || slot.state == "FRONT_CHECKING" + || slot.state == "BACK_CHECKING") { + planned = true; + break; + } + } + } + button->setPlanned(planned); button->setChecked(index == selectedTrayIndex); } } diff --git a/pages/squaretraybutton.cpp b/pages/squaretraybutton.cpp index 7487354..872243a 100644 --- a/pages/squaretraybutton.cpp +++ b/pages/squaretraybutton.cpp @@ -6,6 +6,7 @@ SquareTrayButton::SquareTrayButton(int trayIndex, int loadedCount, QWidget *parent) : QAbstractButton(parent) , m_trayId(0) + , m_planned(false) { setCheckable(true); setCursor(Qt::PointingHandCursor); @@ -26,6 +27,12 @@ void SquareTrayButton::setTrayInfo(int trayId, const QString &code, int loadedCo update(); } +void SquareTrayButton::setPlanned(bool planned) +{ + m_planned = planned; + update(); +} + QSize SquareTrayButton::sizeHint() const { return QSize(120, 120); @@ -44,8 +51,10 @@ void SquareTrayButton::paintEvent(QPaintEvent *event) painter.setRenderHint(QPainter::Antialiasing, true); const QRectF rect = QRectF(1, 1, width() - 2, height() - 2); - const QColor background = isChecked() ? QColor("#00897b") : QColor("#eceff1"); - const QColor border = isChecked() ? QColor("#004d40") : QColor("#b0bec5"); + const QColor background = isChecked() ? QColor("#00897b") + : m_planned ? QColor("#f9a825") : QColor("#eceff1"); + const QColor border = isChecked() ? QColor("#004d40") + : m_planned ? QColor("#ef6c00") : QColor("#b0bec5"); const QColor textColor = isChecked() ? QColor("#ffffff") : QColor("#263238"); painter.setPen(QPen(border, 2)); diff --git a/pages/squaretraybutton.h b/pages/squaretraybutton.h index 7926098..d8c9faa 100644 --- a/pages/squaretraybutton.h +++ b/pages/squaretraybutton.h @@ -10,6 +10,7 @@ public: void setTrayInfo(int trayId, const QString &code, int loadedCount, const QString &status, bool present); + void setPlanned(bool planned); QSize sizeHint() const override; QSize minimumSizeHint() const override; @@ -19,6 +20,7 @@ protected: private: int m_trayId; + bool m_planned; }; #endif // SQUARETRAYBUTTON_H diff --git a/repositories/orderrepository.cpp b/repositories/orderrepository.cpp index f88a7d6..3c84ac5 100644 --- a/repositories/orderrepository.cpp +++ b/repositories/orderrepository.cpp @@ -32,6 +32,9 @@ Order readOrder(QSqlQuery &query) order.qualified = query.value("qualified").toInt(); order.unqualified = query.value("unqualified").toInt(); order.status = query.value("status").toString(); + order.inspectionMode = query.value("inspection_mode").toString(); + order.startTrayNo = query.value("start_tray_no").toInt(); + order.startSlotNo = query.value("start_slot_no").toInt(); order.beginTime = query.value("begin_time").toDateTime(); order.endTime = query.value("end_time").toDateTime(); order.remark = query.value("remark").toString(); @@ -51,7 +54,8 @@ QList OrderRepository::listOrders(QString *error, int limit) QSqlQuery query(DatabaseManager::instance().database()); query.prepare("select id, no, production_no, drawing_no, batch_no, plan_num, " - "qualified, unqualified, status, begin_time, end_time, remark, " + "qualified, unqualified, status, inspection_mode, start_tray_no, " + "start_slot_no, begin_time, end_time, remark, " "created_at, updated_at " "from orders order by id desc limit :limit"); query.bindValue(":limit", limit); @@ -74,7 +78,8 @@ bool OrderRepository::findOrder(int id, Order *order, QString *error) QSqlQuery query(DatabaseManager::instance().database()); query.prepare("select id, no, production_no, drawing_no, batch_no, plan_num, " - "qualified, unqualified, status, begin_time, end_time, remark, " + "qualified, unqualified, status, inspection_mode, start_tray_no, " + "start_slot_no, begin_time, end_time, remark, " "created_at, updated_at from orders where id = :id"); query.bindValue(":id", id); if (!query.exec()) { @@ -100,7 +105,8 @@ bool OrderRepository::findOrderForUpdate(int id, Order *order, QString *error) QSqlQuery query(DatabaseManager::instance().database()); query.prepare("select id, no, production_no, drawing_no, batch_no, plan_num, " - "qualified, unqualified, status, begin_time, end_time, remark, " + "qualified, unqualified, status, inspection_mode, start_tray_no, " + "start_slot_no, begin_time, end_time, remark, " "created_at, updated_at from orders where id = :id for update"); query.bindValue(":id", id); if (!query.exec()) { @@ -118,6 +124,32 @@ bool OrderRepository::findOrderForUpdate(int id, Order *order, QString *error) return true; } +bool OrderRepository::findUnfinishedOrder(Order *order, QString *error) +{ + if (!order || !ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select id, no, production_no, drawing_no, batch_no, plan_num, " + "qualified, unqualified, status, inspection_mode, start_tray_no, " + "start_slot_no, begin_time, end_time, remark, created_at, updated_at " + "from orders " + "where status in ('NOT_START', 'RUNNING', 'PAUSED') " + "order by id desc limit 1"); + if (!query.exec()) { + setError(query, error); + return false; + } + if (!query.next()) { + *order = Order(); + return true; + } + + *order = readOrder(query); + return true; +} + bool OrderRepository::insertOrder(Order *order, QString *error) { if (!order || !ensureOpen(error)) { @@ -127,9 +159,11 @@ bool OrderRepository::insertOrder(Order *order, QString *error) QSqlQuery query(DatabaseManager::instance().database()); query.prepare("insert into orders " "(no, production_no, drawing_no, batch_no, plan_num, qualified, " - "unqualified, status, begin_time, end_time, remark) " + "unqualified, status, inspection_mode, start_tray_no, start_slot_no, " + "begin_time, end_time, remark) " "values (:no, :production_no, :drawing_no, :batch_no, :plan_num, " - ":qualified, :unqualified, :status, :begin_time, :end_time, :remark) " + ":qualified, :unqualified, :status, :inspection_mode, " + ":start_tray_no, :start_slot_no, :begin_time, :end_time, :remark) " "returning id"); query.bindValue(":no", order->no); query.bindValue(":production_no", order->productionNo); @@ -139,6 +173,9 @@ bool OrderRepository::insertOrder(Order *order, QString *error) query.bindValue(":qualified", order->qualified); query.bindValue(":unqualified", order->unqualified); query.bindValue(":status", order->status.isEmpty() ? "NOT_START" : order->status); + query.bindValue(":inspection_mode", order->inspectionMode); + query.bindValue(":start_tray_no", order->startTrayNo); + query.bindValue(":start_slot_no", order->startSlotNo); query.bindValue(":begin_time", order->beginTime.isValid() ? QVariant(order->beginTime) : QVariant(QVariant::DateTime)); query.bindValue(":end_time", order->endTime.isValid() ? QVariant(order->endTime) : QVariant(QVariant::DateTime)); query.bindValue(":remark", order->remark); diff --git a/repositories/orderrepository.h b/repositories/orderrepository.h index 1e9eca4..4e96f97 100644 --- a/repositories/orderrepository.h +++ b/repositories/orderrepository.h @@ -11,6 +11,7 @@ public: QList listOrders(QString *error = nullptr, int limit = 100); bool findOrder(int id, Order *order, QString *error = nullptr); bool findOrderForUpdate(int id, Order *order, QString *error = nullptr); + bool findUnfinishedOrder(Order *order, QString *error = nullptr); bool insertOrder(Order *order, QString *error = nullptr); bool updateOrderStatus(int id, const QString &status, QString *error = nullptr); bool updateOrderLifecycle(int id, const QString &status, diff --git a/repositories/productionrepository.cpp b/repositories/productionrepository.cpp index 522d557..8ae2f8b 100644 --- a/repositories/productionrepository.cpp +++ b/repositories/productionrepository.cpp @@ -28,7 +28,10 @@ QVariant nullableId(int id) } int ProductionRepository::createRun(int orderId, const QString &productionState, - const QString &processStep, QString *error) + const QString &processStep, + const QString &inspectionMode, + int startTrayNo, int startSlotNo, int planNum, + QString *error) { if (!ensureOpen(error)) { return 0; @@ -36,12 +39,18 @@ 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) " - "values (:order_id, :production_state, :process_step) " + "(order_id, production_state, process_step, inspection_mode, " + "start_tray_no, start_slot_no, plan_num) " + "values (:order_id, :production_state, :process_step, " + ":inspection_mode, :start_tray_no, :start_slot_no, :plan_num) " "returning id"); query.bindValue(":order_id", orderId); query.bindValue(":production_state", productionState); query.bindValue(":process_step", processStep); + query.bindValue(":inspection_mode", inspectionMode); + query.bindValue(":start_tray_no", startTrayNo); + query.bindValue(":start_slot_no", startSlotNo); + query.bindValue(":plan_num", planNum); if (!query.exec() || !query.next()) { setError(query, error); return 0; @@ -136,7 +145,8 @@ bool ProductionRepository::findActiveRun(ProductionRunSnapshot *run, QString *er } QSqlQuery query(DatabaseManager::instance().database()); - query.prepare("select id, order_id, current_workpiece_id, run_state, " + query.prepare("select id, order_id, current_workpiece_id, plan_num, " + "start_tray_no, start_slot_no, inspection_mode, run_state, " "production_state, process_step, timeout_state, " "recovery_retry_count, last_error " "from production_runs " @@ -154,6 +164,10 @@ bool ProductionRepository::findActiveRun(ProductionRunSnapshot *run, QString *er run->id = query.value("id").toInt(); run->orderId = query.value("order_id").toInt(); run->currentWorkpieceId = query.value("current_workpiece_id").toInt(); + run->planNum = query.value("plan_num").toInt(); + run->startTrayNo = query.value("start_tray_no").toInt(); + run->startSlotNo = query.value("start_slot_no").toInt(); + run->inspectionMode = query.value("inspection_mode").toString(); run->runState = query.value("run_state").toString(); run->productionState = query.value("production_state").toString(); run->processStep = query.value("process_step").toString(); @@ -195,8 +209,9 @@ bool ProductionRepository::insertStateHistory( } bool ProductionRepository::startWorkpieceProcess( - int orderId, int workpieceId, const QString &processStep, int plcStep, - const QString &source, QString *error) + int orderId, int workpieceId, const QString &processStep, + const QString &inspectionMode, int plcStep, const QString &source, + QString *error) { if (!ensureOpen(error)) { return false; @@ -216,13 +231,14 @@ bool ProductionRepository::startWorkpieceProcess( QSqlQuery query(DatabaseManager::instance().database()); query.prepare("insert into workpiece_process_records " - "(order_id, workpiece_id, process_step, attempt_no, " + "(order_id, workpiece_id, process_step, inspection_mode, attempt_no, " "process_state, plc_step, source) " - "values (:order_id, :workpiece_id, :process_step, " + "values (:order_id, :workpiece_id, :process_step, :inspection_mode, " ":attempt_no, 'RUNNING', :plc_step, :source)"); query.bindValue(":order_id", nullableId(orderId)); query.bindValue(":workpiece_id", workpieceId); query.bindValue(":process_step", processStep); + query.bindValue(":inspection_mode", inspectionMode); query.bindValue(":attempt_no", attemptQuery.value(0).toInt()); query.bindValue(":plc_step", plcStep); query.bindValue(":source", source); @@ -299,8 +315,8 @@ QList ProductionRepository::listProcessRecords( bool ProductionRepository::insertInspection( int orderId, int workpieceId, const QString &side, int rawResult, - const QString &resultState, int plcStep, const QString &source, - const QString &message, QString *error) + const QString &resultState, const QString &inspectionMode, int plcStep, + const QString &source, const QString &message, QString *error) { if (!ensureOpen(error)) { return false; @@ -320,15 +336,16 @@ bool ProductionRepository::insertInspection( QSqlQuery query(DatabaseManager::instance().database()); query.prepare("insert into inspection_records " - "(order_id, workpiece_id, inspection_side, attempt_no, " + "(order_id, workpiece_id, inspection_side, inspection_mode, attempt_no, " "raw_result, result_state, inspection_state, source, " "plc_step, message, started_at, completed_at) " - "values (:order_id, :workpiece_id, :side, :attempt_no, " + "values (:order_id, :workpiece_id, :side, :inspection_mode, :attempt_no, " ":raw_result, :result_state, 'COMPLETED', :source, " ":plc_step, :message, now(), now())"); query.bindValue(":order_id", nullableId(orderId)); query.bindValue(":workpiece_id", workpieceId); query.bindValue(":side", side); + query.bindValue(":inspection_mode", inspectionMode); query.bindValue(":attempt_no", attemptQuery.value(0).toInt()); query.bindValue(":raw_result", rawResult); query.bindValue(":result_state", resultState); diff --git a/repositories/productionrepository.h b/repositories/productionrepository.h index 8805e68..4868a37 100644 --- a/repositories/productionrepository.h +++ b/repositories/productionrepository.h @@ -10,6 +10,10 @@ struct ProductionRunSnapshot int id = 0; int orderId = 0; int currentWorkpieceId = 0; + int planNum = 0; + int startTrayNo = 1; + int startSlotNo = 1; + QString inspectionMode; QString runState; QString productionState; QString processStep; @@ -33,7 +37,9 @@ class ProductionRepository { public: int createRun(int orderId, const QString &productionState, - const QString &processStep, QString *error = nullptr); + const QString &processStep, const QString &inspectionMode, + int startTrayNo, int startSlotNo, int planNum, + QString *error = nullptr); bool updateRun(int runId, const QString &runState, const QString &productionState, const QString &processStep, int currentWorkpieceId, const QString &timeoutState, @@ -52,7 +58,8 @@ public: QString *error = nullptr); bool startWorkpieceProcess(int orderId, int workpieceId, - const QString &processStep, int plcStep, + const QString &processStep, + const QString &inspectionMode, int plcStep, const QString &source, QString *error = nullptr); bool finishWorkpieceProcess(int workpieceId, const QString &processStep, const QString &resultState, int durationMs, @@ -62,7 +69,8 @@ public: bool insertInspection(int orderId, int workpieceId, const QString &side, int rawResult, - const QString &resultState, int plcStep, + const QString &resultState, + const QString &inspectionMode, int plcStep, const QString &source, const QString &message, QString *error = nullptr); diff --git a/services/deviceservice.cpp b/services/deviceservice.cpp index d105d3f..7ec989f 100644 --- a/services/deviceservice.cpp +++ b/services/deviceservice.cpp @@ -11,6 +11,51 @@ namespace { const int FeedbackPollIntervalMs = 50; +bool actionAddresses(DeviceService::ProductionAction action, + const ModbusAddressMap &addresses, + int *commandAddress, int *feedbackAddress) +{ + if (!commandAddress || !feedbackAddress) { + return false; + } + + switch (action) { + case DeviceService::RackPick: + *commandAddress = addresses.rackPickCommand; + *feedbackAddress = addresses.rackPickFeedback; + return true; + case DeviceService::FrontLoad: + *commandAddress = addresses.frontLoadCommand; + *feedbackAddress = addresses.frontLoadFeedback; + return true; + case DeviceService::Inspect: + *commandAddress = addresses.inspectionCommand; + *feedbackAddress = addresses.inspectionFeedback; + return true; + case DeviceService::FrontUnload: + *commandAddress = addresses.frontUnloadCommand; + *feedbackAddress = addresses.frontUnloadFeedback; + return true; + case DeviceService::Flip: + *commandAddress = addresses.flipCommand; + *feedbackAddress = addresses.flipFeedback; + return true; + case DeviceService::BackLoad: + *commandAddress = addresses.backLoadCommand; + *feedbackAddress = addresses.backLoadFeedback; + return true; + case DeviceService::BackUnload: + *commandAddress = addresses.backUnloadCommand; + *feedbackAddress = addresses.backUnloadFeedback; + return true; + case DeviceService::RackPlace: + *commandAddress = addresses.rackPlaceCommand; + *feedbackAddress = addresses.rackPlaceFeedback; + return true; + } + return false; +} + } DeviceService &DeviceService::instance() @@ -188,6 +233,75 @@ bool DeviceService::clearAlarm(QString *error) return executeCommand(addresses.clearAlarmCommand, addresses.clearAlarmFeedback, error); } +bool DeviceService::setInspectionMode(const QString &mode, QString *error) +{ + if (mode != "BEFORE_PLATING" && mode != "AFTER_PLATING") { + if (error) { + *error = "Inspection mode must be BEFORE_PLATING or AFTER_PLATING"; + } + return false; + } + if (ConfigManager::instance().simulationMode()) { + return true; + } + if (!ConfigManager::instance().productionEnabled()) { + if (error) { + *error = "Production control is disabled by configuration"; + } + return false; + } + + const bool afterPlating = mode == "AFTER_PLATING"; + const ModbusAddressMap &addresses = ModbusTcpManager::instance().config().addressMap; + if (!ModbusTcpManager::instance().writeCoil( + addresses.inspectionMode, afterPlating, error)) { + return false; + } + return true; +} + +bool DeviceService::executeProductionAction(ProductionAction action, + int trayNo, int slotNo, + QString *error) +{ + if (ConfigManager::instance().simulationMode()) { + return true; + } + if (!ConfigManager::instance().productionEnabled()) { + if (error) { + *error = "Production control is disabled by configuration"; + } + return false; + } + if (trayNo <= 0 || slotNo < 1 || slotNo > 49) { + if (error) { + *error = "PLC tray or slot position is invalid"; + } + return false; + } + + const ModbusAddressMap &addresses = ModbusTcpManager::instance().config().addressMap; + if (action == RackPick || action == RackPlace) { + ModbusTcpManager &modbus = ModbusTcpManager::instance(); + if (!modbus.writeHoldingRegister( + addresses.trayNumber, static_cast(trayNo), error) + || !modbus.writeHoldingRegister( + addresses.slotNumber, static_cast(slotNo), error)) { + return false; + } + } + + int commandAddress = -1; + int feedbackAddress = -1; + if (!actionAddresses(action, addresses, &commandAddress, &feedbackAddress)) { + if (error) { + *error = "Unknown PLC production action"; + } + return false; + } + return executeCommand(commandAddress, feedbackAddress, error); +} + bool DeviceService::connectWithRetry(QString *error) { ModbusTcpManager &modbus = ModbusTcpManager::instance(); @@ -260,17 +374,22 @@ bool DeviceService::executeCommand(int commandAddress, int feedbackAddress, QStr continue; } - QThread::msleep(qMax(1, config.commandPulseMs)); - if (!modbus.writeCoil(commandAddress, false, &lastError)) { + if (!waitForFeedback(feedbackAddress, &lastError)) { + modbus.writeCoil(commandAddress, false); modbus.disconnectDevice(); continue; } - if (waitForFeedback(feedbackAddress, &lastError)) { - return true; + if (!modbus.writeCoil(commandAddress, false, &lastError)) { + modbus.disconnectDevice(); + continue; + } + if (!modbus.writeCoil(feedbackAddress, false, &lastError)) { + modbus.disconnectDevice(); + continue; } - modbus.disconnectDevice(); + return true; } if (error) { @@ -282,11 +401,12 @@ bool DeviceService::executeCommand(int commandAddress, int feedbackAddress, QStr bool DeviceService::waitForFeedback(int address, QString *error) { ModbusTcpManager &modbus = ModbusTcpManager::instance(); - const int timeoutMs = qMax(1, modbus.config().feedbackTimeoutMs); - QElapsedTimer timer; - timer.start(); +// const int timeoutMs = qMax(1, modbus.config().feedbackTimeoutMs); +// QElapsedTimer timer; +// timer.start(); - while (timer.elapsed() < timeoutMs) { + //while (timer.elapsed() < timeoutMs) { + while (true) { bool feedback = false; if (!modbus.readCoil(address, &feedback, error)) { return false; diff --git a/services/deviceservice.h b/services/deviceservice.h index 08482d9..d9a706c 100644 --- a/services/deviceservice.h +++ b/services/deviceservice.h @@ -26,6 +26,18 @@ class DeviceService : public QObject Q_OBJECT public: + enum ProductionAction + { + RackPick, + FrontLoad, + Inspect, + FrontUnload, + Flip, + BackLoad, + BackUnload, + RackPlace + }; + static DeviceService &instance(); void startPolling(); @@ -37,6 +49,9 @@ public: bool pause(QString *error = nullptr); bool reset(QString *error = nullptr); bool clearAlarm(QString *error = nullptr); + bool setInspectionMode(const QString &mode, QString *error = nullptr); + bool executeProductionAction(ProductionAction action, int trayNo, + int slotNo, QString *error = nullptr); signals: void statusChanged(const DeviceStatus &status); diff --git a/services/orderservice.cpp b/services/orderservice.cpp index acaac09..c19b81a 100644 --- a/services/orderservice.cpp +++ b/services/orderservice.cpp @@ -72,6 +72,20 @@ bool OrderService::createOrder(Order *order, QString *error) } return false; } + if (order->inspectionMode != "BEFORE_PLATING" + && order->inspectionMode != "AFTER_PLATING") { + if (error) { + *error = "Inspection mode must be BEFORE_PLATING or AFTER_PLATING"; + } + return false; + } + if (order->startTrayNo <= 0 + || order->startSlotNo < 1 || order->startSlotNo > 49) { + if (error) { + *error = "Start tray or slot is invalid"; + } + return false; + } order->no = order->no.trimmed(); order->status = "NOT_START"; @@ -88,6 +102,23 @@ bool OrderService::createOrder(Order *order, QString *error) } OrderRepository repository; + Order unfinishedOrder; + if (!repository.findUnfinishedOrder(&unfinishedOrder, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (unfinishedOrder.id > 0) { + database.rollback(); + if (error) { + *error = QString("Unfinished order already exists: %1") + .arg(unfinishedOrder.no); + } + return false; + } + if (!repository.insertOrder(order, &transactionError) || !recordLog("新建订单", "创建订单:" + order->no, "成功", &transactionError) || !database.commit(&transactionError)) { @@ -205,9 +236,50 @@ bool OrderService::generateWorkpiecesAndAssign(int orderId, QString *error) } const int requiredSlotCount = order.planNum - assignedCount; - const QList emptySlots = requiredSlotCount > 0 - ? trayRepository.listEmptySlotsForAllocation(&transactionError) - : QList(); + QList emptySlots; + if (requiredSlotCount > 0) { + const int startTrayIndex = order.startTrayNo - 1; + if (startTrayIndex < 0 || startTrayIndex >= trays.size()) { + database.rollback(); + if (error) { + *error = QString("Start tray %1 is outside the configured tray range") + .arg(order.startTrayNo); + } + return false; + } + + for (int trayIndex = startTrayIndex; + trayIndex < trays.size() && emptySlots.size() < requiredSlotCount; + ++trayIndex) { + const Tray &tray = trays.at(trayIndex); + if (!tray.present) { + continue; + } + + const QList slots = + trayRepository.listSlots(tray.id, &transactionError); + if (!transactionError.isEmpty()) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + + for (const TraySlot &slot : slots) { + const int position = (slot.rowNo - 1) * 7 + slot.columnNo; + if (trayIndex == startTrayIndex && position < order.startSlotNo) { + continue; + } + if (slot.workpieceId == 0 && slot.state == "EMPTY") { + emptySlots.append(slot); + if (emptySlots.size() >= requiredSlotCount) { + break; + } + } + } + } + } if (!transactionError.isEmpty()) { database.rollback(); if (error) { diff --git a/services/productionservice.cpp b/services/productionservice.cpp index 3e1d5ce..898ce20 100644 --- a/services/productionservice.cpp +++ b/services/productionservice.cpp @@ -3,6 +3,7 @@ #include "../config/configmanager.h" #include "../repositories/productionrepository.h" #include "orderservice.h" +#include "trayservice.h" #include "workpieceservice.h" #include @@ -24,6 +25,9 @@ ProductionService::ProductionService(QObject *parent) , m_deviceStatusValid(false) , m_recoveryRetryCount(0) , m_processElapsedMs(0) + , m_currentTrayNo(0) + , m_currentSlotNo(0) + , m_frontRawResult(0) { connect(m_timer, &QTimer::timeout, this, &ProductionService::tick); connect(&DeviceService::instance(), &DeviceService::statusChanged, @@ -48,9 +52,16 @@ QString ProductionService::stateNameForState(State state) const case Idle: return "IDLE"; case Preparing: return "PREPARING"; case WaitingDeviceReady: return "WAITING_DEVICE_READY"; + case RackPicking: return "RACK_PICKING"; + case FrontLoading: return "FRONT_LOADING"; case Loading: return "LOADING"; case FrontChecking: return "FRONT_CHECKING"; + case FrontUnloading: return "FRONT_UNLOADING"; + case Flipping: return "FLIPPING"; + case BackLoading: return "BACK_LOADING"; case BackChecking: return "BACK_CHECKING"; + case BackUnloading: return "BACK_UNLOADING"; + case RackPlacing: return "RACK_PLACING"; case Judging: return "JUDGING"; case Unloading: return "UNLOADING"; case Paused: return "PAUSED"; @@ -70,6 +81,21 @@ int ProductionService::orderId() const return m_orderId; } +int ProductionService::currentTrayNo() const +{ + return m_currentTrayNo; +} + +int ProductionService::currentSlotNo() const +{ + return m_currentSlotNo; +} + +QString ProductionService::inspectionMode() const +{ + return m_inspectionMode; +} + Workpiece ProductionService::currentWorkpiece() const { return m_currentWorkpiece; @@ -101,6 +127,16 @@ bool ProductionService::start(int orderId, QString *error) return false; } + m_inspectionMode = order.inspectionMode; + m_currentTrayNo = 0; + m_currentSlotNo = 0; + m_frontRawResult = 0; + m_frontResultState.clear(); + + if (!DeviceService::instance().setInspectionMode( + m_inspectionMode, error)) { + return false; + } if (!DeviceService::instance().start(error) || !OrderService::instance().startOrder(orderId, error)) { return false; @@ -115,7 +151,9 @@ bool ProductionService::start(int orderId, QString *error) QString persistenceError; m_runId = ProductionRepository().createRun( - m_orderId, "PREPARING", "PREPARING", &persistenceError); + m_orderId, "PREPARING", "PREPARING", order.inspectionMode, + order.startTrayNo, order.startSlotNo, order.planNum, + &persistenceError); if (m_runId <= 0) { DeviceService::instance().pause(); OrderService::instance().pauseOrder(m_orderId); @@ -168,6 +206,8 @@ bool ProductionService::resume(QString *error) } if (!checkRecoverySafety(error) + || !DeviceService::instance().setInspectionMode( + m_inspectionMode, error) || !DeviceService::instance().start(error) || !OrderService::instance().resumeOrder(m_orderId, error)) { return false; @@ -235,6 +275,8 @@ bool ProductionService::stop(QString *error) m_currentWorkpiece = Workpiece(); clearProcessTimer(); emit currentWorkpieceChanged(0, QString()); + emit currentWorkpieceSnapshotChanged(m_currentWorkpiece); + emit currentPositionChanged(0, 0); return true; } @@ -298,6 +340,7 @@ bool ProductionService::restoreActiveRun(QString *error) m_runId = run.id; m_orderId = run.orderId; + m_inspectionMode = run.inspectionMode; m_recoveryRetryCount = run.recoveryRetryCount; m_lastError = run.lastError; @@ -312,6 +355,8 @@ bool ProductionService::restoreActiveRun(QString *error) } emit currentWorkpieceChanged(m_currentWorkpiece.id, m_currentWorkpiece.barcode); + emit currentWorkpieceSnapshotChanged(m_currentWorkpiece); + emit currentPositionChanged(m_currentTrayNo, m_currentSlotNo); startProcessTimer(m_currentWorkpiece.processStep); emitProcessElapsed(); } @@ -351,6 +396,8 @@ bool ProductionService::recover(QString *error) QString operationError; if (!ensureOrderRunning(&operationError) + || !DeviceService::instance().setInspectionMode( + m_inspectionMode, &operationError) || !DeviceService::instance().start(&operationError)) { if (error) { *error = operationError; @@ -392,6 +439,8 @@ bool ProductionService::retry(QString *error) QString operationError; if (!ensureOrderRunning(&operationError) + || !DeviceService::instance().setInspectionMode( + m_inspectionMode, &operationError) || !DeviceService::instance().start(&operationError)) { if (error) { *error = operationError; @@ -454,7 +503,8 @@ bool ProductionService::markCurrentWorkpieceNg(QString *error) const QString previousProcessStep = m_currentWorkpiece.processStep; if (!WorkpieceService::instance().completeWithInspection( m_currentWorkpiece.id, "NG", "COMPLETE", previousProcessStep, - durationMs, -1, "NG", m_deviceStatus.currentStep, "MANUAL", + durationMs, -1, "NG", m_deviceStatus.currentStep, + m_inspectionMode, "MANUAL", &operationError)) { if (error) { *error = operationError; @@ -471,6 +521,8 @@ bool ProductionService::markCurrentWorkpieceNg(QString *error) m_recoveryRetryCount = 0; m_lastError.clear(); emit currentWorkpieceChanged(0, QString()); + emit currentWorkpieceSnapshotChanged(m_currentWorkpiece); + emit currentPositionChanged(0, 0); setState(Preparing); const int interval = qMax(100, ConfigManager::instance() .modbusConfig().pollIntervalMs); @@ -525,12 +577,35 @@ bool ProductionService::claimNextWorkpiece(QString *error) m_currentWorkpiece = workpiece; m_recoveryRetryCount = 0; + m_currentTrayNo = 0; + m_currentSlotNo = workpiece.trayPos; + QString trayError; + const QList trays = TrayService::instance().listTrays(&trayError); + if (!trayError.isEmpty()) { + if (error) { + *error = trayError; + } + return false; + } + for (int index = 0; index < trays.size(); ++index) { + if (trays.at(index).id == workpiece.trayId) { + m_currentTrayNo = index + 1; + break; + } + } + if (m_currentTrayNo <= 0 || m_currentSlotNo < 1 || m_currentSlotNo > 49) { + if (error) { + *error = "Current workpiece tray position cannot be mapped to PLC"; + } + return false; + } + QString persistenceError; const QString source = ConfigManager::instance().simulationMode() ? "SIMULATION" : "PLC"; if (!ProductionRepository().startWorkpieceProcess( m_orderId, workpiece.id, workpiece.processStep, - m_deviceStatus.currentStep, + m_inspectionMode, m_deviceStatus.currentStep, source, &persistenceError)) { if (error) { *error = persistenceError; @@ -539,6 +614,8 @@ bool ProductionService::claimNextWorkpiece(QString *error) } startProcessTimer(workpiece.processStep); emit currentWorkpieceChanged(workpiece.id, workpiece.barcode); + emit currentWorkpieceSnapshotChanged(m_currentWorkpiece); + emit currentPositionChanged(m_currentTrayNo, m_currentSlotNo); emitProcessElapsed(); setState(WaitingDeviceReady); return true; @@ -559,8 +636,9 @@ bool ProductionService::updateCurrentProcessStep(const QString &processStep, ? "SIMULATION" : "PLC"; const int durationMs = currentProcessElapsedMs(); if (!WorkpieceService::instance().updateProcessStepWithRecord( - m_currentWorkpiece.id, processStep, m_deviceStatus.currentStep, - source, durationMs, error, forceRestart)) { + m_currentWorkpiece.id, processStep, m_inspectionMode, + m_deviceStatus.currentStep, source, durationMs, error, + forceRestart)) { return false; } @@ -570,6 +648,55 @@ bool ProductionService::updateCurrentProcessStep(const QString &processStep, return true; } +bool ProductionService::executeCurrentAction( + DeviceService::ProductionAction action, + const QString &nextProcessStep, State nextState, QString *error) +{ + if (m_currentWorkpiece.id <= 0) { + if (error) { + *error = "No current workpiece"; + } + return false; + } + + if (!DeviceService::instance().executeProductionAction( + action, m_currentTrayNo, m_currentSlotNo, error)) { + return false; + } + if (!updateCurrentProcessStep(nextProcessStep, error)) { + return false; + } + setState(nextState); + return true; +} + +bool ProductionService::recordInspection(const QString &side, int rawResult, + const QString &resultState, + QString *error) +{ + const QString source = ConfigManager::instance().simulationMode() + ? "SIMULATION" : "PLC"; + return WorkpieceService::instance().recordInspection( + m_currentWorkpiece.id, side, rawResult, resultState, + m_deviceStatus.currentStep, m_inspectionMode, source, + QString("%1 inspection result").arg(side), error); +} + +QString ProductionService::resultStateForRawResult(int rawResult) const +{ + const ProductionConfig config = ConfigManager::instance().productionConfig(); + if (rawResult == config.okResult) { + return "OK"; + } + if (rawResult == config.ngResult) { + return "NG"; + } + if (rawResult == config.errorResult) { + return "ERROR"; + } + return "UNKNOWN"; +} + void ProductionService::startProcessTimer(const QString &processStep) { m_currentProcessStep = processStep; @@ -751,17 +878,18 @@ bool ProductionService::finishCurrentWorkpiece(const QString &state, const QString source = ConfigManager::instance().simulationMode() ? "SIMULATION" : "PLC"; - setState(Unloading); if (!WorkpieceService::instance().completeWithInspection( m_currentWorkpiece.id, state, processStep, previousProcessStep, processDurationMs, rawResult, state, - m_deviceStatus.currentStep, source, error)) { + m_deviceStatus.currentStep, m_inspectionMode, source, error)) { return false; } clearProcessTimer(); m_currentWorkpiece = Workpiece(); emit currentWorkpieceChanged(0, QString()); + emit currentWorkpieceSnapshotChanged(m_currentWorkpiece); + emit currentPositionChanged(0, 0); setState(Preparing); return true; } @@ -842,10 +970,10 @@ void ProductionService::tick() if (m_state == WaitingDeviceReady) { if (m_deviceStatus.plcReady && m_deviceStatus.robotReady) { QString error; - if (!updateCurrentProcessStep("LOADING", &error)) { + if (!updateCurrentProcessStep("RACK_PICKING", &error)) { fail(error); } else { - setState(Loading); + setState(RackPicking); } } emitProcessElapsed(); @@ -871,65 +999,14 @@ void ProductionService::tickSimulation() return; } - switch (m_state) { - case Loading: { - QString error; - if (!updateCurrentProcessStep("FRONT_CHECKING", &error)) { - fail(error); - } else { - setState(FrontChecking); - } - break; - } - case FrontChecking: { - QString error; - if (!updateCurrentProcessStep("BACK_CHECKING", &error)) { - fail(error); - } else { - setState(BackChecking); - } - break; - } - case BackChecking: { - QString error; - if (!updateCurrentProcessStep("JUDGING", &error)) { - fail(error); - } else { - setState(Judging); - } - break; - } - case Judging: { - const ProductionConfig config = ConfigManager::instance().productionConfig(); - QString resultState; - if (config.simulationResult == config.okResult) { - resultState = "OK"; - } else if (config.simulationResult == config.ngResult) { - resultState = "NG"; - } - QString error; - if (resultState.isEmpty()) { - fail("Invalid simulation inspection result"); - } else if (!finishCurrentWorkpiece(resultState, "COMPLETE", &error)) { - fail(error); - } - break; - } - default: - break; + QString error; + if (!processProductionStep(m_state, &error) && !error.isEmpty()) { + fail(error); } } void ProductionService::tickProduction() { - if (m_state == TimeoutWarning) { - QString error; - if (!processProductionStep(m_timeoutState, &error) && !error.isEmpty()) { - fail(error); - } - return; - } - if (m_state == RecoveryChecking) { QString error; if (!recoverFromPlcStep(&error) && !error.isEmpty()) { @@ -951,62 +1028,117 @@ void ProductionService::tickProduction() bool ProductionService::processProductionStep(State state, QString *error) { - const ProductionConfig config = ConfigManager::instance().productionConfig(); - QString resultState; switch (state) { - case Loading: - if (m_deviceStatus.currentStep == config.frontCheckStep) { - if (!updateCurrentProcessStep("FRONT_CHECKING", error)) { + case RackPicking: + return executeCurrentAction(DeviceService::RackPick, + "FRONT_LOADING", FrontLoading, error); + case FrontLoading: + return executeCurrentAction(DeviceService::FrontLoad, + "FRONT_CHECKING", FrontChecking, error); + case FrontChecking: { + if (!DeviceService::instance().executeProductionAction( + DeviceService::Inspect, m_currentTrayNo, m_currentSlotNo, error)) { + return false; + } + if (!ConfigManager::instance().simulationMode()) { + DeviceStatus status; + if (!DeviceService::instance().readStatus(&status, error)) { return false; - } else { - setState(FrontChecking); } + onDeviceStatusChanged(status); } - break; - case FrontChecking: - if (m_deviceStatus.currentStep == config.backCheckStep) { - if (!updateCurrentProcessStep("BACK_CHECKING", error)) { - return false; - } else { - setState(BackChecking); - } - } - break; - case BackChecking: - if (m_deviceStatus.currentStep == config.unloadStep) { - if (!updateCurrentProcessStep("JUDGING", error)) { - return false; - } else { - setState(Judging); - } - } - break; - case Judging: - if (m_deviceStatus.currentStep != config.cycleCompleteStep) { - return true; - } - if (m_deviceStatus.checkResult == config.okResult) { - resultState = "OK"; - } else if (m_deviceStatus.checkResult == config.ngResult) { - resultState = "NG"; - } else if (m_deviceStatus.checkResult == config.errorResult) { + const int frontRawResult = ConfigManager::instance().simulationMode() + ? ConfigManager::instance().productionConfig().simulationResult + : static_cast(m_deviceStatus.checkResult); + const QString frontResultState = + resultStateForRawResult(frontRawResult); + if (frontResultState == "UNKNOWN" || frontResultState == "ERROR") { if (error) { - *error = QString("PLC inspection error result: %1") - .arg(m_deviceStatus.checkResult); + *error = QString("Invalid front inspection result: %1") + .arg(frontRawResult); } return false; - } else { + } + if (!recordInspection("FRONT", frontRawResult, + frontResultState, error)) { + return false; + } + m_frontRawResult = frontRawResult; + m_frontResultState = frontResultState; + if (!updateCurrentProcessStep("FRONT_UNLOADING", error)) { + return false; + } + setState(FrontUnloading); + return true; + } + case FrontUnloading: + return executeCurrentAction( + DeviceService::FrontUnload, + m_inspectionMode == "AFTER_PLATING" ? "RACK_PLACING" : "FLIPPING", + m_inspectionMode == "AFTER_PLATING" ? RackPlacing : Flipping, + error); + case Flipping: + return executeCurrentAction(DeviceService::Flip, + "BACK_LOADING", BackLoading, error); + case BackLoading: + return executeCurrentAction(DeviceService::BackLoad, + "BACK_CHECKING", BackChecking, error); + case BackChecking: { + if (!DeviceService::instance().executeProductionAction( + DeviceService::Inspect, m_currentTrayNo, m_currentSlotNo, error)) { + return false; + } + if (!ConfigManager::instance().simulationMode()) { + DeviceStatus status; + if (!DeviceService::instance().readStatus(&status, error)) { + return false; + } + onDeviceStatusChanged(status); + } + const int backRawResult = ConfigManager::instance().simulationMode() + ? ConfigManager::instance().productionConfig().simulationResult + : static_cast(m_deviceStatus.checkResult); + const QString backResultState = + resultStateForRawResult(backRawResult); + if (backResultState == "UNKNOWN" || backResultState == "ERROR") { if (error) { - *error = QString("Unknown PLC inspection result: %1") - .arg(m_deviceStatus.checkResult); + *error = QString("Invalid back inspection result: %1") + .arg(backRawResult); } return false; } - - if (!finishCurrentWorkpiece(resultState, "COMPLETE", error)) { + if (!recordInspection("BACK", backRawResult, + backResultState, error)) { return false; } + const QString finalState = + m_frontResultState == "OK" && backResultState == "OK" + ? "OK" : "NG"; + if (!updateCurrentProcessStep("BACK_UNLOADING", error)) { + return false; + } + m_frontResultState = finalState; + setState(BackUnloading); break; + } + case BackUnloading: + return executeCurrentAction(DeviceService::BackUnload, + "RACK_PLACING", RackPlacing, error); + case RackPlacing: { + if (!DeviceService::instance().executeProductionAction( + DeviceService::RackPlace, m_currentTrayNo, m_currentSlotNo, + error)) { + return false; + } + QString finalState = m_frontResultState; + if (finalState != "OK" && finalState != "NG") { + if (error) { + *error = "Final inspection result is not available"; + } + return false; + } + return finishCurrentWorkpiece(finalState, "COMPLETE", error); + } default: break; } @@ -1075,8 +1207,12 @@ bool ProductionService::recoverFromPlcStep(QString *error) bool ProductionService::isTimedState(State state) const { return state == Preparing || state == WaitingDeviceReady + || state == RackPicking || state == FrontLoading || state == Loading || state == FrontChecking - || state == BackChecking || state == Judging; + || state == FrontUnloading || state == Flipping + || state == BackLoading || state == BackChecking + || state == BackUnloading || state == RackPlacing + || state == Judging; } QString ProductionService::processStepForState(State state) const @@ -1084,9 +1220,16 @@ QString ProductionService::processStepForState(State state) const switch (state) { case Preparing: return "PREPARING"; case WaitingDeviceReady: return "WAITING_DEVICE_READY"; + case RackPicking: return "RACK_PICKING"; + case FrontLoading: return "FRONT_LOADING"; case Loading: return "LOADING"; case FrontChecking: return "FRONT_CHECKING"; + case FrontUnloading: return "FRONT_UNLOADING"; + case Flipping: return "FLIPPING"; + case BackLoading: return "BACK_LOADING"; case BackChecking: return "BACK_CHECKING"; + case BackUnloading: return "BACK_UNLOADING"; + case RackPlacing: return "RACK_PLACING"; case Judging: return "JUDGING"; default: return QString(); } @@ -1117,9 +1260,16 @@ ProductionService::State ProductionService::stateFromName(const QString &name) c { if (name == "PREPARING") return Preparing; if (name == "WAITING_DEVICE_READY") return WaitingDeviceReady; + if (name == "RACK_PICKING") return RackPicking; + if (name == "FRONT_LOADING") return FrontLoading; if (name == "LOADING") return Loading; if (name == "FRONT_CHECKING") return FrontChecking; + if (name == "FRONT_UNLOADING") return FrontUnloading; + if (name == "FLIPPING") return Flipping; + if (name == "BACK_LOADING") return BackLoading; if (name == "BACK_CHECKING") return BackChecking; + if (name == "BACK_UNLOADING") return BackUnloading; + if (name == "RACK_PLACING") return RackPlacing; if (name == "JUDGING") return Judging; if (name == "UNLOADING") return Unloading; if (name == "PAUSED") return Paused; diff --git a/services/productionservice.h b/services/productionservice.h index fa0e25f..d8914ca 100644 --- a/services/productionservice.h +++ b/services/productionservice.h @@ -20,9 +20,16 @@ public: Idle, Preparing, WaitingDeviceReady, + RackPicking, + FrontLoading, Loading, FrontChecking, + FrontUnloading, + Flipping, + BackLoading, BackChecking, + BackUnloading, + RackPlacing, Judging, Unloading, Paused, @@ -41,6 +48,9 @@ public: State state() const; QString stateName() const; int orderId() const; + int currentTrayNo() const; + int currentSlotNo() const; + QString inspectionMode() const; Workpiece currentWorkpiece() const; bool start(int orderId, QString *error = nullptr); @@ -56,6 +66,8 @@ public: signals: void stateChanged(ProductionService::State state, const QString &name); void currentWorkpieceChanged(int workpieceId, const QString &barcode); + void currentWorkpieceSnapshotChanged(const Workpiece &workpiece); + void currentPositionChanged(int trayNo, int slotNo); void productionFinished(int orderId); void productionError(const QString &error); void alarmRaised(const QString &code, const QString &message); @@ -69,8 +81,10 @@ private slots: void onDeviceStatusChanged(const DeviceStatus &status); void onCommunicationError(const QString &error); -private: +public: explicit ProductionService(QObject *parent = nullptr); + +private: ProductionService(const ProductionService &) = delete; ProductionService &operator=(const ProductionService &) = delete; @@ -85,6 +99,12 @@ private: void tickProduction(); bool processProductionStep(State state, QString *error); bool recoverFromPlcStep(QString *error); + bool executeCurrentAction(DeviceService::ProductionAction action, + const QString &nextProcessStep, + State nextState, QString *error); + bool recordInspection(const QString &side, int rawResult, + const QString &resultState, QString *error); + QString resultStateForRawResult(int rawResult) const; bool ensureOrderRunning(QString *error); bool checkRecoverySafety(QString *error) const; bool mapPlcStepToState(State *state, QString *processStep) const; @@ -118,8 +138,16 @@ private: bool m_deviceStatusValid; int m_recoveryRetryCount; int m_processElapsedMs; + int m_currentTrayNo; + int m_currentSlotNo; + int m_frontRawResult; + QString m_inspectionMode; + QString m_frontResultState; QString m_currentProcessStep; QString m_lastError; }; +Q_DECLARE_METATYPE(ProductionService::State) +Q_DECLARE_METATYPE(Workpiece) + #endif // PRODUCTIONSERVICE_H diff --git a/services/productionworker.cpp b/services/productionworker.cpp new file mode 100644 index 0000000..64c9216 --- /dev/null +++ b/services/productionworker.cpp @@ -0,0 +1,108 @@ +#include "productionworker.h" + +ProductionWorker::ProductionWorker(QObject *parent) + : QObject(parent) + , m_service(nullptr) +{ +} + +void ProductionWorker::ensureService() +{ + if (m_service) { + return; + } + + m_service = new ProductionService(this); + connect(m_service, &ProductionService::stateChanged, + this, &ProductionWorker::stateChanged); + connect(m_service, &ProductionService::currentWorkpieceChanged, + this, &ProductionWorker::currentWorkpieceChanged); + connect(m_service, &ProductionService::currentWorkpieceSnapshotChanged, + this, &ProductionWorker::currentWorkpieceSnapshotChanged); + connect(m_service, &ProductionService::currentPositionChanged, + this, &ProductionWorker::currentPositionChanged); + connect(m_service, &ProductionService::productionFinished, + this, &ProductionWorker::productionFinished); + connect(m_service, &ProductionService::productionError, + this, &ProductionWorker::productionError); + connect(m_service, &ProductionService::alarmRaised, + this, &ProductionWorker::alarmRaised); + connect(m_service, &ProductionService::processElapsedChanged, + this, &ProductionWorker::processElapsedChanged); + connect(m_service, &ProductionService::timeoutWarning, + this, &ProductionWorker::timeoutWarning); + connect(m_service, &ProductionService::timeoutRecoveryRequired, + this, &ProductionWorker::timeoutRecoveryRequired); + connect(m_service, &ProductionService::recoveryCompleted, + this, &ProductionWorker::recoveryCompleted); +} + +void ProductionWorker::reportFailure(bool success, const QString &error) +{ + if (!success && !error.isEmpty()) { + emit productionError(error); + } +} + +void ProductionWorker::requestStart(int orderId) +{ + ensureService(); + QString error; + reportFailure(m_service->start(orderId, &error), error); +} + +void ProductionWorker::requestPause() +{ + ensureService(); + QString error; + reportFailure(m_service->pause(&error), error); +} + +void ProductionWorker::requestResume() +{ + ensureService(); + QString error; + reportFailure(m_service->resume(&error), error); +} + +void ProductionWorker::requestStop() +{ + ensureService(); + QString error; + reportFailure(m_service->stop(&error), error); +} + +void ProductionWorker::requestReset() +{ + ensureService(); + QString error; + reportFailure(m_service->reset(&error), error); +} + +void ProductionWorker::requestRecover() +{ + ensureService(); + QString error; + reportFailure(m_service->recover(&error), error); +} + +void ProductionWorker::requestRetry() +{ + ensureService(); + QString error; + reportFailure(m_service->retry(&error), error); +} + +void ProductionWorker::requestMarkNg() +{ + ensureService(); + QString error; + reportFailure(m_service->markCurrentWorkpieceNg(&error), error); +} + +void ProductionWorker::requestRestore() +{ + ensureService(); + QString error; + reportFailure(m_service->restoreActiveRun(&error), error); +} diff --git a/services/productionworker.h b/services/productionworker.h new file mode 100644 index 0000000..d1d67d8 --- /dev/null +++ b/services/productionworker.h @@ -0,0 +1,46 @@ +#ifndef PRODUCTIONWORKER_H +#define PRODUCTIONWORKER_H + +#include "productionservice.h" + +#include + +class ProductionWorker : public QObject +{ + Q_OBJECT + +public: + explicit ProductionWorker(QObject *parent = nullptr); + +public slots: + void requestStart(int orderId); + void requestPause(); + void requestResume(); + void requestStop(); + void requestReset(); + void requestRecover(); + void requestRetry(); + void requestMarkNg(); + void requestRestore(); + +signals: + void stateChanged(ProductionService::State state, const QString &name); + void currentWorkpieceChanged(int workpieceId, const QString &barcode); + void currentWorkpieceSnapshotChanged(const Workpiece &workpiece); + void currentPositionChanged(int trayNo, int slotNo); + void productionFinished(int orderId); + void productionError(const QString &error); + void alarmRaised(const QString &code, const QString &message); + void processElapsedChanged(const QString &processStep, int elapsedMs); + void timeoutWarning(const QString &state, int elapsedMs, int timeoutMs); + void timeoutRecoveryRequired(const QString &state, const QString &message); + void recoveryCompleted(const QString &mode); + +private: + void ensureService(); + void reportFailure(bool success, const QString &error); + + ProductionService *m_service; +}; + +#endif // PRODUCTIONWORKER_H diff --git a/services/workpieceservice.cpp b/services/workpieceservice.cpp index 693adc3..9ab3d08 100644 --- a/services/workpieceservice.cpp +++ b/services/workpieceservice.cpp @@ -278,8 +278,9 @@ bool WorkpieceService::updateState(int id, const QString &state, } bool WorkpieceService::updateProcessStepWithRecord( - int id, const QString &processStep, int plcStep, const QString &source, - int durationMs, QString *error, bool forceRestart) + int id, const QString &processStep, const QString &inspectionMode, + int plcStep, const QString &source, int durationMs, QString *error, + bool forceRestart) { if (id <= 0 || processStep.trimmed().isEmpty()) { if (error) { @@ -336,7 +337,8 @@ bool WorkpieceService::updateProcessStepWithRecord( workpiece.orderId, &transactionError)) || (!sameProcess && !ProductionRepository().startWorkpieceProcess( - workpiece.orderId, id, processStep, plcStep, source, + workpiece.orderId, id, processStep, inspectionMode, + plcStep, source, &transactionError)) || !recordLog("更新工件工序", QString("工件 %1 工序更新为 %2") @@ -355,8 +357,8 @@ bool WorkpieceService::updateProcessStepWithRecord( bool WorkpieceService::completeWithInspection( int id, const QString &state, const QString &processStep, const QString &previousProcessStep, int durationMs, int rawResult, - const QString &resultState, int plcStep, const QString &source, - QString *error) + const QString &resultState, int plcStep, const QString &inspectionMode, + const QString &source, QString *error) { if (id <= 0) { if (error) { @@ -400,7 +402,8 @@ bool WorkpieceService::completeWithInspection( &transactionError)) || !ProductionRepository().insertInspection( workpiece.orderId, id, "FINAL", rawResult, resultState, - plcStep, source, "Final production result", &transactionError) + inspectionMode, plcStep, source, "Final production result", + &transactionError) || !recordLog("完成工件检测", QString("工件 %1 检测结果为 %2") .arg(workpiece.barcode, resultState), @@ -415,6 +418,47 @@ bool WorkpieceService::completeWithInspection( return true; } +bool WorkpieceService::recordInspection( + int id, const QString &side, int rawResult, const QString &resultState, + int plcStep, const QString &inspectionMode, const QString &source, + const QString &message, QString *error) +{ + if (id <= 0 || side.trimmed().isEmpty()) { + if (error) { + *error = id <= 0 ? "Workpiece id must be greater than 0" + : "Inspection side cannot be empty"; + } + return false; + } + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + Workpiece workpiece; + if (!WorkpieceRepository().findWorkpiece(id, &workpiece, &transactionError) + || !ProductionRepository().insertInspection( + workpiece.orderId, id, side, rawResult, resultState, + inspectionMode, plcStep, source, message, &transactionError) + || !recordLog("RECORD_INSPECTION", + QString("Workpiece %1 %2 result %3") + .arg(workpiece.barcode, side, resultState), + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + bool WorkpieceService::isValidState(const QString &state) const { return state == "PENDING" || state == "PROCESSING" diff --git a/services/workpieceservice.h b/services/workpieceservice.h index bf2374d..fb08fb3 100644 --- a/services/workpieceservice.h +++ b/services/workpieceservice.h @@ -21,15 +21,22 @@ public: bool updateState(int id, const QString &state, const QString &processStep, QString *error = nullptr); bool updateProcessStepWithRecord(int id, const QString &processStep, - int plcStep, const QString &source, + const QString &inspectionMode, int plcStep, + const QString &source, int durationMs, QString *error = nullptr, bool forceRestart = false); + bool recordInspection(int id, const QString &side, int rawResult, + const QString &resultState, int plcStep, + const QString &inspectionMode, const QString &source, + const QString &message, + QString *error = nullptr); bool completeWithInspection(int id, const QString &state, const QString &processStep, const QString &previousProcessStep, int durationMs, int rawResult, const QString &resultState, int plcStep, + const QString &inspectionMode, const QString &source, QString *error = nullptr); diff --git a/ssp.pro b/ssp.pro index 6802fd4..a034595 100644 --- a/ssp.pro +++ b/ssp.pro @@ -39,6 +39,7 @@ SOURCES += \ services/logservice.cpp \ services/orderservice.cpp \ services/productionservice.cpp \ + services/productionworker.cpp \ services/trayservice.cpp \ services/workpieceservice.cpp \ widget.cpp @@ -70,6 +71,7 @@ HEADERS += \ services/logservice.h \ services/orderservice.h \ services/productionservice.h \ + services/productionworker.h \ services/trayservice.h \ services/workpieceservice.h \ widget.h diff --git a/ssp.pro.user b/ssp.pro.user index 4eb13f0..db5027c 100644 --- a/ssp.pro.user +++ b/ssp.pro.user @@ -1,6 +1,6 @@ - + EnvironmentId