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:
8
.gitignore
vendored
8
.gitignore
vendored
@@ -1,7 +1,7 @@
|
||||
# ESP-IDF
|
||||
/build/
|
||||
/managed_components/
|
||||
/dependencies.lock
|
||||
# ESP-IDF (unanchored: also matches component test_apps/*/build etc.)
|
||||
build/
|
||||
managed_components/
|
||||
dependencies.lock
|
||||
sdkconfig
|
||||
sdkconfig.old
|
||||
*.o
|
||||
|
||||
15
README.md
15
README.md
@@ -32,6 +32,19 @@ docker compose run --rm build idf.py -p <PORT> flash monitor
|
||||
|
||||
Prosjektet er pinnet til ESP-IDF `v6.0.2` (se `docker/Dockerfile`).
|
||||
|
||||
## Testing
|
||||
|
||||
Host-baserte enhetstester ligger per komponent, under `<component>/test_apps/host/`, bygget mot ESP-IDFs `linux`-target (ikke behov for kort) — se `components/sensors/test_apps/host/` for et fungerende eksempel (verifisert i en ren kjøring: bygger, 4 tester passerer).
|
||||
|
||||
```sh
|
||||
docker run --rm -v "$(pwd)":/project -w /project/components/sensors/test_apps/host espressif/idf:v6.0.2 \
|
||||
bash -lc 'idf.py --preview set-target linux && idf.py build && ./build/test_sensor_host.elf'
|
||||
```
|
||||
|
||||
(Imagets entrypoint aktiverer ESP-IDF-miljøet automatisk — ikke `source export.sh` selv.)
|
||||
|
||||
> **Merk:** under gjentatte, raske kjøringer mot denne `test_apps/*/build`-mappen observerte jeg periodisk `FileExistsError` fra `idf.py` (og enkelte ganger `ls`/`rm` som var uenige om mappen fantes) — både via `docker compose run` og ren `docker run`. Mistenkelig likt kjent metadata-cache-lag i WSL2s DrvFs (`/mnt/*`) under raske create/delete-sykluser på tvers av containergrenser, ikke en feil i selve kodebasen (en ren, isolert kjøring bygger og består alltid). Hvis du støter på dette: slett `build`/`sdkconfig` i mappen fra Windows/PowerShell-siden og vent et par sekunder før du prøver igjen.
|
||||
|
||||
## Status
|
||||
|
||||
`main/` bygger og logger oppstart. `components/*` inneholder foreløpig bare README-er som beskriver ansvar per lag — ingen reell logikk ennå. `partitions.csv` har et A/B OTA + LittleFS-oppsett med plassholder-størrelser (4MB flash) som bør justeres når ekte flash-størrelse/image-størrelse er kjent.
|
||||
`main/` bygger og logger oppstart. `components/sensors` har et reelt `Sensor`-grensesnitt (`include/sensor.h`, Zephyr-inspirert: fetch/get-splitt, fixed-point verdier, finkornet kanal-enum, trigger-API) med et verifisert host-testoppsett. Resten av `components/*` inneholder foreløpig bare README-er som beskriver ansvar per lag. `partitions.csv` har et A/B OTA + LittleFS-oppsett med plassholder-størrelser (4MB flash) som bør justeres når ekte flash-størrelse/image-størrelse er kjent.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
idf_component_register(
|
||||
INCLUDE_DIRS "include"
|
||||
REQUIRES drivers
|
||||
)
|
||||
|
||||
@@ -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.
|
||||
|
||||
81
components/sensors/include/sensor.h
Normal file
81
components/sensors/include/sensor.h
Normal 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
|
||||
18
components/sensors/test_apps/host/CMakeLists.txt
Normal file
18
components/sensors/test_apps/host/CMakeLists.txt
Normal 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)
|
||||
4
components/sensors/test_apps/host/main/CMakeLists.txt
Normal file
4
components/sensors/test_apps/host/main/CMakeLists.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
idf_component_register(
|
||||
SRCS "test_sensor.cpp"
|
||||
PRIV_REQUIRES sensors unity
|
||||
)
|
||||
85
components/sensors/test_apps/host/main/test_sensor.cpp
Normal file
85
components/sensors/test_apps/host/main/test_sensor.cpp
Normal 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();
|
||||
}
|
||||
@@ -4,3 +4,7 @@
|
||||
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
|
||||
# Matches the 4MB layout assumed in partitions.csv (TODO: adjust both
|
||||
# together once real hardware's actual flash size is confirmed).
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
# test
|
||||
|
||||
Host-based unit tests for business logic that doesn't need real hardware, per the testing philosophy in `AGENTS.md`: "Everything that can be tested on a desktop should be."
|
||||
|
||||
Primary candidates once they have real code: `components/sensors`, `components/profiles`, and the non-hardware parts of `components/lua_runtime` (Lua sandboxing/API surface, not GPIO access).
|
||||
|
||||
ESP-IDF supports building against its `linux` target (`idf.py --preview set-target linux`) to run component unit tests on the host without a board. No test scaffolding is wired up yet since there's no logic to test.
|
||||
Reference in New Issue
Block a user