Files
trmnl_server_cpp/TRMNL.h

91 lines
2.3 KiB
C++

#ifndef TRMNL_H_
#define TRMNL_H_
#include <functional>
#include <list>
#include <map>
#include <optional>
#include <string>
#include "json.hpp"
constexpr int DEFAULT_REFRESH_RATE = 300;
class TRMNL
{
private:
std::string m_id;
std::string m_api_key;
std::string m_friendly_id;
int m_refresh_rate;
bool m_is_refresh_aligned;
std::function<void (const TRMNL& trmnl)> m_update_handler;
public:
// Constructors
TRMNL(const std::string& id = "",
const std::string& api_key = "",
const std::string& friendly_id = "",
int refresh_rate = DEFAULT_REFRESH_RATE,
bool is_refresh_aligned = true);
TRMNL(const nlohmann::json& j);
// Getters
const std::string& id() const;
const std::string& api_key() const;
const std::string& friendly_id() const;
int refresh_rate() const;
bool is_refresh_aligned() const;
// Uses the current time to return when next this device should refresh
// min_time
// - if calculated time is lower than this - increase by refresh rate until higher
// - Capped to the refresh rate
// offset
// - offset to apply to the refresh rate
// - Capped to the refresh rate
// - useful when generating images via cron and you want the refresh to happen a few seconds later
int get_next_refresh(int min_time = 0, int offset = 0) const;
// Setters
void id(const std::string& id);
void api_key(const std::string& api_key);
void friendly_id(const std::string& friendly_id);
void refresh_rate(int refresh_rate);
void is_refresh_aligned(bool to_align);
void set_update_handler(std::function<void (const TRMNL& trmnl)> handler);
static std::string friendly_from_id(std::string id);
friend void to_json(nlohmann::json& j, const TRMNL& trmnl);
friend class TRMNLContainer;
};
class TRMNLContainer
{
private:
std::list<TRMNL> m_devices;
std::map<std::string, std::list<TRMNL>::iterator> m_by_id;
std::map<std::string, std::list<TRMNL>::iterator> m_by_friendly;
void TRMNL_update_handler(const TRMNL& trmnl);
public:
TRMNLContainer() = default;
TRMNLContainer& operator=(const TRMNLContainer& other);
void add_device(TRMNL trmnl);
TRMNL* get_device_by_id(const std::string& id);
TRMNL* get_device_by_friendly(const std::string& friendly);
void clear();
friend void to_json(nlohmann::json& j, const TRMNLContainer& cont);
};
#endif // TRMNL_H_