Krzysztof Grobelny | 7f06f61 | 2020-09-24 13:42:10 +0200 | [diff] [blame] | 1 | #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 Grobelny | 7f06f61 | 2020-09-24 13:42:10 +0200 | [diff] [blame] | 8 | #include <memory> |
| 9 | #include <string_view> |
| 10 | |
| 11 | class 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 | }; |