Files
ssp/services/productionservice.cpp
T

1904 lines
58 KiB
C++

#include "productionservice.h"
#include "../config/configmanager.h"
#include "../repositories/productionrepository.h"
#include "orderservice.h"
#include "trayservice.h"
#include "workpieceservice.h"
#include <QDebug>
#include <QScopedValueRollback>
#include <QTimer>
namespace {
const int ProductionTickIntervalMs = 50;
}
ProductionService &ProductionService::instance()
{
static ProductionService service;
return service;
}
ProductionService::ProductionService(QObject *parent)
: QObject(parent)
, m_timer(new QTimer(this))
, m_deviceService(new DeviceService(this))
, m_state(Idle)
, m_timeoutState(Idle)
, m_runId(0)
, m_orderId(0)
, m_deviceStatusValid(false)
, m_recoveryRetryCount(0)
, m_processElapsedMs(0)
, m_currentTrayNo(0)
, m_currentSlotNo(0)
, m_frontRawResult(0)
, m_actionPending(false)
, m_actionStarting(false)
, m_actionPollPending(false)
, m_actionCompleted(false)
, m_actionCancelRequested(false)
, m_inspectionStatusPending(false)
, m_inspectionStatusReady(false)
, m_starting(false)
, m_plcStarted(false)
, m_tickRunning(false)
, m_pendingAction(DeviceService::RackPick)
, m_stopRequested(false)
, m_externalStopRequested(nullptr)
, m_shutdownRequested(false)
{
connect(m_timer, &QTimer::timeout, this, &ProductionService::tick);
connect(m_deviceService, &DeviceService::statusChanged,
this, &ProductionService::onDeviceStatusChanged);
connect(m_deviceService, &DeviceService::communicationError,
this, &ProductionService::onCommunicationError);
m_deviceService->startPolling();
}
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 RackPicking: return "RACK_PICKING";
case FrontLoading: return "FRONT_LOADING";
case Loading: return "LOADING";
case FrontChecking: return "FRONT_CHECKING";
case FrontUnloading: return "FRONT_UNLOADING";
case Flipping: return "FLIPPING";
case BackLoading: return "BACK_LOADING";
case BackChecking: return "BACK_CHECKING";
case BackUnloading: return "BACK_UNLOADING";
case RackPlacing: return "RACK_PLACING";
case Judging: return "JUDGING";
case Unloading: return "UNLOADING";
case Paused: return "PAUSED";
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";
case Terminating: return "TERMINATING";
}
return "UNKNOWN";
}
int ProductionService::orderId() const
{
return m_orderId;
}
int ProductionService::currentTrayNo() const
{
return m_currentTrayNo;
}
int ProductionService::currentSlotNo() const
{
return m_currentSlotNo;
}
QString ProductionService::inspectionMode() const
{
return m_inspectionMode;
}
Workpiece ProductionService::currentWorkpiece() const
{
return m_currentWorkpiece;
}
void ProductionService::setExternalStopFlag(std::atomic_bool *flag)
{
m_externalStopRequested = flag;
}
void ProductionService::requestStopImmediate()
{
m_stopRequested.store(true);
}
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;
}
m_inspectionMode = order.inspectionMode;
m_currentTrayNo = 0;
m_currentSlotNo = 0;
m_frontRawResult = 0;
m_actionPending = false;
m_actionStarting = false;
m_actionPollPending = false;
m_actionCompleted = false;
m_actionError.clear();
m_frontResultState.clear();
m_stopRequested.store(false);
if (m_externalStopRequested) {
m_externalStopRequested->store(false);
}
m_orderId = orderId;
m_currentWorkpiece = Workpiece();
clearProcessTimer();
m_deviceStatusValid = false;
m_recoveryRetryCount = 0;
m_lastError.clear();
m_starting = true;
m_plcStarted = false;
QString persistenceError;
m_runId = ProductionRepository().createRun(
m_orderId, "PREPARING", "PREPARING", order.inspectionMode,
order.startTrayNo, order.startSlotNo, order.planNum,
&persistenceError);
if (m_runId <= 0) {
m_orderId = 0;
m_starting = false;
if (error) {
*error = "Failed to create production run: " + persistenceError;
}
return false;
}
setState(Preparing);
m_deviceService->startPolling();
const int interval = ProductionTickIntervalMs;
m_heartbeatTimer.restart();
m_timer->start(interval);
m_deviceService->requestStatus(
[this](bool success, const DeviceStatus &, const QString &statusError) {
if (!success) {
fail(statusError);
return;
}
if (stopRequested()) {
return;
}
QString safetyError;
if (!checkRecoverySafety(&safetyError)) {
fail(safetyError);
return;
}
m_deviceService->setInspectionMode(
m_inspectionMode,
[this](bool modeSuccess, const QString &modeError) {
if (!modeSuccess) {
fail(modeError);
return;
}
if (stopRequested()) {
return;
}
m_deviceService->start(
[this](bool startSuccess,
const QString &startError) {
if (!startSuccess) {
fail(startError);
return;
}
if (stopRequested()) {
return;
}
m_plcStarted = true;
QString orderError;
if (!OrderService::instance().startOrder(
m_orderId, &orderError)) {
m_deviceService->pause(
[](bool, const QString &) {});
fail(orderError);
return;
}
m_starting = false;
tick();
});
});
});
return true;
}
bool ProductionService::pause(QString *error)
{
if (!isActive()) {
if (error) {
*error = "Production service is not active";
}
return false;
}
cancelPendingProductionAction(
[this](bool canceled, const QString &cancelError) {
if (!canceled) {
emit productionError(cancelError);
return;
}
m_deviceService->pause(
[this](bool paused, const QString &pauseError) {
if (!paused) {
emit productionError(pauseError);
return;
}
QString orderError;
if (!OrderService::instance().pauseOrder(
m_orderId, &orderError)) {
emit productionError(orderError);
return;
}
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)) {
return false;
}
m_deviceService->setInspectionMode(
m_inspectionMode,
[this](bool modeSuccess, const QString &modeError) {
if (!modeSuccess) {
emit productionError(modeError);
return;
}
m_deviceService->start(
[this](bool startSuccess, const QString &startError) {
if (!startSuccess) {
emit productionError(startError);
return;
}
QString orderError;
if (!OrderService::instance().resumeOrder(
m_orderId, &orderError)) {
emit productionError(orderError);
return;
}
resumeProcessTimer();
State resumeState = Preparing;
if (m_currentWorkpiece.id > 0) {
resumeState = stateForProcessStep(
m_currentWorkpiece.processStep);
if (resumeState == Idle) {
resumeState = WaitingDeviceReady;
}
}
setState(resumeState);
m_timer->start(ProductionTickIntervalMs);
});
});
return true;
}
bool ProductionService::stop(QString *error)
{
if (m_state == Terminating) {
return true;
}
if (m_state == Idle || m_state == Completed) {
if (error) {
*error = "Production service is not running";
}
return false;
}
m_lastError = "Production stopped by operator";
m_timer->stop();
setState(Terminating);
auto failTermination = [this](const QString &terminationError) {
m_lastError = terminationError.isEmpty()
? "PLC termination cleanup failed" : terminationError;
m_stopRequested.store(false);
if (m_externalStopRequested) {
m_externalStopRequested->store(false);
}
setState(Error);
persistAlarm("TERMINATION_FAILED", m_lastError);
emit productionError(m_lastError);
emit alarmRaised("TERMINATION_FAILED", m_lastError);
finishShutdown(false, m_lastError);
};
m_deviceService->terminate(
[this, failTermination](bool cleaned, const QString &cleanupError) {
if (!cleaned) {
failTermination(cleanupError);
return;
}
QString orderError;
Order order;
if (!OrderService::instance().findOrder(
m_orderId, &order, &orderError)) {
failTermination(orderError);
return;
}
if (order.status == "RUNNING"
&& !OrderService::instance().pauseOrder(
m_orderId, &orderError)) {
failTermination(orderError);
return;
}
QString persistenceError;
if (m_runId > 0
&& !ProductionRepository().finishRun(
m_runId, "STOPPED", m_lastError,
&persistenceError)) {
failTermination(persistenceError);
return;
}
persistRecoveryAction("STOP", m_lastError);
setState(Idle);
m_runId = 0;
m_orderId = 0;
m_currentWorkpiece = Workpiece();
m_starting = false;
m_plcStarted = false;
clearProcessTimer();
emit currentWorkpieceChanged(0, QString());
emit currentWorkpieceSnapshotChanged(m_currentWorkpiece);
emit currentPositionChanged(0, 0);
m_stopRequested.store(false);
if (m_externalStopRequested) {
m_externalStopRequested->store(false);
}
finishShutdown(true, QString());
});
return true;
}
void ProductionService::shutdown(const DeviceService::OperationCallback &callback)
{
if (m_shutdownRequested) {
if (callback) {
callback(false, "Production shutdown is already in progress");
}
return;
}
m_shutdownRequested = true;
m_shutdownCallback = callback;
if (m_state != Idle && m_state != Completed) {
QString stopError;
if (!stop(&stopError)) {
finishShutdown(false, stopError);
}
return;
}
m_timer->stop();
m_deviceService->terminate(
[this](bool cleaned, const QString &cleanupError) {
if (!cleaned) {
finishShutdown(false, cleanupError);
return;
}
setState(Idle);
finishShutdown(true, QString());
});
}
bool ProductionService::reset(QString *error)
{
if (m_state != Error) {
if (error) {
*error = "Only failed production can be reset";
}
return false;
}
cancelPendingProductionAction(
[this](bool canceled, const QString &cancelError) {
if (!canceled) {
emit productionError(cancelError);
return;
}
m_deviceService->reset(
[this](bool resetSuccess, const QString &resetError) {
if (!resetSuccess) {
emit productionError(resetError);
return;
}
m_deviceService->clearAlarm(
[this](bool alarmCleared,
const QString &alarmError) {
if (!alarmCleared) {
emit productionError(alarmError);
return;
}
QString persistenceError;
if (!ProductionRepository().clearActiveAlarms(
QString(), "SYSTEM",
&persistenceError)) {
emit productionError(persistenceError);
return;
}
QString workpieceError;
if (m_currentWorkpiece.id > 0
&& !WorkpieceService::instance().updateState(
m_currentWorkpiece.id, "PENDING",
"RECOVERY", &workpieceError)) {
emit productionError(workpieceError);
return;
}
m_currentWorkpiece = Workpiece();
clearProcessTimer();
m_lastError.clear();
setState(Preparing);
m_heartbeatTimer.restart();
m_timer->start(ProductionTickIntervalMs);
});
});
});
return true;
}
bool ProductionService::clearAlarm(QString *error)
{
Q_UNUSED(error)
m_deviceService->clearAlarm(
[this](bool success, const QString &operationError) {
if (!success) {
emit productionError(operationError);
return;
}
QString persistenceError;
if (!ProductionRepository().clearActiveAlarms(
QString(), "OPERATOR", &persistenceError)) {
emit productionError(persistenceError);
return;
}
});
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_inspectionMode = run.inspectionMode;
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);
emit currentWorkpieceSnapshotChanged(m_currentWorkpiece);
emit currentPositionChanged(m_currentTrayNo, m_currentSlotNo);
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)) {
if (error) {
*error = operationError;
}
return false;
}
m_deviceService->setInspectionMode(
m_inspectionMode,
[this](bool modeSuccess, const QString &modeError) {
if (!modeSuccess) {
emit productionError(modeError);
return;
}
m_deviceService->start(
[this](bool startSuccess, const QString &startError) {
if (!startSuccess) {
emit productionError(startError);
return;
}
persistRecoveryAction(
"CONTINUE",
QString("Continue recovery from %1").arg(stateName()));
setState(RecoveryChecking);
m_heartbeatTimer.restart();
m_timer->start(ProductionTickIntervalMs);
tick();
});
});
return true;
}
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)) {
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;
}
m_deviceService->setInspectionMode(
m_inspectionMode,
[this, processStep](bool modeSuccess, const QString &modeError) {
if (!modeSuccess) {
emit productionError(modeError);
return;
}
m_deviceService->start(
[this, processStep](bool startSuccess,
const QString &startError) {
if (!startSuccess) {
emit productionError(startError);
return;
}
QString operationError;
if (!updateCurrentProcessStep(
processStep, &operationError, true)) {
emit productionError(operationError);
return;
}
++m_recoveryRetryCount;
persistRecoveryAction(
"RETRY",
QString("Retry production step %1").arg(processStep));
setState(Retrying);
m_heartbeatTimer.restart();
m_timer->start(ProductionTickIntervalMs);
});
});
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)) {
if (error) {
*error = operationError;
}
return false;
}
m_deviceService->start(
[this](bool startSuccess, const QString &startError) {
if (!startSuccess) {
emit productionError(startError);
return;
}
const int durationMs = currentProcessElapsedMs();
const QString previousProcessStep =
m_currentWorkpiece.processStep;
QString operationError;
if (!WorkpieceService::instance().completeWithInspection(
m_currentWorkpiece.id, "NG", "COMPLETE",
previousProcessStep, durationMs, -1, "NG",
m_deviceStatus.currentStep, m_inspectionMode, "MANUAL",
&operationError)) {
emit productionError(operationError);
return;
}
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());
emit currentWorkpieceSnapshotChanged(m_currentWorkpiece);
emit currentPositionChanged(0, 0);
setState(Preparing);
m_heartbeatTimer.restart();
m_timer->start(ProductionTickIntervalMs);
});
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;
m_currentTrayNo = 0;
m_currentSlotNo = workpiece.trayPos;
QString trayError;
const QList<Tray> trays = TrayService::instance().listTrays(&trayError);
if (!trayError.isEmpty()) {
if (error) {
*error = trayError;
}
return false;
}
for (int index = 0; index < trays.size(); ++index) {
if (trays.at(index).id == workpiece.trayId) {
m_currentTrayNo = index + 1;
break;
}
}
if (m_currentTrayNo <= 0 || m_currentSlotNo < 1 || m_currentSlotNo > 49) {
if (error) {
*error = "Current workpiece tray position cannot be mapped to PLC";
}
return false;
}
QString persistenceError;
const QString source = ConfigManager::instance().simulationMode()
? "SIMULATION" : "PLC";
if (!ProductionRepository().startWorkpieceProcess(
m_orderId, workpiece.id, workpiece.processStep,
m_inspectionMode, m_deviceStatus.currentStep,
source, &persistenceError)) {
if (error) {
*error = persistenceError;
}
return false;
}
startProcessTimer(workpiece.processStep);
emit currentWorkpieceChanged(workpiece.id, workpiece.barcode);
emit currentWorkpieceSnapshotChanged(m_currentWorkpiece);
emit currentPositionChanged(m_currentTrayNo, m_currentSlotNo);
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_inspectionMode,
m_deviceStatus.currentStep, source, durationMs, error,
forceRestart)) {
return false;
}
m_currentWorkpiece.processStep = processStep;
startProcessTimer(processStep);
emitProcessElapsed();
return true;
}
bool ProductionService::processProductionAction(
DeviceService::ProductionAction action, bool *completed, QString *error)
{
if (!completed) {
if (error) {
*error = "Action completion pointer is null";
}
return false;
}
*completed = false;
if (ConfigManager::instance().simulationMode()) {
*completed = true;
return true;
}
if (!m_actionPending) {
m_pendingAction = action;
m_actionPending = true;
m_actionStarting = true;
m_actionPollPending = false;
m_actionCompleted = false;
m_actionError.clear();
m_deviceService->beginProductionAction(
action, m_currentTrayNo, m_currentSlotNo,
[this](bool success, const QString &actionError) {
m_actionStarting = false;
if (!success) {
m_actionError = actionError;
}
tryDeferredActionCancel();
});
return true;
}
if (m_pendingAction != action) {
if (error) {
*error = "PLC production action does not match current state";
}
return false;
}
if (!m_actionError.isEmpty()) {
if (error) {
*error = m_actionError;
}
return false;
}
if (m_actionStarting || m_actionPollPending) {
return true;
}
if (m_actionCompleted) {
*completed = true;
m_actionPending = false;
m_actionCompleted = false;
return true;
}
m_actionPollPending = true;
m_deviceService->pollProductionAction(
[this](bool success, bool completed,
const QString &actionError) {
m_actionPollPending = false;
if (!success) {
m_actionError = actionError;
return;
}
if (completed) {
m_actionCompleted = true;
}
tryDeferredActionCancel();
});
return true;
}
void ProductionService::cancelPendingProductionAction(
const DeviceService::OperationCallback &callback)
{
if (!m_actionPending) {
if (callback) {
callback(true, QString());
}
return;
}
if (m_actionStarting || m_actionPollPending) {
m_actionCancelRequested = true;
m_deferredCancelCallback = callback;
return;
}
m_deviceService->cancelProductionAction(
[this, callback](bool success, const QString &error) {
if (success) {
m_actionPending = false;
m_actionCompleted = false;
m_actionError.clear();
m_actionCancelRequested = false;
}
if (callback) {
callback(success, error);
}
});
}
void ProductionService::tryDeferredActionCancel()
{
if (!m_actionCancelRequested
|| m_actionStarting || m_actionPollPending) {
return;
}
m_actionCancelRequested = false;
const DeviceService::OperationCallback callback =
m_deferredCancelCallback;
m_deferredCancelCallback = DeviceService::OperationCallback();
if (!m_actionPending) {
if (callback) {
callback(true, QString());
}
return;
}
m_deviceService->cancelProductionAction(
[this, callback](bool success, const QString &error) {
if (success) {
m_actionPending = false;
m_actionCompleted = false;
m_actionError.clear();
}
if (callback) {
callback(success, error);
}
});
}
bool ProductionService::executeCurrentAction(
DeviceService::ProductionAction action,
const QString &nextProcessStep, State nextState, QString *error)
{
if (m_currentWorkpiece.id <= 0) {
if (error) {
*error = "No current workpiece";
}
return false;
}
bool completed = false;
if (!processProductionAction(action, &completed, error)) {
return false;
}
if (!completed) {
return false;
}
if (!updateCurrentProcessStep(nextProcessStep, error)) {
return false;
}
setState(nextState);
return true;
}
bool ProductionService::recordInspection(const QString &side, int rawResult,
const QString &resultState,
QString *error)
{
const QString source = ConfigManager::instance().simulationMode()
? "SIMULATION" : "PLC";
return WorkpieceService::instance().recordInspection(
m_currentWorkpiece.id, side, rawResult, resultState,
m_deviceStatus.currentStep, m_inspectionMode, source,
QString("%1 inspection result").arg(side), error);
}
QString ProductionService::resultStateForRawResult(int rawResult) const
{
const ProductionConfig config = ConfigManager::instance().productionConfig();
if (rawResult == config.okResult) {
return "OK";
}
if (rawResult == config.ngResult) {
return "NG";
}
if (rawResult == config.errorResult) {
return "ERROR";
}
return "UNKNOWN";
}
void ProductionService::startProcessTimer(const QString &processStep)
{
m_currentProcessStep = processStep;
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<int>(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<int>(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 (ConfigManager::instance().productionConfig().usePlcErrorCode
&& 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<int>(m_deviceStatus.checkResult);
const QString source = ConfigManager::instance().simulationMode()
? "SIMULATION" : "PLC";
if (!WorkpieceService::instance().completeWithInspection(
m_currentWorkpiece.id, state, processStep,
previousProcessStep, processDurationMs, rawResult, state,
m_deviceStatus.currentStep, m_inspectionMode, source, error)) {
return false;
}
clearProcessTimer();
m_currentWorkpiece = Workpiece();
emit currentWorkpieceChanged(0, QString());
emit currentWorkpieceSnapshotChanged(m_currentWorkpiece);
emit currentPositionChanged(0, 0);
setState(Preparing);
return true;
}
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 (m_state == Terminating) {
return;
}
if (m_tickRunning) {
return;
}
QScopedValueRollback<bool> tickGuard(m_tickRunning, true);
if (stopRequested()
&& m_state != Idle && m_state != Completed) {
QString stopError;
stop(&stopError);
return;
}
if (!isActive()) {
return;
}
if (m_starting) {
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 (ConfigManager::instance().productionConfig().usePlcErrorCode
&& 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;
State nextState = stateForProcessStep(
m_currentWorkpiece.processStep);
if (nextState == Idle || nextState == WaitingDeviceReady) {
if (!updateCurrentProcessStep("RACK_PICKING", &error)) {
fail(error);
return;
}
nextState = RackPicking;
}
if (error.isEmpty()) {
setState(nextState);
}
}
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;
}
QString error;
if (!processProductionStep(m_state, &error) && !error.isEmpty()) {
fail(error);
}
}
void ProductionService::tickProduction()
{
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)
{
switch (state) {
case RackPicking:
return executeCurrentAction(DeviceService::RackPick,
"FRONT_LOADING", FrontLoading, error);
case FrontLoading:
return executeCurrentAction(DeviceService::FrontLoad,
"FRONT_CHECKING", FrontChecking, error);
case FrontChecking: {
bool completed = false;
if (!processProductionAction(
DeviceService::Inspect, &completed, error)) {
return false;
}
if (!completed) {
return false;
}
if (!ConfigManager::instance().simulationMode()) {
if (!m_inspectionStatusReady) {
if (!m_inspectionStatusPending) {
m_inspectionStatusPending = true;
m_deviceService->requestStatus(
[this](bool success, const DeviceStatus &,
const QString &statusError) {
m_inspectionStatusPending = false;
m_inspectionStatusReady = success;
m_inspectionStatusError = statusError;
});
}
if (m_inspectionStatusPending) {
return true;
}
if (!m_inspectionStatusReady) {
if (error) {
*error = m_inspectionStatusError;
}
return false;
}
}
}
const int frontRawResult = ConfigManager::instance().simulationMode()
? ConfigManager::instance().productionConfig().simulationResult
: static_cast<int>(m_deviceStatus.checkResult);
const QString frontResultState =
resultStateForRawResult(frontRawResult);
if (frontResultState == "UNKNOWN" || frontResultState == "ERROR") {
if (error) {
*error = QString("Invalid front inspection result: %1")
.arg(frontRawResult);
}
return false;
}
if (!recordInspection("FRONT", frontRawResult,
frontResultState, error)) {
return false;
}
m_inspectionStatusReady = false;
m_inspectionStatusError.clear();
m_frontRawResult = frontRawResult;
m_frontResultState = frontResultState;
if (!updateCurrentProcessStep("FRONT_UNLOADING", error)) {
return false;
}
setState(FrontUnloading);
return true;
}
case FrontUnloading:
return executeCurrentAction(
DeviceService::FrontUnload,
m_inspectionMode == "AFTER_PLATING" ? "RACK_PLACING" : "FLIPPING",
m_inspectionMode == "AFTER_PLATING" ? RackPlacing : Flipping,
error);
case Flipping:
return executeCurrentAction(DeviceService::Flip,
"BACK_LOADING", BackLoading, error);
case BackLoading:
return executeCurrentAction(DeviceService::BackLoad,
"BACK_CHECKING", BackChecking, error);
case BackChecking: {
bool completed = false;
if (!processProductionAction(
DeviceService::Inspect, &completed, error)) {
return false;
}
if (!completed) {
return false;
}
if (!ConfigManager::instance().simulationMode()) {
if (!m_inspectionStatusReady) {
if (!m_inspectionStatusPending) {
m_inspectionStatusPending = true;
m_deviceService->requestStatus(
[this](bool success, const DeviceStatus &,
const QString &statusError) {
m_inspectionStatusPending = false;
m_inspectionStatusReady = success;
m_inspectionStatusError = statusError;
});
}
if (m_inspectionStatusPending) {
return true;
}
if (!m_inspectionStatusReady) {
if (error) {
*error = m_inspectionStatusError;
}
return false;
}
}
}
const int backRawResult = ConfigManager::instance().simulationMode()
? ConfigManager::instance().productionConfig().simulationResult
: static_cast<int>(m_deviceStatus.checkResult);
const QString backResultState =
resultStateForRawResult(backRawResult);
if (backResultState == "UNKNOWN" || backResultState == "ERROR") {
if (error) {
*error = QString("Invalid back inspection result: %1")
.arg(backRawResult);
}
return false;
}
if (!recordInspection("BACK", backRawResult,
backResultState, error)) {
return false;
}
m_inspectionStatusReady = false;
m_inspectionStatusError.clear();
const QString finalState =
m_frontResultState == "OK" && backResultState == "OK"
? "OK" : "NG";
if (!updateCurrentProcessStep("BACK_UNLOADING", error)) {
return false;
}
m_frontResultState = finalState;
setState(BackUnloading);
break;
}
case BackUnloading:
return executeCurrentAction(DeviceService::BackUnload,
"RACK_PLACING", RackPlacing, error);
case RackPlacing: {
bool completed = false;
if (!processProductionAction(
DeviceService::RackPlace, &completed, error)) {
return false;
}
if (!completed) {
return false;
}
QString finalState = m_frontResultState;
if (finalState != "OK" && finalState != "NG") {
if (error) {
*error = "Final inspection result is not available";
}
return false;
}
return finishCurrentWorkpiece(finalState, "COMPLETE", error);
}
default:
break;
}
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 == RackPicking || state == FrontLoading
|| state == Loading || state == FrontChecking
|| state == FrontUnloading || state == Flipping
|| state == BackLoading || state == BackChecking
|| state == BackUnloading || state == RackPlacing
|| state == Judging;
}
QString ProductionService::processStepForState(State state) const
{
switch (state) {
case Preparing: return "PREPARING";
case WaitingDeviceReady: return "WAITING_DEVICE_READY";
case RackPicking: return "RACK_PICKING";
case FrontLoading: return "FRONT_LOADING";
case Loading: return "LOADING";
case FrontChecking: return "FRONT_CHECKING";
case FrontUnloading: return "FRONT_UNLOADING";
case Flipping: return "FLIPPING";
case BackLoading: return "BACK_LOADING";
case BackChecking: return "BACK_CHECKING";
case BackUnloading: return "BACK_UNLOADING";
case RackPlacing: return "RACK_PLACING";
case Judging: return "JUDGING";
default: return QString();
}
}
ProductionService::State ProductionService::stateForProcessStep(
const QString &processStep) const
{
if (processStep == "PREPARING") return Preparing;
if (processStep == "WAITING_DEVICE_READY") return WaitingDeviceReady;
if (processStep == "RACK_PICKING") return RackPicking;
if (processStep == "FRONT_LOADING") return FrontLoading;
if (processStep == "LOADING") return Loading;
if (processStep == "FRONT_CHECKING") return FrontChecking;
if (processStep == "FRONT_UNLOADING") return FrontUnloading;
if (processStep == "FLIPPING") return Flipping;
if (processStep == "BACK_LOADING") return BackLoading;
if (processStep == "BACK_CHECKING") return BackChecking;
if (processStep == "BACK_UNLOADING") return BackUnloading;
if (processStep == "RACK_PLACING") return RackPlacing;
if (processStep == "JUDGING") return Judging;
return Idle;
}
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 Terminating:
return "STOPPING";
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 == "RACK_PICKING") return RackPicking;
if (name == "FRONT_LOADING") return FrontLoading;
if (name == "LOADING") return Loading;
if (name == "FRONT_CHECKING") return FrontChecking;
if (name == "FRONT_UNLOADING") return FrontUnloading;
if (name == "FLIPPING") return Flipping;
if (name == "BACK_LOADING") return BackLoading;
if (name == "BACK_CHECKING") return BackChecking;
if (name == "BACK_UNLOADING") return BackUnloading;
if (name == "RACK_PLACING") return RackPlacing;
if (name == "JUDGING") return Judging;
if (name == "UNLOADING") return Unloading;
if (name == "PAUSED") return Paused;
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;
if (name == "TERMINATING") return Terminating;
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 == Terminating) {
return;
}
if (m_state == Error) {
return;
}
m_lastError = error.isEmpty() ? "Production failed" : error;
cancelPendingProductionAction(
[this](bool success, const QString &cleanupError) {
if (!success && !cleanupError.isEmpty()) {
qWarning() << "PLC action cleanup failed:" << cleanupError;
}
});
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);
}
void ProductionService::finishShutdown(bool success, const QString &error)
{
if (!m_shutdownRequested) {
return;
}
const DeviceService::OperationCallback callback = m_shutdownCallback;
m_shutdownCallback = DeviceService::OperationCallback();
m_shutdownRequested = false;
if (callback) {
callback(success, error);
}
}
bool ProductionService::isActive() const
{
return m_state != Idle && m_state != Error
&& m_state != Completed && m_state != Paused
&& m_state != TimeoutPaused && m_state != ManualConfirm
&& m_state != Terminating;
}
bool ProductionService::stopRequested() const
{
return m_stopRequested.load()
|| (m_externalStopRequested
&& m_externalStopRequested->load());
}
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;
emit deviceStatusChanged(status);
if (changed) {
persistDeviceStatus(status);
}
}
void ProductionService::onCommunicationError(const QString &error)
{
emit deviceCommunicationError(error);
if (m_state == RecoveryChecking || m_state == Terminating) {
m_lastError = error;
return;
}
if (isActive()) {
fail(error);
}
}