ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
dfrobot_sen0395.cpp
Go to the documentation of this file.
1#include "dfrobot_sen0395.h"
2
3#include <cmath>
4#include <cstring>
5
8#include "esphome/core/log.h"
10
12
13ESPHOME_LOG_TAG(TAG, "dfrobot_sen0395");
14static constexpr float DET_RANGE_STEP_M = 0.15f;
15static constexpr float LATENCY_STEP_S = 0.025f;
16// Sent after a reset with no line end
17static constexpr char PROMPT[] PROGMEM = "leapMMW:/>";
18
19// What each CommandType cannot do while the sensor runs; empty for commands that do not need it stopped
20PROGMEM_STRING_TABLE(BusyActions, "", "configure range config", "configure output latency",
21 "configure sensor startup behavior", "factory reset", "", "", "set led mode",
22 "set uart output mode", "set sensitivity");
23static_assert(BusyActions::COUNT == static_cast<size_t>(CommandType::COMMAND_TYPE_SENSITIVITY) + 1,
24 "BusyActions needs one entry per CommandType");
25
27 ESP_LOGCONFIG(TAG, "Dfrobot Mmwave Radar:");
28#ifdef USE_BINARY_SENSOR
29 LOG_BINARY_SENSOR(" ", "Registered", this->detected_binary_sensor_);
30#endif
31#ifdef USE_SWITCH
32 LOG_SWITCH(" ", "Sensor Active Switch", this->sensor_active_switch_);
33 LOG_SWITCH(" ", "Turn on LED Switch", this->turn_on_led_switch_);
34 LOG_SWITCH(" ", "Presence via UART Switch", this->presence_via_uart_switch_);
35 LOG_SWITCH(" ", "Start after Boot Switch", this->start_after_boot_switch_);
36#endif
37}
38
39void DfrobotSen0395Component::loop() {
40 if (this->cmd_queue_.empty()) {
41 this->read_state_();
42 return;
43 }
44 // Commands are non-blocking and need to be called repeatedly
45 if (this->run_command_(this->cmd_queue_.front(), App.get_loop_component_start_time())) {
46 this->cmd_queue_.pop();
47 this->cmd_sent_ = false;
48 this->retries_left_ = 2;
49 }
50}
51
52bool DfrobotSen0395Component::enqueue(CommandType type, uint8_t arg) {
53 if (!this->cmd_queue_.push({type, arg})) {
54 ESP_LOGE(TAG, "Command queue is full");
55 return false;
56 }
57 return true;
58}
59
60bool DfrobotSen0395Component::has_queue_room(size_t count) const {
61 if (COMMAND_QUEUE_SIZE - this->cmd_queue_.size() >= count)
62 return true;
63 ESP_LOGE(TAG, "Command queue is full");
64 return false;
65}
66
67void DfrobotSen0395Component::enqueue_det_range_cfg(float min1, float max1, float min2, float max2, float min3,
68 float max3, float min4, float max4) {
69 // TODO: Print warning when values are rounded
70 const float values[8] = {min1, max1, min2, max2, min3, max3, min4, max4};
71 int16_t steps[8];
72 bool in_use = true;
73 for (size_t i = 0; i < 8; i += 2) {
74 in_use = in_use && values[i] >= 0 && values[i + 1] >= 0;
75 for (size_t j = i; j < i + 2; j++) {
76 steps[j] = in_use ? static_cast<int16_t>(clamp(roundf(values[j] / DET_RANGE_STEP_M), 0.0f, 32767.0f)) : -1;
77 }
78 }
79 if (steps[0] < 0) {
80 ESP_LOGW(TAG, "Invalid detection range, using 0 0");
81 steps[0] = steps[1] = 0;
82 }
84 memcpy(this->det_range_steps_, steps, sizeof(steps));
85}
86
87void DfrobotSen0395Component::enqueue_set_latency(float delay_after_detection, float delay_after_disappear) {
88 if (!this->enqueue(CommandType::COMMAND_TYPE_SET_LATENCY))
89 return;
90 // 1638.375 s is 65535 steps
91 this->latency_steps_[0] =
92 static_cast<uint16_t>(clamp(std::round(delay_after_detection / LATENCY_STEP_S), 0.0f, 65535.0f));
93 this->latency_steps_[1] =
94 static_cast<uint16_t>(clamp(std::round(delay_after_disappear / LATENCY_STEP_S), 0.0f, 65535.0f));
95}
96
97void DfrobotSen0395Component::enqueue_saved_setting(CommandType type, bool value) {
98 const bool was_active = this->active_;
99 if (!this->has_queue_room(was_active ? 4 : 2))
100 return;
101 if (was_active)
102 this->enqueue(CommandType::COMMAND_TYPE_POWER, false);
103 this->enqueue(type, value);
105 if (was_active)
106 this->enqueue(CommandType::COMMAND_TYPE_POWER, true);
107}
108
110 // The interval between two commands must be larger than the command duration
111 const uint32_t duration = cmd.type == CommandType::COMMAND_TYPE_SAVE_CFG ? 3000 : 1000;
112 if (!this->cmd_sent_) {
113 if (now - this->ts_last_cmd_sent_ > duration) {
114 char buf[64]; // "detRangeCfg -1" + 8 * " 32767" + null
115 this->format_command(cmd, buf, sizeof(buf));
116 ESP_LOGD(TAG, "Sending command: %s", buf);
117 this->write_str(buf);
118 this->ts_last_cmd_sent_ = now;
119 this->cmd_sent_ = true;
120 }
121 return false; // Command not done yet
122 }
123
124 if (const char *message = this->read_message_()) {
125 if (ESPHOME_strstr_P(message, ESPHOME_PSTR("is not recognized as a CLI command")) == nullptr) {
126 if (!this->handle_reply_(cmd, message))
127 return false; // Command not done yet
128 this->read_message_(); // Skip the prompt
129 return true;
130 }
131 ESP_LOGD(TAG, "Command not recognized properly by sensor");
132 } else if (now - this->ts_last_cmd_sent_ <= duration + 500) {
133 return false; // Command not done yet
134 } else {
135 ESP_LOGD(TAG, "Command timeout");
136 }
137
138 if (this->retries_left_ == 0) {
139 this->read_message_(); // Skip the prompt
140 return true; // Give up
141 }
142 this->retries_left_--;
143 this->cmd_sent_ = false;
144 ESP_LOGD(TAG, "Retrying");
145 return false;
146}
147
149 const char *message = this->read_message_();
150 if (message == nullptr)
151 return;
152 if (ESPHOME_strstr_P(message, ESPHOME_PSTR("$JYBSS,0, , , *")) != nullptr) {
153 this->set_detected_(false);
154 this->set_active(true);
155 } else if (ESPHOME_strstr_P(message, ESPHOME_PSTR("$JYBSS,1, , , *")) != nullptr) {
156 this->set_detected_(true);
157 this->set_active(true);
158 }
159}
160
161static size_t append_cfg_key(char *buf, size_t size, size_t pos) {
162 return buf_append_str(buf, size, pos, " 0x45670123 0xCDEF89AB 0x956128C6 0xDF54AC89");
163}
164
165void DfrobotSen0395Component::format_command(const Command &cmd, char *buf, size_t size) const {
166 buf[0] = '\0';
167 switch (cmd.type) {
169 if (cmd.arg) {
170 buf_append_str(buf, size, 0, "sensorStart");
171 } else {
172 buf_append_str(buf, size, 0, "sensorStop");
173 }
174 break;
176 size_t pos = buf_append_str(buf, size, 0, "detRangeCfg -1");
177 for (size_t i = 0; i < 8 && this->det_range_steps_[i] >= 0; i += 2) {
178 pos = buf_append_printf(buf, size, pos, " %d %d", this->det_range_steps_[i], this->det_range_steps_[i + 1]);
179 }
180 break;
181 }
183 buf_append_printf(buf, size, 0, "setLatency %.03f %.03f", this->latency_steps_[0] * LATENCY_STEP_S,
184 this->latency_steps_[1] * LATENCY_STEP_S);
185 break;
187 buf_append_printf(buf, size, 0, "sensorCfgStart %d", cmd.arg);
188 break;
190 append_cfg_key(buf, size, buf_append_str(buf, size, 0, "factoryReset"));
191 break;
193 buf_append_str(buf, size, 0, "resetSystem");
194 break;
196 append_cfg_key(buf, size, buf_append_str(buf, size, 0, "saveCfg"));
197 break;
199 buf_append_printf(buf, size, 0, "setLedMode 1 %d", cmd.arg ? 0 : 1);
200 break;
202 buf_append_printf(buf, size, 0, "setUartOutput 1 %d", cmd.arg ? 1 : 0);
203 break;
205 buf_append_printf(buf, size, 0, "setSensitivity %d", cmd.arg);
206 break;
207 }
208}
209
211 auto is = [message](ESPHOME_PGM_P text) { return ESPHOME_strcmp_P(message, text) == 0; };
212
213 // Commands with their own replies
214 switch (cmd.type) {
216 if (is(ESPHOME_PSTR("sensor stopped already"))) {
217 this->set_active(false);
218 ESP_LOGI(TAG, "Stopped sensor (already stopped)");
219 } else if (is(ESPHOME_PSTR("sensor started already"))) {
220 this->set_active(true);
221 ESP_LOGI(TAG, "Started sensor (already started)");
222 } else if (is(ESPHOME_PSTR("new parameter isn't save, can't startSensor"))) {
223 this->set_active(false);
224 ESP_LOGE(TAG, "Can't start sensor! (Use SaveCfgCommand to save config first)");
225 } else if (is(ESPHOME_PSTR("Done"))) {
226 this->set_active(cmd.arg);
227 ESP_LOGI(TAG, "%s", cmd.arg ? LOG_STR_LITERAL("Started sensor") : LOG_STR_LITERAL("Stopped sensor"));
228 } else {
229 return false;
230 }
231 return true;
233 if (!is(PROMPT))
234 return false;
235 ESP_LOGI(TAG, "Restarted sensor.");
236 return true;
238 if (is(ESPHOME_PSTR("no parameter has changed"))) {
239 ESP_LOGI(TAG, "Not saving config (no parameter changed).");
240 } else if (is(ESPHOME_PSTR("Done"))) {
241 ESP_LOGI(TAG, "Saved config. Saving a lot may damage the sensor.");
242 } else {
243 return false;
244 }
245 return true;
246 default:
247 break;
248 }
249
250 // Configuration commands, which need the sensor stopped
251 if (is(ESPHOME_PSTR("sensor is not stopped"))) {
252 ESP_LOGE(TAG, "Cannot %s. Sensor is not stopped!",
253 LOG_STR_ARG(BusyActions::get_log_str(static_cast<uint8_t>(cmd.type), 0)));
254 return true;
255 }
256 if (!is(ESPHOME_PSTR("Done")))
257 return false;
258
259 switch (cmd.type) {
261 ESP_LOGI(TAG, "Updated detection area config:");
262 for (size_t i = 0; i < 8 && this->det_range_steps_[i] >= 0; i += 2) {
263 ESP_LOGI(TAG, " Detection area %u from %.02fm to %.02fm.", static_cast<unsigned>(i / 2 + 1),
264 this->det_range_steps_[i] * DET_RANGE_STEP_M, this->det_range_steps_[i + 1] * DET_RANGE_STEP_M);
265 }
266 break;
268 ESP_LOGI(TAG,
269 "Updated output latency config:\n"
270 " Signal that someone was detected is delayed by %.03f s.\n"
271 " Signal that nobody is detected anymore is delayed by %.03f s.",
272 this->latency_steps_[0] * LATENCY_STEP_S, this->latency_steps_[1] * LATENCY_STEP_S);
273 break;
275 this->set_start_after_boot(cmd.arg);
276 ESP_LOGI(TAG, "Updated sensor startup behavior: %s",
277 cmd.arg ? LOG_STR_LITERAL("sensor will start automatically after power-on.")
278 : LOG_STR_LITERAL("sensor needs to be started manually after power-on."));
279 break;
281 ESP_LOGI(TAG, "Sensor factory reset done.");
282 break;
284 this->set_led_active(cmd.arg);
285 ESP_LOGI(TAG, "Set led mode done. %s",
286 cmd.arg ? LOG_STR_LITERAL("Sensor LED will blink.") : LOG_STR_LITERAL("Turned off LED."));
287 break;
289 this->set_uart_presence_active(cmd.arg);
290 ESP_LOGI(TAG, "Set uart mode done. %s",
291 cmd.arg ? LOG_STR_LITERAL("Presence information is sent via UART and GPIO.")
292 : LOG_STR_LITERAL("Presence information is only sent via GPIO."));
293 break;
295 ESP_LOGI(TAG, "Set sensitivity done. Set to value %d.", cmd.arg);
296 break;
297 default:
298 break;
299 }
300 return true;
301}
302
304 while (this->available()) {
305 uint8_t byte;
306 this->read_byte(&byte);
307 if (byte >= 0x7F)
308 byte = '?'; // needs to be valid utf8 string for log functions.
309 const char *line = this->line_reader_.feed(byte);
310 if (line == nullptr && byte == '>' && this->line_reader_.length() == sizeof(PROMPT) - 1) {
311 line = this->line_reader_.partial();
312 this->line_reader_.reset();
313 }
314 if (line != nullptr) {
315 ESP_LOGV(TAG, "Message: %s", line);
316 return line;
317 }
319 }
320 return nullptr;
321}
322
324 this->detected_ = detected;
325#ifdef USE_BINARY_SENSOR
326 PUBLISH_STATE(this->detected_binary_sensor_, detected);
327#endif
328}
329
330} // namespace esphome::dfrobot_sen0395
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 dump_config()
const char * partial()
The partial line, NUL terminated, for prompts with no line end; the first N - 1 characters on the byt...
Definition line_reader.h:60
size_t length() const
Length of the partial line; 0 after a line is returned and while an overlong line is dropped.
Definition line_reader.h:56
char * feed(uint8_t c)
Feed one byte; returns the completed line (empty lines included), valid until the next call,...
Definition line_reader.h:23
void reset()
Forget the partial line and start a new one with the next byte.
Definition line_reader.h:76
void log_if_overflowed(const char *tag) const
Log the shared "line dropped" warning when the last feed() overflowed.
Definition line_reader.h:69
StaticRingBuffer< Command, COMMAND_QUEUE_SIZE > cmd_queue_
LineReader< MMWAVE_READ_BUFFER_LENGTH > line_reader_
const char * read_message_()
The next complete line, valid until the next call, or nullptr.
bool handle_reply_(const Command &cmd, const char *message)
Handle a reply to a sent command; true when the command is done.
bool run_command_(const Command &cmd, uint32_t now)
Run the command at the front of the queue; true when it is done.
void write_str(const char *str)
Definition uart.h:37
bool read_byte(uint8_t *data)
Definition uart.h:39
const LogString * message
Definition component.cpp:35
uint8_t type
unsigned count
Definition gif.cpp:51
uint8_t duration
Definition msa3xx.h:0
PROGMEM_STRING_TABLE(BusyActions, "", "configure range config", "configure output latency", "configure sensor startup behavior", "factory reset", "", "", "set led mode", "set uart output mode", "set sensitivity")
ESPHOME_LOG_TAG(TAG, "dfrobot_sen0395")
size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str)
Safely append a string to buffer, returning new position (capped at size).
Definition helpers.h:1382
uint32_t value
Definition hal.cpp:41
uint16_t size
Definition helpers.cpp:34
size_t size_t pos
Definition helpers.h:1333
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t