49 lines
1.4 KiB
C++
49 lines
1.4 KiB
C++
#pragma once
|
|
// Producer.hpp
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
// Author: Unai Blazquez <unaibg2000@gmail.com>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <filesystem>
|
|
#include <functional>
|
|
#include <thread>
|
|
|
|
#include "SysfsRead.hpp"
|
|
|
|
using RandomFn = std::function<int()>;
|
|
using LogFn = std::function<void(const std::string&)>;
|
|
using SleepFn = std::function<void(std::chrono::milliseconds)>;
|
|
class Producer
|
|
{
|
|
public:
|
|
/// @brief Construct a Producer bound to a sysfs-like control file.
|
|
/// @param sysfs_path Path to the control file (e.g. "./fake_sysfs_input").
|
|
/// @param send_fn Function called whenever a new integer should be sent.
|
|
Producer(const std::filesystem::path& sysfs_path,
|
|
std::function<void(int)> send_fn, RandomFn random_fn,
|
|
LogFn log_fn = nullptr, SleepFn sleep_fn = default_sleep);
|
|
|
|
/// @brief Start the worker thread. Safe to call only once.
|
|
void start();
|
|
|
|
/// @brief Request the worker thread to stop and wait for it to finish.
|
|
void stop();
|
|
|
|
private:
|
|
/// @brief Main loop executed by the worker thread.
|
|
void run_loop();
|
|
|
|
std::thread m_thread;
|
|
std::atomic<bool> m_running;
|
|
SysfsReader m_reader;
|
|
RandomFn m_random;
|
|
SleepFn m_sleep;
|
|
static void default_sleep(std::chrono::milliseconds d)
|
|
{
|
|
std::this_thread::sleep_for(d);
|
|
}
|
|
LogFn m_log;
|
|
std::function<void(int)> m_send;
|
|
std::chrono::milliseconds compute_delay(SysfsStatus status) const;
|
|
};
|