ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
motion_component.h
Go to the documentation of this file.
1#pragma once
2
7#include <array>
8#include <cmath>
9#include <numbers> // required for generated lambda code
10
11namespace esphome::motion {
12
13// ---Data class
14
15struct MotionData {
16 float acceleration[3]{NAN, NAN, NAN};
17 float angular_rate[3]{NAN, NAN, NAN};
18 // TODO - compass
19};
20
21// indices into data arrays
22static constexpr uint8_t X_AXIS = 0;
23static constexpr uint8_t Y_AXIS = 1;
24static constexpr uint8_t Z_AXIS = 2;
25
33inline float orientation_degrees(const MotionData &data, float flat_threshold) {
34 float ax = data.acceleration[X_AXIS];
35 float ay = data.acceleration[Y_AXIS];
36 float az = data.acceleration[Z_AXIS];
37 if (std::isnan(ax) || std::isnan(ay) || std::isnan(az))
38 return NAN;
39 float mag = std::sqrt(ax * ax + ay * ay + az * az);
40 if (mag < 0.1f)
41 return NAN;
42 // Horizontal component of gravity; near zero when the device lies flat.
43 float h = std::sqrt(ax * ax + ay * ay);
44 if (h / mag < flat_threshold)
45 return NAN;
46 // Direction of the horizontal component, snapped to the nearest 90°.
47 float angle = std::atan2(ay, ax) * (180.0f / std::numbers::pi_v<float>);
48 int quadrant = static_cast<int>(std::lround(angle / 90.0f));
49 quadrant = ((quadrant % 4) + 4) % 4; // normalise to 0..3
50 return quadrant * 90.0f;
51}
52
53// Persisted calibration. `base_hash` ties the stored matrix to the build-time
54// (axis_map / transform_matrix) base; if the base changes the saved calibration
55// is ignored. Stored under a stable, ID-derived key so it overwrites in place.
60
61// Main component class
63 public:
64 // Lifecycle
65 void setup() override;
66 void update() override;
67 void dump_config() override;
68
69 void set_matrix(const std::array<float, 9> &m) {
70 memcpy(this->base_matrix_, m.data(), sizeof(this->base_matrix_));
71 memcpy(this->matrix_, m.data(), sizeof(this->matrix_));
72 }
74
76 bool calibrate_level();
78 bool calibrate_heading();
80 bool save_calibration();
83 void clear_calibration(bool save = false);
84
85 template<typename F> void add_listener(F &&cb) { this->motion_data_callback_.add(std::forward<F>(cb)); }
86
87#ifdef USE_MOTION_TAP
89 virtual void set_tap_threshold(float threshold_g);
90 // Callback args: (axis after axis_map, negative side)
91 template<typename F> void add_on_tap_callback(F &&cb) { this->tap_callback_.add(std::forward<F>(cb)); }
92 template<typename F> void add_on_double_tap_callback(F &&cb) { this->double_tap_callback_.add(std::forward<F>(cb)); }
93#endif
94
95 protected:
96 // platforms must implement this method to update raw data.
97 virtual bool update_data(MotionData &data) = 0;
98
99#ifdef USE_MOTION_TAP
100 // chip_axis is the sensor's own axis; it is reported in the axis_map frame
101 void report_tap_(uint8_t chip_axis, bool chip_negative);
102 // Also drops a single tap held by hold_tap_()
103 void report_double_tap_(uint8_t chip_axis, bool chip_negative);
104 // For chips that report the first tap of a double as a single: hold it for tap_hold_ms_
105 void hold_tap_(uint8_t chip_axis, bool chip_negative, uint32_t now);
106 // Reports a held single tap once tap_hold_ms_ has passed with no double tap
107 void release_held_tap_(uint32_t now);
108#endif
109
110 // for mapping axes
111 float matrix_[9]{
112 1, 0, 0, 0, 1, 0, 0, 0, 1,
113 };
114 // build-time base (axis_map / transform_matrix); used to detect config changes
115 // and to restore on clear_calibration().
116 float base_matrix_[9]{
117 1, 0, 0, 0, 1, 0, 0, 0, 1,
118 };
119
120 void map_axes_(float output[3], const float input[3]) const {
121 output[0] = input[X_AXIS] * this->matrix_[0] + input[Y_AXIS] * this->matrix_[1] + input[Z_AXIS] * this->matrix_[2];
122 output[1] = input[X_AXIS] * this->matrix_[3] + input[Y_AXIS] * this->matrix_[4] + input[Z_AXIS] * this->matrix_[5];
123 output[2] = input[X_AXIS] * this->matrix_[6] + input[Y_AXIS] * this->matrix_[7] + input[Z_AXIS] * this->matrix_[8];
124 }
125
128 uint32_t base_hash_{0}; // hash of base_matrix_, captured in setup()
130
131#ifdef USE_MOTION_TAP
132 void resolve_tap_axis_(uint8_t chip_axis, bool chip_negative, uint8_t &axis, bool &negative) const;
133
134 LazyCallbackManager<void(uint8_t, bool)> tap_callback_{};
138 uint8_t tap_held_axis_{0};
140 bool tap_held_{false};
141#endif
142};
143
144// --- Actions ---
145
146template<typename... Ts> class CalibrateLevelAction final : public Action<Ts...> {
147 public:
148 explicit CalibrateLevelAction(MotionComponent *parent) : parent_(parent) {}
149 void set_save(bool save) { this->save_ = save; }
152
153 protected:
154 void play(const Ts &...) override {
155 if (this->parent_->calibrate_level()) {
156 // if not saving, calibration success is enough. If save required only report success after that succeeds too.
157 if (!this->save_ || this->parent_->save_calibration()) {
159 return;
160 }
161 }
162 this->error_trigger_.trigger();
163 }
164
168 bool save_{false};
169};
170
171template<typename... Ts> class CalibrateHeadingAction final : public Action<Ts...> {
172 public:
173 explicit CalibrateHeadingAction(MotionComponent *parent) : parent_(parent) {}
174 void set_save(bool save) { this->save_ = save; }
177
178 protected:
179 void play(const Ts &...) override {
180 if (this->parent_->calibrate_heading()) {
181 // if not saving, calibration success is enough. If save required only report success after that succeeds too.
182 if (!this->save_ || this->parent_->save_calibration()) {
184 return;
185 }
186 }
187 this->error_trigger_.trigger();
188 }
189
193 bool save_{false};
194};
195
196} // namespace esphome::motion
uint8_t m
Definition bl0906.h:1
uint8_t h
Definition bl0906.h:2
This class simplifies creating components that periodically check a state.
Definition component.h:532
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:557
CalibrateHeadingAction(MotionComponent *parent)
CalibrateLevelAction(MotionComponent *parent)
void play(const Ts &...) override
void hold_tap_(uint8_t chip_axis, bool chip_negative, uint32_t now)
LazyCallbackManager< void(uint8_t, bool)> tap_callback_
void map_axes_(float output[3], const float input[3]) const
void resolve_tap_axis_(uint8_t chip_axis, bool chip_negative, uint8_t &axis, bool &negative) const
void report_double_tap_(uint8_t chip_axis, bool chip_negative)
LazyCallbackManager< void(uint8_t, bool)> double_tap_callback_
bool calibrate_heading()
Assuming Y-axis rotation only, correct the heading so X/Y align correctly.
LazyCallbackManager< void(MotionData const &)> motion_data_callback_
void set_matrix(const std::array< float, 9 > &m)
virtual bool update_data(MotionData &data)=0
bool calibrate_level()
Calibrate the matrix so the current reading maps to [0, 0, 1] (device flat).
void clear_calibration(bool save=false)
Restore the build-time (axis_map / transform_matrix) base, discarding calibration,...
void report_tap_(uint8_t chip_axis, bool chip_negative)
virtual void set_tap_threshold(float threshold_g)
Platforms with a tap block convert this to chip steps and clamp it.
bool save_calibration()
Save the current matrix to NVS.
const char * key
float orientation_degrees(const MotionData &data, float flat_threshold)
Compute the device's in-plane orientation from the gravity vector.
struct esphome::motion::CalibrationPref PACKED
static void uint32_t