Created sensor cache class
Created sensor cache and sensor interface that needs to be
implemented by sensors.
Tested:
- Sensors created by sensor cache are stored and reused if
there is try to access same sensor multiple times.
- All other units tests are passing
Change-Id: I552b2016bca4688e1b2a223297587826af256b54
Signed-off-by: Krzysztof Grobelny <krzysztof.grobelny@intel.com>
diff --git a/src/sensor_cache.hpp b/src/sensor_cache.hpp
new file mode 100644
index 0000000..3e19721
--- /dev/null
+++ b/src/sensor_cache.hpp
@@ -0,0 +1,47 @@
+#pragma once
+
+#include "interfaces/sensor.hpp"
+
+#include <boost/container/flat_map.hpp>
+#include <boost/system/error_code.hpp>
+
+#include <iostream>
+#include <memory>
+#include <string_view>
+
+class SensorCache
+{
+ public:
+ template <class SensorType, class... Args>
+ std::shared_ptr<SensorType> makeSensor(std::string_view service,
+ std::string_view path,
+ Args&&... args)
+ {
+ cleanupExpiredSensors();
+
+ auto id = SensorType::makeId(service, path);
+ auto it = sensors.find(id);
+
+ if (it == sensors.end())
+ {
+ auto sensor = std::make_shared<SensorType>(
+ std::move(id), std::forward<Args>(args)...);
+
+ sensors[sensor->id()] = sensor;
+
+ return sensor;
+ }
+
+ return std::static_pointer_cast<SensorType>(it->second.lock());
+ }
+
+ private:
+ using SensorsContainer =
+ boost::container::flat_map<interfaces::Sensor::Id,
+ std::weak_ptr<interfaces::Sensor>>;
+
+ SensorsContainer sensors;
+
+ SensorsContainer::iterator findExpiredSensor(SensorsContainer::iterator);
+ void cleanupExpiredSensors();
+};