Files
move_base2/include/move_base2/io/env_logger.h

78 lines
2.3 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — ghi feature + verdict của EnvMonitor ra JSONL (Test/ENV_MONITOR_PLAN.md §2.6).
*
* Mục đích: replay offline để chỉnh ngưỡng không cần sim, và là dữ liệu huấn luyện ML sau này. Mỗi
* dòng là một tick nặng (5 Hz) hoặc một sườn sự kiện. Tắt mặc định; khi tắt không cấp phát, không mở
* file.
*
* Ghi trên control thread: dòng ~400 byte, gom vào buffer và flush mỗi `flush_period` — một lần
* `write()` vài kB mỗi giây. Nếu đo thấy ảnh hưởng chu kỳ thì chuyển sang thread riêng.
*
* Author: DuongTD
*********************************************************************/
#ifndef MOVE_BASE2_IO_ENV_LOGGER_H_
#define MOVE_BASE2_IO_ENV_LOGGER_H_
#include <cstdint>
#include <fstream>
#include <string>
#include <robot/time.h>
#include <move_base2/core/env_monitor.h>
#include <move_base2/ports/environment_port.h>
namespace move_base2
{
struct EnvLoggerConfig
{
bool enabled = false;
std::string log_dir = "/tmp/env_monitor"; ///< tạo nếu chưa có; file `envmon_<epoch>.jsonl`.
double flush_period = 1.0; ///< [s]
bool validate(std::string& error) const;
};
class EnvLogger
{
public:
EnvLogger() = default;
~EnvLogger();
EnvLogger(const EnvLogger&) = delete;
EnvLogger& operator=(const EnvLogger&) = delete;
/// @return false kèm lý do nếu không mở được file. Không mở gì khi `config.enabled == false`.
bool open(const EnvLoggerConfig& config, std::string& error);
bool isOpen() const
{
return out_.is_open();
}
const std::string& path() const
{
return path_;
}
/// @brief Một dòng JSON. @p geometry có thể null (tick nhẹ). @p state là tên state machine.
void record(const robot::Time& now, const EnvSample& sample, const EnvVerdict& verdict,
const EnvGeometry* geometry, const char* state, std::uint64_t mission_id,
bool used_local_plan);
void flush();
private:
EnvLoggerConfig config_;
std::ofstream out_;
std::string path_;
std::string buffer_;
robot::Time last_flush_;
bool has_last_flush_ = false;
};
} // namespace move_base2
#endif // MOVE_BASE2_IO_ENV_LOGGER_H_