blob: 34dbae986b141f7dd721553eb42c5da320a78b11 [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>
Patrick Williams583ba442025-02-03 14:28:19 -050015 std::shared_ptr<SensorType> makeSensor(
16 std::string_view service, std::string_view path, Args&&... args)
Krzysztof Grobelny7f06f612020-09-24 13:42:10 +020017 {
18 cleanupExpiredSensors();
19
20 auto id = SensorType::makeId(service, path);
21 auto it = sensors.find(id);
22
23 if (it == sensors.end())
24 {
25 auto sensor = std::make_shared<SensorType>(
26 std::move(id), std::forward<Args>(args)...);
27
28 sensors[sensor->id()] = sensor;
29
30 return sensor;
31 }
32
33 return std::static_pointer_cast<SensorType>(it->second.lock());
34 }
35
36 private:
37 using SensorsContainer =
38 boost::container::flat_map<interfaces::Sensor::Id,
39 std::weak_ptr<interfaces::Sensor>>;
40
41 SensorsContainer sensors;
42
43 SensorsContainer::iterator findExpiredSensor(SensorsContainer::iterator);
44 void cleanupExpiredSensors();
45};