blob: bebc4c6910ee9b0a5b211fad1f86b6c0df42f599 [file] [log] [blame]
Krzysztof Grobelny7f06f612020-09-24 13:42:10 +02001#pragma once
2
3#include "interfaces/sensor.hpp"
4
5#include <boost/container/flat_map.hpp>
6#include <boost/system/error_code.hpp>
7
Krzysztof Grobelny7f06f612020-09-24 13:42:10 +02008#include <memory>
9#include <string_view>
10
11class SensorCache
12{
13 public:
14 template <class SensorType, class... Args>
15 std::shared_ptr<SensorType> makeSensor(std::string_view service,
16 std::string_view path,
17 Args&&... args)
18 {
19 cleanupExpiredSensors();
20
21 auto id = SensorType::makeId(service, path);
22 auto it = sensors.find(id);
23
24 if (it == sensors.end())
25 {
26 auto sensor = std::make_shared<SensorType>(
27 std::move(id), std::forward<Args>(args)...);
28
29 sensors[sensor->id()] = sensor;
30
31 return sensor;
32 }
33
34 return std::static_pointer_cast<SensorType>(it->second.lock());
35 }
36
37 private:
38 using SensorsContainer =
39 boost::container::flat_map<interfaces::Sensor::Id,
40 std::weak_ptr<interfaces::Sensor>>;
41
42 SensorsContainer sensors;
43
44 SensorsContainer::iterator findExpiredSensor(SensorsContainer::iterator);
45 void cleanupExpiredSensors();
46};