55 lines
1.3 KiB
C++
55 lines
1.3 KiB
C++
#include "MachineController.h"
|
|
#include "../../include/machine.h"
|
|
#include <chrono>
|
|
#include <QDebug>
|
|
|
|
MachineController::MachineController(std::shared_ptr<Machine> machine, QObject *parent)
|
|
: QObject(parent), m_machine(std::move(machine))
|
|
{
|
|
if (!m_machine) {
|
|
m_machine = std::make_shared<Machine>();
|
|
}
|
|
}
|
|
|
|
MachineController::~MachineController() {
|
|
stop();
|
|
}
|
|
|
|
void MachineController::start() {
|
|
if (m_running.exchange(true)) return;
|
|
m_thread = std::thread([this]{ runLoop(); });
|
|
}
|
|
|
|
void MachineController::stop() {
|
|
if (!m_running.exchange(false)) return;
|
|
if (m_thread.joinable()) m_thread.join();
|
|
}
|
|
|
|
void MachineController::step() {
|
|
try {
|
|
if (m_machine) {
|
|
m_machine->execute();
|
|
m_machine->tick();
|
|
emit tick();
|
|
}
|
|
} catch (const std::exception &e) {
|
|
emit error(QString::fromStdString(e.what()));
|
|
}
|
|
}
|
|
|
|
void MachineController::runLoop() {
|
|
while (m_running.load()) {
|
|
try {
|
|
if (m_machine) {
|
|
m_machine->execute();
|
|
m_machine->tick();
|
|
emit tick();
|
|
}
|
|
} catch (const std::exception &e) {
|
|
emit error(QString::fromStdString(e.what()));
|
|
// Stop on fatal error
|
|
m_running.store(false);
|
|
break;
|
|
}
|
|
}
|
|
}
|