renderbug-cpp/lib/Figments/MainLoop.cpp
Torrie Fischer 9b1600f00b
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
figments: mainloop: run loop() once before ready-to-roll
2023-02-18 16:23:02 +01:00

91 lines
2.5 KiB
C++

#include "./MainLoop.h"
#include "./Input.h"
#include "./Figment.h"
#include <ArduinoLog.h>
void
MainLoop::dispatch(const InputEvent& evt)
{
if (evt.intent == InputEvent::None) {
return;
}
m_eventBuf.insert(evt);
}
void
MainLoop::loop()
{
s_instance = this;
InputEvent evt;
while (m_eventBuf.take(evt)) {
if (evt.intent == InputEvent::StartThing || evt.intent == InputEvent::StopThing) {
const bool jobState = (evt.intent == InputEvent::StartThing);
for(auto figmentJob: scheduler.tasks) {
if (!strcmp(figmentJob->name, evt.asString())) {
if (jobState) {
Log.trace("** Starting %s", figmentJob->name);
figmentJob->start();
} else {
Log.trace("** Stopping %s", figmentJob->name);
figmentJob->stop();
}
}
}
}
for(Task* task : scheduler) {
Log.verbose("** Eventing %s", task->name);
task->handleEvent(evt);
}
}
unsigned int slowest = 0;
unsigned int frameSpeed = 0;
unsigned int frameStart = millis();
unsigned int taskCount = 0;
Task* slowestTask = NULL;
for(Task* task : scheduler) {
//unsigned int start = millis();
#if defined(BOARD_ESP32) or defined(BOARD_ESP8266)
unsigned int start = ESP.getCycleCount();
#else
unsigned int start = millis();
#endif
Log.verbose("Running %s", task->name);
task->loop();
#if defined(BOARD_ESP32) or defined(BOARD_ESP8266)
unsigned int runtime = (ESP.getCycleCount() - start) / 160000;
#else
unsigned int runtime = millis() - start;
#endif
frameSpeed += runtime;
taskCount++;
if (runtime > slowest) {
slowest = runtime;
slowestTask = task;
}
}
frameSpeed = millis() - frameStart;
if (frameSpeed >= 23) {
const char* slowestName = (slowestTask->name ? slowestTask->name : "(Unnamed)");
Log.warning("Slow frame: %dms, %d tasks, longest task %s was %dms", frameSpeed, taskCount, slowestTask->name, slowest);
}
}
void
MainLoop::start()
{
s_instance = this;
Log.notice("Welcome to 🌕 Figment 0.3.0");
Log.notice("*** Starting %d tasks...", scheduler.tasks.size());
Serial.flush();
for(auto task: scheduler) {
Log.notice("** Starting %s", task->name);
task->start();
}
loop();
dispatch(InputEvent::ReadyToRoll);
}
MainLoop* MainLoop::s_instance;