MVSim
Lightweight simulator for 2.5D vehicles and robots
CsvLogger.h
1 /*+-------------------------------------------------------------------------+
2  | MultiVehicle simulator (libmvsim) |
3  | |
4  | Copyright (C) 2014-2026 Jose Luis Blanco Claraco |
5  | Copyright (C) 2017 Borys Tymchenko (Odessa Polytechnic University) |
6  | Distributed under 3-clause BSD License |
7  | See COPYING |
8  +-------------------------------------------------------------------------+ */
9 
10 #pragma once
11 
12 #include <fstream>
13 #include <functional>
14 #include <map>
15 #include <memory>
16 #include <string>
17 #include <vector>
18 
20 class CSVLogger
21 {
22  public:
23  CSVLogger();
24  virtual ~CSVLogger();
25 
26  using Ptr = std::shared_ptr<CSVLogger>;
27 
28  // deleted copy/move constructors and assignment operators:
29  CSVLogger(const CSVLogger&) = delete;
30  CSVLogger& operator=(const CSVLogger&) = delete;
31  CSVLogger(CSVLogger&&) = delete;
32  CSVLogger& operator=(CSVLogger&&) = delete;
33 
37  std::function<void(const std::map<std::string_view, double>& /*columns*/)>;
38 
39  public:
40  void updateColumn(const std::string_view& name, double value);
41  bool writeHeader();
42  bool writeRow();
43 
44  void setFilepath(const std::string& path) { filepath_ = path; }
45  bool open();
46  bool isOpen();
47  bool close();
48  bool clear();
49 
50  void setRecording(bool recording) { isRecording_ = recording; }
51  [[nodiscard]] bool isRecording() const { return isRecording_; }
52 
56  void setFileWritingEnabled(bool enabled) { fileWritingEnabled_ = enabled; }
57  [[nodiscard]] bool isFileWritingEnabled() const { return fileWritingEnabled_; }
58  void newSession();
59 
62  void registerOnRowCallback(const on_row_callback_t& cb) { onRowCallbacks_.emplace_back(cb); }
63 
67  [[nodiscard]] bool isActive() const { return isRecording_ || !onRowCallbacks_.empty(); }
68 
70  [[nodiscard]] const std::map<std::string_view, double>& getColumns() const { return columns_; }
71 
72  private:
73  std::map<std::string_view, double> columns_;
74  std::shared_ptr<std::ofstream> file_;
75  std::string filepath_;
76  bool isRecording_ = false;
77  bool fileWritingEnabled_ = true;
78 
79  std::vector<on_row_callback_t> onRowCallbacks_;
80 };
Definition: CsvLogger.h:21
bool isActive() const
Definition: CsvLogger.h:67
void setFileWritingEnabled(bool enabled)
Definition: CsvLogger.h:56
void registerOnRowCallback(const on_row_callback_t &cb)
Definition: CsvLogger.h:62
std::function< void(const std::map< std::string_view, double > &)> on_row_callback_t
Definition: CsvLogger.h:37
const std::map< std::string_view, double > & getColumns() const
Read-only access to the current column values.
Definition: CsvLogger.h:70