ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
espectre.cpp
Go to the documentation of this file.
1#include "espectre.h"
2
3#ifdef USE_ESPECTRE
4
5#include <cinttypes>
6#include <cmath>
8#include "esphome/core/log.h"
9#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
11#endif
12
14
15ESPHOME_LOG_TAG(TAG, "espectre");
16
17static const char *csi_capture_profile_name(::espectre::CsiCapturePolicy profile) {
18 switch (profile) {
19 case ::espectre::CsiCapturePolicy::LLTF:
20 return LOG_STR_LITERAL("lltf");
21 case ::espectre::CsiCapturePolicy::HT_VHT:
22 return LOG_STR_LITERAL("ht_vht");
23 default:
24 return LOG_STR_LITERAL("auto");
25 }
26}
27
28#ifdef USE_SELECT
29void ESPectreComponent::request_traffic_generator_mode(const char *name) {
30 this->pending_traffic_mode_ = ::espectre::parse_traffic_generator_mode(name);
31}
32
33void ESPectreComponent::request_detection_algorithm(const char *name) {
34 this->pending_detection_algorithm_ = ::espectre::parse_detection_algorithm(name);
35}
36
37void ESPectreComponent::request_csi_sample_spacing(const char *name) {
38 this->pending_csi_sample_spacing_ = ::espectre::parse_csi_sample_spacing(name);
39}
40#endif
41
42static int log_level(::espectre::LogLevel level) {
43 switch (level) {
44 case ::espectre::LogLevel::ERROR:
45 return ESPHOME_LOG_LEVEL_ERROR;
46 case ::espectre::LogLevel::WARNING:
47 return ESPHOME_LOG_LEVEL_WARN;
48 case ::espectre::LogLevel::INFO:
49 return ESPHOME_LOG_LEVEL_INFO;
50 case ::espectre::LogLevel::DEBUG:
51 return ESPHOME_LOG_LEVEL_DEBUG;
52 default:
53 return ESPHOME_LOG_LEVEL_VERBOSE;
54 }
55}
56
58 // ESPHome owns scan results, including scans requested by the SDK's CSI recovery.
59 this->runtime_.config().wifi_scan_results_managed_externally = true;
60 this->restore_controls_();
61 this->start_runtime_();
62}
63
64void ESPectreComponent::start_runtime_() {
65#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
66 // A sensor stays in one place, and each roaming scan takes the radio off-channel for
67 // seconds, emptying the CSI window. Losing the access point still reconnects normally.
68 if (wifi::global_wifi_component != nullptr) {
70 this->roaming_suppressed_ = true;
71 }
72#endif
73 ::espectre::set_log_sink({
74 .context = nullptr,
75 .enabled = [](void *, ::espectre::LogLevel level, const char *) { return log_level(level) <= ESPHOME_LOG_LEVEL; },
76 .write = [](void *, ::espectre::LogLevel level, const char *tag, int line, const char *format,
77 va_list args) { esp_log_vprintf_(log_level(level), tag, line, format, args); },
78 });
79 if (!this->runtime_.setup(this)) {
80 ESP_LOGE(TAG, "Runtime setup failed");
81 this->stop_();
82 this->schedule_restart_();
83 return;
84 }
85 this->running_ = true;
86 this->status_clear_error();
87#ifdef USE_SELECT
88 this->publish_traffic_mode_();
89#endif
90 this->publish_controls_();
91}
92
93void ESPectreComponent::schedule_restart_() {
94 // A fault can be transient, such as a Wi-Fi stall, so retry instead of failing for good.
95 this->runtime_fault_ = false;
96 this->status_set_error(LOG_STR("Runtime stopped"));
97 ESP_LOGW(TAG, "Restarting the runtime in %" PRIu32 " s", RESTART_DELAY_MS / 1000);
98 this->restart_pending_ = true;
99 this->restart_requested_ms_ = App.get_loop_component_start_time();
100}
101
102#ifdef USE_SELECT
103// Selections are saved as SDK enum values, so renumbering an enum would restore the wrong option.
104static_assert(static_cast<uint8_t>(::espectre::TrafficGeneratorMode::PING) == 0 &&
105 static_cast<uint8_t>(::espectre::TrafficGeneratorMode::DNS) == 1 &&
106 static_cast<uint8_t>(::espectre::TrafficGeneratorMode::DNS_TCP) == 2 &&
107 static_cast<uint8_t>(::espectre::TrafficGeneratorMode::WIFI_RAW) == 3 &&
108 static_cast<uint8_t>(::espectre::TrafficGeneratorMode::EXTERNAL_HOST) == 4,
109 "Saved traffic generator modes depend on these values");
110static_assert(static_cast<uint8_t>(::espectre::DetectionAlgorithm::LIGHTWEIGHT) == 0 &&
111 static_cast<uint8_t>(::espectre::DetectionAlgorithm::HIGH_ACCURACY) == 1,
112 "Saved detection algorithms depend on these values");
113static_assert(static_cast<uint8_t>(::espectre::TemporalCsiSpacing::HALF_SLOT) == 0 &&
114 static_cast<uint8_t>(::espectre::TemporalCsiSpacing::DISTINCT) == 1,
115 "Saved CSI sample spacings depend on these values");
116
117template<typename T, typename F>
118static void restore_select_choice(select::Select *select, ESPPreferenceObject &pref, T &value, F accept) {
119 if (select == nullptr)
120 return;
121 pref = select->make_entity_preference<uint8_t>(static_cast<uint32_t>(value) + 1);
122 uint8_t saved;
123 if (pref.load(&saved) && accept(static_cast<T>(saved)))
124 value = static_cast<T>(saved);
125}
126
127// Returns false when no choice was queued; otherwise the caller republishes the active option.
128template<typename T>
129static bool apply_select_choice(::espectre::RuntimeFrontendController &runtime, optional<T> &pending,
130 ESPPreferenceObject &pref, bool (::espectre::RuntimeFrontendController::*set)(T),
131 const char *(*name)(T)) {
132 if (!pending.has_value())
133 return false;
134 const T value = *pending;
135 pending.reset();
136 if ((runtime.*set)(value)) {
137 const auto saved = static_cast<uint8_t>(value);
138 pref.save(&saved);
139 } else {
140 ESP_LOGW(TAG, "Option %s was rejected", name(value));
141 }
142 return true;
143}
144
145void ESPectreComponent::apply_pending_traffic_mode_() {
146 if (apply_select_choice(this->runtime_, this->pending_traffic_mode_, this->traffic_mode_pref_,
147 &::espectre::RuntimeFrontendController::set_traffic_generator_mode,
148 ::espectre::traffic_generator_mode_name))
149 this->publish_traffic_mode_();
150}
151
152void ESPectreComponent::publish_traffic_mode_() {
153 if (this->traffic_mode_select_ == nullptr)
154 return;
155 this->traffic_mode_select_->publish_state(
156 ::espectre::traffic_generator_mode_name(this->runtime_.config().traffic_generator_mode));
157}
158#endif
159
160#ifdef USE_NUMBER
161static void restore_motion_hits(number::Number *number, ESPPreferenceObject &pref, uint8_t &hits) {
162 if (number == nullptr)
163 return;
164 pref = number->make_entity_preference<uint8_t>(hits);
165 uint8_t saved;
166 if (pref.load(&saved) && saved >= ::espectre::RUNTIME_MOTION_HITS_MIN && saved <= ::espectre::RUNTIME_MOTION_HITS_MAX)
167 hits = saved;
168}
169#endif
170
171void ESPectreComponent::restore_controls_() {
172 // Saved values are keyed by the YAML value, so a YAML change discards what the entities saved.
173 auto &config = this->runtime_.config();
174#ifdef USE_NUMBER
175 restore_motion_hits(this->motion_on_hits_number_, this->motion_on_hits_pref_, config.motion_on_hits);
176 restore_motion_hits(this->motion_off_hits_number_, this->motion_off_hits_pref_, config.motion_off_hits);
177#endif
178#ifdef USE_SELECT
179 restore_select_choice(this->traffic_mode_select_, this->traffic_mode_pref_, config.traffic_generator_mode,
180 [this](::espectre::TrafficGeneratorMode mode) {
181 return ::espectre::runtime_traffic_generator_mode_valid(mode) &&
182 this->traffic_mode_select_->has_option(::espectre::traffic_generator_mode_name(mode));
183 });
184 // Without this the SDK rejects every detector change once the runtime runs.
185 if (this->detection_algorithm_select_ != nullptr)
186 config.runtime_detector_selection_enabled = true;
187 restore_select_choice(this->detection_algorithm_select_, this->detection_algorithm_pref_, config.detection_algorithm,
188 ::espectre::runtime_detection_algorithm_valid);
189 restore_select_choice(this->csi_sample_spacing_select_, this->csi_sample_spacing_pref_, config.csi_sample_spacing,
190 ::espectre::runtime_csi_sample_spacing_valid);
191#endif
192#ifdef USE_SWITCH
193 // Applied before the first runtime starts, so a disabled sensor never starts sensing.
194 if (this->sensing_switch_ != nullptr)
195 this->runtime_.set_services_armed(this->sensing_switch_->get_initial_state_with_restore_mode().value_or(true));
196#endif
197}
198
199void ESPectreComponent::apply_pending_controls_() {
200#ifdef USE_NUMBER
201 if (!std::isnan(this->pending_threshold_)) {
202 const float threshold = this->pending_threshold_;
203 this->pending_threshold_ = NAN;
204 if (!this->runtime_.set_threshold(threshold)) {
205 ESP_LOGW(TAG, "Threshold %.2f was rejected", threshold);
206 }
207 // Republished even when rejected, so the entity drops the value it was asked for.
208 PUBLISH_STATE(this->threshold_number_, this->runtime_.snapshot().threshold);
209 }
210 if (this->pending_motion_on_hits_ != 0 || this->pending_motion_off_hits_ != 0) {
211 const auto &config = this->runtime_.config();
212 const uint8_t on_hits = this->pending_motion_on_hits_ != 0 ? this->pending_motion_on_hits_ : config.motion_on_hits;
213 const uint8_t off_hits =
214 this->pending_motion_off_hits_ != 0 ? this->pending_motion_off_hits_ : config.motion_off_hits;
215 this->pending_motion_on_hits_ = 0;
216 this->pending_motion_off_hits_ = 0;
217 if (this->runtime_.set_motion_hits(on_hits, off_hits)) {
218 this->motion_on_hits_pref_.save(&on_hits);
219 this->motion_off_hits_pref_.save(&off_hits);
220 } else {
221 ESP_LOGW(TAG, "Motion on/off hits %u/%u were rejected", on_hits, off_hits);
222 }
223 PUBLISH_STATE(this->motion_on_hits_number_, config.motion_on_hits);
224 PUBLISH_STATE(this->motion_off_hits_number_, config.motion_off_hits);
225 }
226#endif
227#ifdef USE_SELECT
228 // Only the changed entity is republished, because numbers and selects run on_value on every publish.
229 // loop() republishes the threshold that a detector change replaces.
230 if (apply_select_choice(this->runtime_, this->pending_detection_algorithm_, this->detection_algorithm_pref_,
231 &::espectre::RuntimeFrontendController::set_detection_algorithm,
232 ::espectre::detection_algorithm_name)) {
233 PUBLISH_STATE(this->detection_algorithm_select_,
234 ::espectre::detection_algorithm_name(this->runtime_.config().detection_algorithm));
235 }
236 if (apply_select_choice(this->runtime_, this->pending_csi_sample_spacing_, this->csi_sample_spacing_pref_,
237 &::espectre::RuntimeFrontendController::set_csi_sample_spacing,
238 ::espectre::csi_sample_spacing_name)) {
239 PUBLISH_STATE(this->csi_sample_spacing_select_,
240 ::espectre::csi_sample_spacing_name(this->runtime_.config().csi_sample_spacing));
241 }
242#endif
243#ifdef USE_SWITCH
244 if (this->pending_sensing_.has_value()) {
245 this->runtime_.set_services_armed(*this->pending_sensing_);
246 this->pending_sensing_.reset();
247 PUBLISH_STATE(this->sensing_switch_, this->runtime_.services_armed());
248 }
249#endif
250}
251
252void ESPectreComponent::publish_controls_() {
253#ifdef USE_NUMBER
254 PUBLISH_STATE(this->threshold_number_, this->runtime_.snapshot().threshold);
255 PUBLISH_STATE(this->motion_on_hits_number_, this->runtime_.config().motion_on_hits);
256 PUBLISH_STATE(this->motion_off_hits_number_, this->runtime_.config().motion_off_hits);
257#endif
258#ifdef USE_SELECT
259 PUBLISH_STATE(this->detection_algorithm_select_,
260 ::espectre::detection_algorithm_name(this->runtime_.config().detection_algorithm));
261 PUBLISH_STATE(this->csi_sample_spacing_select_,
262 ::espectre::csi_sample_spacing_name(this->runtime_.config().csi_sample_spacing));
263#endif
264#ifdef USE_SWITCH
265 PUBLISH_STATE(this->sensing_switch_, this->runtime_.services_armed());
266#endif
267}
268
269void ESPectreComponent::loop() {
270 if (this->runtime_fault_) {
271 this->stop_();
272 this->schedule_restart_();
273 return;
274 }
275 if (!this->running_) {
276 // Without a backend this only reaps a traffic worker that outlived the last runtime.
277 this->runtime_.loop();
278 if (this->restart_pending_ &&
279 App.get_loop_component_start_time() - this->restart_requested_ms_ >= RESTART_DELAY_MS) {
280 this->restart_pending_ = false;
281 this->start_runtime_();
282 }
283 return;
284 }
285 if (this->recalibrate_pending_) {
286 this->recalibrate_pending_ = false;
287 if (!this->runtime_.trigger_recalibration()) {
288 ESP_LOGW(TAG, "Recalibration is not available");
289 }
290 }
291#ifdef USE_SELECT
292 this->apply_pending_traffic_mode_();
293#endif
294 this->apply_pending_controls_();
295 this->runtime_.loop();
296 if (this->runtime_fault_)
297 return;
298
299 // Read once after the SDK finishes dispatching callbacks, including readiness changes.
300 const auto &snapshot = this->runtime_.snapshot();
301#ifdef USE_NUMBER
302 // Calibration and a detector change both replace the threshold.
303 if (this->threshold_number_ != nullptr && this->threshold_number_->state != snapshot.threshold)
304 this->threshold_number_->publish_state(snapshot.threshold);
305#endif
306#ifdef USE_BINARY_SENSOR
307 if (this->calibrating_binary_sensor_ != nullptr &&
308 (!this->calibrating_published_ || this->calibrating_state_ != snapshot.calibrating)) {
309 this->calibrating_state_ = snapshot.calibrating;
310 this->calibrating_published_ = true;
311 this->calibrating_binary_sensor_->publish_state(snapshot.calibrating);
312 }
313#endif
314 if (!snapshot.ready_to_publish) {
315 if (this->ready_)
316 this->invalidate_sensing_();
317 this->movement_pending_ = false;
318 return;
319 }
320
321#ifdef USE_BINARY_SENSOR
322 const bool motion = snapshot.motion_state == ::espectre::MotionState::MOTION;
323 if (this->motion_binary_sensor_ != nullptr && (!this->ready_ || this->motion_state_ != motion)) {
324 this->motion_state_ = motion;
325 this->motion_binary_sensor_->publish_state(motion);
326 }
327#endif
328#ifdef USE_SENSOR
329 if (this->movement_sensor_ != nullptr && (this->movement_pending_ || !this->ready_))
330 this->movement_sensor_->publish_state(snapshot.movement_metric);
331#endif
332 this->movement_pending_ = false;
333 this->ready_ = true;
334}
335
336void ESPectreComponent::invalidate_sensing_() {
337#ifdef USE_BINARY_SENSOR
338 if (this->motion_binary_sensor_ != nullptr)
339 this->motion_binary_sensor_->invalidate_state();
340#endif
341#ifdef USE_SENSOR
342 PUBLISH_STATE(this->movement_sensor_, NAN);
343#endif
344 this->ready_ = false;
345}
346
347void ESPectreComponent::on_calibration_finished(const ::espectre::RuntimeSnapshot &snapshot, bool success) {
348 if (success) {
349 this->calibrated_ = true;
350 this->status_clear_warning();
351 ESP_LOGI(TAG, "Calibration complete");
352 return;
353 }
354 // After a successful calibration, a failed one keeps that calibrated threshold.
355 if (!this->calibrated_)
356 this->status_set_warning(LOG_STR("Calibration failed"));
357 ESP_LOGW(TAG, "Calibration failed; retaining the previous threshold");
358}
359
360void ESPectreComponent::on_runtime_fault(const char *message) {
361 ESP_LOGE(TAG, "Runtime fault: %s", message);
362 this->runtime_fault_ = true;
363}
364
365void ESPectreComponent::stop_() {
366#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
367 if (this->roaming_suppressed_ && wifi::global_wifi_component != nullptr) {
369 }
370#endif
371 this->roaming_suppressed_ = false;
372 this->running_ = false;
373 // The next runtime reports its own calibration, so forget this one's.
374 this->calibrated_ = false;
375 this->calibrating_published_ = false;
376 this->runtime_.shutdown();
377 ::espectre::clear_log_sink();
378 this->invalidate_sensing_();
379#ifdef USE_BINARY_SENSOR
380 if (this->calibrating_binary_sensor_ != nullptr)
381 this->calibrating_binary_sensor_->invalidate_state();
382#endif
383}
384
385void ESPectreComponent::on_shutdown() {
386 this->restart_pending_ = false;
387 this->stop_();
388}
389
390void ESPectreComponent::dump_config() {
391 const auto &config = this->runtime_.config();
392 ESP_LOGCONFIG(TAG,
393 "ESPectre:\n"
394 " Detection algorithm: %s\n"
395 " CSI capture profile: %s\n"
396 " Traffic generator mode: %s\n"
397 " Traffic generator target MAC: %s\n"
398 " CSI sample spacing: %s\n"
399 " Motion on/off hits: %u/%u\n"
400 " Window size: %" PRIu32 " ms\n"
401 " CSI target rate: %" PRIu32 " pps\n"
402 " Evaluation interval: %" PRIu32 " ms\n"
403 " Low-pass filter: %s (%.1f Hz)\n"
404 " Hampel filter: %s (window %u, threshold %.1f)",
405 ::espectre::detection_algorithm_name(config.detection_algorithm),
406 csi_capture_profile_name(config.csi_capture_policy),
407 ::espectre::traffic_generator_mode_name(config.traffic_generator_mode),
408 config.traffic_generator_target_mac.c_str(),
409 ::espectre::csi_sample_spacing_name(config.csi_sample_spacing), config.motion_on_hits,
410 config.motion_off_hits, config.window_size_ms, config.csi_target_pps, config.evaluation_interval_ms,
411 ONOFF(config.lowpass_enabled), config.lowpass_cutoff, ONOFF(config.hampel_enabled),
412 config.hampel_window, config.hampel_threshold);
413#ifdef USE_BINARY_SENSOR
414 LOG_BINARY_SENSOR(" ", "Motion", this->motion_binary_sensor_);
415 LOG_BINARY_SENSOR(" ", "Calibrating", this->calibrating_binary_sensor_);
416#endif
417#ifdef USE_SENSOR
418 LOG_SENSOR(" ", "Movement score", this->movement_sensor_);
419#endif
420#ifdef USE_NUMBER
421 LOG_NUMBER(" ", "Threshold", this->threshold_number_);
422 LOG_NUMBER(" ", "Motion on hits", this->motion_on_hits_number_);
423 LOG_NUMBER(" ", "Motion off hits", this->motion_off_hits_number_);
424#endif
425#ifdef USE_SELECT
426 LOG_SELECT(" ", "Traffic generator mode", this->traffic_mode_select_);
427 LOG_SELECT(" ", "Detection algorithm", this->detection_algorithm_select_);
428 LOG_SELECT(" ", "CSI sample spacing", this->csi_sample_spacing_select_);
429#endif
430#ifdef USE_SWITCH
431 LOG_SWITCH(" ", "Sensing", this->sensing_switch_);
432#endif
433}
434
435} // namespace esphome::espectre
436
437#endif // USE_ESPECTRE
BedjetMode mode
BedJet operating mode.
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.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
void status_clear_error()
Definition component.h:315
void status_clear_warning()
Definition component.h:309
void release_roaming_suppression()
Release a roaming suppression request.
void request_roaming_suppression()
Request that post-connect roaming scans be suppressed.
const LogString * message
Definition component.cpp:35
const char * format
ESPHOME_LOG_TAG(TAG, "espectre")
WiFiComponent * global_wifi_component
uint32_t value
Definition hal.cpp:41
Application App
Global storage of Application pointer - only one Application can exist.
void HOT esp_log_vprintf_(int level, const char *tag, int line, const char *format, va_list args)
Definition log.cpp:51
static void uint32_t