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-17 02:33:50 +00:00
|
|
|
Timer::Timer(QObject *parent) : QObject(parent) {}
|
|
|
|
|
|
|
|
void Timer::startWithMachine(MachineTypes::TimedMachine *machine, std::mutex *machineMutex) {
|
|
|
|
this->machine = machine;
|
|
|
|
this->machineMutex = machineMutex;
|
|
|
|
|
2020-07-01 22:55:42 +00:00
|
|
|
thread.start();
|
2020-06-17 02:33:50 +00:00
|
|
|
thread.performAsync([this] {
|
2020-06-15 03:22:00 +00:00
|
|
|
// 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.
|
2020-06-15 03:38:44 +00:00
|
|
|
timer = std::make_unique<QTimer>();
|
2020-06-15 03:22:00 +00:00
|
|
|
timer->setInterval(1);
|
|
|
|
|
2020-06-15 04:00:44 +00:00
|
|
|
connect(timer.get(), &QTimer::timeout, this, &Timer::tick, Qt::DirectConnection);
|
2020-06-15 03:22:00 +00:00
|
|
|
timer->start();
|
|
|
|
});
|
2020-06-07 04:31:46 +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));
|
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
|
|
|
|
|
|
|
Timer::~Timer() {
|
2020-06-17 02:33:50 +00:00
|
|
|
thread.performAsync([this] {
|
2020-06-20 00:17:47 +00:00
|
|
|
if(timer) {
|
|
|
|
timer->stop();
|
|
|
|
}
|
2020-06-17 02:33:50 +00:00
|
|
|
});
|
2020-06-15 03:38:44 +00:00
|
|
|
thread.stop();
|
2020-06-07 04:31:46 +00:00
|
|
|
}
|