#include "sensor.h"

#include <print>
#include <string>
#include <cassert>
#include <fcntl.h>
#include <unistd.h>


Sensor::Sensor(const std::filesystem::path& celsius_temperature_file)
: _celsius_temperature_file(celsius_temperature_file)
{}

long Sensor::get_temperature()
{
    if (! _on) {
        std::println("switching sensor on again -> BOOM!");
        return 666'666'666'666;
    }

    int fd = open(_celsius_temperature_file.c_str(), O_RDONLY);
    if (fd == -1) {
        perror(std::format("open(\"{}\", O_RDONLY)", _celsius_temperature_file.string()).c_str());
        assert(false);
    }
    
    char tmp[16] = {};
    ssize_t nread = read(fd, tmp, sizeof(tmp)-1);
    if (nread == -1) {
        perror("read");
        assert(false);
    }

    close(fd);

    try {
        return std::stoi(tmp);
    }
    catch (const std::exception& e) {
        std::println(stderr, "content of file {} ({}) is not an integer", _celsius_temperature_file.string(), tmp);
        assert(false);
    }
}
