ranczo-io/services/temperature_svc/ds18b20_sensor.hpp
2025-11-26 07:06:36 +01:00

67 lines
2.0 KiB
C++

#pragma once
#include <boost/asio/steady_timer.hpp>
#include <config.hpp>
#include <filesystem>
#include <functional>
#include <memory_resource>
#include <string>
#include <string_view>
#include <ranczo-io/utils/memory_resource.hpp>
#include "measurement_publisher.hpp"
namespace ranczo {
class DS18B20Sensor {
public:
DS18B20Sensor(boost::asio::any_io_executor exec, std::filesystem::path device_id) : executor_(exec), device_id_{std::move(device_id)} {}
awaitable_expected< float > read_temperature() const noexcept;
std::string device_id() const {
return device_id_.filename().string();
}
private:
boost::asio::any_io_executor executor_;
std::filesystem::path device_id_;
};
class OneWireBus {
public:
OneWireBus(boost::asio::any_io_executor exec, MqttMeasurementPublisher &pub, std::string_view bus_path, std::chrono::seconds interval = std::chrono::seconds(2))
: _mr{memory_resource::default_resource()}, _pub{pub}, executor_(exec), timer_(exec), bus_path_(std::move(bus_path), _mr), interval_(interval) {}
OneWireBus(const OneWireBus &) = delete;
OneWireBus(OneWireBus && rhs) noexcept = default;
OneWireBus & operator=(const OneWireBus &) = delete;
OneWireBus & operator=(OneWireBus && rhs) =default;
boost::asio::awaitable< void > run();
void stop();
private:
void add_sensor(const std::pmr::string & id) {
std::filesystem::path path{};
path += bus_path_ + "/" + id;
sensors_.emplace_back(executor_, path);
}
void clearSensors() {
sensors_.clear();
}
std::pmr::memory_resource* _mr{};
std::pmr::vector< std::pmr::string > scanBus(std::pmr::memory_resource & mr, const std::filesystem::path & bus_path);
boost::asio::any_io_executor executor_;
std::reference_wrapper<MqttMeasurementPublisher> _pub;
boost::asio::steady_timer timer_;
std::pmr::string bus_path_;
std::chrono::seconds interval_;
std::pmr::vector< DS18B20Sensor > sensors_{_mr};
};
} // namespace ranczo