forked from EmbeddedTeam/app_photomagnetic
Extend the UART protocol to support writing and reading the heating state, and reading individual pole NTC sensors and the heating pad NTC. Cache NTC readings for query on demand. Move PID updates to a workqueue to avoid blocking the timer IRQ context.
77 lines
2.0 KiB
C++
77 lines
2.0 KiB
C++
#ifndef THER_NTC_HPP
|
|
#define THER_NTC_HPP
|
|
#include <array>
|
|
#include <cmath>
|
|
#include <zephyr/device.h>
|
|
#include <zephyr/drivers/sensor.h>
|
|
#include <zephyr/sys/printk.h>
|
|
#include <zpp/result.hpp>
|
|
|
|
namespace ther {
|
|
|
|
class NtcGroup {
|
|
public:
|
|
/// Read all NTC sensors, return the maximum temperature value.
|
|
/// Returns error if every sensor read fails.
|
|
static auto GetSensorValue() -> zpp::result<sensor_value> {
|
|
bool found = false;
|
|
sensor_value max_val{};
|
|
|
|
for (size_t i = 0; i < NTC_COUNT; ++i) {
|
|
const auto *dev = s_devices[i];
|
|
|
|
if (0 != sensor_sample_fetch(dev)) {
|
|
printk("[ntc] #%zu ERR fetch\n", i + 1);
|
|
continue;
|
|
}
|
|
|
|
sensor_value val{};
|
|
if (0 != sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &val)) {
|
|
printk("[ntc] #%zu ERR channel_get\n", i + 1);
|
|
continue;
|
|
}
|
|
|
|
// Always cache the latest reading for individual query
|
|
s_current_temp[i] = val;
|
|
|
|
if (!found || val.val1 > max_val.val1 ||
|
|
(val.val1 == max_val.val1 && val.val2 > max_val.val2)) {
|
|
max_val = val;
|
|
found = true;
|
|
}
|
|
}
|
|
|
|
if (found) {
|
|
return max_val;
|
|
}
|
|
|
|
return zpp::error_code::k_io;
|
|
}
|
|
|
|
/// Return the cached value for a single NTC sensor.
|
|
static auto GetSensorValue(uint8_t id) -> sensor_value {
|
|
if (id >= NTC_COUNT) {
|
|
return sensor_value{};
|
|
}
|
|
return s_current_temp[id];
|
|
}
|
|
|
|
private:
|
|
static constexpr size_t NTC_COUNT = 8;
|
|
inline static std::array<sensor_value, NTC_COUNT> s_current_temp{};
|
|
inline static const device *s_devices[] = {
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc1)),
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc2)),
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc3)),
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc4)),
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc5)),
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc6)),
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc7)),
|
|
DEVICE_DT_GET(DT_NODELABEL(pole_ntc8)),
|
|
};
|
|
};
|
|
|
|
} // namespace ther
|
|
|
|
#endif // THER_NTC_HPP
|