ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
motion_event.cpp
Go to the documentation of this file.
1#include "motion_event.h"
2#include "esphome/core/log.h"
3#include "esphome/core/hal.h"
5
6namespace esphome::motion {
7
8ESPHOME_LOG_TAG(TAG, "motion.event");
9
10MotionEvent::MotionEvent(MotionComponent *parent) : parent_(parent) {}
11
13 this->parent_->add_listener([this](MotionData const &data) { this->process_motion_data_(data); });
14}
15
17 LOG_EVENT("", "Motion Event", this);
18 ESP_LOGCONFIG(TAG,
19 " Threshold: %.3f\n"
20 " Cooldown: %" PRIu32 " ms",
21 this->threshold_, this->cooldown_);
22}
23
25 float ax = data.acceleration[X_AXIS];
26 float ay = data.acceleration[Y_AXIS];
27 float az = data.acceleration[Z_AXIS];
28 if (std::isnan(ax) || std::isnan(ay) || std::isnan(az)) {
29 // Reset the baseline so the next valid sample doesn't jerk-compare across the gap.
30 this->last_accel_[0] = NAN;
31 this->last_accel_[1] = NAN;
32 this->last_accel_[2] = NAN;
33 return;
34 }
35
37
38 if (!std::isnan(this->last_accel_[0])) {
39 float dx = ax - this->last_accel_[0];
40 float dy = ay - this->last_accel_[1];
41 float dz = az - this->last_accel_[2];
42 float jerk_mag = std::sqrt(dx * dx + dy * dy + dz * dz);
43
44 if (jerk_mag > this->threshold_) {
45 if (now - this->last_trigger_time_ >= this->cooldown_) {
46 this->trigger("shake");
47 this->last_trigger_time_ = now;
48 }
49 }
50 }
51
52 this->last_accel_[0] = ax;
53 this->last_accel_[1] = ay;
54 this->last_accel_[2] = az;
55}
56
57} // 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 trigger(const char *event_type)
Trigger an event; the type is matched against the configured types by string compare.
Definition event.cpp:10
void process_motion_data_(const MotionData &data)
MotionEvent(MotionComponent *parent)
MotionComponent * parent_
ESPHOME_LOG_TAG(TAG, "motion.binary_sensor")
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t