~aleteoryx/muditaos

muditaos/module-utils/utility/Temperature.hpp -rw-r--r-- 1.9 KiB
a405cad6Aleteoryx trim readme 6 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright (c) 2017-2024, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/blob/master/LICENSE.md

#pragma once

#include <cstdint>
#include <iomanip>
#include <optional>
#include <string>

namespace utils::temperature
{
    inline constexpr auto celsiusSymbol          = "C";
    inline constexpr auto fahrenheitSymbol       = "F";
    inline constexpr auto degree                 = "\u00B0";
    inline constexpr auto celsiusDegreeSymbol    = "\u00B0C";
    inline constexpr auto fahrenheitDegreeSymbol = "\u00B0F";

    struct Temperature
    {
        using Value = float;
        enum class Unit
        {
            Celsius,
            Fahrenheit
        };
        Unit unit;
        Value value;
    };

    inline float celsiusToFahrenheit(float value)
    {
        return (value * 1.8) + 32;
    }

    inline std::string unitToStr(Temperature::Unit unit)
    {
        return unit == Temperature::Unit::Celsius ? celsiusSymbol : fahrenheitSymbol;
    }

    inline std::optional<Temperature::Unit> strToUnit(std::string_view str)
    {
        if ((str == celsiusDegreeSymbol) || (str == celsiusSymbol)) {
            return Temperature::Unit::Celsius;
        }
        else if ((str == fahrenheitDegreeSymbol) || (str == fahrenheitSymbol)) {
            return Temperature::Unit::Fahrenheit;
        }
        return {};
    }

    inline std::string tempToStrFloat(Temperature temperature, const int precision = 1)
    {
        std::ostringstream stream;
        stream << std::fixed << std::setprecision(precision);
        stream << temperature.value << degree << utils::temperature::unitToStr(temperature.unit);
        return stream.str();
    }

    inline std::string tempToStrDec(Temperature temperature)
    {
        return std::to_string(static_cast<std::int32_t>(temperature.value)) + degree +
               utils::temperature::unitToStr(temperature.unit);
    }
} // namespace utils::temperature