2020-05-31 23:39:08 -04:00
|
|
|
#include "timer.h"
|
|
|
|
|
|
|
|
#include "../../ClockReceiver/TimeTypes.hpp"
|
|
|
|
|
2020-06-03 00:21:37 -04:00
|
|
|
#include <algorithm>
|
2020-05-31 23:39:08 -04:00
|
|
|
#include <QDebug>
|
|
|
|
|
2020-06-16 22:33:50 -04: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 18:55:42 -04:00
|
|
|
thread.start();
|
2020-06-16 22:33:50 -04:00
|
|
|
thread.performAsync([this] {
|
2020-06-14 23:22:00 -04: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-14 23:38:44 -04:00
|
|
|
timer = std::make_unique<QTimer>();
|
2020-06-14 23:22:00 -04:00
|
|
|
timer->setInterval(1);
|
|
|
|
|
2020-06-15 00:00:44 -04:00
|
|
|
connect(timer.get(), &QTimer::timeout, this, &Timer::tick, Qt::DirectConnection);
|
2020-06-14 23:22:00 -04:00
|
|
|
timer->start();
|
|
|
|
});
|
2020-06-07 00:31:46 -04:00
|
|
|
}
|
2020-05-31 23:39:08 -04:00
|
|
|
|
|
|
|
void Timer::tick() {
|
2020-06-03 00:21:37 -04:00
|
|
|
const auto now = Time::nanos_now();
|
2020-06-06 19:47:35 -04:00
|
|
|
const auto duration = std::min(now - lastTickNanos, int64_t(500'000'000));
|
2020-06-03 00:21:37 -04:00
|
|
|
lastTickNanos = now;
|
|
|
|
|
2020-06-05 23:06:28 -04:00
|
|
|
std::lock_guard lock_guard(*machineMutex);
|
2020-06-03 00:21:37 -04:00
|
|
|
machine->run_for(double(duration) / 1e9);
|
2020-05-31 23:39:08 -04:00
|
|
|
}
|
2020-06-07 00:31:46 -04:00
|
|
|
|
|
|
|
Timer::~Timer() {
|
2020-06-16 22:33:50 -04:00
|
|
|
thread.performAsync([this] {
|
2020-06-19 20:17:47 -04:00
|
|
|
if(timer) {
|
|
|
|
timer->stop();
|
|
|
|
}
|
2020-06-16 22:33:50 -04:00
|
|
|
});
|
2020-06-14 23:38:44 -04:00
|
|
|
thread.stop();
|
2020-06-07 00:31:46 -04:00
|
|
|
}
|