ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
motion_binary_sensor.cpp
Go to the documentation of this file.
2#include "esphome/core/log.h"
3#include "esphome/core/hal.h"
6
7namespace esphome::motion {
8
9ESPHOME_LOG_TAG(TAG, "motion.binary_sensor");
10
11// Thresholds used to decide the device is at rest for face_up / face_down detection.
12// While moving (shaking, being picked up) the orientation reading is dominated by
13// linear acceleration and cannot be trusted, so those sensors block (hold) instead.
14static constexpr float STILL_ACCEL_TOLERANCE = 0.12f; // max deviation of |accel| from 1g, in g
15static constexpr float STILL_GYRO_THRESHOLD = 15.0f; // max angular rate magnitude, in °/s
16static constexpr float GYRO_THRESHOLD_SCALE = 50.0f; // arbitrary gyro threshold scale, in °/s per g of acceleration
17
19 float ax = data.acceleration[X_AXIS];
20 float ay = data.acceleration[Y_AXIS];
21 float az = data.acceleration[Z_AXIS];
22 if (std::isnan(ax) || std::isnan(ay) || std::isnan(az))
23 return false;
24
25 // Total acceleration must be close to 1g; a larger deviation means the device is
26 // being accelerated (shaken / moved) and the gravity direction cannot be trusted.
27 float mag = std::sqrt(ax * ax + ay * ay + az * az);
28 if (std::fabs(mag - 1.0f) > STILL_ACCEL_TOLERANCE)
29 return false;
30
31 // If a gyroscope is present, also require the angular rate to be low.
32 float gx = data.angular_rate[X_AXIS];
33 float gy = data.angular_rate[Y_AXIS];
34 float gz = data.angular_rate[Z_AXIS];
35 if (!std::isnan(gx) && !std::isnan(gy) && !std::isnan(gz)) {
36 float gmag = std::sqrt(gx * gx + gy * gy + gz * gz);
37 if (gmag > STILL_GYRO_THRESHOLD)
38 return false;
39 }
40 return true;
41}
42
44 this->publish_state(false); // default to false until the first update
45}
46
47PROGMEM_STRING_TABLE(MotionBinarySensorTypeNames, "face_up", "face_down", "free_fall", "moving", "unknown");
48
50 LOG_BINARY_SENSOR("", "Motion Binary Sensor", this);
51 ESP_LOGCONFIG(TAG,
52 " Type: %s\n"
53 " Threshold: %.3f\n"
54 " Duration: %" PRIu32 " ms",
55 LOG_STR_ARG(MotionBinarySensorTypeNames::get_log_str(this->type_)), this->threshold_, this->duration_);
56}
57
60
61 switch (this->type_) {
64 // Block while the device is moving: hold the last stable state instead of
65 // reacting to transient acceleration spikes from shaking or handling.
66 if (!is_stationary(data))
67 break;
68
69 float ax = data.acceleration[X_AXIS];
70 float ay = data.acceleration[Y_AXIS];
71 float az = data.acceleration[Z_AXIS];
72 float mag = std::sqrt(ax * ax + ay * ay + az * az);
73 // is_stationary_() guarantees mag is close to 1g, so this is just a safety net.
74 if (mag < 0.1f)
75 break;
76
77 // threshold_ is the cosine of the maximum tilt: face_up / face_down are only
78 // reported when the device is within that tilt of horizontal. Beyond it, both
79 // sensors read false. Normalising by the magnitude makes the tilt limit
80 // independent of any residual acceleration.
81 float cos_tilt = az / mag;
83 this->publish_state(cos_tilt > this->threshold_);
84 } else {
85 this->publish_state(cos_tilt < -this->threshold_);
86 }
87 break;
88 }
90 float ax = data.acceleration[X_AXIS];
91 float ay = data.acceleration[Y_AXIS];
92 float az = data.acceleration[Z_AXIS];
93 if (std::isnan(ax) || std::isnan(ay) || std::isnan(az)) {
94 // Don't let a gap in valid data count towards the free-fall duration.
95 this->free_fall_candidate_ = false;
96 return;
97 }
98
99 float mag = std::sqrt(ax * ax + ay * ay + az * az);
100
101 if (mag < this->threshold_) {
102 if (!this->free_fall_candidate_) {
103 this->free_fall_candidate_ = true;
104 this->free_fall_start_time_ = now;
105 } else if (now - this->free_fall_start_time_ >= this->duration_) {
106 this->publish_state(true);
107 }
108 } else {
109 this->free_fall_candidate_ = false;
110 this->publish_state(false);
111 }
112 break;
113 }
115 float ax = data.acceleration[X_AXIS];
116 float ay = data.acceleration[Y_AXIS];
117 float az = data.acceleration[Z_AXIS];
118 float gx = data.angular_rate[X_AXIS];
119 float gy = data.angular_rate[Y_AXIS];
120 float gz = data.angular_rate[Z_AXIS];
121
122 bool moving = false;
123
124 // Check acceleration delta. Require all three axes to be valid so a NaN on any
125 // axis can't poison last_accel_ and silently stop motion detection.
126 bool accel_valid = !std::isnan(ax) && !std::isnan(ay) && !std::isnan(az);
127 if (accel_valid) {
128 if (!std::isnan(this->last_accel_[0])) {
129 float dx = ax - this->last_accel_[0];
130 float dy = ay - this->last_accel_[1];
131 float dz = az - this->last_accel_[2];
132 float accel_diff = std::sqrt(dx * dx + dy * dy + dz * dz);
133 if (accel_diff > this->threshold_) {
134 moving = true;
135 }
136 }
137 this->last_accel_[0] = ax;
138 this->last_accel_[1] = ay;
139 this->last_accel_[2] = az;
140 }
141
142 // Check angular rate delta. Require all three axes to be valid for the same reason.
143 bool gyro_valid = !std::isnan(gx) && !std::isnan(gy) && !std::isnan(gz);
144 if (gyro_valid) {
145 if (!std::isnan(this->last_gyro_[0])) {
146 float dgx = gx - this->last_gyro_[0];
147 float dgy = gy - this->last_gyro_[1];
148 float dgz = gz - this->last_gyro_[2];
149 float gyro_diff = std::sqrt(dgx * dgx + dgy * dgy + dgz * dgz);
150 if (gyro_diff > this->threshold_ * GYRO_THRESHOLD_SCALE) {
151 moving = true;
152 }
153 }
154 this->last_gyro_[0] = gx;
155 this->last_gyro_[1] = gy;
156 this->last_gyro_[2] = gz;
157 }
158
159 // With no usable data this sample, don't assert "not moving" -- just wait for
160 // the next one.
161 if (!accel_valid && !gyro_valid)
162 break;
163
164 if (moving) {
165 this->publish_state(true);
166 this->last_event_time_ = now;
167 } else {
168 if (this->state && (now - this->last_event_time_ >= this->duration_)) {
169 this->publish_state(false);
170 }
171 }
172 break;
173 }
174 }
175}
176
177} // namespace esphome::motion
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void publish_state(bool new_state)
Publish a new state to the front-end.
bool state
The current state of this binary sensor. Also used as the backing storage for StatefulEntityBase.
static bool is_stationary(const MotionData &data)
True when the device is at rest: total acceleration is close to 1g and (if a gyroscope is present) th...
void process_motion_data(const MotionData &data)
PROGMEM_STRING_TABLE(MotionBinarySensorTypeNames, "face_up", "face_down", "free_fall", "moving", "unknown")
ESPHOME_LOG_TAG(TAG, "motion.binary_sensor")
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t