blob: 63c55c6db421db69e8d1fb2bebee038ef4a9a03a [file]
#ifndef THIRD_PARTY_MILOTIC_EXTERNAL_CC_TLBMC_HAL_LED_LED_H_
#define THIRD_PARTY_MILOTIC_EXTERNAL_CC_TLBMC_HAL_LED_LED_H_
#include <optional>
#include <string>
#include "absl/base/thread_annotations.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include <nlohmann/json.hpp>
#include "led_config.pb.h"
namespace milotic_tlbmc {
// Interface for controlling a single LED.
//
// Implementations back the LED with a specific hardware interface (e.g. the
// Linux LED sysfs subsystem, or - in the future - a raw GPIO line). Higher
// level components such as the LedCollector interact with LEDs only through
// this interface, so that support for new hardware backends can be added
// without changing the collector.
//
// This class is thread-safe.
class Led {
public:
static nlohmann::json BehaviorToJson(const LedBehavior& behavior);
virtual ~Led() = default;
// Led is a resource-managing class and should not be copied or moved.
Led(const Led&) = delete;
Led& operator=(const Led&) = delete;
Led(Led&&) = delete;
Led& operator=(Led&&) = delete;
// Returns the default behavior of the LED.
std::optional<LedBehavior> GetDefaultBehavior() const {
return default_behavior_;
}
// Returns the last update timestamp of the LED.
std::optional<absl::Time> GetLastUpdateTime() const {
absl::MutexLock lock(mutex_);
return last_update_time_;
}
// Sets the LED to its default behavior.
absl::Status SetToDefaultBehavior(absl::Time timestamp);
// Applies the given behavior (OFF / ON / BLINK) to the LED.
// If `timestamp` is less than or equal to `last_update_time_`, the update is
// skipped and absl::OkStatus() is returned.
absl::Status SetBehavior(const LedBehavior& behavior, absl::Time timestamp);
// Returns the current behavior of the LED, read back from the hardware.
absl::StatusOr<LedBehavior> GetBehavior() const {
absl::MutexLock lock(mutex_);
return GetBehaviorImpl();
}
// Returns the unique name of this LED (LedConfig.name).
std::string GetName() const { return name_; }
// Returns the JSON representation of the LED.
nlohmann::json ToJson() const;
protected:
explicit Led(const LedConfig& config)
: name_(config.name()),
default_behavior_(config.has_default_behavior()
? std::make_optional(config.default_behavior())
: std::nullopt),
last_update_time_(std::nullopt) {}
// Hardware-specific implementation of setting the LED behavior.
virtual absl::Status SetBehaviorImpl(const LedBehavior& behavior) = 0;
// Hardware-specific implementation of reading the LED behavior.
virtual absl::StatusOr<LedBehavior> GetBehaviorImpl() const = 0;
const std::string name_;
const std::optional<LedBehavior> default_behavior_;
mutable absl::Mutex mutex_;
std::optional<absl::Time> last_update_time_ ABSL_GUARDED_BY(mutex_);
};
} // namespace milotic_tlbmc
#endif // THIRD_PARTY_MILOTIC_EXTERNAL_CC_TLBMC_HAL_LED_LED_H_