From 0c4fd6844c505f12878c02e12e80eba114c35229 Mon Sep 17 00:00:00 2001 From: lidg Date: Tue, 18 Aug 2026 09:40:43 +0800 Subject: [PATCH] first commit --- .idea/.gitignore | 10 + .idea/modules.xml | 8 + .idea/ssp.iml | 9 + .idea/vcs.xml | 6 + config.ini | 54 ++ config/configmanager.cpp | 189 ++++ config/configmanager.h | 56 ++ db/databasemanager.cpp | 138 +++ db/databasemanager.h | 36 + db/dbconfig.cpp | 14 + db/dbconfig.h | 19 + db/schema.sql | 435 +++++++++ main.cpp | 27 + modbus/modbusaddress.cpp | 44 + modbus/modbusaddress.h | 30 + modbus/modbusconfig.cpp | 17 + modbus/modbusconfig.h | 25 + modbus/modbustcpmanager.cpp | 258 ++++++ modbus/modbustcpmanager.h | 46 + models/logrecord.h | 18 + models/order.h | 25 + models/tray.h | 33 + models/workpiece.h | 22 + pages/Test.ui | 22 + pages/dashboardpage.cpp | 668 ++++++++++++++ pages/dashboardpage.h | 86 ++ pages/dashboardpage.ui | 137 +++ pages/devicepage.cpp | 105 +++ pages/devicepage.h | 29 + pages/devicepage.ui | 15 + pages/logpage.cpp | 72 ++ pages/logpage.h | 28 + pages/logpage.ui | 25 + pages/orderpage.cpp | 233 +++++ pages/orderpage.h | 34 + pages/orderpage.ui | 38 + pages/rackpage.cpp | 245 +++++ pages/rackpage.h | 50 + pages/rackpage.ui | 41 + pages/squaretraybutton.cpp | 60 ++ pages/squaretraybutton.h | 24 + pages/uihelpers.cpp | 94 ++ pages/uihelpers.h | 21 + repositories/logrepository.cpp | 73 ++ repositories/logrepository.h | 15 + repositories/orderrepository.cpp | 231 +++++ repositories/orderrepository.h | 23 + repositories/productionrepository.cpp | 467 ++++++++++ repositories/productionrepository.h | 85 ++ repositories/trayrepository.cpp | 256 ++++++ repositories/trayrepository.h | 24 + repositories/workpiecerepository.cpp | 204 ++++ repositories/workpiecerepository.h | 22 + services/deviceservice.cpp | 304 ++++++ services/deviceservice.h | 60 ++ services/logservice.cpp | 24 + services/logservice.h | 20 + services/orderservice.cpp | 441 +++++++++ services/orderservice.h | 33 + services/productionservice.cpp | 1228 +++++++++++++++++++++++++ services/productionservice.h | 125 +++ services/trayservice.cpp | 178 ++++ services/trayservice.h | 27 + services/workpieceservice.cpp | 422 +++++++++ services/workpieceservice.h | 44 + ssp.pro | 92 ++ ssp.pro.user | 562 +++++++++++ widget.cpp | 153 +++ widget.h | 43 + widget.ui | 19 + 70 files changed, 8721 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/modules.xml create mode 100644 .idea/ssp.iml create mode 100644 .idea/vcs.xml create mode 100644 config.ini create mode 100644 config/configmanager.cpp create mode 100644 config/configmanager.h create mode 100644 db/databasemanager.cpp create mode 100644 db/databasemanager.h create mode 100644 db/dbconfig.cpp create mode 100644 db/dbconfig.h create mode 100644 db/schema.sql create mode 100644 main.cpp create mode 100644 modbus/modbusaddress.cpp create mode 100644 modbus/modbusaddress.h create mode 100644 modbus/modbusconfig.cpp create mode 100644 modbus/modbusconfig.h create mode 100644 modbus/modbustcpmanager.cpp create mode 100644 modbus/modbustcpmanager.h create mode 100644 models/logrecord.h create mode 100644 models/order.h create mode 100644 models/tray.h create mode 100644 models/workpiece.h create mode 100644 pages/Test.ui create mode 100644 pages/dashboardpage.cpp create mode 100644 pages/dashboardpage.h create mode 100644 pages/dashboardpage.ui create mode 100644 pages/devicepage.cpp create mode 100644 pages/devicepage.h create mode 100644 pages/devicepage.ui create mode 100644 pages/logpage.cpp create mode 100644 pages/logpage.h create mode 100644 pages/logpage.ui create mode 100644 pages/orderpage.cpp create mode 100644 pages/orderpage.h create mode 100644 pages/orderpage.ui create mode 100644 pages/rackpage.cpp create mode 100644 pages/rackpage.h create mode 100644 pages/rackpage.ui create mode 100644 pages/squaretraybutton.cpp create mode 100644 pages/squaretraybutton.h create mode 100644 pages/uihelpers.cpp create mode 100644 pages/uihelpers.h create mode 100644 repositories/logrepository.cpp create mode 100644 repositories/logrepository.h create mode 100644 repositories/orderrepository.cpp create mode 100644 repositories/orderrepository.h create mode 100644 repositories/productionrepository.cpp create mode 100644 repositories/productionrepository.h create mode 100644 repositories/trayrepository.cpp create mode 100644 repositories/trayrepository.h create mode 100644 repositories/workpiecerepository.cpp create mode 100644 repositories/workpiecerepository.h create mode 100644 services/deviceservice.cpp create mode 100644 services/deviceservice.h create mode 100644 services/logservice.cpp create mode 100644 services/logservice.h create mode 100644 services/orderservice.cpp create mode 100644 services/orderservice.h create mode 100644 services/productionservice.cpp create mode 100644 services/productionservice.h create mode 100644 services/trayservice.cpp create mode 100644 services/trayservice.h create mode 100644 services/workpieceservice.cpp create mode 100644 services/workpieceservice.h create mode 100644 ssp.pro create mode 100644 ssp.pro.user create mode 100644 widget.cpp create mode 100644 widget.h create mode 100644 widget.ui diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..b6b1ecf --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 已忽略包含查询文件的默认文件夹 +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..5dc6187 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/ssp.iml b/.idea/ssp.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/ssp.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/config.ini b/config.ini new file mode 100644 index 0000000..e13dc57 --- /dev/null +++ b/config.ini @@ -0,0 +1,54 @@ +[database] +driver=QPSQL +host=127.0.0.1 +port=5432 +name=ssp +user=postgres +password=hardman +connection=ssp_postgres + +[modbus] +host=127.0.0.1 +port=502 +serverAddress=1 +timeoutMs=1000 +retryCount=1 +pollIntervalMs=1000 +commandPulseMs=100 +feedbackTimeoutMs=2000 +reconnectDelayMs=200 +reconnectAttempts=2 +startCommand=0 +pauseCommand=1 +resetCommand=2 +clearAlarmCommand=3 +startFeedback=10 +pauseFeedback=11 +resetFeedback=12 +clearAlarmFeedback=13 +plcReady=100 +robotReady=101 +safetyDoorClosed=102 +emergencyStop=103 +currentStep=200 +checkResult=201 +errorCode=202 + +[production] +loadStep=1 +frontCheckStep=2 +backCheckStep=3 +unloadStep=4 +cycleCompleteStep=5 +okResult=1 +ngResult=2 +errorResult=3 +simulationResult=1 +timeoutWarningMs=8000 +stateTimeoutMs=10000 +maxRecoveryRetries=1 +simulationStepMs=500 + +[system] +simulation=true +productionEnabled=false diff --git a/config/configmanager.cpp b/config/configmanager.cpp new file mode 100644 index 0000000..a7a184b --- /dev/null +++ b/config/configmanager.cpp @@ -0,0 +1,189 @@ +#include "configmanager.h" + +#include +#include +#include +#include + +ConfigManager &ConfigManager::instance() +{ + static ConfigManager manager; + return manager; +} + +ConfigManager::ConfigManager() + : m_databaseConfig(DbConfig::defaultConfig()), + m_modbusConfig(ModbusConfig::defaultConfig()), + m_simulationMode(true), + m_productionEnabled(false) +{ +} + +bool ConfigManager::load(const QString &filePath) +{ + m_filePath = filePath.isEmpty() ? defaultFilePath() : filePath; + + QSettings settings(m_filePath, QSettings::IniFormat); + m_databaseConfig.driverName = settings.value("database/driver", m_databaseConfig.driverName).toString(); + m_databaseConfig.hostName = settings.value("database/host", m_databaseConfig.hostName).toString(); + m_databaseConfig.port = settings.value("database/port", m_databaseConfig.port).toInt(); + m_databaseConfig.databaseName = settings.value("database/name", m_databaseConfig.databaseName).toString(); + m_databaseConfig.userName = settings.value("database/user", m_databaseConfig.userName).toString(); + m_databaseConfig.password = settings.value("database/password", m_databaseConfig.password).toString(); + m_databaseConfig.connectionName = settings.value("database/connection", m_databaseConfig.connectionName).toString(); + + m_modbusConfig.host = settings.value("modbus/host", m_modbusConfig.host).toString(); + m_modbusConfig.port = settings.value("modbus/port", m_modbusConfig.port).toInt(); + m_modbusConfig.serverAddress = settings.value("modbus/serverAddress", m_modbusConfig.serverAddress).toInt(); + 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(); + + ModbusAddressMap &addresses = m_modbusConfig.addressMap; + addresses.startCommand = settings.value("modbus/startCommand", addresses.startCommand).toInt(); + addresses.pauseCommand = settings.value("modbus/pauseCommand", addresses.pauseCommand).toInt(); + addresses.resetCommand = settings.value("modbus/resetCommand", addresses.resetCommand).toInt(); + addresses.clearAlarmCommand = settings.value("modbus/clearAlarmCommand", addresses.clearAlarmCommand).toInt(); + addresses.startFeedback = settings.value("modbus/startFeedback", addresses.startFeedback).toInt(); + addresses.pauseFeedback = settings.value("modbus/pauseFeedback", addresses.pauseFeedback).toInt(); + addresses.resetFeedback = settings.value("modbus/resetFeedback", addresses.resetFeedback).toInt(); + addresses.clearAlarmFeedback = settings.value("modbus/clearAlarmFeedback", addresses.clearAlarmFeedback).toInt(); + addresses.plcReady = settings.value("modbus/plcReady", addresses.plcReady).toInt(); + addresses.robotReady = settings.value("modbus/robotReady", addresses.robotReady).toInt(); + addresses.safetyDoorClosed = settings.value("modbus/safetyDoorClosed", addresses.safetyDoorClosed).toInt(); + addresses.emergencyStop = settings.value("modbus/emergencyStop", addresses.emergencyStop).toInt(); + 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(); + + m_productionConfig.loadStep = + settings.value("production/loadStep", m_productionConfig.loadStep).toInt(); + m_productionConfig.frontCheckStep = + settings.value("production/frontCheckStep", m_productionConfig.frontCheckStep).toInt(); + m_productionConfig.backCheckStep = + settings.value("production/backCheckStep", m_productionConfig.backCheckStep).toInt(); + m_productionConfig.unloadStep = + settings.value("production/unloadStep", m_productionConfig.unloadStep).toInt(); + m_productionConfig.cycleCompleteStep = + settings.value("production/cycleCompleteStep", + m_productionConfig.cycleCompleteStep).toInt(); + m_productionConfig.okResult = + settings.value("production/okResult", m_productionConfig.okResult).toInt(); + m_productionConfig.ngResult = + settings.value("production/ngResult", m_productionConfig.ngResult).toInt(); + m_productionConfig.errorResult = + settings.value("production/errorResult", m_productionConfig.errorResult).toInt(); + m_productionConfig.simulationResult = + settings.value("production/simulationResult", + m_productionConfig.simulationResult).toInt(); + m_productionConfig.timeoutWarningMs = + settings.value("production/timeoutWarningMs", + m_productionConfig.timeoutWarningMs).toInt(); + m_productionConfig.stateTimeoutMs = + settings.value("production/stateTimeoutMs", + m_productionConfig.stateTimeoutMs).toInt(); + m_productionConfig.maxRecoveryRetries = + settings.value("production/maxRecoveryRetries", + m_productionConfig.maxRecoveryRetries).toInt(); + m_productionConfig.simulationStepMs = + settings.value("production/simulationStepMs", + m_productionConfig.simulationStepMs).toInt(); + + m_simulationMode = settings.value("system/simulation", m_simulationMode).toBool(); + m_productionEnabled = settings.value("system/productionEnabled", m_productionEnabled).toBool(); + return settings.status() == QSettings::NoError; +} + +QString ConfigManager::filePath() const +{ + return m_filePath; +} + +DbConfig ConfigManager::databaseConfig() const +{ + return m_databaseConfig; +} + +ModbusConfig ConfigManager::modbusConfig() const +{ + return m_modbusConfig; +} + +ProductionConfig ConfigManager::productionConfig() const +{ + return m_productionConfig; +} + +bool ConfigManager::simulationMode() const +{ + return m_simulationMode; +} + +bool ConfigManager::productionEnabled() const +{ + return m_productionEnabled; +} + +bool ConfigManager::validate(QString *error) const +{ + QStringList errors; + if (m_modbusConfig.host.trimmed().isEmpty()) { + errors.append("Modbus host is empty"); + } + if (m_modbusConfig.port <= 0 || m_modbusConfig.port > 65535) { + errors.append("Modbus port is invalid"); + } + if (m_modbusConfig.serverAddress < 0 || m_modbusConfig.serverAddress > 255) { + errors.append("Modbus server address is invalid"); + } + if (m_modbusConfig.timeoutMs <= 0) { + errors.append("Modbus timeoutMs must be greater than 0"); + } + if (m_modbusConfig.pollIntervalMs <= 0) { + errors.append("Modbus pollIntervalMs must be greater than 0"); + } + if (m_modbusConfig.commandPulseMs <= 0 + || m_modbusConfig.feedbackTimeoutMs <= 0 + || m_modbusConfig.reconnectDelayMs < 0 + || m_modbusConfig.reconnectAttempts < 0) { + errors.append("Modbus timing or retry settings are invalid"); + } + + QString addressError; + if (!m_modbusConfig.addressMap.isValid(&addressError)) { + errors.append(addressError); + } + if (m_productionEnabled && m_simulationMode) { + errors.append("productionEnabled cannot be true while simulation is enabled"); + } + if (m_productionConfig.timeoutWarningMs <= 0 + || m_productionConfig.stateTimeoutMs <= 0 + || m_productionConfig.timeoutWarningMs >= m_productionConfig.stateTimeoutMs + || m_productionConfig.maxRecoveryRetries < 0 + || m_productionConfig.simulationStepMs <= 0) { + errors.append("Production timing settings are invalid"); + } + if (m_productionConfig.okResult == m_productionConfig.ngResult + || m_productionConfig.okResult == m_productionConfig.errorResult + || m_productionConfig.ngResult == m_productionConfig.errorResult) { + errors.append("Production result values must be different"); + } + if (m_productionConfig.simulationResult != m_productionConfig.okResult + && m_productionConfig.simulationResult != m_productionConfig.ngResult) { + errors.append("Simulation result must be OK or NG"); + } + + if (error) { + *error = errors.join("; "); + } + return errors.isEmpty(); +} + +QString ConfigManager::defaultFilePath() const +{ + return QDir(QCoreApplication::applicationDirPath()).filePath("config.ini"); +} diff --git a/config/configmanager.h b/config/configmanager.h new file mode 100644 index 0000000..cde86ca --- /dev/null +++ b/config/configmanager.h @@ -0,0 +1,56 @@ +#ifndef CONFIGMANAGER_H +#define CONFIGMANAGER_H + +#include "../db/dbconfig.h" +#include "../modbus/modbusconfig.h" + +#include + +struct ProductionConfig +{ + int loadStep = 1; + int frontCheckStep = 2; + int backCheckStep = 3; + int unloadStep = 4; + int cycleCompleteStep = 5; + int okResult = 1; + int ngResult = 2; + int errorResult = 3; + int simulationResult = 1; + int timeoutWarningMs = 8000; + int stateTimeoutMs = 10000; + int maxRecoveryRetries = 1; + int simulationStepMs = 500; +}; + +class ConfigManager +{ +public: + static ConfigManager &instance(); + + bool load(const QString &filePath = QString()); + QString filePath() const; + + DbConfig databaseConfig() const; + ModbusConfig modbusConfig() const; + ProductionConfig productionConfig() const; + bool simulationMode() const; + bool productionEnabled() const; + bool validate(QString *error = nullptr) const; + +private: + ConfigManager(); + ConfigManager(const ConfigManager &) = delete; + ConfigManager &operator=(const ConfigManager &) = delete; + + QString defaultFilePath() const; + + QString m_filePath; + DbConfig m_databaseConfig; + ModbusConfig m_modbusConfig; + ProductionConfig m_productionConfig; + bool m_simulationMode; + bool m_productionEnabled; +}; + +#endif // CONFIGMANAGER_H diff --git a/db/databasemanager.cpp b/db/databasemanager.cpp new file mode 100644 index 0000000..26ac226 --- /dev/null +++ b/db/databasemanager.cpp @@ -0,0 +1,138 @@ +#include "databasemanager.h" + +#include + +DatabaseManager &DatabaseManager::instance() +{ + static DatabaseManager manager; + return manager; +} + +DatabaseManager::DatabaseManager() + : m_config(DbConfig::defaultConfig()) +{ +} + +void DatabaseManager::setConfig(const DbConfig &config) +{ + if (isOpen()) { + close(); + } + m_config = config; +} + +DbConfig DatabaseManager::config() const +{ + return m_config; +} + +bool DatabaseManager::open(QString *error) +{ + QSqlDatabase db; + if (QSqlDatabase::contains(m_config.connectionName)) { + db = QSqlDatabase::database(m_config.connectionName); + } else { + db = QSqlDatabase::addDatabase(m_config.driverName, m_config.connectionName); + } + + if (db.isOpen()) { + return true; + } + + db.setHostName(m_config.hostName); + db.setPort(m_config.port); + db.setDatabaseName(m_config.databaseName); + db.setUserName(m_config.userName); + db.setPassword(m_config.password); + + if (!db.open()) { + m_lastErrorText = db.lastError().text(); + if (error) { + *error = m_lastErrorText; + } + return false; + } + + m_lastErrorText.clear(); + return true; +} + +void DatabaseManager::close() +{ + const QString connectionName = m_config.connectionName; + if (!QSqlDatabase::contains(connectionName)) { + return; + } + + { + QSqlDatabase db = QSqlDatabase::database(connectionName, false); + if (db.isValid() && db.isOpen()) { + db.close(); + } + } + + QSqlDatabase::removeDatabase(connectionName); +} + +bool DatabaseManager::isOpen() const +{ + if (!QSqlDatabase::contains(m_config.connectionName)) { + return false; + } + return QSqlDatabase::database(m_config.connectionName, false).isOpen(); +} + +QSqlDatabase DatabaseManager::database() const +{ + if (!QSqlDatabase::contains(m_config.connectionName)) { + return QSqlDatabase(); + } + return QSqlDatabase::database(m_config.connectionName); +} + +QString DatabaseManager::lastErrorText() const +{ + return m_lastErrorText; +} + +bool DatabaseManager::transaction(QString *error) +{ + if (!open(error)) { + return false; + } + QSqlDatabase db = database(); + if (!db.transaction()) { + m_lastErrorText = db.lastError().text(); + if (error) { + *error = m_lastErrorText; + } + return false; + } + return true; +} + +bool DatabaseManager::commit(QString *error) +{ + QSqlDatabase db = database(); + if (!db.commit()) { + m_lastErrorText = db.lastError().text(); + if (error) { + *error = m_lastErrorText; + } + return false; + } + return true; +} + +bool DatabaseManager::rollback(QString *error) +{ + QSqlDatabase db = database(); + if (!db.rollback()) { + m_lastErrorText = db.lastError().text(); + if (error) { + *error = m_lastErrorText; + } + return false; + } + return true; +} diff --git a/db/databasemanager.h b/db/databasemanager.h new file mode 100644 index 0000000..69350b7 --- /dev/null +++ b/db/databasemanager.h @@ -0,0 +1,36 @@ +#ifndef DATABASEMANAGER_H +#define DATABASEMANAGER_H + +#include "dbconfig.h" + +#include +#include + +class DatabaseManager +{ +public: + static DatabaseManager &instance(); + + void setConfig(const DbConfig &config); + DbConfig config() const; + + bool open(QString *error = nullptr); + void close(); + bool isOpen() const; + QSqlDatabase database() const; + QString lastErrorText() const; + + bool transaction(QString *error = nullptr); + bool commit(QString *error = nullptr); + bool rollback(QString *error = nullptr); + +private: + DatabaseManager(); + DatabaseManager(const DatabaseManager &) = delete; + DatabaseManager &operator=(const DatabaseManager &) = delete; + + DbConfig m_config; + QString m_lastErrorText; +}; + +#endif // DATABASEMANAGER_H diff --git a/db/dbconfig.cpp b/db/dbconfig.cpp new file mode 100644 index 0000000..2fe44c7 --- /dev/null +++ b/db/dbconfig.cpp @@ -0,0 +1,14 @@ +#include "dbconfig.h" + +DbConfig DbConfig::defaultConfig() +{ + DbConfig config; + config.driverName = "QPSQL"; + config.hostName = "127.0.0.1"; + config.port = 5432; + config.databaseName = "ssp"; + config.userName = "postgres"; + config.password = "hardman"; + config.connectionName = "ssp_postgres"; + return config; +} diff --git a/db/dbconfig.h b/db/dbconfig.h new file mode 100644 index 0000000..b04730c --- /dev/null +++ b/db/dbconfig.h @@ -0,0 +1,19 @@ +#ifndef DBCONFIG_H +#define DBCONFIG_H + +#include + +struct DbConfig +{ + QString driverName; + QString hostName; + int port; + QString databaseName; + QString userName; + QString password; + QString connectionName; + + static DbConfig defaultConfig(); +}; + +#endif // DBCONFIG_H diff --git a/db/schema.sql b/db/schema.sql new file mode 100644 index 0000000..3fd5f5b --- /dev/null +++ b/db/schema.sql @@ -0,0 +1,435 @@ +create table if not exists orders ( + id bigserial primary key, + no varchar(64) not null unique, + production_no varchar(64), + drawing_no varchar(64), + batch_no varchar(64), + plan_num integer not null default 0, + qualified integer not null default 0, + unqualified integer not null default 0, + status varchar(32) not null default 'NOT_START', + begin_time timestamp, + end_time timestamp, + remark text, + created_at timestamp not null default now(), + updated_at timestamp not null default now() +); + +create table if not exists trays ( + id bigserial primary key, + code varchar(64), + rfid varchar(64), + rack_row integer not null, + rack_column integer not null, + present boolean not null default false, + loaded_count integer not null default 0, + qualified integer not null default 0, + unqualified integer not null default 0, + status varchar(32) not null default 'EMPTY', + created_at timestamp not null default now(), + updated_at timestamp not null default now(), + unique (rack_row, rack_column) +); + +create table if not exists workpieces ( + id bigserial primary key, + barcode varchar(128) not null unique, + order_id bigint references orders(id) on delete set null, + tray_id bigint references trays(id) on delete set null, + tray_pos integer not null default 0, + row_no integer not null default 0, + column_no integer not null default 0, + state varchar(32) not null default 'PENDING', + process_step varchar(32), + created_at timestamp not null default now(), + updated_at timestamp not null default now() +); + +create table if not exists tray_slots ( + id bigserial primary key, + tray_id bigint not null references trays(id) on delete cascade, + row_no integer not null, + column_no integer not null, + workpiece_id bigint references workpieces(id) on delete set null, + state varchar(32) not null default 'EMPTY', + unique (tray_id, row_no, column_no) +); + +create table if not exists devices ( + id bigserial primary key, + code varchar(64) not null unique, + name varchar(128) not null, + connection_state varchar(32) not null default 'OFFLINE', + run_state varchar(32) not null default 'IDLE', + current_action varchar(128), + updated_at timestamp not null default now() +); + +create table if not exists operation_logs ( + id bigserial primary key, + type varchar(32) not null, + module varchar(64) not null, + action varchar(64) not null, + content text, + status varchar(32) not null default 'success', + created_at timestamp not null default now() +); + +insert into trays (code, rack_row, rack_column, present, loaded_count, status) +values + ('TRAY-1', 1, 1, true, 49, 'PRESENT'), + ('TRAY-2', 1, 2, true, 46, 'PRESENT'), + ('TRAY-3', 1, 3, true, 43, 'PRESENT'), + ('TRAY-4', 2, 1, true, 40, 'PRESENT'), + ('TRAY-5', 2, 2, true, 37, 'PRESENT'), + ('TRAY-6', 2, 3, true, 34, 'PRESENT') +on conflict (rack_row, rack_column) do nothing; + +-- Database schema version +create table if not exists schema_version ( + id smallint primary key default 1, + version integer not null default 0, + description varchar(256), + updated_at timestamp not null default now(), + constraint ck_schema_version_id check (id = 1) +); + +insert into schema_version (id, version, description) +values (1, 3, 'Production records, alarm closed-loop and final inspection tables') +on conflict (id) do update +set version = excluded.version, + description = excluded.description, + updated_at = now(); + +-- Production runtime snapshot +create table if not exists production_runs ( + id bigserial primary key, + order_id bigint not null references orders(id), + current_workpiece_id bigint references workpieces(id) on delete set null, + run_state varchar(32) not null default 'RUNNING', + production_state varchar(64) not null, + process_step varchar(64), + timeout_state varchar(64), + recovery_retry_count integer not null default 0, + last_error text, + started_at timestamp not null default now(), + state_entered_at timestamp not null default now(), + last_heartbeat_at timestamp not null default now(), + ended_at timestamp, + created_at timestamp not null default now(), + updated_at timestamp not null default now(), + constraint ck_production_run_state + check (run_state in ( + 'RUNNING', + 'PAUSED', + 'RECOVERY', + 'ERROR', + 'COMPLETED', + 'STOPPED' + )), + constraint ck_production_retry_count + check (recovery_retry_count >= 0) +); + +create unique index if not exists ux_production_runs_active_order +on production_runs(order_id) +where run_state in ('RUNNING', 'PAUSED', 'RECOVERY'); + +create index if not exists ix_production_runs_order_id +on production_runs(order_id); + +create index if not exists ix_production_runs_workpiece_id +on production_runs(current_workpiece_id); + +-- Production state history +create table if not exists production_state_history ( + id bigserial primary key, + production_run_id bigint references production_runs(id) on delete cascade, + order_id bigint references orders(id) on delete set null, + workpiece_id bigint references workpieces(id) on delete set null, + from_state varchar(64), + to_state varchar(64) not null, + process_step varchar(64), + source varchar(16) not null default 'SYSTEM', + reason varchar(128), + message text, + operator_name varchar(64), + elapsed_ms integer, + changed_at timestamp not null default now(), + created_at timestamp not null default now(), + constraint ck_state_history_source + check (source in ('SYSTEM', 'PLC', 'OPERATOR', 'RECOVERY')), + constraint ck_state_history_elapsed + check (elapsed_ms is null or elapsed_ms >= 0) +); + +create index if not exists ix_state_history_run_id +on production_state_history(production_run_id); + +create index if not exists ix_state_history_order_id +on production_state_history(order_id); + +create index if not exists ix_state_history_workpiece_id +on production_state_history(workpiece_id); + +create index if not exists ix_state_history_changed_at +on production_state_history(changed_at); + +-- Inspection records +create table if not exists inspection_records ( + id bigserial primary key, + order_id bigint references orders(id) on delete set null, + workpiece_id bigint not null references workpieces(id), + inspection_side varchar(16) not null, + attempt_no integer not null default 1, + raw_result integer, + result_state varchar(16) not null, + inspection_state varchar(16) not null default 'COMPLETED', + source varchar(32) not null default 'PLC', + plc_step integer, + message text, + started_at timestamp, + completed_at timestamp, + duration_ms integer, + created_at timestamp not null default now(), + constraint ck_inspection_side + check (inspection_side in ('FRONT', 'BACK', 'FINAL')), + constraint ck_inspection_attempt + check (attempt_no > 0), + constraint ck_inspection_result_state + check (result_state in ('OK', 'NG', 'ERROR', 'UNKNOWN')), + constraint ck_inspection_state + check (inspection_state in ('RUNNING', 'COMPLETED', 'FAILED')), + constraint ck_inspection_source + check (source in ('PLC', 'SIMULATION', 'MANUAL')), + constraint ck_inspection_duration + check (duration_ms is null or duration_ms >= 0), + unique (workpiece_id, inspection_side, attempt_no) +); + +create index if not exists ix_inspection_records_order_id +on inspection_records(order_id); + +create index if not exists ix_inspection_records_workpiece_id +on inspection_records(workpiece_id); + +create index if not exists ix_inspection_records_created_at +on inspection_records(created_at); + +do $$ +begin + if exists ( + select 1 + from information_schema.table_constraints + where table_schema = 'public' + and table_name = 'inspection_records' + and constraint_name = 'ck_inspection_side' + ) then + alter table public.inspection_records + drop constraint ck_inspection_side; + end if; + + alter table public.inspection_records + add constraint ck_inspection_side + check (inspection_side in ('FRONT', 'BACK', 'FINAL')); +end +$$; + +-- Workpiece process history +create table if not exists workpiece_process_records ( + id bigserial primary key, + order_id bigint references orders(id) on delete set null, + workpiece_id bigint not null references workpieces(id), + process_step varchar(64) not null, + attempt_no integer not null default 1, + process_state varchar(16) not null default 'RUNNING', + result_state varchar(16), + plc_step integer, + source varchar(16) not null default 'PLC', + failure_reason text, + started_at timestamp not null default now(), + completed_at timestamp, + duration_ms integer, + created_at timestamp not null default now(), + constraint ck_process_record_attempt + check (attempt_no > 0), + constraint ck_process_record_state + check (process_state in ('RUNNING', 'COMPLETED', 'FAILED', 'SKIPPED')), + constraint ck_process_record_result + check (result_state is null or result_state in ('OK', 'NG', 'ERROR', 'UNKNOWN')), + constraint ck_process_record_source + check (source in ('PLC', 'SIMULATION', 'MANUAL', 'RECOVERY')), + constraint ck_process_record_duration + check (duration_ms is null or duration_ms >= 0), + unique (workpiece_id, process_step, attempt_no) +); + +create index if not exists ix_process_records_order_id +on workpiece_process_records(order_id); + +create index if not exists ix_process_records_workpiece_id +on workpiece_process_records(workpiece_id); + +create index if not exists ix_process_records_step +on workpiece_process_records(process_step); + +create index if not exists ix_process_records_started_at +on workpiece_process_records(started_at); + +-- Alarm definitions +create table if not exists alarm_definitions ( + id bigserial primary key, + code varchar(64) not null unique, + name varchar(128) not null, + level varchar(16) not null default 'ERROR', + source varchar(32) not null, + description text, + recovery_hint text, + auto_recover boolean not null default false, + enabled boolean not null default true, + created_at timestamp not null default now(), + updated_at timestamp not null default now(), + constraint ck_alarm_definition_level + check (level in ('INFO', 'WARNING', 'ERROR', 'CRITICAL')), + constraint ck_alarm_definition_source + check (source in ( + 'PLC', + 'DEVICE', + 'PRODUCTION', + 'SYSTEM', + 'OPERATOR' + )) +); + +insert into alarm_definitions + (code, name, level, source, description, recovery_hint, auto_recover) +values + ('PLC_DISCONNECTED', 'PLC disconnected', 'CRITICAL', 'PLC', + 'PLC communication is unavailable', + 'Check network and PLC power, then reconnect', false), + ('EMERGENCY_STOP', 'Emergency stop active', 'CRITICAL', 'DEVICE', + 'Emergency stop signal is active', + 'Release emergency stop after confirming equipment safety', false), + ('SAFETY_DOOR_OPEN', 'Safety door open', 'CRITICAL', 'DEVICE', + 'Safety door is not closed', + 'Close the safety door after confirming equipment safety', false), + ('PRODUCTION_TIMEOUT_WARNING', 'Production timeout warning', 'WARNING', 'PRODUCTION', + 'A production state is approaching its timeout', + 'Check the equipment and continue if the process is safe', true), + ('PRODUCTION_TIMEOUT', 'Production timeout', 'ERROR', 'PRODUCTION', + 'A production state exceeded its timeout', + 'Inspect the PLC step and recover or retry the current process', false), + ('PLC_ERROR', 'PLC error', 'ERROR', 'PLC', + 'The PLC reported an error code', + 'Resolve the PLC error and clear the alarm', false) +on conflict (code) do update +set name = excluded.name, + level = excluded.level, + source = excluded.source, + description = excluded.description, + recovery_hint = excluded.recovery_hint, + auto_recover = excluded.auto_recover, + updated_at = now(); + +-- Alarm records +create table if not exists alarm_records ( + id bigserial primary key, + code varchar(64) not null, + level varchar(16) not null default 'ERROR', + source varchar(32) not null, + order_id bigint references orders(id) on delete set null, + workpiece_id bigint references workpieces(id) on delete set null, + message text not null, + alarm_state varchar(16) not null default 'ACTIVE', + raised_at timestamp not null default now(), + acknowledged_at timestamp, + cleared_at timestamp, + acknowledged_by varchar(64), + cleared_by varchar(64), + recovery_action varchar(64), + details jsonb, + created_at timestamp not null default now(), + constraint ck_alarm_level + check (level in ('INFO', 'WARNING', 'ERROR', 'CRITICAL')), + constraint ck_alarm_source + check (source in ( + 'PLC', + 'DEVICE', + 'PRODUCTION', + 'SYSTEM', + 'OPERATOR' + )), + constraint ck_alarm_state + check (alarm_state in ('ACTIVE', 'ACK', 'CLEARED')), + constraint ck_alarm_time_order + check ( + cleared_at is null + or acknowledged_at is null + or cleared_at >= acknowledged_at + ) +); + +create index if not exists ix_alarm_records_active +on alarm_records(alarm_state, raised_at); + +create index if not exists ix_alarm_records_code +on alarm_records(code); + +create index if not exists ix_alarm_records_order_id +on alarm_records(order_id); + +create index if not exists ix_alarm_records_workpiece_id +on alarm_records(workpiece_id); + +create index if not exists ix_alarm_records_raised_at +on alarm_records(raised_at); + +do $$ +begin + if not exists ( + select 1 + from information_schema.columns + where table_schema = 'public' + and table_name = 'alarm_records' + and column_name = 'definition_id' + ) then + alter table public.alarm_records + add column definition_id bigint; + + alter table public.alarm_records + add constraint fk_alarm_records_definition + foreign key (definition_id) + references public.alarm_definitions(id) + on delete set null; + end if; +end +$$; + +create index if not exists ix_alarm_records_definition_id +on alarm_records(definition_id); + +-- Device status history +create table if not exists device_status_history ( + id bigserial primary key, + device_id bigint references devices(id) on delete set null, + device_code varchar(64), + plc_connected boolean not null, + plc_ready boolean not null, + robot_ready boolean not null, + safety_door_closed boolean not null, + emergency_stop boolean not null, + current_step integer not null default 0, + check_result integer not null default 0, + error_code integer not null default 0, + changed_at timestamp not null default now(), + created_at timestamp not null default now() +); + +create index if not exists ix_device_status_history_device_id +on device_status_history(device_id); + +create index if not exists ix_device_status_history_device_code +on device_status_history(device_code); + +create index if not exists ix_device_status_history_changed_at +on device_status_history(changed_at); diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..1a5f37c --- /dev/null +++ b/main.cpp @@ -0,0 +1,27 @@ +#include "widget.h" + +#include "config/configmanager.h" +#include "db/databasemanager.h" +#include "modbus/modbustcpmanager.h" + +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + + ConfigManager &configManager = ConfigManager::instance(); + configManager.load(); + DatabaseManager::instance().setConfig(configManager.databaseConfig()); + ModbusTcpManager::instance().setConfig(configManager.modbusConfig()); + + QString configError; + if (!configManager.validate(&configError)) { + qWarning() << "Configuration validation failed:" << configError; + } + + Widget w; + w.show(); + return a.exec(); +} diff --git a/modbus/modbusaddress.cpp b/modbus/modbusaddress.cpp new file mode 100644 index 0000000..03a7107 --- /dev/null +++ b/modbus/modbusaddress.cpp @@ -0,0 +1,44 @@ +#include "modbusaddress.h" + +#include +#include + +namespace { + +bool isValidAddress(int address) +{ + return address >= 0; +} + +} + +bool ModbusAddressMap::isValid(QString *error) const +{ + const QList > addresses = QList >() + << qMakePair(QString("startCommand"), startCommand) + << qMakePair(QString("pauseCommand"), pauseCommand) + << qMakePair(QString("resetCommand"), resetCommand) + << qMakePair(QString("clearAlarmCommand"), clearAlarmCommand) + << qMakePair(QString("startFeedback"), startFeedback) + << qMakePair(QString("pauseFeedback"), pauseFeedback) + << qMakePair(QString("resetFeedback"), resetFeedback) + << qMakePair(QString("clearAlarmFeedback"), clearAlarmFeedback) + << qMakePair(QString("plcReady"), plcReady) + << qMakePair(QString("robotReady"), robotReady) + << qMakePair(QString("safetyDoorClosed"), safetyDoorClosed) + << qMakePair(QString("emergencyStop"), emergencyStop) + << qMakePair(QString("currentStep"), currentStep) + << qMakePair(QString("checkResult"), checkResult) + << qMakePair(QString("errorCode"), errorCode); + + for (const QPair &item : addresses) { + if (!isValidAddress(item.second)) { + if (error) { + *error = QString("Modbus address is invalid: %1").arg(item.first); + } + return false; + } + } + + return true; +} diff --git a/modbus/modbusaddress.h b/modbus/modbusaddress.h new file mode 100644 index 0000000..e9725c3 --- /dev/null +++ b/modbus/modbusaddress.h @@ -0,0 +1,30 @@ +#ifndef MODBUSADDRESS_H +#define MODBUSADDRESS_H + +#include + +struct ModbusAddressMap +{ + int startCommand = 0; + int pauseCommand = 1; + int resetCommand = 2; + int clearAlarmCommand = 3; + + int startFeedback = 10; + int pauseFeedback = 11; + int resetFeedback = 12; + int clearAlarmFeedback = 13; + + int plcReady = 100; + int robotReady = 101; + int safetyDoorClosed = 102; + int emergencyStop = 103; + + int currentStep = 200; + int checkResult = 201; + int errorCode = 202; + + bool isValid(QString *error = nullptr) const; +}; + +#endif // MODBUSADDRESS_H diff --git a/modbus/modbusconfig.cpp b/modbus/modbusconfig.cpp new file mode 100644 index 0000000..30293e5 --- /dev/null +++ b/modbus/modbusconfig.cpp @@ -0,0 +1,17 @@ +#include "modbusconfig.h" + +ModbusConfig ModbusConfig::defaultConfig() +{ + ModbusConfig config; + config.host = "127.0.0.1"; + config.port = 502; + config.serverAddress = 1; + config.timeoutMs = 1000; + config.retryCount = 1; + config.pollIntervalMs = 1000; + config.commandPulseMs = 100; + config.feedbackTimeoutMs = 2000; + config.reconnectDelayMs = 200; + config.reconnectAttempts = 2; + return config; +} diff --git a/modbus/modbusconfig.h b/modbus/modbusconfig.h new file mode 100644 index 0000000..d87219f --- /dev/null +++ b/modbus/modbusconfig.h @@ -0,0 +1,25 @@ +#ifndef MODBUSCONFIG_H +#define MODBUSCONFIG_H + +#include "modbusaddress.h" + +#include + +struct ModbusConfig +{ + QString host; + int port; + int serverAddress; + int timeoutMs; + int retryCount; + int pollIntervalMs; + int commandPulseMs; + int feedbackTimeoutMs; + int reconnectDelayMs; + int reconnectAttempts; + ModbusAddressMap addressMap; + + static ModbusConfig defaultConfig(); +}; + +#endif // MODBUSCONFIG_H diff --git a/modbus/modbustcpmanager.cpp b/modbus/modbustcpmanager.cpp new file mode 100644 index 0000000..cf1cfa9 --- /dev/null +++ b/modbus/modbustcpmanager.cpp @@ -0,0 +1,258 @@ +#include "modbustcpmanager.h" + +#include +#include +#include +#include +#include +#include + +ModbusTcpManager &ModbusTcpManager::instance() +{ + static ModbusTcpManager manager; + return manager; +} + +ModbusTcpManager::ModbusTcpManager() + : m_config(ModbusConfig::defaultConfig()), + m_client(nullptr) +{ +} + +ModbusTcpManager::~ModbusTcpManager() +{ + disconnectDevice(); + delete m_client; +} + +void ModbusTcpManager::setConfig(const ModbusConfig &config) +{ + if (isConnected()) { + disconnectDevice(); + } + m_config = config; +} + +ModbusConfig ModbusTcpManager::config() const +{ + return m_config; +} + +bool ModbusTcpManager::connectDevice(QString *error) +{ + ensureClient(); + if (isConnected()) { + return true; + } + + m_client->setConnectionParameter(QModbusDevice::NetworkAddressParameter, QVariant(m_config.host)); + m_client->setConnectionParameter(QModbusDevice::NetworkPortParameter, QVariant(m_config.port)); + m_client->setTimeout(m_config.timeoutMs); + m_client->setNumberOfRetries(m_config.retryCount); + + if (!m_client->connectDevice()) { + setError(m_client->errorString(), error); + return false; + } + + QEventLoop loop; + QTimer timer; + timer.setSingleShot(true); + + QObject::connect(m_client, &QModbusClient::stateChanged, &loop, [&](QModbusDevice::State state) { + if (state == QModbusDevice::ConnectedState || state == QModbusDevice::UnconnectedState) { + loop.quit(); + } + }); + QObject::connect(m_client, &QModbusClient::errorOccurred, &loop, [&](QModbusDevice::Error) { + loop.quit(); + }); + QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + timer.start(m_config.timeoutMs); + loop.exec(); + + if (!isConnected()) { + QString text = m_client->errorString(); + if (text.isEmpty()) { + text = "Modbus TCP connect timeout"; + } + setError(text, error); + return false; + } + + m_lastErrorText.clear(); + return true; +} + +void ModbusTcpManager::disconnectDevice() +{ + if (m_client) { + m_client->disconnectDevice(); + } +} + +bool ModbusTcpManager::isConnected() const +{ + return m_client && m_client->state() == QModbusDevice::ConnectedState; +} + +bool ModbusTcpManager::readCoil(int address, bool *value, QString *error) +{ + if (!value) { + setError("Output value pointer is null", error); + return false; + } + + quint16 rawValue = 0; + if (!readSingleValue(QModbusDataUnit::Coils, address, &rawValue, error)) { + return false; + } + + *value = rawValue != 0; + return true; +} + +bool ModbusTcpManager::readHoldingRegister(int address, quint16 *value, QString *error) +{ + if (!value) { + setError("Output value pointer is null", error); + return false; + } + + return readSingleValue(QModbusDataUnit::HoldingRegisters, address, value, error); +} + +bool ModbusTcpManager::writeCoil(int address, bool value, QString *error) +{ + return writeSingleValue(QModbusDataUnit::Coils, address, value ? 1 : 0, error); +} + +bool ModbusTcpManager::writeHoldingRegister(int address, quint16 value, QString *error) +{ + return writeSingleValue(QModbusDataUnit::HoldingRegisters, address, value, error); +} + +QString ModbusTcpManager::lastErrorText() const +{ + return m_lastErrorText; +} + +bool ModbusTcpManager::readSingleValue(int registerType, int address, quint16 *value, QString *error) +{ + if (address < 0) { + setError("Modbus address must be greater than or equal to 0", error); + return false; + } + + if (!connectDevice(error)) { + return false; + } + + QModbusDataUnit unit(static_cast(registerType), address, 1); + QModbusReply *reply = m_client->sendReadRequest(unit, m_config.serverAddress); + if (!reply) { + setError(m_client->errorString(), error); + return false; + } + + QEventLoop loop; + QTimer timer; + timer.setSingleShot(true); + + QObject::connect(reply, &QModbusReply::finished, &loop, &QEventLoop::quit); + QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + timer.start(m_config.timeoutMs); + loop.exec(); + + if (!reply->isFinished()) { + reply->deleteLater(); + setError("Modbus TCP read timeout", error); + return false; + } + + if (reply->error() != QModbusDevice::NoError) { + const QString text = reply->errorString(); + reply->deleteLater(); + setError(text, error); + return false; + } + + const QModbusDataUnit result = reply->result(); + if (result.valueCount() < 1) { + reply->deleteLater(); + setError("Modbus TCP read returned empty result", error); + return false; + } + + *value = result.value(0); + reply->deleteLater(); + m_lastErrorText.clear(); + return true; +} + +bool ModbusTcpManager::writeSingleValue(int registerType, int address, quint16 value, QString *error) +{ + if (address < 0) { + setError("Modbus address must be greater than or equal to 0", error); + return false; + } + + if (!connectDevice(error)) { + return false; + } + + QModbusDataUnit unit(static_cast(registerType), address, 1); + unit.setValue(0, value); + + QModbusReply *reply = m_client->sendWriteRequest(unit, m_config.serverAddress); + if (!reply) { + setError(m_client->errorString(), error); + return false; + } + + QEventLoop loop; + QTimer timer; + timer.setSingleShot(true); + + QObject::connect(reply, &QModbusReply::finished, &loop, &QEventLoop::quit); + QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + timer.start(m_config.timeoutMs); + loop.exec(); + + if (!reply->isFinished()) { + reply->deleteLater(); + setError("Modbus TCP write timeout", error); + return false; + } + + if (reply->error() != QModbusDevice::NoError) { + const QString text = reply->errorString(); + reply->deleteLater(); + setError(text, error); + return false; + } + + reply->deleteLater(); + m_lastErrorText.clear(); + return true; +} + +void ModbusTcpManager::ensureClient() +{ + if (m_client) { + return; + } + + m_client = new QModbusTcpClient(); +} + +void ModbusTcpManager::setError(const QString &text, QString *error) +{ + m_lastErrorText = text; + if (error) { + *error = m_lastErrorText; + } +} diff --git a/modbus/modbustcpmanager.h b/modbus/modbustcpmanager.h new file mode 100644 index 0000000..95a4760 --- /dev/null +++ b/modbus/modbustcpmanager.h @@ -0,0 +1,46 @@ +#ifndef MODBUSTCPMANAGER_H +#define MODBUSTCPMANAGER_H + +#include "modbusconfig.h" + +#include +#include + +class QModbusTcpClient; + +class ModbusTcpManager +{ +public: + static ModbusTcpManager &instance(); + ~ModbusTcpManager(); + + void setConfig(const ModbusConfig &config); + ModbusConfig config() const; + + bool connectDevice(QString *error = nullptr); + void disconnectDevice(); + bool isConnected() const; + + bool readCoil(int address, bool *value, QString *error = nullptr); + bool readHoldingRegister(int address, quint16 *value, QString *error = nullptr); + bool writeCoil(int address, bool value, QString *error = nullptr); + bool writeHoldingRegister(int address, quint16 value, QString *error = nullptr); + + QString lastErrorText() const; + +private: + ModbusTcpManager(); + ModbusTcpManager(const ModbusTcpManager &) = delete; + ModbusTcpManager &operator=(const ModbusTcpManager &) = delete; + + bool readSingleValue(int registerType, int address, quint16 *value, QString *error); + bool writeSingleValue(int registerType, int address, quint16 value, QString *error); + void ensureClient(); + void setError(const QString &text, QString *error); + + ModbusConfig m_config; + QModbusTcpClient *m_client; + QString m_lastErrorText; +}; + +#endif // MODBUSTCPMANAGER_H diff --git a/models/logrecord.h b/models/logrecord.h new file mode 100644 index 0000000..2610b67 --- /dev/null +++ b/models/logrecord.h @@ -0,0 +1,18 @@ +#ifndef LOGRECORD_H +#define LOGRECORD_H + +#include +#include + +struct LogRecord +{ + int id = 0; + QString type; + QString module; + QString action; + QString content; + QString status; + QDateTime createdAt; +}; + +#endif // LOGRECORD_H diff --git a/models/order.h b/models/order.h new file mode 100644 index 0000000..50afef8 --- /dev/null +++ b/models/order.h @@ -0,0 +1,25 @@ +#ifndef ORDER_H +#define ORDER_H + +#include +#include + +struct Order +{ + int id = 0; + QString no; + QString productionNo; + QString drawingNo; + QString batchNo; + int planNum = 0; + int qualified = 0; + int unqualified = 0; + QString status; + QDateTime beginTime; + QDateTime endTime; + QString remark; + QDateTime createdAt; + QDateTime updatedAt; +}; + +#endif // ORDER_H diff --git a/models/tray.h b/models/tray.h new file mode 100644 index 0000000..f0072cc --- /dev/null +++ b/models/tray.h @@ -0,0 +1,33 @@ +#ifndef TRAY_H +#define TRAY_H + +#include +#include + +struct Tray +{ + int id = 0; + QString code; + QString rfid; + int rackRow = 0; + int rackColumn = 0; + bool present = false; + int loadedCount = 0; + int qualified = 0; + int unqualified = 0; + QString status; + QDateTime createdAt; + QDateTime updatedAt; +}; + +struct TraySlot +{ + int id = 0; + int trayId = 0; + int rowNo = 0; + int columnNo = 0; + int workpieceId = 0; + QString state; +}; + +#endif // TRAY_H diff --git a/models/workpiece.h b/models/workpiece.h new file mode 100644 index 0000000..199c3f1 --- /dev/null +++ b/models/workpiece.h @@ -0,0 +1,22 @@ +#ifndef WORKPIECE_H +#define WORKPIECE_H + +#include +#include + +struct Workpiece +{ + int id = 0; + QString barcode; + int orderId = 0; + int trayId = 0; + int trayPos = 0; + int rowNo = 0; + int columnNo = 0; + QString state; + QString processStep; + QDateTime createdAt; + QDateTime updatedAt; +}; + +#endif // WORKPIECE_H diff --git a/pages/Test.ui b/pages/Test.ui new file mode 100644 index 0000000..9580b0b --- /dev/null +++ b/pages/Test.ui @@ -0,0 +1,22 @@ + + + + + Form + + + + 0 + 0 + 400 + 300 + + + + Form + + + + + + diff --git a/pages/dashboardpage.cpp b/pages/dashboardpage.cpp new file mode 100644 index 0000000..a5d7dc7 --- /dev/null +++ b/pages/dashboardpage.cpp @@ -0,0 +1,668 @@ +#include "dashboardpage.h" +#include "ui_dashboardpage.h" + +#include "../services/orderservice.h" +#include "../services/workpieceservice.h" +#include "../repositories/productionrepository.h" +#include "uihelpers.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DashboardPage::DashboardPage(QWidget *parent) + : QWidget(parent) + , ui(new Ui::DashboardPage) + , orderCombo(new QComboBox(this)) + , rackBox(nullptr) + , deviceStatusLabel(new QLabel("PLC: - | Robot: - | Safety: -", this)) + , recoverButton(new QPushButton("Recover", this)) + , retryButton(new QPushButton("Retry", this)) + , markNgButton(new QPushButton("Mark NG", this)) + , stopButton(new QPushButton("Stop", this)) + , processBox(new QGroupBox("Process timing", this)) + , currentProcessLabel(new QLabel("-", processBox)) + , processElapsedLabel(new QLabel("00:00:00.000", processBox)) + , processTotalElapsedLabel(new QLabel("00:00:00.000", processBox)) + , processTable(new QTableWidget(processBox)) + , processRefreshTimer(new QTimer(this)) + , currentProcessElapsedMs(0) +{ + ui->setupUi(this); + + const QList values = QList() + << ui->planValue << ui->pendingValue << ui->frontValue + << ui->backValue << ui->okValue << ui->ngValue; + for (QLabel *label : values) { + label->setStyleSheet("font-size: 26px; font-weight: bold; color: #00897b;"); + } + + ui->startButton->setObjectName("primaryButton"); + ui->nextButton->setVisible(false); + recoverButton->setObjectName("recoveryButton"); + recoverButton->setVisible(false); + ui->buttonLayout->insertWidget(3, recoverButton); + retryButton->setObjectName("recoveryRetryButton"); + retryButton->setVisible(false); + ui->buttonLayout->insertWidget(4, retryButton); + markNgButton->setObjectName("recoveryNgButton"); + markNgButton->setVisible(false); + ui->buttonLayout->insertWidget(5, markNgButton); + stopButton->setObjectName("stopButton"); + stopButton->setVisible(false); + ui->buttonLayout->insertWidget(6, stopButton); + orderCombo->setObjectName("orderSelector"); + orderCombo->setMinimumWidth(220); + ui->taskLayout->insertWidget(0, orderCombo); + deviceStatusLabel->setStyleSheet("color: #546e7a;"); + ui->taskLayout->insertWidget(1, deviceStatusLabel); + + QFormLayout *processSummaryLayout = new QFormLayout; + processSummaryLayout->addRow("Current process:", currentProcessLabel); + processSummaryLayout->addRow("Elapsed:", processElapsedLabel); + processSummaryLayout->addRow("Total:", processTotalElapsedLabel); + + QVBoxLayout *processLayout = new QVBoxLayout(processBox); + processLayout->addLayout(processSummaryLayout); + processTable->setColumnCount(4); + processTable->setHorizontalHeaderLabels( + QStringList() << "Process" << "Status" << "Attempt" << "Duration"); + processTable->horizontalHeader()->setStretchLastSection(true); + processTable->horizontalHeader()->setSectionResizeMode( + 0, QHeaderView::Stretch); + processTable->verticalHeader()->setVisible(false); + processTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + processTable->setAlternatingRowColors(true); + processTable->setMinimumHeight(150); + processLayout->addWidget(processTable); + ui->taskLayout->insertWidget(6, processBox); + + ui->recentLogTable->setColumnCount(5); + ui->recentLogTable->setHorizontalHeaderLabels(QStringList() << "时间" << "类型" << "模块" << "内容" << "状态"); + ui->recentLogTable->horizontalHeader()->setStretchLastSection(true); + ui->recentLogTable->verticalHeader()->setVisible(false); + ui->recentLogTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui->recentLogTable->setAlternatingRowColors(true); + + ui->deviceLayout->setSpacing(10); + ui->deviceLayout->setColumnStretch(0, 1); + ui->deviceLayout->setColumnStretch(1, 1); + ui->deviceLayout->setColumnStretch(2, 2); + ui->deviceLayout->setColumnStretch(3, 2); + ui->deviceLayout->setColumnStretch(4, 2); + ui->deviceLayout->setColumnStretch(5, 1); + ui->deviceLayout->setRowStretch(0, 1); + ui->deviceLayout->setRowStretch(1, 1); + ui->deviceLayout->setRowStretch(2, 1); + ui->deviceLayout->setRowStretch(3, 1); + ui->deviceLayout->setRowStretch(4, 1); + ui->deviceLayout->setRowStretch(5, 1); + ui->deviceLayout->addWidget(UiHelpers::makeStatusCell("检测机\n待机", "#607d8b"), 0, 0, 2, 2); + ui->deviceLayout->addWidget(UiHelpers::makeStatusCell("总控电脑", "#43a047"), 0, 3); + ui->deviceLayout->addWidget(UiHelpers::makeStatusCell("安全门1\n关闭", "#2e7d32"), 0, 4); + QLabel *robotCell = UiHelpers::makeStatusCell("机器人\n空闲", "#f9a825"); + robotCell->setFixedSize(82, 58); + ui->deviceLayout->addWidget(robotCell, 2, 3, 2, 2, Qt::AlignCenter); + ui->deviceLayout->addWidget(UiHelpers::makeStatusCell("机器人\n控制柜", "#546e7a"), 3, 0); + ui->deviceLayout->addWidget(UiHelpers::makeStatusCell("总控柜", "#546e7a"), 4, 0); + ui->deviceLayout->addWidget(UiHelpers::makeStatusCell("安全门2\n关闭", "#2e7d32"), 2, 5); + ui->deviceLayout->addWidget(UiHelpers::makeStatusCell("安全门3\n关闭", "#2e7d32"), 5, 0); + + rackBox = new QGroupBox("料架 2x3"); + rackBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + QGridLayout *rackLayout = new QGridLayout(rackBox); + rackLayout->setContentsMargins(8, 18, 8, 8); + rackLayout->setSpacing(4); + for (int i = 0; i < 6; ++i) { + QLabel *trayCell = UiHelpers::makeSquareStatusCell(QString("托盘%1\n%2/49").arg(i + 1).arg(49 - i * 4), + i == 0 ? "#00897b" : "#78909c"); + rackTrayCells.append(trayCell); + rackLayout->addWidget(trayCell, i / 3, i % 3, Qt::AlignCenter); + } + ui->deviceLayout->addWidget(rackBox, 4, 2, 2, 3); + updateRackSize(); + + connect(ui->startButton, &QPushButton::clicked, + this, &DashboardPage::startProduction); + connect(ui->pauseButton, &QPushButton::clicked, + this, &DashboardPage::pauseProduction); + connect(stopButton, &QPushButton::clicked, + this, &DashboardPage::stopProduction); + connect(ui->resetButton, &QPushButton::clicked, + this, &DashboardPage::resetProduction); + connect(ui->clearAlarmButton, &QPushButton::clicked, + this, &DashboardPage::clearAlarm); + connect(recoverButton, &QPushButton::clicked, + this, &DashboardPage::recoverProduction); + connect(retryButton, &QPushButton::clicked, + this, &DashboardPage::retryRecovery); + connect(markNgButton, &QPushButton::clicked, + this, &DashboardPage::markWorkpieceNg); + connect(orderCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &DashboardPage::onOrderChanged); + + ProductionService &production = ProductionService::instance(); + connect(&production, &ProductionService::stateChanged, + this, &DashboardPage::onProductionStateChanged); + connect(&production, &ProductionService::currentWorkpieceChanged, + this, &DashboardPage::onCurrentWorkpieceChanged); + connect(&production, &ProductionService::productionError, + this, &DashboardPage::onProductionError); + connect(&production, &ProductionService::productionFinished, + this, &DashboardPage::onProductionFinished); + connect(&production, &ProductionService::processElapsedChanged, + this, &DashboardPage::onProcessElapsedChanged); + connect(&production, &ProductionService::timeoutRecoveryRequired, + this, &DashboardPage::onTimeoutRecoveryRequired); + connect(&production, &ProductionService::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"); + } + + loadOrderOptions(); + DeviceService::instance().startPolling(); + processRefreshTimer->setInterval(1000); + connect(processRefreshTimer, &QTimer::timeout, + this, &DashboardPage::refreshProcessRecords); + processRefreshTimer->start(); + refreshProcessRecords(); +} + +DashboardPage::~DashboardPage() +{ + delete ui; +} + +void DashboardPage::addLog(const QString &type, const QString &module, const QString &content, + const QString &status) +{ + ui->recentLogTable->insertRow(0); + const QStringList values = QStringList() + << QDateTime::currentDateTime().toString("HH:mm:ss") + << type << module << content << status; + for (int col = 0; col < values.size(); ++col) { + ui->recentLogTable->setItem(0, col, new QTableWidgetItem(values.at(col))); + } + while (ui->recentLogTable->rowCount() > 8) { + ui->recentLogTable->removeRow(ui->recentLogTable->rowCount() - 1); + } +} + +void DashboardPage::resizeEvent(QResizeEvent *event) +{ + QWidget::resizeEvent(event); + updateRackSize(); +} + +void DashboardPage::updateRackSize() +{ + if (!rackBox || rackTrayCells.isEmpty()) { + return; + } + + const int spacing = 4; + const int leftMargin = 8; + const int rightMargin = 8; + const int topMargin = 18; + const int bottomMargin = 8; + const int maxRackHeight = qMax(150, ui->layoutGroup->height() / 3); + const int maxCellByHeight = (maxRackHeight - topMargin - bottomMargin - spacing) / 2; + const int maxCellByWidth = (ui->layoutGroup->width() - leftMargin - rightMargin - spacing * 2) / 3; + const int cellSide = qMax(52, qMin(maxCellByHeight, maxCellByWidth)); + const int rackWidth = leftMargin + rightMargin + cellSide * 3 + spacing * 2; + const int rackHeight = topMargin + bottomMargin + cellSide * 2 + spacing; + + for (QLabel *cell : rackTrayCells) { + cell->setFixedSize(cellSide, cellSide); + } + rackBox->setFixedSize(rackWidth, rackHeight); +} + +void DashboardPage::startProduction() +{ + int selectedOrderId = orderCombo->currentData().toInt(); + if (selectedOrderId <= 0) { + loadOrderOptions(); + selectedOrderId = orderCombo->currentData().toInt(); + } + if (selectedOrderId <= 0) { + QMessageBox::information(this, "Start production", + "No prepared order is available"); + 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"); + } +} + +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"); + } +} + +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"); + } +} + +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"); + } +} + +void DashboardPage::clearAlarm() +{ + QString error; + if (!DeviceService::instance().clearAlarm(&error)) { + QMessageBox::warning(this, "Clear alarm failed", error); + emit logRequested("Alarm log", "Dashboard", "Clear alarm", + error, "Failed"); + return; + } + if (!ProductionRepository().clearActiveAlarms( + QString(), "OPERATOR", &error)) { + QMessageBox::warning(this, "Clear alarm failed", error); + emit logRequested("Alarm log", "Dashboard", "Clear alarm", + error, "Failed"); + return; + } + emit logRequested("Alarm log", "Dashboard", "Clear alarm", + "PLC alarm clear command completed", "Success"); +} + +void DashboardPage::onOrderChanged(int) +{ + updateOrderSummary(); +} + +void DashboardPage::onProductionStateChanged(ProductionService::State, + const QString &name) +{ + ui->actionLabel->setText("Production state: " + name); + const ProductionService::State state = ProductionService::instance().state(); + Q_UNUSED(state); + updateRecoveryButtons(); + emit systemStateChanged(name); + emit currentStepChanged(name); + refreshProcessRecords(); + updateProductionStats(); +} + +void DashboardPage::onCurrentWorkpieceChanged(int workpieceId, + const QString &barcode) +{ + if (workpieceId <= 0) { + ui->workpieceLabel->setText("Current workpiece: -"); + currentProcessElapsedMs = 0; + } else { + ui->workpieceLabel->setText( + QString("Current workpiece: %1").arg(barcode)); + } + refreshProcessRecords(); + updateRecoveryButtons(); + updateProductionStats(); +} + +void DashboardPage::onProductionError(const QString &error) +{ + ui->actionLabel->setText("Production error: " + error); + emit systemStateChanged("ERROR"); + emit logRequested("Alarm log", "Production", "Production error", + error, "Failed"); +} + +void DashboardPage::onProductionFinished(int orderId) +{ + emit logRequested("Production log", "Production", "Order completed", + QString("Order %1 completed").arg(orderId), "Success"); + loadOrderOptions(); + updateProductionStats(); +} + +void DashboardPage::onProcessElapsedChanged(const QString &processStep, + int elapsedMs) +{ + currentProcessElapsedMs = elapsedMs; + currentProcessLabel->setText(processStep); + processElapsedLabel->setText(formatDuration(elapsedMs)); + updateCurrentProcessDuration(elapsedMs); +} + +void DashboardPage::onTimeoutRecoveryRequired(const QString &state, + const QString &message) +{ + ui->actionLabel->setText("Manual recovery required: " + message); + emit logRequested("Operation log", "Production", "Manual recovery", + state + ": " + message, "Pending"); +} + +void DashboardPage::onRecoveryCompleted(const QString &mode) +{ + emit logRequested("Production log", "Production", "Recovery completed", + mode, "Success"); +} + +void DashboardPage::recoverProduction() +{ + ProductionService &production = ProductionService::instance(); + QString error; + if (production.state() == ProductionService::ManualConfirm + && QMessageBox::question( + this, "Continue production", + "Continue only after confirming the equipment and current PLC step are safe?", + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) + != QMessageBox::Yes) { + return; + } + + const bool success = production.recover(&error); + if (!success) { + QMessageBox::warning(this, "Recovery failed", error); + emit logRequested("Operation log", "Production", "Manual recovery", + error, "Failed"); + } +} + +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"); + } +} + +void DashboardPage::markWorkpieceNg() +{ + if (QMessageBox::question( + this, "Mark workpiece NG", + "Mark the current workpiece as NG and continue with the next workpiece?", + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) + != QMessageBox::Yes) { + 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"); + } +} + +void DashboardPage::updateRecoveryButtons() +{ + const ProductionService::State state = ProductionService::instance().state(); + const bool recoveryRequired = state == ProductionService::TimeoutPaused + || state == ProductionService::ManualConfirm; + const bool running = state != ProductionService::Idle + && state != ProductionService::Completed; + recoverButton->setVisible(recoveryRequired); + retryButton->setVisible(recoveryRequired); + markNgButton->setVisible(recoveryRequired + && ProductionService::instance() + .currentWorkpiece().id > 0); + stopButton->setVisible(running); + recoverButton->setText(state == ProductionService::ManualConfirm + ? "Continue" : "Recover"); +} + +QString DashboardPage::formatDuration(int elapsedMs) +{ + const int totalSeconds = qMax(0, elapsedMs) / 1000; + const int hours = totalSeconds / 3600; + const int minutes = (totalSeconds % 3600) / 60; + const int seconds = totalSeconds % 60; + const int milliseconds = qMax(0, elapsedMs) % 1000; + return QString("%1:%2:%3.%4") + .arg(hours, 2, 10, QLatin1Char('0')) + .arg(minutes, 2, 10, QLatin1Char('0')) + .arg(seconds, 2, 10, QLatin1Char('0')) + .arg(milliseconds, 3, 10, QLatin1Char('0')); +} + +void DashboardPage::refreshProcessRecords() +{ + const Workpiece workpiece = ProductionService::instance().currentWorkpiece(); + if (workpiece.id <= 0) { + currentProcessLabel->setText("-"); + processElapsedLabel->setText(formatDuration(0)); + processTotalElapsedLabel->setText(formatDuration(0)); + processTable->setRowCount(0); + return; + } + + QString error; + const QList records = + ProductionRepository().listProcessRecords(workpiece.id, &error); + if (!error.isEmpty()) { + return; + } + + const QString currentStep = workpiece.processStep; + const qint64 nowMs = QDateTime::currentDateTime().toMSecsSinceEpoch(); + int totalElapsedMs = 0; + processTable->setRowCount(records.size()); + for (int row = 0; row < records.size(); ++row) { + const WorkpieceProcessRecord &record = records.at(row); + int durationMs = record.durationMs; + if (durationMs < 0 && record.startedAt.isValid()) { + if (record.processState == "RUNNING" + && record.processStep == currentStep + && currentProcessElapsedMs > 0) { + durationMs = currentProcessElapsedMs; + } else { + const qint64 elapsedMs = qMax( + 0, nowMs - record.startedAt.toMSecsSinceEpoch()); + durationMs = static_cast( + qMin(elapsedMs, 2147483647)); + } + } + if (durationMs >= 0) { + totalElapsedMs += durationMs; + } + + processTable->setItem(row, 0, + new QTableWidgetItem(record.processStep)); + processTable->setItem(row, 1, + new QTableWidgetItem(record.processState)); + processTable->setItem(row, 2, + new QTableWidgetItem( + QString::number(record.attemptNo))); + processTable->setItem(row, 3, + new QTableWidgetItem( + durationMs >= 0 + ? formatDuration(durationMs) : "-")); + } + + if (!currentStep.isEmpty()) { + currentProcessLabel->setText(currentStep); + } + processTotalElapsedLabel->setText(formatDuration(totalElapsedMs)); +} + +void DashboardPage::updateCurrentProcessDuration(int elapsedMs) +{ + const Workpiece workpiece = ProductionService::instance().currentWorkpiece(); + if (workpiece.id <= 0) { + return; + } + + for (int row = 0; row < processTable->rowCount(); ++row) { + QTableWidgetItem *stepItem = processTable->item(row, 0); + if (!stepItem || stepItem->text() != workpiece.processStep) { + continue; + } + QTableWidgetItem *statusItem = processTable->item(row, 1); + if (!statusItem || statusItem->text() != "RUNNING") { + continue; + } + processTable->setItem(row, 3, + new QTableWidgetItem(formatDuration(elapsedMs))); + break; + } +} + +void DashboardPage::onDeviceStatusChanged(const DeviceStatus &status) +{ + deviceStatusLabel->setText( + QString("PLC: %1 | Robot: %2 | Safety door: %3 | E-stop: %4") + .arg(status.plcConnected ? "ONLINE" : "OFFLINE") + .arg(status.robotReady ? "READY" : "NOT_READY") + .arg(status.safetyDoorClosed ? "CLOSED" : "OPEN") + .arg(status.emergencyStop ? "ACTIVE" : "CLEAR")); +} + +void DashboardPage::loadOrderOptions() +{ + QString error; + const QList orders = OrderService::instance().listOrders(&error); + if (!error.isEmpty()) { + orderCombo->clear(); + orderCombo->addItem("No order data", 0); + emit logRequested("Operation log", "Dashboard", "Load orders", + error, "Failed"); + return; + } + + const int previousOrderId = orderCombo->currentData().toInt(); + QSignalBlocker blocker(orderCombo); + orderCombo->clear(); + for (const Order &order : orders) { + if (order.status != "NOT_START") { + continue; + } + + QString workpieceError; + const QList workpieces = + WorkpieceService::instance().listByOrder(order.id, &workpieceError); + if (!workpieceError.isEmpty() || workpieces.isEmpty()) { + continue; + } + orderCombo->addItem(order.no, order.id); + } + + if (orderCombo->count() == 0) { + orderCombo->addItem("No prepared order", 0); + } else { + const int previousIndex = orderCombo->findData(previousOrderId); + orderCombo->setCurrentIndex(previousIndex >= 0 ? previousIndex : 0); + } + updateOrderSummary(); +} + +void DashboardPage::updateOrderSummary() +{ + const int selectedOrderId = orderCombo->currentData().toInt(); + if (selectedOrderId <= 0) { + ui->orderLabel->setText("Current order: -"); + ui->trayLabel->setText("Current tray: -"); + ui->workpieceLabel->setText("Current workpiece: -"); + updateProductionStats(); + return; + } + + Order order; + QString error; + if (!OrderService::instance().findOrder(selectedOrderId, &order, &error)) { + ui->orderLabel->setText("Current order: -"); + return; + } + ui->orderLabel->setText("Current order: " + order.no); + updateProductionStats(); +} + +void DashboardPage::updateProductionStats() +{ + const int selectedOrderId = orderCombo->currentData().toInt(); + if (selectedOrderId <= 0) { + ui->planValue->setText("0"); + ui->pendingValue->setText("0"); + ui->frontValue->setText("0"); + ui->backValue->setText("0"); + ui->okValue->setText("0"); + ui->ngValue->setText("0"); + return; + } + + Order order; + QString error; + if (!OrderService::instance().findOrder(selectedOrderId, &order, &error)) { + return; + } + const QList workpieces = + WorkpieceService::instance().listByOrder(selectedOrderId, &error); + if (!error.isEmpty()) { + return; + } + + int pending = 0; + int frontChecking = 0; + int backChecking = 0; + int ok = 0; + int ng = 0; + for (const Workpiece &workpiece : workpieces) { + if (workpiece.state == "PENDING") { + ++pending; + } else if (workpiece.processStep == "FRONT_CHECKING") { + ++frontChecking; + } else if (workpiece.processStep == "BACK_CHECKING") { + ++backChecking; + } else if (workpiece.state == "OK") { + ++ok; + } else if (workpiece.state == "NG") { + ++ng; + } + } + + ui->planValue->setText(QString::number(order.planNum)); + ui->pendingValue->setText(QString::number(pending)); + ui->frontValue->setText(QString::number(frontChecking)); + ui->backValue->setText(QString::number(backChecking)); + ui->okValue->setText(QString::number(ok)); + ui->ngValue->setText(QString::number(ng)); +} diff --git a/pages/dashboardpage.h b/pages/dashboardpage.h new file mode 100644 index 0000000..41d0bab --- /dev/null +++ b/pages/dashboardpage.h @@ -0,0 +1,86 @@ +#ifndef DASHBOARDPAGE_H +#define DASHBOARDPAGE_H + +#include "../services/productionservice.h" + +#include +#include + +class QComboBox; +class QTableWidget; +class QGroupBox; +class QResizeEvent; +class QLabel; +class QPushButton; +class QTimer; + +namespace Ui { class DashboardPage; } + +class DashboardPage : public QWidget +{ + Q_OBJECT + +public: + explicit DashboardPage(QWidget *parent = nullptr); + ~DashboardPage(); + void addLog(const QString &type, const QString &module, const QString &content, + const QString &status); + +signals: + void systemStateChanged(const QString &state); + void currentStepChanged(const QString &step); + void logRequested(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status); + +private slots: + void startProduction(); + void pauseProduction(); + void stopProduction(); + void resetProduction(); + void clearAlarm(); + void onOrderChanged(int index); + void onProductionStateChanged(ProductionService::State state, + const QString &name); + void onCurrentWorkpieceChanged(int workpieceId, const QString &barcode); + void onProductionError(const QString &error); + void onProductionFinished(int orderId); + void onDeviceStatusChanged(const DeviceStatus &status); + void onProcessElapsedChanged(const QString &processStep, int elapsedMs); + void onTimeoutRecoveryRequired(const QString &state, const QString &message); + void onRecoveryCompleted(const QString &mode); + void recoverProduction(); + void retryRecovery(); + void markWorkpieceNg(); + +protected: + void resizeEvent(QResizeEvent *event) override; + +private: + void loadOrderOptions(); + void updateOrderSummary(); + void updateProductionStats(); + void updateRackSize(); + void updateRecoveryButtons(); + void refreshProcessRecords(); + void updateCurrentProcessDuration(int elapsedMs); + static QString formatDuration(int elapsedMs); + + Ui::DashboardPage *ui; + QComboBox *orderCombo; + QGroupBox *rackBox; + QVector rackTrayCells; + QLabel *deviceStatusLabel; + QPushButton *recoverButton; + QPushButton *retryButton; + QPushButton *markNgButton; + QPushButton *stopButton; + QGroupBox *processBox; + QLabel *currentProcessLabel; + QLabel *processElapsedLabel; + QLabel *processTotalElapsedLabel; + QTableWidget *processTable; + QTimer *processRefreshTimer; + int currentProcessElapsedMs; +}; + +#endif // DASHBOARDPAGE_H diff --git a/pages/dashboardpage.ui b/pages/dashboardpage.ui new file mode 100644 index 0000000..c6028ee --- /dev/null +++ b/pages/dashboardpage.ui @@ -0,0 +1,137 @@ + + + DashboardPage + + + + 0 + 0 + 1024 + 720 + + + + + 14 + + + 14 + + + 14 + + + 14 + + + 12 + + + + + + + QFrame::StyledPanel + + + 计划数量 + 294Qt::AlignCenter + + + + + + + QFrame::StyledPanel + + + 待检测 + 286Qt::AlignCenter + + + + + + + QFrame::StyledPanel + + + 正面检测 + 5Qt::AlignCenter + + + + + + + QFrame::StyledPanel + + + 反面检测 + 3Qt::AlignCenter + + + + + + + QFrame::StyledPanel + + + OK + 2Qt::AlignCenter + + + + + + + QFrame::StyledPanel + + + NG + 1Qt::AlignCenter + + + + + + + + + + 设备布局示意 + + + + + + 当前任务 + + 订单编号:ORD-20260808-001 + 当前托盘:托盘 1 + 当前工件:第 1 行第 1 列 + 动作说明:等待人工启动单元检测程序 + + + 启动 + 暂停 + 复位 + 模拟下一步 + 清除报警 + + + Qt::Vertical2040 + + + + + + + + + + + + + diff --git a/pages/devicepage.cpp b/pages/devicepage.cpp new file mode 100644 index 0000000..ed1eaa9 --- /dev/null +++ b/pages/devicepage.cpp @@ -0,0 +1,105 @@ +#include "devicepage.h" +#include "ui_devicepage.h" + +#include "../services/deviceservice.h" + +#include +#include +#include +#include +#include +#include + +DevicePage::DevicePage(QWidget *parent) + : QWidget(parent) + , ui(new Ui::DevicePage) +{ + ui->setupUi(this); + + setupTable(); + connect(&DeviceService::instance(), &DeviceService::statusChanged, + this, &DevicePage::updateStatus); + connect(&DeviceService::instance(), &DeviceService::communicationError, + this, &DevicePage::handleCommunicationError); + DeviceService::instance().startPolling(); +} + +void DevicePage::setupTable() +{ + QTableWidget *table = ui->deviceTable; + table->setColumnCount(5); + table->setHorizontalHeaderLabels(QStringList() + << "设备/信号" << "连接状态" << "运行状态" << "当前动作" << "最后更新时间"); + table->horizontalHeader()->setStretchLastSection(true); + table->verticalHeader()->setVisible(false); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + table->setAlternatingRowColors(true); + + const QStringList names = QStringList() + << "PLC" << "上下料机器人" << "检测机" << "视觉引导系统" + << "总控柜" << "机器人控制柜" << "安全门 1" << "安全门 2" + << "安全门 3" << "急停"; + table->setRowCount(names.size()); + for (int row = 0; row < names.size(); ++row) { + table->setItem(row, 0, new QTableWidgetItem(names.at(row))); + } +} + +void DevicePage::setRow(int row, const QStringList &values) +{ + QTableWidget *table = ui->deviceTable; + for (int column = 0; column < values.size(); ++column) { + QTableWidgetItem *item = table->item(row, column); + if (!item) { + item = new QTableWidgetItem; + table->setItem(row, column, item); + } + item->setText(values.at(column)); + } +} + +void DevicePage::updateStatus(const DeviceStatus &status) +{ + const QString connection = status.plcConnected ? "在线" : "离线"; + const QString plcState = status.plcReady ? "就绪" : "未就绪"; + const QString robotState = status.robotReady ? "就绪" : "未就绪"; + const QString safetyState = status.safetyDoorClosed ? "关闭" : "打开"; + const QString emergencyState = status.emergencyStop ? "已触发" : "未触发"; + const QString now = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"); + + setRow(0, QStringList() << "PLC" << connection << plcState + << QString("当前工序 %1").arg(status.currentStep) << now); + setRow(1, QStringList() << "上下料机器人" << connection << robotState + << (status.robotReady ? "等待取料" : "等待就绪") << now); + setRow(2, QStringList() << "检测机" << connection + << (status.plcConnected ? "待机" : "离线") + << QString("检测结果 %1").arg(status.checkResult) << now); + setRow(3, QStringList() << "视觉引导系统" << connection + << (status.plcConnected ? "待机" : "离线") + << "等待拍照" << now); + setRow(4, QStringList() << "总控柜" << connection + << (status.plcConnected ? "正常" : "离线") + << "供电状态由 PLC 提供" << now); + setRow(5, QStringList() << "机器人控制柜" << connection + << (status.robotReady ? "正常" : "未就绪") + << "等待机器人状态" << now); + setRow(6, QStringList() << "安全门 1" << connection << safetyState + << (status.safetyDoorClosed ? "互锁正常" : "请关闭安全门") << now); + setRow(7, QStringList() << "安全门 2" << connection << safetyState + << (status.safetyDoorClosed ? "互锁正常" : "请关闭安全门") << now); + setRow(8, QStringList() << "安全门 3" << connection << safetyState + << (status.safetyDoorClosed ? "互锁正常" : "请关闭安全门") << now); + setRow(9, QStringList() << "急停" << connection << emergencyState + << (status.emergencyStop ? "安全回路断开" : "安全回路正常") << now); +} + +void DevicePage::handleCommunicationError(const QString &error) +{ + qWarning() << "Device communication error:" << error; +} + +DevicePage::~DevicePage() +{ + DeviceService::instance().stopPolling(); + delete ui; +} diff --git a/pages/devicepage.h b/pages/devicepage.h new file mode 100644 index 0000000..122a470 --- /dev/null +++ b/pages/devicepage.h @@ -0,0 +1,29 @@ +#ifndef DEVICEPAGE_H +#define DEVICEPAGE_H + +#include + +#include "../services/deviceservice.h" + +namespace Ui { class DevicePage; } + +class DevicePage : public QWidget +{ + Q_OBJECT + +public: + explicit DevicePage(QWidget *parent = nullptr); + ~DevicePage(); + +private slots: + void updateStatus(const DeviceStatus &status); + void handleCommunicationError(const QString &error); + +private: + void setupTable(); + void setRow(int row, const QStringList &values); + + Ui::DevicePage *ui; +}; + +#endif // DEVICEPAGE_H diff --git a/pages/devicepage.ui b/pages/devicepage.ui new file mode 100644 index 0000000..9d1d58f --- /dev/null +++ b/pages/devicepage.ui @@ -0,0 +1,15 @@ + + + DevicePage + + + 14 + 14 + 14 + 14 + + + + + + diff --git a/pages/logpage.cpp b/pages/logpage.cpp new file mode 100644 index 0000000..41df34c --- /dev/null +++ b/pages/logpage.cpp @@ -0,0 +1,72 @@ +#include "logpage.h" +#include "ui_logpage.h" + +#include "../models/logrecord.h" +#include "../repositories/logrepository.h" + +#include +#include +#include +#include +#include +#include + +LogPage::LogPage(QWidget *parent) + : QWidget(parent) + , ui(new Ui::LogPage) +{ + ui->setupUi(this); + + ui->logTable->setColumnCount(6); + ui->logTable->setHorizontalHeaderLabels(QStringList() << "时间" << "类型" << "模块" << "动作" << "内容" << "状态"); + ui->logTable->horizontalHeader()->setStretchLastSection(true); + ui->logTable->verticalHeader()->setVisible(false); + ui->logTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui->logTable->setAlternatingRowColors(true); + + loadLogs(); +} + +LogPage::~LogPage() +{ + delete ui; +} + +void LogPage::addLog(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status) +{ + addLogRow(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"), + type, module, action, content, status); +} + +void LogPage::loadLogs() +{ + QString error; + LogRepository repository; + const QList records = repository.listLogs(&error); + if (!error.isEmpty()) { + qWarning() << "Failed to load operation logs:" << error; + return; + } + + ui->logTable->setRowCount(0); + for (int index = records.size() - 1; index >= 0; --index) { + const LogRecord &record = records.at(index); + const QString time = record.createdAt.isValid() + ? record.createdAt.toString("yyyy-MM-dd HH:mm:ss") + : "-"; + addLogRow(time, record.type, record.module, record.action, + record.content, record.status); + } +} + +void LogPage::addLogRow(const QString &time, const QString &type, const QString &module, + const QString &action, const QString &content, const QString &status) +{ + ui->logTable->insertRow(0); + const QStringList values = QStringList() + << time << type << module << action << content << status; + for (int col = 0; col < values.size(); ++col) { + ui->logTable->setItem(0, col, new QTableWidgetItem(values.at(col))); + } +} diff --git a/pages/logpage.h b/pages/logpage.h new file mode 100644 index 0000000..ae08c97 --- /dev/null +++ b/pages/logpage.h @@ -0,0 +1,28 @@ +#ifndef LOGPAGE_H +#define LOGPAGE_H + +#include + +class QTableWidget; + +namespace Ui { class LogPage; } + +class LogPage : public QWidget +{ + Q_OBJECT + +public: + explicit LogPage(QWidget *parent = nullptr); + ~LogPage(); + void addLog(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status); + +private: + void loadLogs(); + void addLogRow(const QString &time, const QString &type, const QString &module, + const QString &action, const QString &content, const QString &status); + + Ui::LogPage *ui; +}; + +#endif // LOGPAGE_H diff --git a/pages/logpage.ui b/pages/logpage.ui new file mode 100644 index 0000000..47686cc --- /dev/null +++ b/pages/logpage.ui @@ -0,0 +1,25 @@ + + + LogPage + + + 14 + 14 + 14 + 14 + + + 日志类型: + 全部 + 关键字: + + 查询 + Qt::Horizontal4020 + + + + + + + + diff --git a/pages/orderpage.cpp b/pages/orderpage.cpp new file mode 100644 index 0000000..29920c0 --- /dev/null +++ b/pages/orderpage.cpp @@ -0,0 +1,233 @@ +#include "orderpage.h" +#include "ui_orderpage.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +OrderPage::OrderPage(QWidget *parent) + : QWidget(parent) + , ui(new Ui::OrderPage) +{ + ui->setupUi(this); + + ui->newButton->setObjectName("primaryButton"); + ui->deleteButton->setObjectName("dangerButton"); + QPushButton *generateButton = new QPushButton("生成工件", this); + ui->toolbarLayout->insertWidget(5, generateButton); + + QTableWidget *table = ui->orderTable; + table->setColumnCount(11); + table->setHorizontalHeaderLabels(QStringList() + << "订单编号" << "生产号" << "图纸号" << "批次号" << "计划" + << "OK" << "NG" << "状态" << "开始时间" << "结束时间" << "备注"); + table->horizontalHeader()->setStretchLastSection(true); + table->verticalHeader()->setVisible(false); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + table->setAlternatingRowColors(true); + + connect(ui->newButton, &QPushButton::clicked, this, &OrderPage::createOrder); + connect(ui->refreshButton, &QPushButton::clicked, this, &OrderPage::loadOrders); + connect(generateButton, &QPushButton::clicked, + this, &OrderPage::generateSelectedWorkpieces); + connect(ui->deleteButton, &QPushButton::clicked, this, &OrderPage::deleteSelectedOrder); + + loadOrders(); +} + +OrderPage::~OrderPage() +{ + delete ui; +} + +void OrderPage::loadOrders() +{ + QString error; + const QList orders = OrderService::instance().listOrders(&error); + if (!error.isEmpty()) { + QMessageBox::warning(this, "读取订单失败", error); + emit logRequested("操作日志", "订单管理", "刷新订单", error, "失败"); + return; + } + + fillOrderTable(orders); + emit logRequested("操作日志", "订单管理", "刷新订单", "读取订单列表", "成功"); +} + +void OrderPage::fillOrderTable(const QList &orders) +{ + QTableWidget *table = ui->orderTable; + table->setRowCount(0); + orderIds.clear(); + + for (const Order &order : orders) { + const int row = table->rowCount(); + table->insertRow(row); + orderIds.append(order.id); + + const QString beginTime = order.beginTime.isValid() + ? order.beginTime.toString("yyyy-MM-dd HH:mm:ss") : "-"; + const QString endTime = order.endTime.isValid() + ? order.endTime.toString("yyyy-MM-dd HH:mm:ss") : "-"; + const QStringList values = QStringList() + << order.no + << order.productionNo + << order.drawingNo + << order.batchNo + << QString::number(order.planNum) + << QString::number(order.qualified) + << QString::number(order.unqualified) + << order.status + << beginTime + << endTime + << order.remark; + + for (int col = 0; col < values.size(); ++col) { + table->setItem(row, col, new QTableWidgetItem(values.at(col))); + } + } + + if (orders.isEmpty()) { + ui->currentOrderLabel->setText("当前订单:-"); + ui->progressLabel->setText("当前进度:0 / 0"); + ui->currentStepLabel->setText("当前工序:-"); + ui->memoLabel->setText("说明:暂无订单"); + return; + } + + const Order &first = orders.first(); + ui->currentOrderLabel->setText("当前订单:" + first.no); + ui->progressLabel->setText(QString("当前进度:%1 / %2") + .arg(first.qualified + first.unqualified) + .arg(first.planNum)); + ui->currentStepLabel->setText("当前工序:" + first.status); + ui->memoLabel->setText("说明:" + first.remark); +} + +void OrderPage::createOrder() +{ + QDialog dialog(this); + dialog.setWindowTitle("新建订单"); + + QLineEdit *noEdit = new QLineEdit(ui->orderNoEdit->text().trimmed(), &dialog); + QLineEdit *productionNoEdit = new QLineEdit(&dialog); + QLineEdit *drawingNoEdit = new QLineEdit(&dialog); + QLineEdit *batchNoEdit = new QLineEdit(&dialog); + QSpinBox *planNumSpin = new QSpinBox(&dialog); + QTextEdit *remarkEdit = new QTextEdit(&dialog); + + planNumSpin->setRange(1, 999999); + planNumSpin->setValue(49); + remarkEdit->setFixedHeight(70); + + QFormLayout *formLayout = new QFormLayout; + formLayout->addRow("订单编号:", noEdit); + formLayout->addRow("生产号:", productionNoEdit); + formLayout->addRow("图纸号:", drawingNoEdit); + formLayout->addRow("批次号:", batchNoEdit); + formLayout->addRow("计划数量:", planNumSpin); + formLayout->addRow("备注:", remarkEdit); + + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, + &dialog); + QVBoxLayout *layout = new QVBoxLayout(&dialog); + layout->addLayout(formLayout); + layout->addWidget(buttons); + + connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + + if (dialog.exec() != QDialog::Accepted) { + return; + } + + Order order; + order.no = noEdit->text().trimmed(); + order.productionNo = productionNoEdit->text().trimmed(); + order.drawingNo = drawingNoEdit->text().trimmed(); + order.batchNo = batchNoEdit->text().trimmed(); + order.planNum = planNumSpin->value(); + order.status = "NOT_START"; + order.remark = remarkEdit->toPlainText().trimmed(); + + if (order.no.isEmpty()) { + QMessageBox::warning(this, "新建订单失败", "订单编号不能为空"); + return; + } + + QString error; + if (!OrderService::instance().createOrder(&order, &error)) { + QMessageBox::warning(this, "新建订单失败", error); + emit logRequested("操作日志", "订单管理", "新建订单", error, "失败"); + return; + } + + loadOrders(); + emit logRequested("操作日志", "订单管理", "新建订单", + "创建订单:" + order.no, "成功"); +} + +void OrderPage::generateSelectedWorkpieces() +{ + const int row = ui->orderTable->currentRow(); + if (row < 0 || row >= orderIds.size()) { + QMessageBox::information(this, "生成工件", "请先选择要生成工件的订单"); + return; + } + + const QString orderNo = ui->orderTable->item(row, 0) + ? ui->orderTable->item(row, 0)->text() : QString::number(orderIds.at(row)); + if (QMessageBox::question(this, "生成工件", + "确认生成并分配订单 " + orderNo + " 的工件?") + != QMessageBox::Yes) { + return; + } + + QString error; + if (!OrderService::instance().generateWorkpiecesAndAssign(orderIds.at(row), &error)) { + QMessageBox::warning(this, "生成工件失败", error); + emit logRequested("鎿嶄綔鏃ュ織", "璁㈠崟绠$悊", "生成工件", error, "澶辫触"); + return; + } + + loadOrders(); + emit logRequested("鎿嶄綔鏃ュ織", "璁㈠崟绠$悊", "生成工件", + "生成并分配订单 " + orderNo + " 的工件", "鎴愬姛"); +} + +void OrderPage::deleteSelectedOrder() +{ + const int row = ui->orderTable->currentRow(); + if (row < 0 || row >= orderIds.size()) { + QMessageBox::information(this, "删除订单", "请先选择要删除的订单"); + return; + } + + const QString orderNo = ui->orderTable->item(row, 0) + ? ui->orderTable->item(row, 0)->text() : QString::number(orderIds.at(row)); + if (QMessageBox::question(this, "删除订单", + "确认删除订单:" + orderNo + "?") != QMessageBox::Yes) { + return; + } + + QString error; + if (!OrderService::instance().deleteOrder(orderIds.at(row), &error)) { + QMessageBox::warning(this, "删除订单失败", error); + emit logRequested("操作日志", "订单管理", "删除订单", error, "失败"); + return; + } + + loadOrders(); + emit logRequested("操作日志", "订单管理", "删除订单", + "删除订单:" + orderNo, "成功"); +} diff --git a/pages/orderpage.h b/pages/orderpage.h new file mode 100644 index 0000000..d4b4e53 --- /dev/null +++ b/pages/orderpage.h @@ -0,0 +1,34 @@ +#ifndef ORDERPAGE_H +#define ORDERPAGE_H + +#include "../services/orderservice.h" + +#include +#include + +namespace Ui { class OrderPage; } + +class OrderPage : public QWidget +{ + Q_OBJECT + +public: + explicit OrderPage(QWidget *parent = nullptr); + ~OrderPage(); + +signals: + void logRequested(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status); + +private: + void loadOrders(); + void fillOrderTable(const QList &orders); + void createOrder(); + void generateSelectedWorkpieces(); + void deleteSelectedOrder(); + + Ui::OrderPage *ui; + QVector orderIds; +}; + +#endif // ORDERPAGE_H diff --git a/pages/orderpage.ui b/pages/orderpage.ui new file mode 100644 index 0000000..62beaae --- /dev/null +++ b/pages/orderpage.ui @@ -0,0 +1,38 @@ + + + OrderPage + + + 14 + 14 + 14 + 14 + + + 订单编号: + ORD-20260808-001 + 状态: + 全部 + 新建订单 + 刷新 + 删除 + Qt::Horizontal4020 + + + + + + 订单详情 + + 当前订单:ORD-20260808-001 + 当前进度:3 / 294 + 当前工序:正面检测 + 说明:第一版仅展示页面,不保存数据 + + + + + + + + diff --git a/pages/rackpage.cpp b/pages/rackpage.cpp new file mode 100644 index 0000000..0606246 --- /dev/null +++ b/pages/rackpage.cpp @@ -0,0 +1,245 @@ +#include "rackpage.h" +#include "ui_rackpage.h" + +#include "squaretraybutton.h" +#include "uihelpers.h" + +#include "../services/trayservice.h" + +#include +#include +#include +#include +#include +#include +#include + +RackPage::RackPage(QWidget *parent) + : QWidget(parent) + , ui(new Ui::RackPage) + , rackButtonGroup(new QButtonGroup(this)) + , selectedTrayId(0) + , selectedTrayIndex(0) +{ + ui->setupUi(this); + + ui->mainLayout->setStretch(0, 1); + ui->mainLayout->setStretch(1, 1); + ui->rackGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + ui->trayGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + + ui->rackGridLayout->setContentsMargins(8, 18, 8, 8); + ui->rackGridLayout->setSpacing(4); + ui->rackGridLayout->setAlignment(Qt::AlignCenter); + rackButtonGroup->setExclusive(true); + for (int i = 0; i < 6; ++i) { + SquareTrayButton *trayButton = new SquareTrayButton(i, 0, this); + rackTrayButtons.append(trayButton); + rackButtonGroup->addButton(trayButton, i); + ui->rackGridLayout->addWidget(trayButton, i / 3, i % 3, Qt::AlignCenter); + connect(trayButton, &QAbstractButton::clicked, this, [this, i]() { + showTrayDetail(i); + }); + } + + ui->trayGridLayout->setContentsMargins(8, 8, 8, 8); + ui->trayGridLayout->setSpacing(4); + ui->trayGridLayout->setAlignment(Qt::AlignHCenter | Qt::AlignTop); + ui->trayOuterLayout->setStretch(0, 0); + ui->trayOuterLayout->setStretch(1, 1); + ui->trayOuterLayout->setStretch(2, 0); + ui->trayOuterLayout->setStretch(3, 0); + for (int r = 0; r < 7; ++r) { + for (int c = 0; c < 7; ++c) { + QLabel *cell = UiHelpers::makeSquareStatusCell(QString("%1-%2").arg(r + 1).arg(c + 1), "#78909c"); + trayCells.append(cell); + ui->trayGridLayout->addWidget(cell, r, c, Qt::AlignCenter); + } + } + + setupLegend(); + loadTrays(); + updateCellSizes(); +} + +RackPage::~RackPage() +{ + delete ui; +} + +void RackPage::setupLegend() +{ + ui->pendingLegend->setStyleSheet("QLabel { color: white; background: #f9a825; border-radius: 4px; padding: 4px 10px; }"); + ui->frontLegend->setStyleSheet("QLabel { color: white; background: #1e88e5; border-radius: 4px; padding: 4px 10px; }"); + ui->backLegend->setStyleSheet("QLabel { color: white; background: #8e24aa; border-radius: 4px; padding: 4px 10px; }"); + ui->okLegend->setStyleSheet("QLabel { color: white; background: #2e7d32; border-radius: 4px; padding: 4px 10px; }"); + ui->ngLegend->setStyleSheet("QLabel { color: white; background: #d32f2f; border-radius: 4px; padding: 4px 10px; }"); + ui->emptyLegend->setStyleSheet("QLabel { color: white; background: #90a4ae; border-radius: 4px; padding: 4px 10px; }"); +} + +void RackPage::resizeEvent(QResizeEvent *event) +{ + QWidget::resizeEvent(event); + updateCellSizes(); +} + +void RackPage::updateCellSizes() +{ + const int rackSpacing = ui->rackGridLayout->spacing(); + const int rackSide = qMax(70, qMin((ui->rackGroup->width() - 24 - rackSpacing * 2) / 3, + (ui->rackGroup->height() - 34 - rackSpacing) / 2)); + for (SquareTrayButton *button : rackTrayButtons) { + button->setFixedSize(rackSide, rackSide); + } + + const int detailSpacing = ui->trayGridLayout->spacing(); + const int detailAvailableSide = qMin((ui->trayGroup->width() - 32 - detailSpacing * 6) / 7, + (ui->trayGroup->height() - 100 - detailSpacing * 6) / 7); + const int detailSide = qMax(24, qMin(42, detailAvailableSide)); + for (QLabel *cell : trayCells) { + cell->setFixedSize(detailSide, detailSide); + } +} + +void RackPage::loadTrays() +{ + QString error; + if (!TrayService::instance().ensureAllTrayGrids(&error)) { + trays.clear(); + updateTrayButtons(); + updateTrayCells(QList()); + ui->trayDetailTitle->setText("暂无托盘数据"); + emit logRequested("操作日志", "料架/托盘", "加载托盘", error, "失败"); + qWarning() << "Failed to initialize tray grids:" << error; + return; + } + + trays = TrayService::instance().listTrays(&error); + if (!error.isEmpty()) { + trays.clear(); + updateTrayButtons(); + updateTrayCells(QList()); + ui->trayDetailTitle->setText("暂无托盘数据"); + emit logRequested("操作日志", "料架/托盘", "加载托盘", error, "失败"); + qWarning() << "Failed to load trays:" << error; + return; + } + + updateTrayButtons(); + if (trays.isEmpty()) { + selectedTrayId = 0; + selectedTrayIndex = -1; + ui->trayDetailTitle->setText("暂无托盘数据"); + updateTrayCells(QList()); + return; + } + + selectedTrayIndex = qBound(0, selectedTrayIndex, trays.size() - 1); + showTrayDetail(selectedTrayIndex); +} + +void RackPage::updateTrayButtons() +{ + for (int index = 0; index < rackTrayButtons.size(); ++index) { + SquareTrayButton *button = rackTrayButtons.at(index); + if (index >= trays.size()) { + button->setTrayInfo(0, QString(), 0, "无数据", false); + button->setChecked(false); + continue; + } + + const Tray &tray = trays.at(index); + button->setTrayInfo(tray.id, tray.code, tray.loadedCount, + tray.status, tray.present); + button->setChecked(index == selectedTrayIndex); + } +} + +void RackPage::updateTrayCells(const QList &traySlots) +{ + const QStringList colors = QStringList() + << "#90a4ae" << "#f9a825" << "#1e88e5" << "#8e24aa" + << "#2e7d32" << "#d32f2f" << "#ef6c00"; + const QStringList names = QStringList() + << "空" << "待" << "正检" << "反检" << "OK" << "NG" << "异常"; + + for (int index = 0; index < trayCells.size(); ++index) { + const int rowNo = index / 7 + 1; + const int columnNo = index % 7 + 1; + const TraySlot *slot = nullptr; + for (const TraySlot &candidate : traySlots) { + if (candidate.rowNo == rowNo && candidate.columnNo == columnNo) { + slot = &candidate; + break; + } + } + + QString state = "EMPTY"; + int workpieceId = 0; + if (slot) { + state = slot->state; + workpieceId = slot->workpieceId; + } + + int stateIndex = 0; + if (state == "PENDING") { + stateIndex = 1; + } else if (state == "FRONT_CHECKING") { + stateIndex = 2; + } else if (state == "BACK_CHECKING") { + stateIndex = 3; + } else if (state == "OK") { + stateIndex = 4; + } else if (state == "NG") { + stateIndex = 5; + } else if (state == "ERROR" || state == "PROCESSING") { + stateIndex = 6; + } + + const QString workpieceText = workpieceId > 0 + ? QString("工件 %1").arg(workpieceId) : QString(); + trayCells.at(index)->setText(QString("%1-%2\n%3%4") + .arg(rowNo) + .arg(columnNo) + .arg(names.at(stateIndex)) + .arg(workpieceText.isEmpty() ? QString() + : "\n" + workpieceText)); + trayCells.at(index)->setStyleSheet( + QString("QLabel { background: %1; border: 1px solid #ffffff; " + "border-radius: 3px; color: white; font-size: 11px; }") + .arg(colors.at(stateIndex))); + } +} + +void RackPage::showTrayDetail(int trayIndex) +{ + if (trayIndex < 0 || trayIndex >= trays.size()) { + selectedTrayId = 0; + selectedTrayIndex = -1; + ui->trayDetailTitle->setText("暂无托盘数据"); + updateTrayCells(QList()); + return; + } + + selectedTrayIndex = trayIndex; + selectedTrayId = trays.at(trayIndex).id; + if (trayIndex < rackTrayButtons.size()) { + rackTrayButtons.at(trayIndex)->setChecked(true); + } + const Tray &tray = trays.at(trayIndex); + ui->trayDetailTitle->setText(QString("%1:7 行 x 7 列").arg(tray.code)); + + QString error; + const QList loadedSlots = TrayService::instance().listSlots(selectedTrayId, &error); + if (!error.isEmpty()) { + updateTrayCells(QList()); + emit logRequested("操作日志", "料架/托盘", "查看托盘", error, "失败"); + qWarning() << "Failed to load tray slots:" << error; + return; + } + + updateTrayCells(loadedSlots); + emit logRequested("操作日志", "料架/托盘", "查看托盘", + QString("查看托盘 %1 的 7x7 工件状态").arg(tray.code), "成功"); + updateCellSizes(); +} diff --git a/pages/rackpage.h b/pages/rackpage.h new file mode 100644 index 0000000..79e0e12 --- /dev/null +++ b/pages/rackpage.h @@ -0,0 +1,50 @@ +#ifndef RACKPAGE_H +#define RACKPAGE_H + +#include "../models/tray.h" + +#include +#include +#include + +class QLabel; +class QButtonGroup; +class QResizeEvent; +class SquareTrayButton; + +namespace Ui { class RackPage; } + +class RackPage : public QWidget +{ + Q_OBJECT + +public: + explicit RackPage(QWidget *parent = nullptr); + ~RackPage(); + +signals: + void logRequested(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status); + +private: + void loadTrays(); + void showTrayDetail(int trayIndex); + void setupLegend(); + void updateCellSizes(); + void updateTrayButtons(); + void updateTrayCells(const QList &traySlots); + +protected: + void resizeEvent(QResizeEvent *event) override; + +private: + Ui::RackPage *ui; + QButtonGroup *rackButtonGroup; + QVector rackTrayButtons; + QVector trayCells; + QList trays; + int selectedTrayId; + int selectedTrayIndex; +}; + +#endif // RACKPAGE_H diff --git a/pages/rackpage.ui b/pages/rackpage.ui new file mode 100644 index 0000000..23ab5b0 --- /dev/null +++ b/pages/rackpage.ui @@ -0,0 +1,41 @@ + + + RackPage + + + 14 + 14 + 14 + 14 + 12 + + + 固定料架:2 行 x 3 列,最多 6 个托盘 + + + + + + 托盘详情 + + 托盘 1:7 行 x 7 列 + + + + 待检测Qt::AlignCenter + 正面检测Qt::AlignCenter + 反面检测Qt::AlignCenter + OKQt::AlignCenter + NGQt::AlignCenter + 空位Qt::AlignCenter + + + Qt::Vertical2040 + + + + + + + + diff --git a/pages/squaretraybutton.cpp b/pages/squaretraybutton.cpp new file mode 100644 index 0000000..7487354 --- /dev/null +++ b/pages/squaretraybutton.cpp @@ -0,0 +1,60 @@ +#include "squaretraybutton.h" + +#include +#include + +SquareTrayButton::SquareTrayButton(int trayIndex, int loadedCount, QWidget *parent) + : QAbstractButton(parent) + , m_trayId(0) +{ + setCheckable(true); + setCursor(Qt::PointingHandCursor); + setText(QString("托盘 %1\n7 x 7\n已装 %2/49").arg(trayIndex + 1).arg(loadedCount)); +} + +void SquareTrayButton::setTrayInfo(int trayId, const QString &code, int loadedCount, + const QString &status, bool present) +{ + m_trayId = trayId; + const QString displayCode = code.isEmpty() ? QString("托盘 %1").arg(trayId) : code; + const QString displayStatus = present ? status : "离位"; + setText(QString("%1\n7 x 7\n%2 %3/49") + .arg(displayCode) + .arg(displayStatus) + .arg(loadedCount)); + setEnabled(present); + update(); +} + +QSize SquareTrayButton::sizeHint() const +{ + return QSize(120, 120); +} + +QSize SquareTrayButton::minimumSizeHint() const +{ + return QSize(70, 70); +} + +void SquareTrayButton::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + + QPainter painter(this); + 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 textColor = isChecked() ? QColor("#ffffff") : QColor("#263238"); + + painter.setPen(QPen(border, 2)); + painter.setBrush(background); + painter.drawRoundedRect(rect, 6, 6); + + QFont font = painter.font(); + font.setBold(isChecked()); + painter.setFont(font); + painter.setPen(textColor); + painter.drawText(rect.adjusted(6, 6, -6, -6), Qt::AlignCenter | Qt::TextWordWrap, text()); +} diff --git a/pages/squaretraybutton.h b/pages/squaretraybutton.h new file mode 100644 index 0000000..7926098 --- /dev/null +++ b/pages/squaretraybutton.h @@ -0,0 +1,24 @@ +#ifndef SQUARETRAYBUTTON_H +#define SQUARETRAYBUTTON_H + +#include + +class SquareTrayButton : public QAbstractButton +{ +public: + explicit SquareTrayButton(int trayIndex, int loadedCount, QWidget *parent = nullptr); + + void setTrayInfo(int trayId, const QString &code, int loadedCount, + const QString &status, bool present); + + QSize sizeHint() const override; + QSize minimumSizeHint() const override; + +protected: + void paintEvent(QPaintEvent *event) override; + +private: + int m_trayId; +}; + +#endif // SQUARETRAYBUTTON_H diff --git a/pages/uihelpers.cpp b/pages/uihelpers.cpp new file mode 100644 index 0000000..d3a9d63 --- /dev/null +++ b/pages/uihelpers.cpp @@ -0,0 +1,94 @@ +#include "uihelpers.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace UiHelpers { + +class SquareLabel : public QLabel +{ +public: + explicit SquareLabel(const QString &text) : QLabel(text) {} + + bool hasHeightForWidth() const override { return true; } + int heightForWidth(int width) const override { return width; } + + QSize sizeHint() const override + { + const int side = qMax(QLabel::sizeHint().width(), QLabel::sizeHint().height()); + return QSize(side, side); + } +}; + +QFrame *makeCard(const QString &title) +{ + QFrame *card = new QFrame; + card->setObjectName("card"); + card->setFrameShape(QFrame::StyledPanel); + + QVBoxLayout *layout = new QVBoxLayout(card); + layout->setContentsMargins(12, 10, 12, 12); + layout->setSpacing(8); + + QLabel *titleLabel = new QLabel(title); + titleLabel->setObjectName("cardTitle"); + layout->addWidget(titleLabel); + return card; +} + +QLabel *makeBadge(const QString &text, const QString &color) +{ + QLabel *label = new QLabel(text); + label->setAlignment(Qt::AlignCenter); + label->setMinimumHeight(26); + label->setStyleSheet(QString("QLabel { color: white; background: %1; border-radius: 4px; padding: 4px 10px; }").arg(color)); + return label; +} + +QLabel *makeStatusCell(const QString &text, const QString &color) +{ + QLabel *label = new QLabel(text); + label->setAlignment(Qt::AlignCenter); + label->setMinimumSize(34, 30); + label->setStyleSheet(QString("QLabel { background: %1; border: 1px solid #ffffff; border-radius: 3px; color: white; font-size: 11px; }").arg(color)); + return label; +} + +QLabel *makeSquareStatusCell(const QString &text, const QString &color) +{ + QLabel *label = new SquareLabel(text); + label->setAlignment(Qt::AlignCenter); + label->setMinimumSize(60, 60); + label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + label->setStyleSheet(QString("QLabel { background: %1; border: 1px solid #ffffff; border-radius: 3px; color: white; font-size: 11px; }").arg(color)); + return label; +} + +QTableWidget *makeTable(const QStringList &headers) +{ + QTableWidget *table = new QTableWidget(0, headers.size()); + table->setHorizontalHeaderLabels(headers); + table->horizontalHeader()->setStretchLastSection(true); + table->verticalHeader()->setVisible(false); + table->setSelectionBehavior(QAbstractItemView::SelectRows); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + table->setAlternatingRowColors(true); + return table; +} + +void addRow(QTableWidget *table, const QStringList &values) +{ + const int row = table->rowCount(); + table->insertRow(row); + for (int col = 0; col < values.size(); ++col) { + table->setItem(row, col, new QTableWidgetItem(values.at(col))); + } +} + +} diff --git a/pages/uihelpers.h b/pages/uihelpers.h new file mode 100644 index 0000000..6ebdf3e --- /dev/null +++ b/pages/uihelpers.h @@ -0,0 +1,21 @@ +#ifndef UIHELPERS_H +#define UIHELPERS_H + +#include + +class QFrame; +class QLabel; +class QTableWidget; + +namespace UiHelpers { + +QFrame *makeCard(const QString &title); +QLabel *makeBadge(const QString &text, const QString &color); +QLabel *makeStatusCell(const QString &text, const QString &color); +QLabel *makeSquareStatusCell(const QString &text, const QString &color); +QTableWidget *makeTable(const QStringList &headers); +void addRow(QTableWidget *table, const QStringList &values); + +} + +#endif // UIHELPERS_H diff --git a/repositories/logrepository.cpp b/repositories/logrepository.cpp new file mode 100644 index 0000000..3d682e7 --- /dev/null +++ b/repositories/logrepository.cpp @@ -0,0 +1,73 @@ +#include "logrepository.h" + +#include "../db/databasemanager.h" + +#include +#include +#include + +namespace { + +bool ensureOpen(QString *error) +{ + return DatabaseManager::instance().open(error); +} + +void setError(const QSqlQuery &query, QString *error) +{ + if (error) { + *error = query.lastError().text(); + } +} + +} + +QList LogRepository::listLogs(QString *error, int limit) +{ + QList records; + if (!ensureOpen(error)) { + return records; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select * from operation_logs order by id desc limit :limit"); + query.bindValue(":limit", limit); + if (!query.exec()) { + setError(query, error); + return records; + } + + while (query.next()) { + LogRecord record; + record.id = query.value("id").toInt(); + record.type = query.value("type").toString(); + record.module = query.value("module").toString(); + record.action = query.value("action").toString(); + record.content = query.value("content").toString(); + record.status = query.value("status").toString(); + record.createdAt = query.value("created_at").toDateTime(); + records.append(record); + } + return records; +} + +bool LogRepository::insertLog(const LogRecord &record, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into operation_logs (type, module, action, content, status) " + "values (:type, :module, :action, :content, :status)"); + query.bindValue(":type", record.type); + query.bindValue(":module", record.module); + query.bindValue(":action", record.action); + query.bindValue(":content", record.content); + query.bindValue(":status", record.status); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} diff --git a/repositories/logrepository.h b/repositories/logrepository.h new file mode 100644 index 0000000..41507a2 --- /dev/null +++ b/repositories/logrepository.h @@ -0,0 +1,15 @@ +#ifndef LOGREPOSITORY_H +#define LOGREPOSITORY_H + +#include "../models/logrecord.h" + +#include + +class LogRepository +{ +public: + QList listLogs(QString *error = nullptr, int limit = 200); + bool insertLog(const LogRecord &record, QString *error = nullptr); +}; + +#endif // LOGREPOSITORY_H diff --git a/repositories/orderrepository.cpp b/repositories/orderrepository.cpp new file mode 100644 index 0000000..f88a7d6 --- /dev/null +++ b/repositories/orderrepository.cpp @@ -0,0 +1,231 @@ +#include "orderrepository.h" + +#include "../db/databasemanager.h" + +#include +#include +#include + +namespace { + +bool ensureOpen(QString *error) +{ + return DatabaseManager::instance().open(error); +} + +void setError(const QSqlQuery &query, QString *error) +{ + if (error) { + *error = query.lastError().text(); + } +} + +Order readOrder(QSqlQuery &query) +{ + Order order; + order.id = query.value("id").toInt(); + order.no = query.value("no").toString(); + order.productionNo = query.value("production_no").toString(); + order.drawingNo = query.value("drawing_no").toString(); + order.batchNo = query.value("batch_no").toString(); + order.planNum = query.value("plan_num").toInt(); + order.qualified = query.value("qualified").toInt(); + order.unqualified = query.value("unqualified").toInt(); + order.status = query.value("status").toString(); + order.beginTime = query.value("begin_time").toDateTime(); + order.endTime = query.value("end_time").toDateTime(); + order.remark = query.value("remark").toString(); + order.createdAt = query.value("created_at").toDateTime(); + order.updatedAt = query.value("updated_at").toDateTime(); + return order; +} + +} + +QList OrderRepository::listOrders(QString *error, int limit) +{ + QList orders; + if (!ensureOpen(error)) { + return orders; + } + + 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, " + "created_at, updated_at " + "from orders order by id desc limit :limit"); + query.bindValue(":limit", limit); + if (!query.exec()) { + setError(query, error); + return orders; + } + + while (query.next()) { + orders.append(readOrder(query)); + } + return orders; +} + +bool OrderRepository::findOrder(int id, 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, begin_time, end_time, remark, " + "created_at, updated_at from orders where id = :id"); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + if (!query.next()) { + if (error) { + *error = QString("Order not found: %1").arg(id); + } + return false; + } + + *order = readOrder(query); + return true; +} + +bool OrderRepository::findOrderForUpdate(int id, 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, begin_time, end_time, remark, " + "created_at, updated_at from orders where id = :id for update"); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + if (!query.next()) { + if (error) { + *error = QString("Order not found: %1").arg(id); + } + return false; + } + + *order = readOrder(query); + return true; +} + +bool OrderRepository::insertOrder(Order *order, QString *error) +{ + if (!order || !ensureOpen(error)) { + return false; + } + + 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) " + "values (:no, :production_no, :drawing_no, :batch_no, :plan_num, " + ":qualified, :unqualified, :status, :begin_time, :end_time, :remark) " + "returning id"); + query.bindValue(":no", order->no); + query.bindValue(":production_no", order->productionNo); + query.bindValue(":drawing_no", order->drawingNo); + query.bindValue(":batch_no", order->batchNo); + query.bindValue(":plan_num", order->planNum); + query.bindValue(":qualified", order->qualified); + query.bindValue(":unqualified", order->unqualified); + query.bindValue(":status", order->status.isEmpty() ? "NOT_START" : order->status); + 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); + + if (!query.exec() || !query.next()) { + setError(query, error); + return false; + } + order->id = query.value(0).toInt(); + return true; +} + +bool OrderRepository::updateOrderStatus(int id, const QString &status, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update orders set status = :status, updated_at = now() where id = :id"); + query.bindValue(":status", status); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool OrderRepository::updateOrderLifecycle(int id, const QString &status, + const QDateTime &beginTime, + const QDateTime &endTime, + QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update orders set status = :status, begin_time = :begin_time, " + "end_time = :end_time, updated_at = now() where id = :id"); + query.bindValue(":status", status); + query.bindValue(":begin_time", beginTime.isValid() + ? QVariant(beginTime) : QVariant(QVariant::DateTime)); + query.bindValue(":end_time", endTime.isValid() + ? QVariant(endTime) : QVariant(QVariant::DateTime)); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + return query.numRowsAffected() == 1; +} + +bool OrderRepository::refreshProgress(int id, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update orders set " + "qualified = (select count(*) from workpieces " + "where order_id = :id and state = 'OK'), " + "unqualified = (select count(*) from workpieces " + "where order_id = :id and state = 'NG'), " + "updated_at = now() where id = :id"); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + return query.numRowsAffected() == 1; +} + +bool OrderRepository::removeOrder(int id, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("delete from orders where id = :id"); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} diff --git a/repositories/orderrepository.h b/repositories/orderrepository.h new file mode 100644 index 0000000..1e9eca4 --- /dev/null +++ b/repositories/orderrepository.h @@ -0,0 +1,23 @@ +#ifndef ORDERREPOSITORY_H +#define ORDERREPOSITORY_H + +#include "../models/order.h" + +#include + +class OrderRepository +{ +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 insertOrder(Order *order, QString *error = nullptr); + bool updateOrderStatus(int id, const QString &status, QString *error = nullptr); + bool updateOrderLifecycle(int id, const QString &status, + const QDateTime &beginTime, const QDateTime &endTime, + QString *error = nullptr); + bool refreshProgress(int id, QString *error = nullptr); + bool removeOrder(int id, QString *error = nullptr); +}; + +#endif // ORDERREPOSITORY_H diff --git a/repositories/productionrepository.cpp b/repositories/productionrepository.cpp new file mode 100644 index 0000000..522d557 --- /dev/null +++ b/repositories/productionrepository.cpp @@ -0,0 +1,467 @@ +#include "productionrepository.h" + +#include "../db/databasemanager.h" + +#include +#include +#include + +namespace { + +bool ensureOpen(QString *error) +{ + return DatabaseManager::instance().open(error); +} + +void setError(const QSqlQuery &query, QString *error) +{ + if (error) { + *error = query.lastError().text(); + } +} + +QVariant nullableId(int id) +{ + return id > 0 ? QVariant(id) : QVariant(QVariant::Int); +} + +} + +int ProductionRepository::createRun(int orderId, const QString &productionState, + const QString &processStep, QString *error) +{ + if (!ensureOpen(error)) { + return 0; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into production_runs " + "(order_id, production_state, process_step) " + "values (:order_id, :production_state, :process_step) " + "returning id"); + query.bindValue(":order_id", orderId); + query.bindValue(":production_state", productionState); + query.bindValue(":process_step", processStep); + if (!query.exec() || !query.next()) { + setError(query, error); + return 0; + } + return query.value(0).toInt(); +} + +bool ProductionRepository::updateRun(int runId, const QString &runState, + const QString &productionState, + const QString &processStep, + int currentWorkpieceId, + const QString &timeoutState, + int recoveryRetryCount, + const QString &lastError, + QString *error) +{ + if (runId <= 0 || !ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update production_runs set " + "run_state = :run_state, " + "production_state = :production_state, " + "process_step = :process_step, " + "current_workpiece_id = :current_workpiece_id, " + "timeout_state = :timeout_state, " + "recovery_retry_count = :recovery_retry_count, " + "last_error = :last_error, " + "last_heartbeat_at = now(), updated_at = now() " + "where id = :id"); + query.bindValue(":run_state", runState); + query.bindValue(":production_state", productionState); + query.bindValue(":process_step", processStep); + query.bindValue(":current_workpiece_id", nullableId(currentWorkpieceId)); + query.bindValue(":timeout_state", timeoutState); + query.bindValue(":recovery_retry_count", recoveryRetryCount); + query.bindValue(":last_error", lastError); + query.bindValue(":id", runId); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool ProductionRepository::finishRun(int runId, const QString &runState, + const QString &lastError, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update production_runs set run_state = :run_state, " + "last_error = :last_error, ended_at = now(), " + "last_heartbeat_at = now(), updated_at = now() " + "where id = :id"); + query.bindValue(":run_state", runState); + query.bindValue(":last_error", lastError); + query.bindValue(":id", runId); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool ProductionRepository::heartbeatRun(int runId, QString *error) +{ + if (runId <= 0 || !ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update production_runs set " + "last_heartbeat_at = now(), updated_at = now() " + "where id = :id " + "and run_state in ('RUNNING', 'PAUSED', 'RECOVERY')"); + query.bindValue(":id", runId); + if (!query.exec()) { + setError(query, error); + return false; + } + return query.numRowsAffected() == 1; +} + +bool ProductionRepository::findActiveRun(ProductionRunSnapshot *run, QString *error) +{ + if (!run || !ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select id, order_id, current_workpiece_id, run_state, " + "production_state, process_step, timeout_state, " + "recovery_retry_count, last_error " + "from production_runs " + "where run_state in ('RUNNING', 'PAUSED', 'RECOVERY') " + "order by id desc limit 1"); + if (!query.exec()) { + setError(query, error); + return false; + } + if (!query.next()) { + *run = ProductionRunSnapshot(); + return true; + } + + run->id = query.value("id").toInt(); + run->orderId = query.value("order_id").toInt(); + run->currentWorkpieceId = query.value("current_workpiece_id").toInt(); + run->runState = query.value("run_state").toString(); + run->productionState = query.value("production_state").toString(); + run->processStep = query.value("process_step").toString(); + run->timeoutState = query.value("timeout_state").toString(); + run->recoveryRetryCount = query.value("recovery_retry_count").toInt(); + run->lastError = query.value("last_error").toString(); + return true; +} + +bool ProductionRepository::insertStateHistory( + int runId, int orderId, int workpieceId, const QString &fromState, + const QString &toState, const QString &processStep, const QString &source, + const QString &reason, const QString &message, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into production_state_history " + "(production_run_id, order_id, workpiece_id, from_state, " + "to_state, process_step, source, reason, message) " + "values (:run_id, :order_id, :workpiece_id, :from_state, " + ":to_state, :process_step, :source, :reason, :message)"); + query.bindValue(":run_id", nullableId(runId)); + query.bindValue(":order_id", nullableId(orderId)); + query.bindValue(":workpiece_id", nullableId(workpieceId)); + query.bindValue(":from_state", fromState); + query.bindValue(":to_state", toState); + query.bindValue(":process_step", processStep); + query.bindValue(":source", source); + query.bindValue(":reason", reason); + query.bindValue(":message", message); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool ProductionRepository::startWorkpieceProcess( + int orderId, int workpieceId, const QString &processStep, int plcStep, + const QString &source, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery attemptQuery(DatabaseManager::instance().database()); + attemptQuery.prepare("select coalesce(max(attempt_no), 0) + 1 " + "from workpiece_process_records " + "where workpiece_id = :workpiece_id " + "and process_step = :process_step"); + attemptQuery.bindValue(":workpiece_id", workpieceId); + attemptQuery.bindValue(":process_step", processStep); + if (!attemptQuery.exec() || !attemptQuery.next()) { + setError(attemptQuery, error); + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into workpiece_process_records " + "(order_id, workpiece_id, process_step, attempt_no, " + "process_state, plc_step, source) " + "values (:order_id, :workpiece_id, :process_step, " + ":attempt_no, 'RUNNING', :plc_step, :source)"); + query.bindValue(":order_id", nullableId(orderId)); + query.bindValue(":workpiece_id", workpieceId); + query.bindValue(":process_step", processStep); + query.bindValue(":attempt_no", attemptQuery.value(0).toInt()); + query.bindValue(":plc_step", plcStep); + query.bindValue(":source", source); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool ProductionRepository::finishWorkpieceProcess( + int workpieceId, const QString &processStep, const QString &resultState, + int durationMs, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update workpiece_process_records set " + "process_state = 'COMPLETED', result_state = :result_state, " + "completed_at = now(), duration_ms = :duration_ms " + "where id = (select id from workpiece_process_records " + "where workpiece_id = :workpiece_id " + "and process_step = :process_step " + "and process_state = 'RUNNING' " + "order by id desc limit 1)"); + query.bindValue(":result_state", resultState); + query.bindValue(":duration_ms", durationMs >= 0 ? QVariant(durationMs) + : QVariant(QVariant::Int)); + query.bindValue(":workpiece_id", workpieceId); + query.bindValue(":process_step", processStep); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +QList ProductionRepository::listProcessRecords( + int workpieceId, QString *error) +{ + QList records; + if (workpieceId <= 0 || !ensureOpen(error)) { + return records; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select process_step, attempt_no, process_state, " + "result_state, duration_ms, started_at, completed_at " + "from workpiece_process_records " + "where workpiece_id = :workpiece_id " + "order by started_at, id"); + query.bindValue(":workpiece_id", workpieceId); + if (!query.exec()) { + setError(query, error); + return records; + } + + while (query.next()) { + WorkpieceProcessRecord record; + record.processStep = query.value("process_step").toString(); + record.attemptNo = query.value("attempt_no").toInt(); + record.processState = query.value("process_state").toString(); + record.resultState = query.value("result_state").toString(); + record.durationMs = query.value("duration_ms").isNull() + ? -1 : query.value("duration_ms").toInt(); + record.startedAt = query.value("started_at").toDateTime(); + record.completedAt = query.value("completed_at").toDateTime(); + records.append(record); + } + return records; +} + +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) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery attemptQuery(DatabaseManager::instance().database()); + attemptQuery.prepare("select coalesce(max(attempt_no), 0) + 1 " + "from inspection_records " + "where workpiece_id = :workpiece_id " + "and inspection_side = :side"); + attemptQuery.bindValue(":workpiece_id", workpieceId); + attemptQuery.bindValue(":side", side); + if (!attemptQuery.exec() || !attemptQuery.next()) { + setError(attemptQuery, error); + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into inspection_records " + "(order_id, workpiece_id, inspection_side, attempt_no, " + "raw_result, result_state, inspection_state, source, " + "plc_step, message, started_at, completed_at) " + "values (:order_id, :workpiece_id, :side, :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(":attempt_no", attemptQuery.value(0).toInt()); + query.bindValue(":raw_result", rawResult); + query.bindValue(":result_state", resultState); + query.bindValue(":source", source); + query.bindValue(":plc_step", plcStep); + query.bindValue(":message", message); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool ProductionRepository::insertAlarm( + const QString &code, const QString &message, int orderId, + int workpieceId, const QString &fallbackLevel, + const QString &fallbackSource, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery duplicateQuery(DatabaseManager::instance().database()); + duplicateQuery.prepare("select id from alarm_records " + "where code = :code " + "and alarm_state <> 'CLEARED' " + "and order_id is not distinct from :order_id " + "and workpiece_id is not distinct from :workpiece_id " + "limit 1"); + duplicateQuery.bindValue(":code", code); + duplicateQuery.bindValue(":order_id", nullableId(orderId)); + duplicateQuery.bindValue(":workpiece_id", nullableId(workpieceId)); + if (!duplicateQuery.exec()) { + setError(duplicateQuery, error); + return false; + } + if (duplicateQuery.next()) { + return true; + } + + QSqlQuery definitionQuery(DatabaseManager::instance().database()); + definitionQuery.prepare("select id, level, source from alarm_definitions " + "where code = :code"); + definitionQuery.bindValue(":code", code); + if (!definitionQuery.exec()) { + setError(definitionQuery, error); + return false; + } + + QVariant definitionId(QVariant::Int); + QString level = fallbackLevel; + QString source = fallbackSource; + if (definitionQuery.next()) { + definitionId = definitionQuery.value("id"); + level = definitionQuery.value("level").toString(); + source = definitionQuery.value("source").toString(); + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into alarm_records " + "(definition_id, code, level, source, order_id, workpiece_id, message) " + "values (:definition_id, :code, :level, :source, " + ":order_id, :workpiece_id, :message)"); + query.bindValue(":definition_id", definitionId); + query.bindValue(":code", code); + query.bindValue(":level", level); + query.bindValue(":source", source); + query.bindValue(":order_id", nullableId(orderId)); + query.bindValue(":workpiece_id", nullableId(workpieceId)); + query.bindValue(":message", message); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool ProductionRepository::clearActiveAlarms(const QString &code, + const QString &clearedBy, + QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare(code.trimmed().isEmpty() + ? "update alarm_records set alarm_state = 'CLEARED', " + "cleared_at = now(), cleared_by = :cleared_by " + "where alarm_state <> 'CLEARED'" + : "update alarm_records set alarm_state = 'CLEARED', " + "cleared_at = now(), cleared_by = :cleared_by " + "where alarm_state <> 'CLEARED' and code = :code"); + query.bindValue(":cleared_by", clearedBy); + if (!code.trimmed().isEmpty()) { + query.bindValue(":code", code); + } + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool ProductionRepository::insertDeviceStatus( + const QString &deviceCode, bool plcConnected, bool plcReady, + bool robotReady, bool safetyDoorClosed, bool emergencyStop, + int currentStep, int checkResult, int errorCode, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into device_status_history " + "(device_code, plc_connected, plc_ready, robot_ready, " + "safety_door_closed, emergency_stop, current_step, " + "check_result, error_code) " + "values (:device_code, :plc_connected, :plc_ready, " + ":robot_ready, :safety_door_closed, :emergency_stop, " + ":current_step, :check_result, :error_code)"); + query.bindValue(":device_code", deviceCode); + query.bindValue(":plc_connected", plcConnected); + query.bindValue(":plc_ready", plcReady); + query.bindValue(":robot_ready", robotReady); + query.bindValue(":safety_door_closed", safetyDoorClosed); + query.bindValue(":emergency_stop", emergencyStop); + query.bindValue(":current_step", currentStep); + query.bindValue(":check_result", checkResult); + query.bindValue(":error_code", errorCode); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} diff --git a/repositories/productionrepository.h b/repositories/productionrepository.h new file mode 100644 index 0000000..8805e68 --- /dev/null +++ b/repositories/productionrepository.h @@ -0,0 +1,85 @@ +#ifndef PRODUCTIONREPOSITORY_H +#define PRODUCTIONREPOSITORY_H + +#include +#include +#include + +struct ProductionRunSnapshot +{ + int id = 0; + int orderId = 0; + int currentWorkpieceId = 0; + QString runState; + QString productionState; + QString processStep; + QString timeoutState; + int recoveryRetryCount = 0; + QString lastError; +}; + +struct WorkpieceProcessRecord +{ + QString processStep; + int attemptNo = 0; + QString processState; + QString resultState; + int durationMs = -1; + QDateTime startedAt; + QDateTime completedAt; +}; + +class ProductionRepository +{ +public: + int createRun(int orderId, const QString &productionState, + const QString &processStep, QString *error = nullptr); + bool updateRun(int runId, const QString &runState, + const QString &productionState, const QString &processStep, + int currentWorkpieceId, const QString &timeoutState, + int recoveryRetryCount, const QString &lastError, + QString *error = nullptr); + bool finishRun(int runId, const QString &runState, + const QString &lastError = QString(), + QString *error = nullptr); + bool heartbeatRun(int runId, QString *error = nullptr); + bool findActiveRun(ProductionRunSnapshot *run, QString *error = nullptr); + + bool insertStateHistory(int runId, int orderId, int workpieceId, + const QString &fromState, const QString &toState, + const QString &processStep, const QString &source, + const QString &reason, const QString &message, + QString *error = nullptr); + + bool startWorkpieceProcess(int orderId, int workpieceId, + const QString &processStep, int plcStep, + const QString &source, QString *error = nullptr); + bool finishWorkpieceProcess(int workpieceId, const QString &processStep, + const QString &resultState, int durationMs, + QString *error = nullptr); + QList listProcessRecords( + int workpieceId, QString *error = nullptr); + + bool insertInspection(int orderId, int workpieceId, + const QString &side, int rawResult, + const QString &resultState, int plcStep, + const QString &source, const QString &message, + QString *error = nullptr); + + bool insertAlarm(const QString &code, const QString &message, + int orderId, int workpieceId, + const QString &fallbackLevel, + const QString &fallbackSource, + QString *error = nullptr); + bool clearActiveAlarms(const QString &code = QString(), + const QString &clearedBy = "OPERATOR", + QString *error = nullptr); + + bool insertDeviceStatus(const QString &deviceCode, bool plcConnected, + bool plcReady, bool robotReady, + bool safetyDoorClosed, bool emergencyStop, + int currentStep, int checkResult, int errorCode, + QString *error = nullptr); +}; + +#endif // PRODUCTIONREPOSITORY_H diff --git a/repositories/trayrepository.cpp b/repositories/trayrepository.cpp new file mode 100644 index 0000000..e2c82e2 --- /dev/null +++ b/repositories/trayrepository.cpp @@ -0,0 +1,256 @@ +#include "trayrepository.h" + +#include "../db/databasemanager.h" + +#include +#include +#include + +namespace { + +bool ensureOpen(QString *error) +{ + return DatabaseManager::instance().open(error); +} + +void setError(const QSqlQuery &query, QString *error) +{ + if (error) { + *error = query.lastError().text(); + } +} + +} + +QList TrayRepository::listTrays(QString *error) +{ + QList trays; + if (!ensureOpen(error)) { + return trays; + } + + QSqlQuery query(DatabaseManager::instance().database()); + if (!query.exec("select * from trays order by rack_row, rack_column")) { + setError(query, error); + return trays; + } + + while (query.next()) { + Tray tray; + tray.id = query.value("id").toInt(); + tray.code = query.value("code").toString(); + tray.rfid = query.value("rfid").toString(); + tray.rackRow = query.value("rack_row").toInt(); + tray.rackColumn = query.value("rack_column").toInt(); + tray.present = query.value("present").toBool(); + tray.loadedCount = query.value("loaded_count").toInt(); + tray.qualified = query.value("qualified").toInt(); + tray.unqualified = query.value("unqualified").toInt(); + tray.status = query.value("status").toString(); + tray.createdAt = query.value("created_at").toDateTime(); + tray.updatedAt = query.value("updated_at").toDateTime(); + trays.append(tray); + } + return trays; +} + +QList TrayRepository::listSlots(int trayId, QString *error) +{ + QList items; + if (!ensureOpen(error)) { + return items; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select * from tray_slots where tray_id = :tray_id order by row_no, column_no"); + query.bindValue(":tray_id", trayId); + if (!query.exec()) { + setError(query, error); + return items; + } + + while (query.next()) { + TraySlot slot; + slot.id = query.value("id").toInt(); + slot.trayId = query.value("tray_id").toInt(); + slot.rowNo = query.value("row_no").toInt(); + slot.columnNo = query.value("column_no").toInt(); + slot.workpieceId = query.value("workpiece_id").toInt(); + slot.state = query.value("state").toString(); + items.append(slot); + } + return items; +} + +QList TrayRepository::listEmptySlotsForAllocation(QString *error) +{ + QList items; + if (!ensureOpen(error)) { + return items; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select ts.id, ts.tray_id, ts.row_no, ts.column_no, " + "ts.workpiece_id, ts.state " + "from tray_slots ts " + "join trays t on t.id = ts.tray_id " + "where t.present = true " + "and ts.workpiece_id is null " + "and ts.state = 'EMPTY' " + "order by t.rack_row, t.rack_column, ts.row_no, ts.column_no " + "for update of ts skip locked"); + if (!query.exec()) { + setError(query, error); + return items; + } + + while (query.next()) { + TraySlot slot; + slot.id = query.value("id").toInt(); + slot.trayId = query.value("tray_id").toInt(); + slot.rowNo = query.value("row_no").toInt(); + slot.columnNo = query.value("column_no").toInt(); + slot.workpieceId = query.value("workpiece_id").toInt(); + slot.state = query.value("state").toString(); + items.append(slot); + } + return items; +} + +bool TrayRepository::initializeSlots(int trayId, int rows, int columns, QString *error) +{ + if (rows <= 0 || columns <= 0 || !ensureOpen(error)) { + if (error && rows <= 0) { + *error = "Tray row count must be greater than 0"; + } else if (error && columns <= 0) { + *error = "Tray column count must be greater than 0"; + } + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into tray_slots (tray_id, row_no, column_no, state) " + "values (:tray_id, :row_no, :column_no, 'EMPTY') " + "on conflict (tray_id, row_no, column_no) do nothing"); + for (int row = 1; row <= rows; ++row) { + for (int column = 1; column <= columns; ++column) { + query.bindValue(":tray_id", trayId); + query.bindValue(":row_no", row); + query.bindValue(":column_no", column); + if (!query.exec()) { + setError(query, error); + return false; + } + } + } + return true; +} + +bool TrayRepository::assignSlot(int trayId, int rowNo, int columnNo, int workpieceId, + const QString &state, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update tray_slots set workpiece_id = :workpiece_id, state = :state " + "where tray_id = :tray_id and row_no = :row_no and column_no = :column_no " + "and workpiece_id is null and state = 'EMPTY'"); + query.bindValue(":workpiece_id", workpieceId); + query.bindValue(":state", state); + query.bindValue(":tray_id", trayId); + query.bindValue(":row_no", rowNo); + query.bindValue(":column_no", columnNo); + if (!query.exec()) { + setError(query, error); + return false; + } + if (query.numRowsAffected() != 1) { + if (error) { + *error = "Tray slot is not empty or does not exist"; + } + return false; + } + return true; +} + +bool TrayRepository::refreshStats(int trayId, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update trays set " + "loaded_count = (select count(*) from tray_slots " + "where tray_id = :tray_id and workpiece_id is not null), " + "qualified = (select count(*) from tray_slots " + "where tray_id = :tray_id and state = 'OK'), " + "unqualified = (select count(*) from tray_slots " + "where tray_id = :tray_id and state = 'NG'), " + "status = case when exists (select 1 from tray_slots " + "where tray_id = :tray_id and workpiece_id is not null) " + "then 'PRESENT' when present then 'EMPTY' else 'ABSENT' end, " + "updated_at = now() where id = :tray_id"); + query.bindValue(":tray_id", trayId); + if (!query.exec()) { + setError(query, error); + return false; + } + return query.numRowsAffected() == 1; +} + +bool TrayRepository::upsertTray(const Tray &tray, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into trays " + "(code, rfid, rack_row, rack_column, present, loaded_count, qualified, unqualified, status) " + "values (:code, :rfid, :rack_row, :rack_column, :present, :loaded_count, :qualified, :unqualified, :status) " + "on conflict (rack_row, rack_column) do update set " + "code = excluded.code, rfid = excluded.rfid, present = excluded.present, " + "loaded_count = excluded.loaded_count, qualified = excluded.qualified, " + "unqualified = excluded.unqualified, status = excluded.status, updated_at = now()"); + query.bindValue(":code", tray.code); + query.bindValue(":rfid", tray.rfid); + query.bindValue(":rack_row", tray.rackRow); + query.bindValue(":rack_column", tray.rackColumn); + query.bindValue(":present", tray.present); + query.bindValue(":loaded_count", tray.loadedCount); + query.bindValue(":qualified", tray.qualified); + query.bindValue(":unqualified", tray.unqualified); + query.bindValue(":status", tray.status); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} + +bool TrayRepository::updateSlotState(int trayId, int rowNo, int columnNo, const QString &state, + int workpieceId, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into tray_slots (tray_id, row_no, column_no, workpiece_id, state) " + "values (:tray_id, :row_no, :column_no, :workpiece_id, :state) " + "on conflict (tray_id, row_no, column_no) do update set " + "workpiece_id = excluded.workpiece_id, state = excluded.state"); + query.bindValue(":tray_id", trayId); + query.bindValue(":row_no", rowNo); + query.bindValue(":column_no", columnNo); + query.bindValue(":workpiece_id", workpieceId > 0 ? QVariant(workpieceId) : QVariant(QVariant::Int)); + query.bindValue(":state", state); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} diff --git a/repositories/trayrepository.h b/repositories/trayrepository.h new file mode 100644 index 0000000..7468733 --- /dev/null +++ b/repositories/trayrepository.h @@ -0,0 +1,24 @@ +#ifndef TRAYREPOSITORY_H +#define TRAYREPOSITORY_H + +#include "../models/tray.h" + +#include + +class TrayRepository +{ +public: + QList listTrays(QString *error = nullptr); + QList listSlots(int trayId, QString *error = nullptr); + QList listEmptySlotsForAllocation(QString *error = nullptr); + bool initializeSlots(int trayId, int rows = 7, int columns = 7, + QString *error = nullptr); + bool assignSlot(int trayId, int rowNo, int columnNo, int workpieceId, + const QString &state, QString *error = nullptr); + bool refreshStats(int trayId, QString *error = nullptr); + bool upsertTray(const Tray &tray, QString *error = nullptr); + bool updateSlotState(int trayId, int rowNo, int columnNo, const QString &state, + int workpieceId = 0, QString *error = nullptr); +}; + +#endif // TRAYREPOSITORY_H diff --git a/repositories/workpiecerepository.cpp b/repositories/workpiecerepository.cpp new file mode 100644 index 0000000..3bea32e --- /dev/null +++ b/repositories/workpiecerepository.cpp @@ -0,0 +1,204 @@ +#include "workpiecerepository.h" + +#include "../db/databasemanager.h" + +#include +#include +#include + +namespace { + +bool ensureOpen(QString *error) +{ + return DatabaseManager::instance().open(error); +} + +void setError(const QSqlQuery &query, QString *error) +{ + if (error) { + *error = query.lastError().text(); + } +} + +Workpiece readWorkpiece(QSqlQuery &query) +{ + Workpiece workpiece; + workpiece.id = query.value("id").toInt(); + workpiece.barcode = query.value("barcode").toString(); + workpiece.orderId = query.value("order_id").toInt(); + workpiece.trayId = query.value("tray_id").toInt(); + workpiece.trayPos = query.value("tray_pos").toInt(); + workpiece.rowNo = query.value("row_no").toInt(); + workpiece.columnNo = query.value("column_no").toInt(); + workpiece.state = query.value("state").toString(); + workpiece.processStep = query.value("process_step").toString(); + workpiece.createdAt = query.value("created_at").toDateTime(); + workpiece.updatedAt = query.value("updated_at").toDateTime(); + return workpiece; +} + +QList listWithSql(const QString &sql, int id, QString *error) +{ + QList workpieces; + if (!ensureOpen(error)) { + return workpieces; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare(sql); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return workpieces; + } + + while (query.next()) { + workpieces.append(readWorkpiece(query)); + } + return workpieces; +} + +} + +QList WorkpieceRepository::listByOrder(int orderId, QString *error) +{ + return listWithSql("select * from workpieces where order_id = :id order by tray_id, tray_pos", orderId, error); +} + +QList WorkpieceRepository::listByTray(int trayId, QString *error) +{ + return listWithSql("select * from workpieces where tray_id = :id order by tray_pos", trayId, error); +} + +bool WorkpieceRepository::findWorkpiece(int id, Workpiece *workpiece, QString *error) +{ + if (!workpiece || !ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("select * from workpieces where id = :id"); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + if (!query.next()) { + if (error) { + *error = QString("Workpiece not found: %1").arg(id); + } + return false; + } + + *workpiece = readWorkpiece(query); + return true; +} + +bool WorkpieceRepository::claimNextPending(int orderId, Workpiece *workpiece, + QString *error) +{ + if (!workpiece || !ensureOpen(error)) { + return false; + } + + *workpiece = Workpiece(); + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("with candidate as (" + "select id from workpieces " + "where order_id = :order_id and state = 'PENDING' " + "order by tray_id nulls last, tray_pos, id " + "for update skip locked limit 1" + ") " + "update workpieces w set state = 'PROCESSING', " + "process_step = 'WAITING_DEVICE_READY', updated_at = now() " + "from candidate where w.id = candidate.id " + "returning w.*"); + query.bindValue(":order_id", orderId); + if (!query.exec()) { + setError(query, error); + return false; + } + if (!query.next()) { + return true; + } + + *workpiece = readWorkpiece(query); + return true; +} + +bool WorkpieceRepository::insertWorkpiece(Workpiece *workpiece, QString *error) +{ + if (!workpiece || !ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("insert into workpieces " + "(barcode, order_id, tray_id, tray_pos, row_no, column_no, state, process_step) " + "values (:barcode, :order_id, :tray_id, :tray_pos, :row_no, :column_no, :state, :process_step) " + "returning id"); + query.bindValue(":barcode", workpiece->barcode); + query.bindValue(":order_id", workpiece->orderId > 0 ? QVariant(workpiece->orderId) : QVariant(QVariant::Int)); + query.bindValue(":tray_id", workpiece->trayId > 0 ? QVariant(workpiece->trayId) : QVariant(QVariant::Int)); + query.bindValue(":tray_pos", workpiece->trayPos); + query.bindValue(":row_no", workpiece->rowNo); + query.bindValue(":column_no", workpiece->columnNo); + query.bindValue(":state", workpiece->state.isEmpty() ? "PENDING" : workpiece->state); + query.bindValue(":process_step", workpiece->processStep); + + if (!query.exec() || !query.next()) { + setError(query, error); + return false; + } + workpiece->id = query.value(0).toInt(); + return true; +} + +bool WorkpieceRepository::assignToSlot(int id, int trayId, int trayPos, + int rowNo, int columnNo, QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update workpieces set tray_id = :tray_id, tray_pos = :tray_pos, " + "row_no = :row_no, column_no = :column_no, updated_at = now() " + "where id = :id and (tray_id is null or tray_id = 0)"); + query.bindValue(":tray_id", trayId); + query.bindValue(":tray_pos", trayPos); + query.bindValue(":row_no", rowNo); + query.bindValue(":column_no", columnNo); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + if (query.numRowsAffected() != 1) { + if (error) { + *error = "Workpiece is already assigned to a tray"; + } + return false; + } + return true; +} + +bool WorkpieceRepository::updateState(int id, const QString &state, const QString &processStep, + QString *error) +{ + if (!ensureOpen(error)) { + return false; + } + + QSqlQuery query(DatabaseManager::instance().database()); + query.prepare("update workpieces set state = :state, process_step = :process_step, " + "updated_at = now() where id = :id"); + query.bindValue(":state", state); + query.bindValue(":process_step", processStep); + query.bindValue(":id", id); + if (!query.exec()) { + setError(query, error); + return false; + } + return true; +} diff --git a/repositories/workpiecerepository.h b/repositories/workpiecerepository.h new file mode 100644 index 0000000..92da597 --- /dev/null +++ b/repositories/workpiecerepository.h @@ -0,0 +1,22 @@ +#ifndef WORKPIECEREPOSITORY_H +#define WORKPIECEREPOSITORY_H + +#include "../models/workpiece.h" + +#include + +class WorkpieceRepository +{ +public: + QList listByOrder(int orderId, QString *error = nullptr); + QList listByTray(int trayId, QString *error = nullptr); + bool findWorkpiece(int id, Workpiece *workpiece, QString *error = nullptr); + bool claimNextPending(int orderId, Workpiece *workpiece, QString *error = nullptr); + bool insertWorkpiece(Workpiece *workpiece, QString *error = nullptr); + bool assignToSlot(int id, int trayId, int trayPos, int rowNo, int columnNo, + QString *error = nullptr); + bool updateState(int id, const QString &state, const QString &processStep, + QString *error = nullptr); +}; + +#endif // WORKPIECEREPOSITORY_H diff --git a/services/deviceservice.cpp b/services/deviceservice.cpp new file mode 100644 index 0000000..d105d3f --- /dev/null +++ b/services/deviceservice.cpp @@ -0,0 +1,304 @@ +#include "deviceservice.h" + +#include "../config/configmanager.h" +#include "../modbus/modbustcpmanager.h" + +#include +#include +#include + +namespace { + +const int FeedbackPollIntervalMs = 50; + +} + +DeviceService &DeviceService::instance() +{ + static DeviceService service; + return service; +} + +DeviceService::DeviceService(QObject *parent) + : QObject(parent) + , m_pollTimer(new QTimer(this)) +{ + connect(m_pollTimer, &QTimer::timeout, this, &DeviceService::pollStatus); +} + +void DeviceService::startPolling() +{ + if (m_pollTimer->isActive()) { + return; + } + + const int interval = qMax(100, ModbusTcpManager::instance().config().pollIntervalMs); + m_pollTimer->start(interval); + pollStatus(); +} + +void DeviceService::stopPolling() +{ + m_pollTimer->stop(); +} + +bool DeviceService::isPolling() const +{ + return m_pollTimer->isActive(); +} + +bool DeviceService::readStatus(DeviceStatus *status, QString *error) +{ + if (!status) { + if (error) { + *error = "Device status pointer is null"; + } + return false; + } + + if (ConfigManager::instance().simulationMode()) { + *status = simulatedStatus(); + return true; + } + + QString configError; + if (!ConfigManager::instance().validate(&configError)) { + if (error) { + *error = configError; + } + status->plcConnected = false; + return false; + } + + const int attempts = qMax(1, ModbusTcpManager::instance().config().reconnectAttempts + 1); + QString lastError; + for (int attempt = 0; attempt < attempts; ++attempt) { + if (attempt > 0) { + QThread::msleep(qMax(0, ModbusTcpManager::instance().config().reconnectDelayMs)); + } + + if (!connectWithRetry(&lastError)) { + continue; + } + + if (readStatusOnce(status, &lastError)) { + return true; + } + + ModbusTcpManager::instance().disconnectDevice(); + } + + status->plcConnected = false; + if (error) { + *error = lastError.isEmpty() ? "Failed to read PLC status" : lastError; + } + return false; +} + +void DeviceService::pollStatus() +{ + DeviceStatus status; + QString error; + if (readStatus(&status, &error)) { + emit statusChanged(status); + return; + } + + status.plcConnected = false; + emit statusChanged(status); + if (!error.isEmpty()) { + emit communicationError(error); + } +} + +DeviceStatus DeviceService::simulatedStatus() const +{ + DeviceStatus status; + status.plcConnected = true; + status.plcReady = true; + status.robotReady = true; + status.safetyDoorClosed = true; + status.emergencyStop = false; + status.currentStep = 0; + status.checkResult = 0; + return status; +} + +bool DeviceService::start(QString *error) +{ + if (ConfigManager::instance().simulationMode()) { + return true; + } + if (!ConfigManager::instance().productionEnabled()) { + if (error) { + *error = "Production control is disabled by configuration"; + } + return false; + } + + const ModbusAddressMap &addresses = ModbusTcpManager::instance().config().addressMap; + return executeCommand(addresses.startCommand, addresses.startFeedback, error); +} + +bool DeviceService::pause(QString *error) +{ + if (ConfigManager::instance().simulationMode()) { + return true; + } + if (!ConfigManager::instance().productionEnabled()) { + if (error) { + *error = "Production control is disabled by configuration"; + } + return false; + } + + const ModbusAddressMap &addresses = ModbusTcpManager::instance().config().addressMap; + return executeCommand(addresses.pauseCommand, addresses.pauseFeedback, error); +} + +bool DeviceService::reset(QString *error) +{ + if (ConfigManager::instance().simulationMode()) { + return true; + } + if (!ConfigManager::instance().productionEnabled()) { + if (error) { + *error = "Production control is disabled by configuration"; + } + return false; + } + + const ModbusAddressMap &addresses = ModbusTcpManager::instance().config().addressMap; + return executeCommand(addresses.resetCommand, addresses.resetFeedback, error); +} + +bool DeviceService::clearAlarm(QString *error) +{ + if (ConfigManager::instance().simulationMode()) { + return true; + } + if (!ConfigManager::instance().productionEnabled()) { + if (error) { + *error = "Production control is disabled by configuration"; + } + return false; + } + + const ModbusAddressMap &addresses = ModbusTcpManager::instance().config().addressMap; + return executeCommand(addresses.clearAlarmCommand, addresses.clearAlarmFeedback, error); +} + +bool DeviceService::connectWithRetry(QString *error) +{ + ModbusTcpManager &modbus = ModbusTcpManager::instance(); + const ModbusConfig config = modbus.config(); + const int attempts = qMax(1, config.reconnectAttempts + 1); + QString lastError; + + for (int attempt = 0; attempt < attempts; ++attempt) { + if (attempt > 0) { + QThread::msleep(qMax(0, config.reconnectDelayMs)); + } + + if (modbus.connectDevice(&lastError)) { + return true; + } + modbus.disconnectDevice(); + } + + if (error) { + *error = lastError.isEmpty() ? "Failed to connect to PLC" : lastError; + } + return false; +} + +bool DeviceService::readStatusOnce(DeviceStatus *status, QString *error) +{ + ModbusTcpManager &modbus = ModbusTcpManager::instance(); + const ModbusAddressMap &addresses = modbus.config().addressMap; + + status->plcConnected = true; + if (!modbus.readCoil(addresses.plcReady, &status->plcReady, error) + || !modbus.readCoil(addresses.robotReady, &status->robotReady, error) + || !modbus.readCoil(addresses.safetyDoorClosed, &status->safetyDoorClosed, error) + || !modbus.readCoil(addresses.emergencyStop, &status->emergencyStop, error) + || !modbus.readHoldingRegister(addresses.currentStep, &status->currentStep, error) + || !modbus.readHoldingRegister(addresses.checkResult, &status->checkResult, error) + || !modbus.readHoldingRegister(addresses.errorCode, &status->errorCode, error)) { + return false; + } + + return true; +} + +bool DeviceService::executeCommand(int commandAddress, int feedbackAddress, QString *error) +{ + QString configError; + if (!ConfigManager::instance().validate(&configError)) { + if (error) { + *error = configError; + } + return false; + } + + const ModbusConfig config = ModbusTcpManager::instance().config(); + const int attempts = qMax(1, config.reconnectAttempts + 1); + QString lastError; + + for (int attempt = 0; attempt < attempts; ++attempt) { + if (attempt > 0) { + QThread::msleep(qMax(0, config.reconnectDelayMs)); + } + + if (!connectWithRetry(&lastError)) { + continue; + } + + ModbusTcpManager &modbus = ModbusTcpManager::instance(); + if (!modbus.writeCoil(commandAddress, true, &lastError)) { + modbus.disconnectDevice(); + continue; + } + + QThread::msleep(qMax(1, config.commandPulseMs)); + if (!modbus.writeCoil(commandAddress, false, &lastError)) { + modbus.disconnectDevice(); + continue; + } + + if (waitForFeedback(feedbackAddress, &lastError)) { + return true; + } + + modbus.disconnectDevice(); + } + + if (error) { + *error = lastError.isEmpty() ? "PLC command failed" : lastError; + } + return false; +} + +bool DeviceService::waitForFeedback(int address, QString *error) +{ + ModbusTcpManager &modbus = ModbusTcpManager::instance(); + const int timeoutMs = qMax(1, modbus.config().feedbackTimeoutMs); + QElapsedTimer timer; + timer.start(); + + while (timer.elapsed() < timeoutMs) { + bool feedback = false; + if (!modbus.readCoil(address, &feedback, error)) { + return false; + } + if (feedback) { + return true; + } + QThread::msleep(FeedbackPollIntervalMs); + } + + if (error) { + *error = QString("PLC feedback timeout at address %1").arg(address); + } + return false; +} diff --git a/services/deviceservice.h b/services/deviceservice.h new file mode 100644 index 0000000..08482d9 --- /dev/null +++ b/services/deviceservice.h @@ -0,0 +1,60 @@ +#ifndef DEVICESERVICE_H +#define DEVICESERVICE_H + +#include +#include +#include + +struct DeviceStatus +{ + bool plcConnected = false; + bool plcReady = false; + bool robotReady = false; + bool safetyDoorClosed = false; + bool emergencyStop = false; + quint16 currentStep = 0; + quint16 checkResult = 0; + quint16 errorCode = 0; +}; + +Q_DECLARE_METATYPE(DeviceStatus) + +class QTimer; + +class DeviceService : public QObject +{ + Q_OBJECT + +public: + static DeviceService &instance(); + + void startPolling(); + void stopPolling(); + bool isPolling() const; + + bool readStatus(DeviceStatus *status, QString *error = nullptr); + bool start(QString *error = nullptr); + bool pause(QString *error = nullptr); + bool reset(QString *error = nullptr); + bool clearAlarm(QString *error = nullptr); + +signals: + void statusChanged(const DeviceStatus &status); + void communicationError(const QString &error); + +private: + explicit DeviceService(QObject *parent = nullptr); + DeviceService(const DeviceService &) = delete; + DeviceService &operator=(const DeviceService &) = delete; + + void pollStatus(); + DeviceStatus simulatedStatus() const; + bool connectWithRetry(QString *error); + bool readStatusOnce(DeviceStatus *status, QString *error); + bool executeCommand(int commandAddress, int feedbackAddress, QString *error); + bool waitForFeedback(int address, QString *error); + + QTimer *m_pollTimer; +}; + +#endif // DEVICESERVICE_H diff --git a/services/logservice.cpp b/services/logservice.cpp new file mode 100644 index 0000000..559d85a --- /dev/null +++ b/services/logservice.cpp @@ -0,0 +1,24 @@ +#include "logservice.h" + +#include "../models/logrecord.h" +#include "../repositories/logrepository.h" + +LogService &LogService::instance() +{ + static LogService service; + return service; +} + +bool LogService::record(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status, QString *error) +{ + LogRecord record; + record.type = type; + record.module = module; + record.action = action; + record.content = content; + record.status = status; + + LogRepository repository; + return repository.insertLog(record, error); +} diff --git a/services/logservice.h b/services/logservice.h new file mode 100644 index 0000000..ae4148e --- /dev/null +++ b/services/logservice.h @@ -0,0 +1,20 @@ +#ifndef LOGSERVICE_H +#define LOGSERVICE_H + +#include + +class LogService +{ +public: + static LogService &instance(); + + bool record(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status, QString *error = nullptr); + +private: + LogService() = default; + LogService(const LogService &) = delete; + LogService &operator=(const LogService &) = delete; +}; + +#endif // LOGSERVICE_H diff --git a/services/orderservice.cpp b/services/orderservice.cpp new file mode 100644 index 0000000..acaac09 --- /dev/null +++ b/services/orderservice.cpp @@ -0,0 +1,441 @@ +#include "orderservice.h" + +#include "../db/databasemanager.h" +#include "../repositories/logrepository.h" +#include "../repositories/orderrepository.h" +#include "../repositories/trayrepository.h" +#include "../repositories/workpiecerepository.h" + +#include +#include +#include + +namespace { + +bool recordLog(const QString &action, const QString &content, const QString &status, + QString *error) +{ + LogRecord record; + record.type = "操作日志"; + record.module = "订单管理"; + record.action = action; + record.content = content; + record.status = status; + return LogRepository().insertLog(record, error); +} + +bool containsState(const QStringList &states, const QString &state) +{ + return states.contains(state); +} + +QString workpieceBarcode(const QString &orderNo, int sequence) +{ + return QString("%1-%2").arg(orderNo).arg(sequence, 6, 10, QChar('0')); +} + +} + +OrderService &OrderService::instance() +{ + static OrderService service; + return service; +} + +QList OrderService::listOrders(QString *error, int limit) +{ + return OrderRepository().listOrders(error, limit); +} + +bool OrderService::findOrder(int id, Order *order, QString *error) +{ + return OrderRepository().findOrder(id, order, error); +} + +bool OrderService::createOrder(Order *order, QString *error) +{ + if (!order) { + if (error) { + *error = "Order pointer is null"; + } + return false; + } + if (order->no.trimmed().isEmpty()) { + if (error) { + *error = "Order number cannot be empty"; + } + return false; + } + if (order->planNum <= 0) { + if (error) { + *error = "Order plan quantity must be greater than 0"; + } + return false; + } + + order->no = order->no.trimmed(); + order->status = "NOT_START"; + order->qualified = 0; + order->unqualified = 0; + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + OrderRepository repository; + if (!repository.insertOrder(order, &transactionError) + || !recordLog("新建订单", "创建订单:" + order->no, "成功", &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool OrderService::generateWorkpiecesAndAssign(int orderId, QString *error) +{ + if (orderId <= 0) { + if (error) { + *error = "Order id must be greater than 0"; + } + return false; + } + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + OrderRepository orderRepository; + Order order; + if (!orderRepository.findOrderForUpdate(orderId, &order, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (order.status != "NOT_START") { + database.rollback(); + if (error) { + *error = "Only not-started orders can generate workpieces"; + } + return false; + } + + WorkpieceRepository workpieceRepository; + TrayRepository trayRepository; + QList workpieces = + workpieceRepository.listByOrder(orderId, &transactionError); + if (!transactionError.isEmpty()) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (workpieces.size() > order.planNum) { + database.rollback(); + if (error) { + *error = "Existing workpieces exceed order plan quantity"; + } + return false; + } + + const QList trays = trayRepository.listTrays(&transactionError); + if (!transactionError.isEmpty()) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + for (const Tray &tray : trays) { + if (!trayRepository.initializeSlots(tray.id, 7, 7, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + } + + QSet existingBarcodes; + int assignedCount = 0; + for (const Workpiece &workpiece : workpieces) { + existingBarcodes.insert(workpiece.barcode); + if (workpiece.trayId > 0) { + ++assignedCount; + } + } + + const int missingCount = order.planNum - workpieces.size(); + int nextSequence = 1; + for (int index = 0; index < missingCount; ++index) { + while (existingBarcodes.contains(workpieceBarcode(order.no, nextSequence))) { + ++nextSequence; + } + + Workpiece workpiece; + workpiece.barcode = workpieceBarcode(order.no, nextSequence); + workpiece.orderId = order.id; + workpiece.state = "PENDING"; + if (!workpieceRepository.insertWorkpiece(&workpiece, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + workpieces.append(workpiece); + existingBarcodes.insert(workpiece.barcode); + ++nextSequence; + } + + const int requiredSlotCount = order.planNum - assignedCount; + const QList emptySlots = requiredSlotCount > 0 + ? trayRepository.listEmptySlotsForAllocation(&transactionError) + : QList(); + if (!transactionError.isEmpty()) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (emptySlots.size() < requiredSlotCount) { + database.rollback(); + if (error) { + *error = QString("Not enough empty slots: required %1, available %2") + .arg(requiredSlotCount).arg(emptySlots.size()); + } + return false; + } + + QList touchedTrayIds; + int slotIndex = 0; + for (const Workpiece &workpiece : workpieces) { + if (workpiece.trayId > 0) { + continue; + } + + const TraySlot &slot = emptySlots.at(slotIndex++); + if (!workpieceRepository.assignToSlot(workpiece.id, slot.trayId, + (slot.rowNo - 1) * 7 + slot.columnNo, + slot.rowNo, slot.columnNo, + &transactionError) + || !trayRepository.assignSlot(slot.trayId, slot.rowNo, slot.columnNo, + workpiece.id, "PENDING", + &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (!touchedTrayIds.contains(slot.trayId)) { + touchedTrayIds.append(slot.trayId); + } + } + + for (const int trayId : touchedTrayIds) { + if (!trayRepository.refreshStats(trayId, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + } + + if (!orderRepository.refreshProgress(orderId, &transactionError) + || !recordLog("生成工件", QString("订单 %1 生成并分配 %2 个工件") + .arg(order.no).arg(workpieces.size()), "成功", + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool OrderService::startOrder(int id, QString *error) +{ + return transition(id, QStringList() << "NOT_START", "RUNNING", "开始订单", error); +} + +bool OrderService::pauseOrder(int id, QString *error) +{ + return transition(id, QStringList() << "RUNNING", "PAUSED", "暂停订单", error); +} + +bool OrderService::resumeOrder(int id, QString *error) +{ + return transition(id, QStringList() << "PAUSED", "RUNNING", "恢复订单", error); +} + +bool OrderService::completeOrder(int id, QString *error) +{ + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + OrderRepository repository; + if (!repository.refreshProgress(id, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + + Order order; + if (!repository.findOrder(id, &order, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (!containsState(QStringList() << "RUNNING" << "PAUSED", order.status)) { + database.rollback(); + if (error) { + *error = "Only running or paused orders can be completed"; + } + return false; + } + if (order.qualified + order.unqualified < order.planNum) { + database.rollback(); + if (error) { + *error = "Order is not fully processed"; + } + return false; + } + + if (!repository.updateOrderLifecycle(id, "FINISHED", order.beginTime, + QDateTime::currentDateTime(), &transactionError) + || !recordLog("完成订单", "完成订单:" + order.no, "成功", &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool OrderService::cancelOrder(int id, QString *error) +{ + return transition(id, QStringList() << "NOT_START" << "PAUSED", + "CANCELED", "取消订单", error); +} + +bool OrderService::deleteOrder(int id, QString *error) +{ + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + OrderRepository repository; + Order order; + if (!repository.findOrder(id, &order, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (order.status == "RUNNING" || order.status == "PAUSED") { + database.rollback(); + if (error) { + *error = "Running or paused orders cannot be deleted"; + } + return false; + } + + if (!repository.removeOrder(id, &transactionError) + || !recordLog("删除订单", "删除订单:" + order.no, "成功", &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool OrderService::transition(int id, const QStringList &allowedStates, + const QString &targetState, const QString &action, + QString *error) +{ + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + OrderRepository repository; + Order order; + if (!repository.findOrder(id, &order, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (!containsState(allowedStates, order.status)) { + database.rollback(); + if (error) { + *error = QString("Invalid order state transition: %1 -> %2") + .arg(order.status, targetState); + } + return false; + } + + const QDateTime beginTime = targetState == "RUNNING" && !order.beginTime.isValid() + ? QDateTime::currentDateTime() : order.beginTime; + const QDateTime endTime = targetState == "CANCELED" + ? QDateTime::currentDateTime() : order.endTime; + + if (!repository.updateOrderLifecycle(id, targetState, beginTime, endTime, &transactionError) + || !recordLog(action, QString("%1:%2").arg(action, order.no), + "成功", &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} diff --git a/services/orderservice.h b/services/orderservice.h new file mode 100644 index 0000000..d6f635f --- /dev/null +++ b/services/orderservice.h @@ -0,0 +1,33 @@ +#ifndef ORDERSERVICE_H +#define ORDERSERVICE_H + +#include "../models/order.h" + +#include + +class OrderService +{ +public: + static OrderService &instance(); + + QList listOrders(QString *error = nullptr, int limit = 100); + bool findOrder(int id, Order *order, QString *error = nullptr); + bool createOrder(Order *order, QString *error = nullptr); + bool generateWorkpiecesAndAssign(int orderId, QString *error = nullptr); + bool startOrder(int id, QString *error = nullptr); + bool pauseOrder(int id, QString *error = nullptr); + bool resumeOrder(int id, QString *error = nullptr); + bool completeOrder(int id, QString *error = nullptr); + bool cancelOrder(int id, QString *error = nullptr); + bool deleteOrder(int id, QString *error = nullptr); + +private: + OrderService() = default; + OrderService(const OrderService &) = delete; + OrderService &operator=(const OrderService &) = delete; + + bool transition(int id, const QStringList &allowedStates, const QString &targetState, + const QString &action, QString *error); +}; + +#endif // ORDERSERVICE_H diff --git a/services/productionservice.cpp b/services/productionservice.cpp new file mode 100644 index 0000000..3e1d5ce --- /dev/null +++ b/services/productionservice.cpp @@ -0,0 +1,1228 @@ +#include "productionservice.h" + +#include "../config/configmanager.h" +#include "../repositories/productionrepository.h" +#include "orderservice.h" +#include "workpieceservice.h" + +#include +#include + +ProductionService &ProductionService::instance() +{ + static ProductionService service; + return service; +} + +ProductionService::ProductionService(QObject *parent) + : QObject(parent) + , m_timer(new QTimer(this)) + , m_state(Idle) + , m_timeoutState(Idle) + , m_runId(0) + , m_orderId(0) + , m_deviceStatusValid(false) + , m_recoveryRetryCount(0) + , m_processElapsedMs(0) +{ + connect(m_timer, &QTimer::timeout, this, &ProductionService::tick); + connect(&DeviceService::instance(), &DeviceService::statusChanged, + this, &ProductionService::onDeviceStatusChanged); + connect(&DeviceService::instance(), &DeviceService::communicationError, + this, &ProductionService::onCommunicationError); +} + +ProductionService::State ProductionService::state() const +{ + return m_state; +} + +QString ProductionService::stateName() const +{ + return stateNameForState(m_state); +} + +QString ProductionService::stateNameForState(State state) const +{ + switch (state) { + case Idle: return "IDLE"; + case Preparing: return "PREPARING"; + case WaitingDeviceReady: return "WAITING_DEVICE_READY"; + case Loading: return "LOADING"; + case FrontChecking: return "FRONT_CHECKING"; + case BackChecking: return "BACK_CHECKING"; + case Judging: return "JUDGING"; + case Unloading: return "UNLOADING"; + case Paused: return "PAUSED"; + case Error: return "ERROR"; + case Completed: return "COMPLETED"; + case TimeoutWarning: return "TIMEOUT_WARNING"; + case TimeoutPaused: return "TIMEOUT_PAUSED"; + case RecoveryChecking: return "RECOVERY_CHECKING"; + case ManualConfirm: return "MANUAL_CONFIRM"; + case Retrying: return "RETRYING"; + } + return "UNKNOWN"; +} + +int ProductionService::orderId() const +{ + return m_orderId; +} + +Workpiece ProductionService::currentWorkpiece() const +{ + return m_currentWorkpiece; +} + +bool ProductionService::start(int orderId, QString *error) +{ + if (orderId <= 0) { + if (error) { + *error = "Order id must be greater than 0"; + } + return false; + } + if (m_state != Idle && m_state != Completed) { + if (error) { + *error = "Production service is already active"; + } + return false; + } + + Order order; + if (!OrderService::instance().findOrder(orderId, &order, error)) { + return false; + } + if (order.status != "NOT_START") { + if (error) { + *error = "Only not-started orders can start production"; + } + return false; + } + + if (!DeviceService::instance().start(error) + || !OrderService::instance().startOrder(orderId, error)) { + return false; + } + + m_orderId = orderId; + m_currentWorkpiece = Workpiece(); + clearProcessTimer(); + m_deviceStatusValid = false; + m_recoveryRetryCount = 0; + m_lastError.clear(); + + QString persistenceError; + m_runId = ProductionRepository().createRun( + m_orderId, "PREPARING", "PREPARING", &persistenceError); + if (m_runId <= 0) { + DeviceService::instance().pause(); + OrderService::instance().pauseOrder(m_orderId); + m_orderId = 0; + if (error) { + *error = "Failed to create production run: " + persistenceError; + } + return false; + } + + setState(Preparing); + + DeviceService::instance().startPolling(); + const int interval = qMax(100, ConfigManager::instance() + .modbusConfig().pollIntervalMs); + m_heartbeatTimer.restart(); + m_timer->start(interval); + tick(); + return true; +} + +bool ProductionService::pause(QString *error) +{ + if (!isActive()) { + if (error) { + *error = "Production service is not active"; + } + return false; + } + + if (!DeviceService::instance().pause(error) + || !OrderService::instance().pauseOrder(m_orderId, error)) { + return false; + } + + pauseProcessTimer(); + m_timer->stop(); + setState(Paused); + emitProcessElapsed(); + return true; +} + +bool ProductionService::resume(QString *error) +{ + if (m_state != Paused) { + if (error) { + *error = "Production service is not paused"; + } + return false; + } + + if (!checkRecoverySafety(error) + || !DeviceService::instance().start(error) + || !OrderService::instance().resumeOrder(m_orderId, error)) { + return false; + } + + resumeProcessTimer(); + setState(m_currentWorkpiece.id > 0 ? WaitingDeviceReady : Preparing); + const int interval = qMax(100, ConfigManager::instance() + .modbusConfig().pollIntervalMs); + m_timer->start(interval); + return true; +} + +bool ProductionService::stop(QString *error) +{ + if (m_state == Idle || m_state == Completed) { + if (error) { + *error = "Production service is not running"; + } + return false; + } + + QString operationError; + if (m_state != Paused && m_state != TimeoutPaused + && m_state != ManualConfirm + && !DeviceService::instance().pause(&operationError)) { + if (error) { + *error = operationError; + } + return false; + } + + Order order; + if (!OrderService::instance().findOrder(m_orderId, &order, &operationError)) { + if (error) { + *error = operationError; + } + return false; + } + if (order.status == "RUNNING" + && !OrderService::instance().pauseOrder(m_orderId, &operationError)) { + if (error) { + *error = operationError; + } + return false; + } + + m_lastError = "Production stopped by operator"; + m_timer->stop(); + setState(Idle); + + QString persistenceError; + if (m_runId > 0 + && !ProductionRepository().finishRun( + m_runId, "STOPPED", m_lastError, &persistenceError)) { + if (error) { + *error = persistenceError; + } + return false; + } + + persistRecoveryAction("STOP", m_lastError); + m_runId = 0; + m_orderId = 0; + m_currentWorkpiece = Workpiece(); + clearProcessTimer(); + emit currentWorkpieceChanged(0, QString()); + return true; +} + +bool ProductionService::reset(QString *error) +{ + if (m_state != Error) { + if (error) { + *error = "Only failed production can be reset"; + } + return false; + } + + if (!DeviceService::instance().reset(error) + || !DeviceService::instance().clearAlarm(error)) { + return false; + } + + QString persistenceError; + if (!ProductionRepository().clearActiveAlarms( + QString(), "SYSTEM", &persistenceError)) { + if (error) { + *error = persistenceError; + } + return false; + } + + if (m_currentWorkpiece.id > 0 + && !WorkpieceService::instance().updateState( + m_currentWorkpiece.id, "PENDING", "RECOVERY", error)) { + return false; + } + + m_currentWorkpiece = Workpiece(); + clearProcessTimer(); + m_lastError.clear(); + setState(Preparing); + const int interval = qMax(100, ConfigManager::instance() + .modbusConfig().pollIntervalMs); + m_heartbeatTimer.restart(); + m_timer->start(interval); + return true; +} + +bool ProductionService::restoreActiveRun(QString *error) +{ + if (m_state != Idle) { + return true; + } + + ProductionRunSnapshot run; + QString persistenceError; + if (!ProductionRepository().findActiveRun(&run, &persistenceError)) { + if (error) { + *error = persistenceError; + } + return false; + } + if (run.id <= 0) { + return true; + } + + m_runId = run.id; + m_orderId = run.orderId; + m_recoveryRetryCount = run.recoveryRetryCount; + m_lastError = run.lastError; + + if (run.currentWorkpieceId > 0) { + QString workpieceError; + if (!WorkpieceService::instance().findWorkpiece( + run.currentWorkpieceId, &m_currentWorkpiece, &workpieceError)) { + if (error) { + *error = workpieceError; + } + return false; + } + emit currentWorkpieceChanged(m_currentWorkpiece.id, + m_currentWorkpiece.barcode); + startProcessTimer(m_currentWorkpiece.processStep); + emitProcessElapsed(); + } + + State persistedState = stateFromName(run.productionState); + if (persistedState == Idle || persistedState == Completed + || persistedState == Error) { + persistedState = Preparing; + } + m_timeoutState = stateFromName(run.timeoutState); + if (!isTimedState(m_timeoutState)) { + m_timeoutState = persistedState; + } + + setState(ManualConfirm); + m_heartbeatTimer.restart(); + m_timer->stop(); + emit timeoutRecoveryRequired( + "STARTUP_RECOVERY", + QString("Unfinished production run %1 requires recovery confirmation") + .arg(run.id)); + return true; +} + +bool ProductionService::recover(QString *error) +{ + if (m_state != TimeoutPaused && m_state != ManualConfirm) { + if (error) { + *error = "Production is not waiting for recovery"; + } + return false; + } + + if (!checkRecoverySafety(error)) { + return false; + } + + QString operationError; + if (!ensureOrderRunning(&operationError) + || !DeviceService::instance().start(&operationError)) { + if (error) { + *error = operationError; + } + return false; + } + + persistRecoveryAction("CONTINUE", + QString("Continue recovery from %1").arg(stateName())); + setState(RecoveryChecking); + const int interval = qMax(100, ConfigManager::instance() + .modbusConfig().pollIntervalMs); + m_heartbeatTimer.restart(); + m_timer->start(interval); + tick(); + return m_state != Error; +} + +bool ProductionService::retry(QString *error) +{ + if (m_state != TimeoutPaused && m_state != ManualConfirm) { + if (error) { + *error = "Production is not waiting for a retry"; + } + return false; + } + + if (!checkRecoverySafety(error)) { + return false; + } + + const ProductionConfig config = ConfigManager::instance().productionConfig(); + if (m_recoveryRetryCount >= config.maxRecoveryRetries) { + if (error) { + *error = "Maximum timeout recovery retries reached"; + } + return false; + } + + QString operationError; + if (!ensureOrderRunning(&operationError) + || !DeviceService::instance().start(&operationError)) { + if (error) { + *error = operationError; + } + return false; + } + const QString processStep = processStepForState(m_timeoutState); + if (m_currentWorkpiece.id <= 0 || processStep.isEmpty()) { + if (error) { + *error = "Cannot retry without a current production step"; + } + return false; + } + if (!updateCurrentProcessStep(processStep, &operationError, true)) { + if (error) { + *error = operationError; + } + return false; + } + + ++m_recoveryRetryCount; + persistRecoveryAction("RETRY", + QString("Retry production step %1").arg(processStep)); + setState(Retrying); + const int interval = qMax(100, ConfigManager::instance() + .modbusConfig().pollIntervalMs); + m_heartbeatTimer.restart(); + m_timer->start(interval); + return true; +} + +bool ProductionService::markCurrentWorkpieceNg(QString *error) +{ + if (m_state != TimeoutPaused && m_state != ManualConfirm) { + if (error) { + *error = "Production is not waiting for manual recovery"; + } + return false; + } + if (m_currentWorkpiece.id <= 0) { + if (error) { + *error = "No current workpiece can be marked as NG"; + } + return false; + } + if (!checkRecoverySafety(error)) { + return false; + } + + QString operationError; + if (!ensureOrderRunning(&operationError) + || !DeviceService::instance().start(&operationError)) { + if (error) { + *error = operationError; + } + return false; + } + + const int durationMs = currentProcessElapsedMs(); + const QString previousProcessStep = m_currentWorkpiece.processStep; + if (!WorkpieceService::instance().completeWithInspection( + m_currentWorkpiece.id, "NG", "COMPLETE", previousProcessStep, + durationMs, -1, "NG", m_deviceStatus.currentStep, "MANUAL", + &operationError)) { + if (error) { + *error = operationError; + } + return false; + } + + persistRecoveryAction( + "MARK_NG", + QString("Current workpiece %1 was manually marked as NG") + .arg(m_currentWorkpiece.barcode)); + m_currentWorkpiece = Workpiece(); + clearProcessTimer(); + m_recoveryRetryCount = 0; + m_lastError.clear(); + emit currentWorkpieceChanged(0, QString()); + setState(Preparing); + const int interval = qMax(100, ConfigManager::instance() + .modbusConfig().pollIntervalMs); + m_heartbeatTimer.restart(); + m_timer->start(interval); + return true; +} + +void ProductionService::setState(State state) +{ + if (m_state == state) { + return; + } + + const QString previousStateName = stateName(); + m_state = state; + m_stateTimer.restart(); + emit stateChanged(m_state, stateName()); + + if (m_runId > 0) { + const QString processStep = processStepForState(state).isEmpty() + ? processStepForState(m_timeoutState) + : processStepForState(state); + QString persistenceError; + ProductionRepository repository; + if (!repository.updateRun( + m_runId, runStateForState(state), stateName(), processStep, + m_currentWorkpiece.id, + isTimedState(m_timeoutState) ? stateNameForState(m_timeoutState) + : QString(), + m_recoveryRetryCount, m_lastError, &persistenceError) + || !repository.insertStateHistory( + m_runId, m_orderId, m_currentWorkpiece.id, + previousStateName, stateName(), processStep, + state == RecoveryChecking || state == ManualConfirm + || state == Retrying ? "RECOVERY" : "SYSTEM", + QString(), QString(), &persistenceError)) { + qWarning() << "Failed to persist production state:" << persistenceError; + } + } +} + +bool ProductionService::claimNextWorkpiece(QString *error) +{ + Workpiece workpiece; + if (!WorkpieceService::instance().claimNextPending(m_orderId, &workpiece, error)) { + return false; + } + if (workpiece.id <= 0) { + return finishOrder(error); + } + + m_currentWorkpiece = workpiece; + m_recoveryRetryCount = 0; + QString persistenceError; + const QString source = ConfigManager::instance().simulationMode() + ? "SIMULATION" : "PLC"; + if (!ProductionRepository().startWorkpieceProcess( + m_orderId, workpiece.id, workpiece.processStep, + m_deviceStatus.currentStep, + source, &persistenceError)) { + if (error) { + *error = persistenceError; + } + return false; + } + startProcessTimer(workpiece.processStep); + emit currentWorkpieceChanged(workpiece.id, workpiece.barcode); + emitProcessElapsed(); + setState(WaitingDeviceReady); + return true; +} + +bool ProductionService::updateCurrentProcessStep(const QString &processStep, + QString *error, + bool forceRestart) +{ + if (m_currentWorkpiece.id <= 0) { + if (error) { + *error = "No current workpiece"; + } + return false; + } + + const QString source = ConfigManager::instance().simulationMode() + ? "SIMULATION" : "PLC"; + const int durationMs = currentProcessElapsedMs(); + if (!WorkpieceService::instance().updateProcessStepWithRecord( + m_currentWorkpiece.id, processStep, m_deviceStatus.currentStep, + source, durationMs, error, forceRestart)) { + return false; + } + + m_currentWorkpiece.processStep = processStep; + startProcessTimer(processStep); + emitProcessElapsed(); + return true; +} + +void ProductionService::startProcessTimer(const QString &processStep) +{ + m_currentProcessStep = processStep; + m_processElapsedMs = 0; + if (processStep.trimmed().isEmpty()) { + m_processTimer.invalidate(); + return; + } + m_processTimer.restart(); +} + +void ProductionService::pauseProcessTimer() +{ + if (m_processTimer.isValid()) { + m_processElapsedMs += static_cast(m_processTimer.elapsed()); + m_processTimer.invalidate(); + } +} + +void ProductionService::resumeProcessTimer() +{ + if (m_currentProcessStep.trimmed().isEmpty()) { + return; + } + m_processTimer.restart(); +} + +void ProductionService::clearProcessTimer() +{ + m_processTimer.invalidate(); + m_processElapsedMs = 0; + m_currentProcessStep.clear(); +} + +int ProductionService::currentProcessElapsedMs() const +{ + if (!m_processTimer.isValid()) { + return m_processElapsedMs; + } + return m_processElapsedMs + static_cast(m_processTimer.elapsed()); +} + +void ProductionService::emitProcessElapsed() +{ + if (m_currentProcessStep.trimmed().isEmpty()) { + return; + } + emit processElapsedChanged(m_currentProcessStep, currentProcessElapsedMs()); +} + +bool ProductionService::ensureOrderRunning(QString *error) +{ + Order order; + if (!OrderService::instance().findOrder(m_orderId, &order, error)) { + return false; + } + if (order.status == "RUNNING") { + return true; + } + if (order.status == "PAUSED") { + return OrderService::instance().resumeOrder(m_orderId, error); + } + if (error) { + *error = QString("Order cannot resume from state: %1").arg(order.status); + } + return false; +} + +bool ProductionService::checkRecoverySafety(QString *error) const +{ + if (!m_deviceStatusValid) { + if (error) { + *error = "Device status is not available"; + } + return false; + } + if (!m_deviceStatus.plcConnected) { + if (error) { + *error = "PLC is disconnected"; + } + 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 (m_deviceStatus.errorCode > 0) { + if (error) { + *error = QString("PLC error code: %1").arg(m_deviceStatus.errorCode); + } + return false; + } + return true; +} + +bool ProductionService::mapPlcStepToState(State *state, QString *processStep) const +{ + if (!state || !processStep) { + return false; + } + + const ProductionConfig config = ConfigManager::instance().productionConfig(); + if (m_deviceStatus.currentStep == config.loadStep) { + *state = Loading; + *processStep = "LOADING"; + return true; + } + if (m_deviceStatus.currentStep == config.frontCheckStep) { + *state = FrontChecking; + *processStep = "FRONT_CHECKING"; + return true; + } + if (m_deviceStatus.currentStep == config.backCheckStep) { + *state = BackChecking; + *processStep = "BACK_CHECKING"; + return true; + } + if (m_deviceStatus.currentStep == config.unloadStep + || m_deviceStatus.currentStep == config.cycleCompleteStep) { + *state = Judging; + *processStep = "JUDGING"; + return true; + } + return false; +} + +void ProductionService::persistRecoveryAction(const QString &action, + const QString &message) +{ + if (m_runId <= 0) { + return; + } + + QString persistenceError; + if (!ProductionRepository().insertStateHistory( + m_runId, m_orderId, m_currentWorkpiece.id, + stateName(), stateName(), processStepForState(m_state), + "RECOVERY", action, message, &persistenceError)) { + qWarning() << "Failed to persist recovery action:" << persistenceError; + } +} + +bool ProductionService::finishCurrentWorkpiece(const QString &state, + const QString &processStep, + QString *error) +{ + if (m_currentWorkpiece.id <= 0) { + if (error) { + *error = "No current workpiece"; + } + return false; + } + + const QString previousProcessStep = m_currentWorkpiece.processStep; + const int processDurationMs = currentProcessElapsedMs(); + const int rawResult = ConfigManager::instance().simulationMode() + ? ConfigManager::instance().productionConfig().simulationResult + : static_cast(m_deviceStatus.checkResult); + 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)) { + return false; + } + + clearProcessTimer(); + m_currentWorkpiece = Workpiece(); + emit currentWorkpieceChanged(0, QString()); + setState(Preparing); + 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; + } + + m_timer->stop(); + setState(Completed); + emit productionFinished(m_orderId); + return true; +} + +void ProductionService::tick() +{ + if (!isActive()) { + return; + } + + if (!m_deviceStatusValid) { + return; + } + + if (m_heartbeatTimer.isValid() && m_heartbeatTimer.elapsed() >= 1000) { + QString heartbeatError; + if (!ProductionRepository().heartbeatRun(m_runId, &heartbeatError)) { + qWarning() << "Failed to persist production heartbeat:" << heartbeatError; + } + 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 (m_deviceStatus.errorCode > 0) { + fail(QString("PLC error code: %1").arg(m_deviceStatus.errorCode)); + return; + } + } + + if (m_state == Preparing) { + QString error; + if (!claimNextWorkpiece(&error)) { + fail(error); + } + return; + } + + if (m_state == WaitingDeviceReady) { + if (m_deviceStatus.plcReady && m_deviceStatus.robotReady) { + QString error; + if (!updateCurrentProcessStep("LOADING", &error)) { + fail(error); + } else { + setState(Loading); + } + } + emitProcessElapsed(); + return; + } + + if (m_state == RecoveryChecking || m_state == Retrying) { + tickProduction(); + } else if (ConfigManager::instance().simulationMode()) { + tickSimulation(); + } else { + tickProduction(); + } + + emitProcessElapsed(); +} + +void ProductionService::tickSimulation() +{ + const int stepMs = qMax(1, ConfigManager::instance() + .productionConfig().simulationStepMs); + if (m_stateTimer.elapsed() < stepMs) { + 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; + } +} + +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()) { + fail(error); + } + return; + } + + if (m_state == Retrying) { + setState(m_timeoutState); + return; + } + + QString error; + if (!processProductionStep(m_state, &error) && !error.isEmpty()) { + fail(error); + } +} + +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)) { + return false; + } else { + setState(FrontChecking); + } + } + 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) { + if (error) { + *error = QString("PLC inspection error result: %1") + .arg(m_deviceStatus.checkResult); + } + return false; + } else { + if (error) { + *error = QString("Unknown PLC inspection result: %1") + .arg(m_deviceStatus.checkResult); + } + return false; + } + + if (!finishCurrentWorkpiece(resultState, "COMPLETE", error)) { + return false; + } + break; + default: + break; + } + return true; +} + +bool ProductionService::recoverFromPlcStep(QString *error) +{ + if (!checkRecoverySafety(error)) { + return true; + } + + if (ConfigManager::instance().simulationMode() + && isTimedState(m_timeoutState)) { + setState(m_timeoutState); + emit recoveryCompleted("SIMULATION_STATE"); + return true; + } + + if (m_timeoutState == Preparing) { + setState(Preparing); + emit recoveryCompleted("PREPARING"); + return true; + } + + if (m_timeoutState == WaitingDeviceReady) { + if (m_deviceStatus.plcReady && m_deviceStatus.robotReady) { + if (m_currentWorkpiece.id > 0 + && m_currentWorkpiece.processStep != "LOADING" + && !updateCurrentProcessStep("LOADING", error)) { + return false; + } + setState(Loading); + } else { + setState(WaitingDeviceReady); + } + emit recoveryCompleted("DEVICE_STATUS"); + return true; + } + + State recoveredState = Idle; + QString processStep; + if (!mapPlcStepToState(&recoveredState, &processStep)) { + m_timer->stop(); + setState(ManualConfirm); + const QString message = QString("PLC current step %1 cannot be mapped automatically") + .arg(m_deviceStatus.currentStep); + emit timeoutRecoveryRequired(stateName(), message); + return true; + } + + if (m_currentWorkpiece.id > 0 + && m_currentWorkpiece.processStep != processStep + && !updateCurrentProcessStep(processStep, error)) { + return false; + } + persistRecoveryAction( + "PLC_STEP", + QString("Recovered from PLC step %1 to %2") + .arg(m_deviceStatus.currentStep).arg(processStep)); + setState(recoveredState); + emit recoveryCompleted("PLC_CURRENT_STEP"); + return true; +} + +bool ProductionService::isTimedState(State state) const +{ + return state == Preparing || state == WaitingDeviceReady + || state == Loading || state == FrontChecking + || state == BackChecking || state == Judging; +} + +QString ProductionService::processStepForState(State state) const +{ + switch (state) { + case Preparing: return "PREPARING"; + case WaitingDeviceReady: return "WAITING_DEVICE_READY"; + case Loading: return "LOADING"; + case FrontChecking: return "FRONT_CHECKING"; + case BackChecking: return "BACK_CHECKING"; + case Judging: return "JUDGING"; + default: return QString(); + } +} + +QString ProductionService::runStateForState(State state) const +{ + switch (state) { + case Paused: + return "PAUSED"; + case Error: + return "ERROR"; + case Completed: + return "COMPLETED"; + case TimeoutPaused: + case RecoveryChecking: + case ManualConfirm: + case Retrying: + return "RECOVERY"; + case Idle: + return "STOPPED"; + default: + return "RUNNING"; + } +} + +ProductionService::State ProductionService::stateFromName(const QString &name) const +{ + if (name == "PREPARING") return Preparing; + if (name == "WAITING_DEVICE_READY") return WaitingDeviceReady; + if (name == "LOADING") return Loading; + if (name == "FRONT_CHECKING") return FrontChecking; + if (name == "BACK_CHECKING") return BackChecking; + if (name == "JUDGING") return Judging; + if (name == "UNLOADING") return Unloading; + if (name == "PAUSED") return Paused; + if (name == "ERROR") return Error; + if (name == "COMPLETED") return Completed; + if (name == "TIMEOUT_WARNING") return TimeoutWarning; + if (name == "TIMEOUT_PAUSED") return TimeoutPaused; + if (name == "RECOVERY_CHECKING") return RecoveryChecking; + if (name == "MANUAL_CONFIRM") return ManualConfirm; + if (name == "RETRYING") return Retrying; + return Idle; +} + +void ProductionService::persistAlarm(const QString &code, const QString &message) +{ + QString persistenceError; + QString level = "ERROR"; + QString source = "PRODUCTION"; + if (code.contains("WARNING")) { + level = "WARNING"; + } else if (code == "EMERGENCY_STOP" || code == "SAFETY_DOOR_OPEN") { + level = "CRITICAL"; + source = "DEVICE"; + } else if (code == "PLC_DISCONNECTED") { + level = "CRITICAL"; + source = "PLC"; + } + + if (!ProductionRepository().insertAlarm( + code, message, m_orderId, m_currentWorkpiece.id, + level, source, &persistenceError)) { + qWarning() << "Failed to persist alarm:" << persistenceError; + } +} + +void ProductionService::persistDeviceStatus(const DeviceStatus &status) +{ + QString persistenceError; + if (!ProductionRepository().insertDeviceStatus( + "PLC", status.plcConnected, status.plcReady, + status.robotReady, status.safetyDoorClosed, + status.emergencyStop, status.currentStep, + status.checkResult, status.errorCode, &persistenceError)) { + qWarning() << "Failed to persist device status:" << persistenceError; + } +} + +void ProductionService::fail(const QString &error) +{ + if (m_state == Error) { + return; + } + + m_lastError = error.isEmpty() ? "Production failed" : error; + m_timer->stop(); + setState(Error); + QString alarmCode = "PRODUCTION"; + if (m_lastError == "PLC is disconnected" + || m_lastError.startsWith("Failed to connect") + || m_lastError.startsWith("Failed to read PLC")) { + alarmCode = "PLC_DISCONNECTED"; + } else if (m_lastError == "Emergency stop is active") { + alarmCode = "EMERGENCY_STOP"; + } else if (m_lastError == "Safety door is open") { + alarmCode = "SAFETY_DOOR_OPEN"; + } + persistAlarm(alarmCode, m_lastError); + emit productionError(m_lastError); + emit alarmRaised(alarmCode, m_lastError); +} + +bool ProductionService::isActive() const +{ + return m_state != Idle && m_state != Error + && m_state != Completed && m_state != Paused + && m_state != TimeoutPaused && m_state != ManualConfirm; +} + +void ProductionService::onDeviceStatusChanged(const DeviceStatus &status) +{ + const bool changed = !m_deviceStatusValid + || status.plcConnected != m_deviceStatus.plcConnected + || status.plcReady != m_deviceStatus.plcReady + || status.robotReady != m_deviceStatus.robotReady + || status.safetyDoorClosed != m_deviceStatus.safetyDoorClosed + || status.emergencyStop != m_deviceStatus.emergencyStop + || status.currentStep != m_deviceStatus.currentStep + || status.checkResult != m_deviceStatus.checkResult + || status.errorCode != m_deviceStatus.errorCode; + m_deviceStatus = status; + m_deviceStatusValid = true; + if (changed) { + persistDeviceStatus(status); + } +} + +void ProductionService::onCommunicationError(const QString &error) +{ + if (m_state == RecoveryChecking) { + m_lastError = error; + return; + } + if (isActive()) { + fail(error); + } +} diff --git a/services/productionservice.h b/services/productionservice.h new file mode 100644 index 0000000..fa0e25f --- /dev/null +++ b/services/productionservice.h @@ -0,0 +1,125 @@ +#ifndef PRODUCTIONSERVICE_H +#define PRODUCTIONSERVICE_H + +#include "deviceservice.h" + +#include "../models/workpiece.h" + +#include +#include + +class QTimer; + +class ProductionService : public QObject +{ + Q_OBJECT + +public: + enum State + { + Idle, + Preparing, + WaitingDeviceReady, + Loading, + FrontChecking, + BackChecking, + Judging, + Unloading, + Paused, + Error, + Completed, + TimeoutWarning, + TimeoutPaused, + RecoveryChecking, + ManualConfirm, + Retrying + }; + Q_ENUM(State) + + static ProductionService &instance(); + + State state() const; + QString stateName() const; + int orderId() const; + Workpiece currentWorkpiece() const; + + bool start(int orderId, QString *error = nullptr); + bool pause(QString *error = nullptr); + bool resume(QString *error = nullptr); + bool stop(QString *error = nullptr); + bool reset(QString *error = nullptr); + bool recover(QString *error = nullptr); + bool retry(QString *error = nullptr); + bool markCurrentWorkpieceNg(QString *error = nullptr); + bool restoreActiveRun(QString *error = nullptr); + +signals: + void stateChanged(ProductionService::State state, const QString &name); + void currentWorkpieceChanged(int workpieceId, const QString &barcode); + 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 slots: + void tick(); + void onDeviceStatusChanged(const DeviceStatus &status); + void onCommunicationError(const QString &error); + +private: + explicit ProductionService(QObject *parent = nullptr); + ProductionService(const ProductionService &) = delete; + ProductionService &operator=(const ProductionService &) = delete; + + void setState(State state); + bool claimNextWorkpiece(QString *error); + bool updateCurrentProcessStep(const QString &processStep, QString *error, + bool forceRestart = false); + bool finishCurrentWorkpiece(const QString &state, const QString &processStep, + QString *error); + bool finishOrder(QString *error); + void tickSimulation(); + void tickProduction(); + bool processProductionStep(State state, QString *error); + bool recoverFromPlcStep(QString *error); + bool ensureOrderRunning(QString *error); + bool checkRecoverySafety(QString *error) const; + bool mapPlcStepToState(State *state, QString *processStep) const; + void startProcessTimer(const QString &processStep); + void pauseProcessTimer(); + void resumeProcessTimer(); + void clearProcessTimer(); + int currentProcessElapsedMs() const; + void emitProcessElapsed(); + void persistRecoveryAction(const QString &action, const QString &message); + bool isTimedState(State state) const; + QString stateNameForState(State state) const; + QString processStepForState(State state) const; + QString runStateForState(State state) const; + State stateFromName(const QString &name) const; + void persistAlarm(const QString &code, const QString &message); + void persistDeviceStatus(const DeviceStatus &status); + void fail(const QString &error); + bool isActive() const; + + QTimer *m_timer; + QElapsedTimer m_stateTimer; + QElapsedTimer m_processTimer; + QElapsedTimer m_heartbeatTimer; + State m_state; + State m_timeoutState; + int m_runId; + int m_orderId; + Workpiece m_currentWorkpiece; + DeviceStatus m_deviceStatus; + bool m_deviceStatusValid; + int m_recoveryRetryCount; + int m_processElapsedMs; + QString m_currentProcessStep; + QString m_lastError; +}; + +#endif // PRODUCTIONSERVICE_H diff --git a/services/trayservice.cpp b/services/trayservice.cpp new file mode 100644 index 0000000..66ccd84 --- /dev/null +++ b/services/trayservice.cpp @@ -0,0 +1,178 @@ +#include "trayservice.h" + +#include "../db/databasemanager.h" +#include "../repositories/logrepository.h" +#include "../repositories/trayrepository.h" + +namespace { + +bool recordLog(const QString &action, const QString &content, QString *error) +{ + LogRecord record; + record.type = "操作日志"; + record.module = "料架/托盘"; + record.action = action; + record.content = content; + record.status = "成功"; + return LogRepository().insertLog(record, error); +} + +} + +TrayService &TrayService::instance() +{ + static TrayService service; + return service; +} + +QList TrayService::listTrays(QString *error) +{ + return TrayRepository().listTrays(error); +} + +QList TrayService::listSlots(int trayId, QString *error) +{ + return TrayRepository().listSlots(trayId, error); +} + +bool TrayService::initializeTrayGrid(int trayId, QString *error) +{ + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + TrayRepository repository; + if (!repository.initializeSlots(trayId, 7, 7, &transactionError) + || !recordLog("初始化托盘格位", + QString("初始化托盘 %1 的 7x7 格位").arg(trayId), + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool TrayService::initializeAllTrayGrids(QString *error) +{ + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + TrayRepository repository; + const QList trays = repository.listTrays(&transactionError); + if (!transactionError.isEmpty()) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + for (const Tray &tray : trays) { + if (!repository.initializeSlots(tray.id, 7, 7, &transactionError) + || !repository.refreshStats(tray.id, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + } + if (!recordLog("初始化托盘格位", + QString("初始化 %1 个托盘的 7x7 格位").arg(trays.size()), + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool TrayService::ensureAllTrayGrids(QString *error) +{ + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + TrayRepository repository; + const QList trays = repository.listTrays(&transactionError); + if (!transactionError.isEmpty()) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + + for (const Tray &tray : trays) { + if (!repository.initializeSlots(tray.id, 7, 7, &transactionError) + || !repository.refreshStats(tray.id, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + } + + if (!database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool TrayService::findFirstEmptySlot(int trayId, TraySlot *slot, QString *error) +{ + if (!slot) { + if (error) { + *error = "Tray slot pointer is null"; + } + return false; + } + + const QList slots = listSlots(trayId, error); + if (error && !error->isEmpty()) { + return false; + } + for (const TraySlot &candidate : slots) { + if (candidate.workpieceId <= 0 && candidate.state == "EMPTY") { + *slot = candidate; + return true; + } + } + + if (error) { + *error = "No empty slot found"; + } + return false; +} + +bool TrayService::refreshTrayStats(int trayId, QString *error) +{ + return TrayRepository().refreshStats(trayId, error); +} diff --git a/services/trayservice.h b/services/trayservice.h new file mode 100644 index 0000000..0dae63a --- /dev/null +++ b/services/trayservice.h @@ -0,0 +1,27 @@ +#ifndef TRAYSERVICE_H +#define TRAYSERVICE_H + +#include "../models/tray.h" + +#include + +class TrayService +{ +public: + static TrayService &instance(); + + QList listTrays(QString *error = nullptr); + QList listSlots(int trayId, QString *error = nullptr); + bool initializeTrayGrid(int trayId, QString *error = nullptr); + bool initializeAllTrayGrids(QString *error = nullptr); + bool ensureAllTrayGrids(QString *error = nullptr); + bool findFirstEmptySlot(int trayId, TraySlot *slot, QString *error = nullptr); + bool refreshTrayStats(int trayId, QString *error = nullptr); + +private: + TrayService() = default; + TrayService(const TrayService &) = delete; + TrayService &operator=(const TrayService &) = delete; +}; + +#endif // TRAYSERVICE_H diff --git a/services/workpieceservice.cpp b/services/workpieceservice.cpp new file mode 100644 index 0000000..693adc3 --- /dev/null +++ b/services/workpieceservice.cpp @@ -0,0 +1,422 @@ +#include "workpieceservice.h" + +#include "../db/databasemanager.h" +#include "../repositories/logrepository.h" +#include "../repositories/orderrepository.h" +#include "../repositories/productionrepository.h" +#include "../repositories/trayrepository.h" +#include "../repositories/workpiecerepository.h" +#include "trayservice.h" + +namespace { + +bool recordLog(const QString &action, const QString &content, QString *error) +{ + LogRecord record; + record.type = "生产日志"; + record.module = "工件管理"; + record.action = action; + record.content = content; + record.status = "成功"; + return LogRepository().insertLog(record, error); +} + +bool validSlotCoordinate(int rowNo, int columnNo) +{ + return rowNo >= 1 && rowNo <= 7 && columnNo >= 1 && columnNo <= 7; +} + +} + +WorkpieceService &WorkpieceService::instance() +{ + static WorkpieceService service; + return service; +} + +QList WorkpieceService::listByOrder(int orderId, QString *error) +{ + return WorkpieceRepository().listByOrder(orderId, error); +} + +QList WorkpieceService::listByTray(int trayId, QString *error) +{ + return WorkpieceRepository().listByTray(trayId, error); +} + +bool WorkpieceService::findWorkpiece(int id, Workpiece *workpiece, QString *error) +{ + return WorkpieceRepository().findWorkpiece(id, workpiece, error); +} + +bool WorkpieceService::claimNextPending(int orderId, Workpiece *workpiece, + QString *error) +{ + if (orderId <= 0 || !workpiece) { + if (error) { + *error = orderId <= 0 ? "Order id must be greater than 0" + : "Workpiece pointer is null"; + } + return false; + } + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + WorkpieceRepository workpieceRepository; + if (!workpieceRepository.claimNextPending(orderId, workpiece, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (workpiece->id <= 0) { + if (!database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; + } + + if (workpiece->trayId > 0 + && (!TrayRepository().updateSlotState(workpiece->trayId, workpiece->rowNo, + workpiece->columnNo, "PROCESSING", + workpiece->id, &transactionError) + || !TrayRepository().refreshStats(workpiece->trayId, &transactionError))) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + + if (!OrderRepository().refreshProgress(orderId, &transactionError) + || !recordLog("CLAIM_WORKPIECE", + QString("Claimed workpiece %1").arg(workpiece->barcode), + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool WorkpieceService::createWorkpiece(Workpiece *workpiece, QString *error) +{ + if (!workpiece || workpiece->barcode.trimmed().isEmpty()) { + if (error) { + *error = workpiece ? "Workpiece barcode cannot be empty" + : "Workpiece pointer is null"; + } + return false; + } + + workpiece->barcode = workpiece->barcode.trimmed(); + workpiece->state = "PENDING"; + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + if (!WorkpieceRepository().insertWorkpiece(workpiece, &transactionError) + || !recordLog("创建工件", "创建工件:" + workpiece->barcode, + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool WorkpieceService::assignToFirstEmptySlot(int workpieceId, int trayId, + QString *error) +{ + TraySlot slot; + if (!TrayService::instance().findFirstEmptySlot(trayId, &slot, error)) { + return false; + } + return assignToSlot(workpieceId, trayId, slot.rowNo, slot.columnNo, error); +} + +bool WorkpieceService::assignToSlot(int workpieceId, int trayId, int rowNo, + int columnNo, QString *error) +{ + if (!validSlotCoordinate(rowNo, columnNo)) { + if (error) { + *error = "Tray slot coordinate must be between 1 and 7"; + } + return false; + } + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + WorkpieceRepository workpieceRepository; + TrayRepository trayRepository; + Workpiece workpiece; + if (!workpieceRepository.findWorkpiece(workpieceId, &workpiece, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + if (workpiece.trayId > 0) { + database.rollback(); + if (error) { + *error = "Workpiece is already assigned to a tray"; + } + return false; + } + + const QList trays = trayRepository.listTrays(&transactionError); + Tray tray; + bool trayFound = false; + for (const Tray &candidate : trays) { + if (candidate.id == trayId) { + tray = candidate; + trayFound = true; + break; + } + } + if (!trayFound || !tray.present) { + database.rollback(); + if (error) { + *error = "Tray does not exist or is not present"; + } + return false; + } + + const int trayPos = (rowNo - 1) * 7 + columnNo; + if (!workpieceRepository.assignToSlot(workpieceId, trayId, trayPos, + rowNo, columnNo, &transactionError) + || !trayRepository.assignSlot(trayId, rowNo, columnNo, workpieceId, + "PENDING", &transactionError) + || !trayRepository.refreshStats(trayId, &transactionError) + || (workpiece.orderId > 0 + && !OrderRepository().refreshProgress(workpiece.orderId, &transactionError)) + || !recordLog("分配工件", QString("工件 %1 分配到托盘 %2 [%3,%4]") + .arg(workpiece.barcode).arg(tray.code) + .arg(rowNo).arg(columnNo), &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool WorkpieceService::updateState(int id, const QString &state, + const QString &processStep, QString *error) +{ + if (!isValidState(state)) { + if (error) { + *error = "Invalid workpiece state: " + state; + } + return false; + } + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + WorkpieceRepository workpieceRepository; + Workpiece workpiece; + if (!workpieceRepository.findWorkpiece(id, &workpiece, &transactionError) + || !workpieceRepository.updateState(id, state, processStep, &transactionError) + || (workpiece.trayId > 0 + && (!TrayRepository().updateSlotState(workpiece.trayId, workpiece.rowNo, + workpiece.columnNo, state, id, + &transactionError) + || !TrayRepository().refreshStats(workpiece.trayId, &transactionError))) + || (workpiece.orderId > 0 + && !OrderRepository().refreshProgress(workpiece.orderId, &transactionError)) + || !recordLog("更新工件状态", + QString("工件 %1 状态更新为 %2").arg(workpiece.barcode, state), + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +bool WorkpieceService::updateProcessStepWithRecord( + int id, const QString &processStep, int plcStep, const QString &source, + int durationMs, QString *error, bool forceRestart) +{ + if (id <= 0 || processStep.trimmed().isEmpty()) { + if (error) { + *error = id <= 0 ? "Workpiece id must be greater than 0" + : "Process step cannot be empty"; + } + return false; + } + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + WorkpieceRepository workpieceRepository; + Workpiece workpiece; + if (!workpieceRepository.findWorkpiece(id, &workpiece, &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + + const bool sameProcess = workpiece.processStep == processStep + && !forceRestart; + if (!sameProcess + && !workpiece.processStep.trimmed().isEmpty() + && !ProductionRepository().finishWorkpieceProcess( + id, workpiece.processStep, + forceRestart ? "ERROR" : "UNKNOWN", durationMs, + &transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + + if (!workpieceRepository.updateState( + id, "PROCESSING", processStep, &transactionError) + || (workpiece.trayId > 0 + && (!TrayRepository().updateSlotState( + workpiece.trayId, workpiece.rowNo, workpiece.columnNo, + "PROCESSING", id, &transactionError) + || !TrayRepository().refreshStats( + workpiece.trayId, &transactionError))) + || (workpiece.orderId > 0 + && !OrderRepository().refreshProgress( + workpiece.orderId, &transactionError)) + || (!sameProcess + && !ProductionRepository().startWorkpieceProcess( + workpiece.orderId, id, processStep, plcStep, source, + &transactionError)) + || !recordLog("更新工件工序", + QString("工件 %1 工序更新为 %2") + .arg(workpiece.barcode, processStep), + &transactionError) + || !database.commit(&transactionError)) { + database.rollback(); + if (error) { + *error = transactionError; + } + return false; + } + return true; +} + +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) +{ + if (id <= 0) { + if (error) { + *error = "Workpiece id must be greater than 0"; + } + return false; + } + if (!isValidState(state) || state == "PENDING" || state == "PROCESSING") { + if (error) { + *error = "Completion state must be OK, NG or ERROR"; + } + return false; + } + + DatabaseManager &database = DatabaseManager::instance(); + QString transactionError; + if (!database.transaction(&transactionError)) { + if (error) { + *error = transactionError; + } + return false; + } + + WorkpieceRepository workpieceRepository; + Workpiece workpiece; + if (!workpieceRepository.findWorkpiece(id, &workpiece, &transactionError) + || !workpieceRepository.updateState( + id, state, processStep, &transactionError) + || (workpiece.trayId > 0 + && (!TrayRepository().updateSlotState( + workpiece.trayId, workpiece.rowNo, workpiece.columnNo, + state, id, &transactionError) + || !TrayRepository().refreshStats( + workpiece.trayId, &transactionError))) + || (workpiece.orderId > 0 + && !OrderRepository().refreshProgress( + workpiece.orderId, &transactionError)) + || (!previousProcessStep.trimmed().isEmpty() + && !ProductionRepository().finishWorkpieceProcess( + id, previousProcessStep, resultState, durationMs, + &transactionError)) + || !ProductionRepository().insertInspection( + workpiece.orderId, id, "FINAL", rawResult, resultState, + plcStep, source, "Final production result", &transactionError) + || !recordLog("完成工件检测", + QString("工件 %1 检测结果为 %2") + .arg(workpiece.barcode, 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" + || state == "OK" || state == "NG" || state == "ERROR"; +} diff --git a/services/workpieceservice.h b/services/workpieceservice.h new file mode 100644 index 0000000..bf2374d --- /dev/null +++ b/services/workpieceservice.h @@ -0,0 +1,44 @@ +#ifndef WORKPIECESERVICE_H +#define WORKPIECESERVICE_H + +#include "../models/workpiece.h" + +#include + +class WorkpieceService +{ +public: + static WorkpieceService &instance(); + + QList listByOrder(int orderId, QString *error = nullptr); + QList listByTray(int trayId, QString *error = nullptr); + bool findWorkpiece(int id, Workpiece *workpiece, QString *error = nullptr); + bool claimNextPending(int orderId, Workpiece *workpiece, QString *error = nullptr); + bool createWorkpiece(Workpiece *workpiece, QString *error = nullptr); + bool assignToSlot(int workpieceId, int trayId, int rowNo, int columnNo, + QString *error = nullptr); + bool assignToFirstEmptySlot(int workpieceId, int trayId, QString *error = nullptr); + 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, + int durationMs, + QString *error = nullptr, + bool forceRestart = false); + bool 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 = nullptr); + +private: + WorkpieceService() = default; + WorkpieceService(const WorkpieceService &) = delete; + WorkpieceService &operator=(const WorkpieceService &) = delete; + + bool isValidState(const QString &state) const; +}; + +#endif // WORKPIECESERVICE_H diff --git a/ssp.pro b/ssp.pro new file mode 100644 index 0000000..6802fd4 --- /dev/null +++ b/ssp.pro @@ -0,0 +1,92 @@ +QT += core gui sql serialbus + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +CONFIG += c++11 + +# The following define makes your compiler emit warnings if you use +# any Qt feature that has been marked deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +SOURCES += \ + config/configmanager.cpp \ + db/databasemanager.cpp \ + db/dbconfig.cpp \ + main.cpp \ + modbus/modbusaddress.cpp \ + modbus/modbusconfig.cpp \ + modbus/modbustcpmanager.cpp \ + pages/dashboardpage.cpp \ + pages/devicepage.cpp \ + pages/logpage.cpp \ + pages/orderpage.cpp \ + pages/rackpage.cpp \ + pages/squaretraybutton.cpp \ + pages/uihelpers.cpp \ + repositories/logrepository.cpp \ + repositories/orderrepository.cpp \ + repositories/productionrepository.cpp \ + repositories/trayrepository.cpp \ + repositories/workpiecerepository.cpp \ + services/deviceservice.cpp \ + services/logservice.cpp \ + services/orderservice.cpp \ + services/productionservice.cpp \ + services/trayservice.cpp \ + services/workpieceservice.cpp \ + widget.cpp + +HEADERS += \ + config/configmanager.h \ + db/databasemanager.h \ + db/dbconfig.h \ + modbus/modbusaddress.h \ + modbus/modbusconfig.h \ + modbus/modbustcpmanager.h \ + models/logrecord.h \ + models/order.h \ + models/tray.h \ + models/workpiece.h \ + pages/dashboardpage.h \ + pages/devicepage.h \ + pages/logpage.h \ + pages/orderpage.h \ + pages/rackpage.h \ + pages/squaretraybutton.h \ + pages/uihelpers.h \ + repositories/logrepository.h \ + repositories/orderrepository.h \ + repositories/productionrepository.h \ + repositories/trayrepository.h \ + repositories/workpiecerepository.h \ + services/deviceservice.h \ + services/logservice.h \ + services/orderservice.h \ + services/productionservice.h \ + services/trayservice.h \ + services/workpieceservice.h \ + widget.h + +FORMS += \ + pages/Test.ui \ + pages/dashboardpage.ui \ + pages/devicepage.ui \ + pages/logpage.ui \ + pages/orderpage.ui \ + pages/rackpage.ui \ + widget.ui + +DISTFILES += \ + config.ini + +# Default rules for deployment. +qnx: target.path = /tmp/$${TARGET}/bin +else: unix:!android: target.path = /opt/$${TARGET}/bin +!isEmpty(target.path): INSTALLS += target diff --git a/ssp.pro.user b/ssp.pro.user new file mode 100644 index 0000000..4eb13f0 --- /dev/null +++ b/ssp.pro.user @@ -0,0 +1,562 @@ + + + + + + EnvironmentId + {bb223407-2910-451b-83cb-8f9ffd4e788e} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + true + 0 + 8 + true + 1 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + -fno-delayed-template-parsing + + true + + + + ProjectExplorer.Project.Target.0 + + Desktop Qt 5.14.1 MinGW 64-bit + Desktop Qt 5.14.1 MinGW 64-bit + qt.qt5.5141.win64_mingw73_kit + 0 + 0 + 0 + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Debug + + + true + QtProjectManager.QMakeBuildStep + true + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Release + + + true + QtProjectManager.QMakeBuildStep + false + + false + false + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Profile + + + true + QtProjectManager.QMakeBuildStep + true + + false + true + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:E:/QTCode/ssp/ssp/ssp.pro + E:/QTCode/ssp/ssp/ssp.pro + + false + + false + true + true + false + false + true + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Debug + + 1 + + + + ProjectExplorer.Project.Target.1 + + Desktop Qt 5.14.1 MinGW 32-bit + Desktop Qt 5.14.1 MinGW 32-bit + qt.qt5.5141.win32_mingw73_kit + 0 + 0 + 0 + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_32_bit-Debug + + + true + QtProjectManager.QMakeBuildStep + true + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_32_bit-Release + + + true + QtProjectManager.QMakeBuildStep + false + + false + false + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_32_bit-Profile + + + true + QtProjectManager.QMakeBuildStep + true + + false + true + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:E:/QTCode/ssp/ssp/ssp.pro + E:/QTCode/ssp/ssp/ssp.pro + + false + + false + true + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.TargetCount + 2 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/widget.cpp b/widget.cpp new file mode 100644 index 0000000..9000ec8 --- /dev/null +++ b/widget.cpp @@ -0,0 +1,153 @@ +#include "widget.h" +#include "ui_widget.h" + +#include "pages/dashboardpage.h" +#include "pages/devicepage.h" +#include "pages/logpage.h" +#include "pages/orderpage.h" +#include "pages/rackpage.h" +#include "pages/uihelpers.h" +#include "services/logservice.h" + +#include +#include +#include +#include +#include +#include +#include + +Widget::Widget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::Widget) + , navList(nullptr) + , pageStack(nullptr) + , dashboardPage(nullptr) + , logPage(nullptr) + , systemStateLabel(nullptr) + , currentOrderLabel(nullptr) + , currentWorkpieceLabel(nullptr) + , currentStepLabel(nullptr) +{ + ui->setupUi(this); + setWindowTitle("小轴多参数上下料单元管控系统"); + resize(1280, 820); + setupStyle(); + + QVBoxLayout *rootLayout = new QVBoxLayout(this); + rootLayout->setContentsMargins(0, 0, 0, 0); + rootLayout->setSpacing(0); + + setupTopBar(rootLayout); + setupMainArea(rootLayout); + + appendLog("生产日志", "系统", "启动", "页面原型已启动,当前为模拟模式", "成功"); +} + +Widget::~Widget() +{ + delete ui; +} + +void Widget::setupStyle() +{ + setStyleSheet( + "QWidget { font-family: 'Microsoft YaHei'; font-size: 13px; color: #1f2933; }" + "QListWidget { background: #263238; color: #e8eef2; border: none; padding: 8px; }" + "QListWidget::item { height: 42px; padding-left: 12px; border-radius: 4px; }" + "QListWidget::item:selected { background: #00897b; color: white; }" + "QPushButton { min-height: 28px; padding: 5px 12px; border: 1px solid #cfd8dc; border-radius: 4px; background: #ffffff; }" + "QPushButton:hover { background: #eef7f5; }" + "QPushButton#primaryButton { background: #00897b; color: white; border-color: #00897b; }" + "QPushButton#dangerButton { background: #d32f2f; color: white; border-color: #d32f2f; }" + "QFrame#card { background: #ffffff; border: 1px solid #d8dee4; border-radius: 6px; }" + "QLabel#cardTitle { font-size: 15px; font-weight: bold; color: #263238; }" + "QGroupBox { font-weight: bold; border: 1px solid #d8dee4; border-radius: 6px; margin-top: 10px; padding-top: 12px; }" + "QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 4px; }" + "QTableWidget { background: white; border: 1px solid #d8dee4; gridline-color: #e5e9ef; }" + "QHeaderView::section { background: #eef3f5; padding: 6px; border: none; border-right: 1px solid #d8dee4; }" + ); +} + +void Widget::setupTopBar(QVBoxLayout *rootLayout) +{ + QFrame *topBar = new QFrame; + topBar->setStyleSheet("QFrame { background: #f5f7f8; border-bottom: 1px solid #d8dee4; }"); + + QHBoxLayout *topLayout = new QHBoxLayout(topBar); + topLayout->setContentsMargins(14, 8, 14, 8); + topLayout->setSpacing(10); + topLayout->addWidget(new QLabel("小轴单元")); + + systemStateLabel = UiHelpers::makeBadge("系统:待机", "#607d8b"); + currentOrderLabel = UiHelpers::makeBadge("订单:ORD-20260808-001", "#455a64"); + currentWorkpieceLabel = UiHelpers::makeBadge("工件:WP-0001", "#455a64"); + currentStepLabel = UiHelpers::makeBadge("工序:待取料", "#00897b"); + + topLayout->addWidget(systemStateLabel); + topLayout->addWidget(currentOrderLabel); + topLayout->addWidget(currentWorkpieceLabel); + topLayout->addWidget(currentStepLabel); + topLayout->addStretch(); + topLayout->addWidget(UiHelpers::makeBadge("PLC:模拟", "#795548")); + topLayout->addWidget(UiHelpers::makeBadge("机器人:模拟", "#795548")); + topLayout->addWidget(UiHelpers::makeBadge("安全门:关闭", "#2e7d32")); + + rootLayout->addWidget(topBar); +} + +void Widget::setupMainArea(QVBoxLayout *rootLayout) +{ + QHBoxLayout *bodyLayout = new QHBoxLayout; + bodyLayout->setContentsMargins(0, 0, 0, 0); + bodyLayout->setSpacing(0); + + navList = new QListWidget; + navList->setFixedWidth(170); + navList->addItems(QStringList() << "控制面板" << "订单管理" << "料架/托盘" << "设备状态" << "日志"); + navList->setCurrentRow(0); + bodyLayout->addWidget(navList); + + dashboardPage = new DashboardPage(this); + OrderPage *orderPage = new OrderPage(this); + RackPage *rackPage = new RackPage(this); + DevicePage *devicePage = new DevicePage(this); + logPage = new LogPage(this); + + pageStack = new QStackedWidget; + pageStack->addWidget(dashboardPage); + pageStack->addWidget(orderPage); + pageStack->addWidget(rackPage); + pageStack->addWidget(devicePage); + pageStack->addWidget(logPage); + bodyLayout->addWidget(pageStack, 1); + + rootLayout->addLayout(bodyLayout, 1); + + connect(navList, &QListWidget::currentRowChanged, pageStack, &QStackedWidget::setCurrentIndex); + connect(dashboardPage, &DashboardPage::systemStateChanged, this, [this](const QString &state) { + systemStateLabel->setText("系统:" + state); + }); + connect(dashboardPage, &DashboardPage::currentStepChanged, this, [this](const QString &step) { + currentStepLabel->setText("工序:" + step); + }); + connect(dashboardPage, &DashboardPage::logRequested, this, &Widget::appendLog); + connect(orderPage, &OrderPage::logRequested, this, &Widget::appendLog); + connect(rackPage, &RackPage::logRequested, this, &Widget::appendLog); +} + +void Widget::appendLog(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status) +{ + if (dashboardPage) { + dashboardPage->addLog(type, module, content, status); + } + if (logPage) { + logPage->addLog(type, module, action, content, status); + } + + QString error; + if (!LogService::instance().record(type, module, action, content, status, &error)) { + qWarning() << "Failed to persist operation log:" << error; + } +} diff --git a/widget.h b/widget.h new file mode 100644 index 0000000..0a8737c --- /dev/null +++ b/widget.h @@ -0,0 +1,43 @@ +#ifndef WIDGET_H +#define WIDGET_H + +#include + +QT_BEGIN_NAMESPACE +namespace Ui { class Widget; } +QT_END_NAMESPACE + +class DashboardPage; +class QLabel; +class QListWidget; +class LogPage; +class QStackedWidget; +class QVBoxLayout; + +class Widget : public QWidget +{ + Q_OBJECT + +public: + Widget(QWidget *parent = nullptr); + ~Widget(); + +private: + void setupStyle(); + void setupTopBar(QVBoxLayout *rootLayout); + void setupMainArea(QVBoxLayout *rootLayout); + void appendLog(const QString &type, const QString &module, const QString &action, + const QString &content, const QString &status); + + Ui::Widget *ui; + QListWidget *navList; + QStackedWidget *pageStack; + DashboardPage *dashboardPage; + LogPage *logPage; + QLabel *systemStateLabel; + QLabel *currentOrderLabel; + QLabel *currentWorkpieceLabel; + QLabel *currentStepLabel; +}; + +#endif // WIDGET_H diff --git a/widget.ui b/widget.ui new file mode 100644 index 0000000..b90248d --- /dev/null +++ b/widget.ui @@ -0,0 +1,19 @@ + + + Widget + + + + 0 + 0 + 800 + 600 + + + + Widget + + + + +