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