ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
rd03d.cpp
Go to the documentation of this file.
1#include "rd03d.h"
3#include "esphome/core/log.h"
4
5#include <cinttypes>
6#include <cmath>
7#include <numbers>
8
9namespace esphome::rd03d {
10
11static const char *const TAG = "rd03d";
12
13// Delay before sending configuration commands to allow radar to initialize
14static constexpr uint32_t SETUP_TIMEOUT_MS = 100;
15
16// Data frame format (radar -> host)
17static constexpr uint8_t FRAME_HEADER[] = {0xAA, 0xFF, 0x03, 0x00};
18static constexpr uint8_t FRAME_FOOTER[] = {0x55, 0xCC};
19
20// Command frame format (host -> radar)
21static constexpr uint8_t CMD_FRAME_HEADER[] = {0xFD, 0xFC, 0xFB, 0xFA};
22static constexpr uint8_t CMD_FRAME_FOOTER[] = {0x04, 0x03, 0x02, 0x01};
23
24// RD-03D tracking mode commands
25static constexpr uint16_t CMD_SINGLE_TARGET = 0x0080;
26static constexpr uint16_t CMD_MULTI_TARGET = 0x0090;
27
28// Speed sentinel values (cm/s) - radar outputs these when no valid Doppler measurement
29// FMCW radars detect motion via Doppler shift; targets with these speeds are likely noise
30static constexpr int16_t SPEED_SENTINEL_248 = 248;
31static constexpr int16_t SPEED_SENTINEL_256 = 256;
32
33// Decode coordinate/speed value from RD-03D format
34// Per datasheet: MSB=1 means positive, MSB=0 means negative
35static constexpr int16_t decode_value(uint8_t low_byte, uint8_t high_byte) {
36 int16_t value = ((high_byte & 0x7F) << 8) | low_byte;
37 if ((high_byte & 0x80) == 0) {
38 value = -value;
39 }
40 return value;
41}
42
43// Check if speed value indicates a valid Doppler measurement
44// Zero, ±248, or ±256 cm/s are sentinel values from the radar firmware
45static constexpr bool is_speed_valid(int16_t speed) {
46 int16_t abs_speed = speed < 0 ? -speed : speed;
47 return speed != 0 && abs_speed != SPEED_SENTINEL_248 && abs_speed != SPEED_SENTINEL_256;
48}
49
51 ESP_LOGCONFIG(TAG, "Setting up RD-03D...");
52 this->set_timeout(SETUP_TIMEOUT_MS, [this]() { this->apply_config_(); });
53}
54
56 ESP_LOGCONFIG(TAG, "RD-03D:");
57 if (this->tracking_mode_.has_value()) {
58 ESP_LOGCONFIG(TAG, " Tracking Mode: %s",
59 *this->tracking_mode_ == TrackingMode::SINGLE_TARGET ? "single" : "multi");
60 }
61 if (this->throttle_ > 0) {
62 ESP_LOGCONFIG(TAG, " Throttle: %" PRIu32 "ms", this->throttle_);
63 }
64#ifdef USE_SENSOR
65 LOG_SENSOR(" ", "Target Count", this->target_count_sensor_);
66#endif
67#ifdef USE_BINARY_SENSOR
68 LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_);
69#endif
70 for (uint8_t i = 0; i < MAX_TARGETS; i++) {
71 ESP_LOGCONFIG(TAG, " Target %d:", i + 1);
72#ifdef USE_SENSOR
73 LOG_SENSOR(" ", "X", this->targets_[i].x);
74 LOG_SENSOR(" ", "Y", this->targets_[i].y);
75 LOG_SENSOR(" ", "Speed", this->targets_[i].speed);
76 LOG_SENSOR(" ", "Distance", this->targets_[i].distance);
77 LOG_SENSOR(" ", "Resolution", this->targets_[i].resolution);
78 LOG_SENSOR(" ", "Angle", this->targets_[i].angle);
79#endif
80#ifdef USE_BINARY_SENSOR
81 LOG_BINARY_SENSOR(" ", "Presence", this->target_presence_[i]);
82#endif
83 }
84}
85
87 // Read all available bytes in batches to reduce UART call overhead.
88 size_t avail = this->available();
89 uint8_t buf[64];
90 while (avail > 0) {
91 size_t to_read = std::min(avail, sizeof(buf));
92 if (!this->read_array(buf, to_read)) {
93 break;
94 }
95 avail -= to_read;
96 for (size_t i = 0; i < to_read; i++) {
97 uint8_t byte = buf[i];
98 ESP_LOGVV(TAG, "Received byte: 0x%02X, buffer_pos: %d", byte, this->buffer_pos_);
99
100 // Check if we're looking for frame header
101 if (this->buffer_pos_ < FRAME_HEADER_SIZE) {
102 if (byte == FRAME_HEADER[this->buffer_pos_]) {
103 this->buffer_[this->buffer_pos_++] = byte;
104 } else if (byte == FRAME_HEADER[0]) {
105 // Start over if we see a potential new header
106 this->buffer_[0] = byte;
107 this->buffer_pos_ = 1;
108 } else {
109 this->buffer_pos_ = 0;
110 }
111 continue;
112 }
113
114 // Accumulate data bytes
115 this->buffer_[this->buffer_pos_++] = byte;
116
117 // Check if we have a complete frame
118 if (this->buffer_pos_ == FRAME_SIZE) {
119 // Validate footer
120 if (this->buffer_[FRAME_SIZE - 2] == FRAME_FOOTER[0] && this->buffer_[FRAME_SIZE - 1] == FRAME_FOOTER[1]) {
121 this->process_frame_();
122 } else {
123 ESP_LOGW(TAG, "Invalid frame footer: 0x%02X 0x%02X (expected 0x55 0xCC)", this->buffer_[FRAME_SIZE - 2],
124 this->buffer_[FRAME_SIZE - 1]);
125 }
126 this->buffer_pos_ = 0;
127 }
128 }
129 }
130}
131
133 // Apply throttle if configured
134 if (this->throttle_ > 0) {
135 uint32_t now = millis();
136 if (now - this->last_publish_time_ < this->throttle_) {
137 return;
138 }
139 this->last_publish_time_ = now;
140 }
141
142 uint8_t target_count = 0;
143
144 for (uint8_t i = 0; i < MAX_TARGETS; i++) {
145 // Calculate offset for this target's data
146 // Header is 4 bytes, each target is 8 bytes
147 uint8_t offset = FRAME_HEADER_SIZE + (i * TARGET_DATA_SIZE);
148
149 // Extract raw bytes for this target (per datasheet Table 5-2: X, Y, Speed, Resolution)
150 uint8_t x_low = this->buffer_[offset + 0];
151 uint8_t x_high = this->buffer_[offset + 1];
152 uint8_t y_low = this->buffer_[offset + 2];
153 uint8_t y_high = this->buffer_[offset + 3];
154 uint8_t speed_low = this->buffer_[offset + 4];
155 uint8_t speed_high = this->buffer_[offset + 5];
156 uint8_t res_low = this->buffer_[offset + 6];
157 uint8_t res_high = this->buffer_[offset + 7];
158
159 // Decode values per RD-03D format
160 int16_t x = decode_value(x_low, x_high);
161 int16_t y = decode_value(y_low, y_high);
162 int16_t speed = decode_value(speed_low, speed_high);
163 uint16_t resolution = (res_high << 8) | res_low;
164
165 // Check if target is present
166 // Requires non-zero coordinates AND valid speed (not a sentinel value)
167 // FMCW radars detect motion via Doppler; sentinel speed indicates no real target
168 bool has_position = (x != 0 || y != 0);
169 bool has_valid_speed = is_speed_valid(speed);
170 bool target_present = has_position && has_valid_speed;
171 if (target_present) {
172 target_count++;
173 }
174
175#ifdef USE_SENSOR
176 this->publish_target_(i, x, y, speed, resolution);
177#endif
178
179#ifdef USE_BINARY_SENSOR
180 if (this->target_presence_[i] != nullptr) {
181 this->target_presence_[i]->publish_state(target_present);
182 }
183#endif
184 }
185
186#ifdef USE_SENSOR
187 if (this->target_count_sensor_ != nullptr) {
188 this->target_count_sensor_->publish_state(target_count);
189 }
190#endif
191
192#ifdef USE_BINARY_SENSOR
193 if (this->target_binary_sensor_ != nullptr) {
194 this->target_binary_sensor_->publish_state(target_count > 0);
195 }
196#endif
197}
198
199#ifdef USE_SENSOR
200void RD03DComponent::publish_target_(uint8_t target_num, int16_t x, int16_t y, int16_t speed, uint16_t resolution) {
201 TargetSensor &target = this->targets_[target_num];
202 bool valid = is_speed_valid(speed);
203
204 // Publish X coordinate (mm) - NaN if target invalid
205 if (target.x != nullptr) {
206 target.x->publish_state(valid ? static_cast<float>(x) : NAN);
207 }
208
209 // Publish Y coordinate (mm) - NaN if target invalid
210 if (target.y != nullptr) {
211 target.y->publish_state(valid ? static_cast<float>(y) : NAN);
212 }
213
214 // Publish speed (convert from cm/s to mm/s) - NaN if target invalid
215 if (target.speed != nullptr) {
216 target.speed->publish_state(valid ? static_cast<float>(speed) * 10.0f : NAN);
217 }
218
219 // Publish resolution (mm)
220 if (target.resolution != nullptr) {
222 }
223
224 // Calculate and publish distance (mm) - NaN if target invalid
225 if (target.distance != nullptr) {
226 if (valid) {
227 target.distance->publish_state(std::hypot(static_cast<float>(x), static_cast<float>(y)));
228 } else {
229 target.distance->publish_state(NAN);
230 }
231 }
232
233 // Calculate and publish angle (degrees) - NaN if target invalid
234 // Angle is measured from the Y axis (radar forward direction)
235 if (target.angle != nullptr) {
236 if (valid) {
237 float angle = std::atan2(static_cast<float>(x), static_cast<float>(y)) * 180.0f / std::numbers::pi_v<float>;
238 target.angle->publish_state(angle);
239 } else {
240 target.angle->publish_state(NAN);
241 }
242 }
243}
244#endif
245
246void RD03DComponent::send_command_(uint16_t command, const uint8_t *data, uint8_t data_len) {
247 // Send header
248 this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
249
250 // Send length (command word + data)
251 uint16_t len = 2 + data_len;
252 this->write_byte(len & 0xFF);
253 this->write_byte((len >> 8) & 0xFF);
254
255 // Send command word (little-endian)
256 this->write_byte(command & 0xFF);
257 this->write_byte((command >> 8) & 0xFF);
258
259 // Send data if any
260 if (data != nullptr && data_len > 0) {
261 this->write_array(data, data_len);
262 }
263
264 // Send footer
265 this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
266
267 ESP_LOGD(TAG, "Sent command 0x%04X with %d bytes of data", command, data_len);
268}
269
271 if (this->tracking_mode_.has_value()) {
272 uint16_t mode_cmd = (*this->tracking_mode_ == TrackingMode::SINGLE_TARGET) ? CMD_SINGLE_TARGET : CMD_MULTI_TARGET;
273 this->send_command_(mode_cmd);
274 }
275}
276
277} // namespace esphome::rd03d
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void publish_state(bool new_state)
Publish a new state to the front-end.
optional< TrackingMode > tracking_mode_
Definition rd03d.h:84
std::array< TargetSensor, MAX_TARGETS > targets_
Definition rd03d.h:75
void dump_config() override
Definition rd03d.cpp:55
void send_command_(uint16_t command, const uint8_t *data=nullptr, uint8_t data_len=0)
Definition rd03d.cpp:246
binary_sensor::BinarySensor * target_binary_sensor_
Definition rd03d.h:80
std::array< uint8_t, FRAME_SIZE > buffer_
Definition rd03d.h:88
void publish_target_(uint8_t target_num, int16_t x, int16_t y, int16_t speed, uint16_t resolution)
Definition rd03d.cpp:200
std::array< binary_sensor::BinarySensor *, MAX_TARGETS > target_presence_
Definition rd03d.h:79
sensor::Sensor * target_count_sensor_
Definition rd03d.h:76
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
optional< std::array< uint8_t, N > > read_array()
Definition uart.h:38
void write_byte(uint8_t data)
Definition uart.h:18
void write_array(const uint8_t *data, size_t len)
Definition uart.h:26
int speed
Definition fan.h:3
Resolution resolution
Definition msa3xx.h:1
const void size_t len
Definition hal.h:64
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
bool valid
static void uint32_t
sensor::Sensor * resolution
Definition rd03d.h:35
sensor::Sensor * distance
Definition rd03d.h:34
sensor::Sensor * x
Definition rd03d.h:31
sensor::Sensor * speed
Definition rd03d.h:33
sensor::Sensor * y
Definition rd03d.h:32
sensor::Sensor * angle
Definition rd03d.h:36
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6