2020-06-01 03:39:08 +00:00
|
|
|
#include "timer.h"
|
|
|
|
|
|
|
|
#include "../../ClockReceiver/TimeTypes.hpp"
|
|
|
|
|
2020-06-03 04:21:37 +00:00
|
|
|
#include <algorithm>
|
2020-06-01 03:39:08 +00:00
|
|
|
#include <QDebug>
|
|
|
|
|
2020-06-07 04:31:46 +00:00
|
|
|
Timer::Timer(QObject *parent) : QObject(parent) {
|
|
|
|
// Set up the emulation timer. Bluffer's guide: the QTimer will post an
|
|
|
|
// event to an event loop. QThread is a thread with an event loop.
|
|
|
|
// My class, Timer, will be wired up to receive the QTimer's events.
|
|
|
|
timer = std::make_unique<QTimer>(this);
|
|
|
|
timer->setInterval(1);
|
|
|
|
|
|
|
|
thread = std::make_unique<QThread>(this);
|
|
|
|
|
|
|
|
moveToThread(thread.get());
|
|
|
|
connect(timer.get(), SIGNAL(timeout()), this, SLOT(tick()));
|
|
|
|
}
|
2020-06-01 03:39:08 +00:00
|
|
|
|
2020-06-06 03:06:28 +00:00
|
|
|
void Timer::setMachine(MachineTypes::TimedMachine *machine, std::mutex *machineMutex) {
|
2020-06-03 04:21:37 +00:00
|
|
|
this->machine = machine;
|
2020-06-06 03:06:28 +00:00
|
|
|
this->machineMutex = machineMutex;
|
2020-06-03 04:21:37 +00:00
|
|
|
}
|
|
|
|
|
2020-06-01 03:39:08 +00:00
|
|
|
void Timer::tick() {
|
2020-06-03 04:21:37 +00:00
|
|
|
const auto now = Time::nanos_now();
|
2020-06-06 23:47:35 +00:00
|
|
|
const auto duration = std::min(now - lastTickNanos, int64_t(500'000'000));
|
|
|
|
// qDebug() << duration << " [not " << now - lastTickNanos << "]";
|
2020-06-03 04:21:37 +00:00
|
|
|
lastTickNanos = now;
|
|
|
|
|
2020-06-06 03:06:28 +00:00
|
|
|
std::lock_guard lock_guard(*machineMutex);
|
2020-06-03 04:21:37 +00:00
|
|
|
machine->run_for(double(duration) / 1e9);
|
2020-06-01 03:39:08 +00:00
|
|
|
}
|
2020-06-07 04:31:46 +00:00
|
|
|
|
|
|
|
void Timer::start() {
|
|
|
|
thread->start();
|
|
|
|
timer->start();
|
|
|
|
}
|
|
|
|
|
|
|
|
Timer::~Timer() {
|
|
|
|
// Stop the timer, then ask the QThread to exit and wait for it to do so.
|
|
|
|
timer->stop();
|
|
|
|
thread->exit();
|
|
|
|
while(thread->isRunning());
|
|
|
|
}
|