Add sensors Sensor interface and a verified host test setup

Sensor/SensorValue in components/sensors/include/sensor.h is modeled
on Zephyr's sensor API: a fetch()/get() split so multi-channel sensors
(e.g. BME280) pay the hardware read cost once, fixed-point SensorValue
(no float/double -- ESP32-C6 has no hardware FPU), a fine-grained
SensorChannel enum, and an optional interrupt-driven set_trigger() for
the battery-first sleep/wake design.

Adds components/sensors/test_apps/host, a self-contained ESP-IDF
project building against the `linux` target so this logic is
host-testable per AGENTS.md's testing philosophy -- verified in a
clean run against the pinned espressif/idf:v6.0.2 image (builds, 4/4
tests pass). Replaces the earlier generic top-level test/README.md
placeholder now that a real per-component pattern exists.

Also fixes .gitignore's build/managed_components patterns to match
nested paths, not just the repo root.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Ronny Eia
2026-07-08 20:44:48 +02:00
parent 524714148b
commit f1be175dc2
10 changed files with 220 additions and 12 deletions

View File

@@ -1,3 +1,4 @@
idf_component_register(
INCLUDE_DIRS "include"
REQUIRES drivers
)

View File

@@ -1,3 +1,12 @@
# sensors
Turns raw `drivers` readings into typed sensor values (e.g. debounced contact state, calibrated analog readings). Knows values, not hardware. `REQUIRES drivers`.
Common interface: `include/sensor.h` defines `Sensor` and `SensorValue`, deliberately modeled on Zephyr's sensor API:
- **fetch()/get() split**: `fetch()` triggers one hardware read and caches it; `get(channel, out)` pulls a single channel out of that cache. Multi-channel sensors (e.g. BME280: temperature + humidity + pressure) pay the hardware cost once per `fetch()`, not once per channel.
- **Fixed-point `SensorValue`**: `val1 + val2 * 1e-6`, no `float`/`double`. ESP32-C6 has no hardware FPU, so this avoids software-emulated floating point on every sample.
- **Fine-grained `SensorChannel`** enum (`AmbientTemperature`, `Humidity`, `AccelX`, ...), mirroring Zephyr's `SENSOR_CHAN_*` granularity. `supports(channel)` lets `profiles` discover capabilities generically.
- **`set_trigger()`** for interrupt-driven sensors (data-ready pin, threshold, reed switch edge), so wake-on-event is possible instead of pure polling -- matters for the battery-first sleep/wake philosophy in `AGENTS.md`. Defaults to unsupported; polling-only sensors don't override it.
Every concrete sensor (reed switch, DS18B20, BME280, ...) implements `Sensor`, so `profiles` and `lua_runtime` can consume any of them uniformly.

View File

@@ -0,0 +1,81 @@
#pragma once
#include <cstdint>
namespace kvida {
// Fine-grained channel identifiers, one per physical quantity a sensor can
// expose -- mirrors Zephyr's SENSOR_CHAN_* granularity so a single sensor
// (e.g. a BME280) can expose several channels from one fetch().
enum class SensorChannel {
Contact,
Motion,
AmbientTemperature,
Humidity,
Pressure,
AccelX,
AccelY,
AccelZ,
Analog,
PulseCount,
Generic,
};
// Fixed-point value: actual value = val1 + val2 * 1e-6 (same convention as
// Zephyr's struct sensor_value). ESP32-C6 has no hardware FPU, so avoiding
// float/double here avoids paying for software-emulated floating point on
// every sample -- relevant given the battery-first design goal.
struct SensorValue {
int32_t val1;
int32_t val2;
const char* unit;
uint64_t timestamp_ms;
};
enum class SensorTriggerType {
DataReady,
Threshold,
};
// Plain function pointer + user_data, not std::function, to avoid heap
// allocation for callback storage on embedded targets.
using SensorTriggerHandler = void (*)(void* user_data);
class Sensor {
public:
virtual ~Sensor() = default;
virtual const char* id() const = 0;
virtual void begin() = 0;
// True if this sensor exposes the given channel. Lets `profiles`
// discover capabilities generically instead of hardcoding per
// concrete sensor.
virtual bool supports(SensorChannel channel) const = 0;
// Triggers a hardware read and caches the result internally. A
// single fetch() may populate several channels at once (e.g. one
// I2C transaction on a BME280 yields temperature + humidity +
// pressure), so multi-channel sensors only pay the hardware cost
// once per fetch(), not once per channel.
virtual bool fetch() = 0;
// Reads a previously fetched channel from the internal cache.
// Returns false if the sensor doesn't support the channel, or if
// fetch() hasn't been called yet.
virtual bool get(SensorChannel channel, SensorValue& out) = 0;
// Registers an interrupt-driven callback (data-ready pin, threshold
// crossing, edge on a reed switch, ...) for sensors that support it.
// Default: not supported: polling-only sensors don't override this.
virtual bool set_trigger(SensorTriggerType type, SensorTriggerHandler handler, void* user_data)
{
(void)type;
(void)handler;
(void)user_data;
return false;
}
};
} // namespace kvida

View File

@@ -0,0 +1,18 @@
# Host-based unit tests for the `sensors` component, run on ESP-IDF's
# `linux` target (no board needed). Build/run with:
#
# idf.py --preview set-target linux
# idf.py build
# ./build/test_sensor_host.elf
#
# COMPONENTS is restricted (mirrors the pattern used by ESP-IDF's own
# in-tree host test apps, e.g. components/cxx/test_apps/*) so the build
# doesn't try to pull in board-only components that don't build for
# linux.
cmake_minimum_required(VERSION 3.16)
set(EXTRA_COMPONENT_DIRS "${CMAKE_CURRENT_LIST_DIR}/../../../")
set(COMPONENTS main sensors unity)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(test_sensor_host)

View File

@@ -0,0 +1,4 @@
idf_component_register(
SRCS "test_sensor.cpp"
PRIV_REQUIRES sensors unity
)

View File

@@ -0,0 +1,85 @@
#include "sensor.h"
#include "unity.h"
using namespace kvida;
namespace {
// Minimal fake sensor exercising the fetch()/get() cache contract and
// SensorValue's fixed-point convention (val1 + val2 * 1e-6).
class FakeSensor : public Sensor {
public:
const char *id() const override { return "fake0"; }
void begin() override {}
bool supports(SensorChannel channel) const override
{
return channel == SensorChannel::AmbientTemperature;
}
bool fetch() override
{
fetched_ = true;
return true;
}
bool get(SensorChannel channel, SensorValue &out) override
{
if (!fetched_ || channel != SensorChannel::AmbientTemperature) {
return false;
}
out = SensorValue{21, 500000, "C", 1234};
return true;
}
private:
bool fetched_ = false;
};
double to_double(const SensorValue &v)
{
return v.val1 + v.val2 * 1e-6;
}
} // namespace
TEST_CASE("get fails before fetch", "[sensor]")
{
FakeSensor sensor;
SensorValue value{};
TEST_ASSERT_FALSE(sensor.get(SensorChannel::AmbientTemperature, value));
}
TEST_CASE("fetch then get returns the cached value", "[sensor]")
{
FakeSensor sensor;
sensor.begin();
TEST_ASSERT_TRUE(sensor.fetch());
SensorValue value{};
TEST_ASSERT_TRUE(sensor.get(SensorChannel::AmbientTemperature, value));
TEST_ASSERT_EQUAL_DOUBLE(21.5, to_double(value));
}
TEST_CASE("get fails for an unsupported channel", "[sensor]")
{
FakeSensor sensor;
sensor.begin();
sensor.fetch();
SensorValue value{};
TEST_ASSERT_FALSE(sensor.get(SensorChannel::Humidity, value));
}
TEST_CASE("default set_trigger reports unsupported", "[sensor]")
{
FakeSensor sensor;
TEST_ASSERT_FALSE(sensor.set_trigger(SensorTriggerType::DataReady, nullptr, nullptr));
}
extern "C" void app_main(void)
{
UNITY_BEGIN();
unity_run_all_tests();
UNITY_END();
}