arduino-audio-tools
Loading...
Searching...
No Matches
AudioTimerDesktop.h
1#pragma once
2
3#include "AudioTimerBase.h"
4
5#if defined(USE_TIMER) && defined(USE_CPP_TASK)
6
7#include <atomic>
8#include <chrono>
9#include <thread>
10
11namespace audio_tools {
12
30class TimerAlarmRepeatingDriverLinux : public TimerAlarmRepeatingDriverBase {
31 public:
32 TimerAlarmRepeatingDriverLinux() = default;
33 ~TimerAlarmRepeatingDriverLinux() { end(); }
34
35 bool begin(repeating_timer_callback_t callback_f, uint32_t time,
36 TimeUnit unit = MS) override {
37 // Stop any existing timer first
38 end();
39 if (callback_f == nullptr || time == 0) return false;
40 callback = callback_f;
41 period_us = toMicroseconds(time, unit);
42 running.store(true);
43 worker = std::thread([this]() { this->runLoop(); });
44 return true;
45 }
46
47 bool end() override {
48 if (running.load()) {
49 running.store(false);
50 if (worker.joinable()) worker.join();
51 }
52 return true;
53 }
54
55 protected:
56 std::thread worker;
57 std::atomic<bool> running{false};
58 repeating_timer_callback_t callback = nullptr;
59 uint64_t period_us = 0;
60
61 static uint64_t toMicroseconds(uint32_t value, TimeUnit unit) {
62 switch (unit) {
63 case US:
64 return value;
65 case MS:
66 return static_cast<uint64_t>(value) * 1000ULL;
67 default:
68 return static_cast<uint64_t>(value) * 1000ULL;
69 }
70 }
71
72 void runLoop() {
73 auto next = std::chrono::steady_clock::now();
74 while (running.load()) {
75 next += std::chrono::microseconds(period_us);
76 if (callback) {
77 // Execute callback; pass stored object pointer
78 callback(callbackParameter());
79 }
80 std::this_thread::sleep_until(next);
81 }
82 }
83};
84
86using TimerAlarmRepeatingDriver = TimerAlarmRepeatingDriverLinux;
87
88
89} // namespace audio_tools
90
91#endif // USE_TIMER
TimeUnit
Time Units.
Definition AudioTypes.h:48
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition AudioCodecsBase.h:10
TimerAlarmRepeatingDriverAVR TimerAlarmRepeatingDriver
use TimerAlarmRepeating!
Definition AudioTimerAVR.h:94