obmon  1.4.0
 All Classes Functions Variables Typedefs Enumerations Groups Pages
ObSensor.cpp
1 #include <ObSensor.h>
2 
3 ObSensor::ObSensor(std::string name) : _name{name}, _enabled(true) {
7 
8  _logger = spdlog::get("console");
9 }
14 }
15 
20 
21  bool rc;
22  for (auto s : _sensors) {
23  if (s->enabled()) {
24  rc = s->init();
25  if (!rc)
26  s->enabled(false);
27  }
28  }
29 
30  return true;
31 }
32 
33 void ObSensor::update(unsigned int timeout) {
37 
38  if (!enabled())
39  return;
40 
41  // switch pointers
42  if (_first) {
43  auto s_ptr = _first;
44  _first = _second;
45  _second = s_ptr;
46  }
47  for (auto s : _sensors) {
48  if (s->_first) {
49  s->_first->type(SensorType::VALUE);
50  s->_first->process();
51  }
52  if (s->_change) {
53  s->_change->type(SensorType::SPEED);
54  s->_change->speed(s->_second, s->_first, timeout);
55  }
56  s->update(timeout);
57  }
58 }
59 
60 std::string ObSensor::json(const std::string name) const {
64 
65  using namespace fmt::literals;
66 
67  if (!enabled()) {
68  return "";
69  }
70 
71  std::string json;
72  std::string const &useName = (name.empty() ? _name : name);
73 
74  json += R"("hostname": "{}",)"_format(useName);
75  json += R"("nodename": "{}",)"_format(useName.substr(0, useName.find('.')));
76 
77  for (auto s : _sensors) {
78  if (!s->enabled()) {
79  continue;
80  }
81 
82  // ---------- BEGIN object ROOT ----------
83  json += R"("{}" : {{)"_format(s->name());
84 
85  if (s->_first) {
86  json += s->_first->json("value");
87  json += ",";
88  } else {
89  json += s->json(s->name());
90  json += ",";
91  }
92 
93  if (s->_change) {
94  std::string str = s->_change->json("change");
95  if (!str.empty()) {
96  json += str;
97  json += ",";
98  }
99  } else {
100  json += s->json(s->name());
101  json += ",";
102  }
103 
104  if (json.back() == ',') {
105  json.pop_back();
106  }
107 
108  // ---------- END object ROOT ----------
109  json += "},";
110  }
111 
112  if (json.back() == ',') {
113  json.pop_back();
114  }
115 
116  return json;
117 }
ObSensor(std::string name={"sensor"})
Definition: ObSensor.cpp:3
virtual void update(unsigned int timeout) final
Definition: ObSensor.cpp:33
std::string name() const
Returns name of sensor.
Definition: ObSensor.h:38
std::vector< ObSensor * > _sensors
List of subsensors.
Definition: ObSensor.h:63
ObSensor * _first
Pointer to first sensor.
Definition: ObSensor.h:60
virtual bool init()
Definition: ObSensor.cpp:16
virtual std::string json(const std::string name={}) const
Definition: ObSensor.cpp:60
ObSensor * _second
Pointer to second sensor.
Definition: ObSensor.h:61
bool enabled() const
Returns flag if sensor is enabled.
Definition: ObSensor.h:50
virtual ~ObSensor()
Definition: ObSensor.cpp:10
std::string _name
Sensor name.
Definition: ObSensor.h:57
void type(SensorType t)
Sets sensor type.
Definition: ObSensor.h:41