blob: 34e3af494c54a1f47cca11500742384df970769d [file]
#include "tlbmc/hal/led/led.h"
#include <optional>
#include <string>
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "g3/macros.h"
#include <nlohmann/json.hpp>
#include "led_config.pb.h"
#include "google/protobuf/json/json.h"
#include "google/protobuf/util/json_util.h"
namespace milotic_tlbmc {
nlohmann::json Led::BehaviorToJson(const LedBehavior& behavior) {
std::string json_string;
::google::protobuf::util::JsonPrintOptions opts;
opts.preserve_proto_field_names = true;
if (::google::protobuf::json::MessageToJsonString(behavior, &json_string, opts).ok()) {
return nlohmann::json::parse(json_string, nullptr, false);
}
LOG(ERROR) << "Failed to convert behavior to JSON: " << behavior;
return nullptr;
}
absl::Status Led::SetToDefaultBehavior(absl::Time timestamp) {
if (!default_behavior_.has_value() ||
default_behavior_->state() == LED_STATE_UNSPECIFIED) {
return absl::OkStatus();
}
return SetBehavior(*default_behavior_, timestamp);
}
absl::Status Led::SetBehavior(const LedBehavior& behavior,
absl::Time timestamp) {
absl::MutexLock lock(mutex_);
if (last_update_time_.has_value() && timestamp <= *last_update_time_) {
return absl::OkStatus();
}
ECCLESIA_RETURN_IF_ERROR(SetBehaviorImpl(behavior));
last_update_time_ = timestamp;
return absl::OkStatus();
}
nlohmann::json Led::ToJson() const {
nlohmann::json led_json;
std::string name = GetName();
led_json["name"] = name;
if (default_behavior_.has_value()) {
led_json["default_behavior"] = BehaviorToJson(*default_behavior_);
}
{
absl::MutexLock lock(mutex_);
absl::StatusOr<LedBehavior> behavior = GetBehaviorImpl();
if (behavior.ok()) {
led_json["behavior"] = BehaviorToJson(*behavior);
} else {
LOG(ERROR) << "Failed to get behavior for LED " << name << " : "
<< behavior.status();
led_json["behavior"] = nullptr;
}
if (last_update_time_.has_value()) {
led_json["last_update_time"] = absl::FormatTime(*last_update_time_);
}
}
return led_json;
}
} // namespace milotic_tlbmc