ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ufm01.cpp
Go to the documentation of this file.
1#include "ufm01.h"
4#include "esphome/core/log.h"
5
6#include <algorithm>
7#include <array>
8#include <cinttypes>
9#include <cstring>
10
11namespace esphome::ufm01 {
12
13ESPHOME_LOG_TAG(TAG, "ufm01");
14
15static constexpr uint8_t COMMAND_ACK = 0xE5;
16static constexpr uint32_t COMMAND_ACK_TIMEOUT_MS = 500;
17static constexpr uint32_t CLEAR_QUEUE_TIMEOUT_MS = 15000;
18static constexpr uint32_t STARTUP_DELAY_MS = 2000;
19static constexpr uint32_t POST_RESET_DELAY_MS = 2000;
20static constexpr uint32_t RESET_RETRY_DELAY_MS = 800;
21static constexpr uint32_t STARTUP_RETRY_MS = 3000;
22static constexpr uint32_t PASSIVE_POLL_INTERVAL_MS = 1000;
23static constexpr uint32_t ACTIVE_STALE_MS = 5000;
24static constexpr uint32_t PASSIVE_READ_TIMEOUT_MS = 1000;
25static constexpr uint32_t SOFTWARE_VERSION_READ_TIMEOUT_MS = 2000;
26static constexpr uint32_t SOFTWARE_VERSION_RETRY_MS = 30000;
27static constexpr uint8_t SOFTWARE_VERSION_MAX_ATTEMPTS = 3;
28static constexpr uint32_t ACTIVE_FRAME_TIMEOUT_MS = 3000;
29// After this many consecutive passive poll failures, re-run the reset/startup sequence
30static constexpr uint8_t PASSIVE_FAIL_ESCALATE_COUNT = 8;
31
32static constexpr float L_PER_M3 = 1000.0f;
33static constexpr float M3_PER_L = 1.0f / L_PER_M3;
34
35static constexpr std::array<uint8_t, 7> ACTIVE_MODE = {0xFE, 0xFE, 0x11, 0x5C, 0x00, 0x5C, 0x16};
36static constexpr std::array<uint8_t, 7> PASSIVE_MODE = {0xFE, 0xFE, 0x11, 0x5C, 0x01, 0x5D, 0x16};
37static constexpr std::array<uint8_t, 7> CLEAR_ACCUMULATED_FLOW = {0xFE, 0xFE, 0x11, 0x5A, 0xFD, 0x57, 0x16};
38static constexpr std::array<uint8_t, 7> RESET_DEVICE = {0xFE, 0xFE, 0x11, 0x5D, 0xCB, 0x28, 0x16};
39static constexpr std::array<uint8_t, 7> READ_SENSOR_DATA_NO_ID = {0xFE, 0xFE, 0x11, 0x5B, 0x0F, 0x6A, 0x16};
40static constexpr std::array<uint8_t, 7> READ_SENSOR_DATA_WITH_ID = {0xFE, 0xFE, 0x11, 0x5B, 0xCB, 0x26, 0x16};
41static constexpr std::array<uint8_t, 7> GET_SOFTWARE_VERSION = {0xFE, 0xFE, 0x11, 0x5E, 0x62, 0xC0, 0x16};
42
43// Active-mode frame layout (datasheet Table 7)
44static constexpr size_t FRAME_DEVICE_ID_INDEX = 2;
45static constexpr size_t FRAME_CHECKSUM_INDEX = 30;
46static constexpr size_t FRAME_STOP_INDEX = 31;
47static constexpr uint8_t PASSIVE_START_BYTE_2 = 0x64;
48static constexpr uint8_t PASSIVE_START_BYTE_2_WITH_ID = 0x96;
49static constexpr uint8_t FRAME_STOP_BYTE = 0x16;
50static constexpr size_t PASSIVE_WITH_ID_DEVICE_ID_INDEX = 2;
51static constexpr uint8_t PASSIVE_WITH_ID_ACC_FLOW_FLAG_INDEX = 8;
52static constexpr uint8_t PASSIVE_WITH_ID_INSTANT_FLOW_FLAG_INDEX = 22;
53static constexpr uint8_t PASSIVE_WITH_ID_TEMP_FLAG_INDEX = 31;
54static constexpr uint8_t PASSIVE_WITH_ID_ST1_INDEX = 35;
55static constexpr size_t PASSIVE_WITH_ID_CHECKSUM_INDEX = 37;
56static constexpr size_t PASSIVE_WITH_ID_STOP_INDEX = 38;
57static constexpr uint8_t FRAME_INDEX_INSTANT_FLOW_FLAG = 15;
58static constexpr uint8_t FRAME_INDEX_RESERVED_SECTION = 21;
59static constexpr uint8_t FRAME_INDEX_TEMP_FLAG = 24;
60static constexpr uint8_t FRAME_FLAG_INSTANT_FLOW = 0x0B;
61static constexpr uint8_t FRAME_FLAG_RESERVED_SECTION = 0x0C;
62static constexpr uint8_t FRAME_FLAG_TEMP = 0x0D;
63
64// Measurement decoding
65static constexpr uint8_t FRAME_ACC_FLOW_FLAG_INDEX = 8;
66static constexpr uint8_t ACC_FLOW_M3_FLAG = 0x1A;
67static constexpr uint8_t FRAME_FLOW_SIGN_INDEX = 20;
68static constexpr uint8_t FLOW_NEGATIVE_SIGN = 0x80;
69
70// Status bytes (datasheet ST1 / ST2)
71static constexpr uint8_t FRAME_ST1_INDEX = 28;
72static constexpr uint8_t FRAME_ST2_INDEX = 29;
73static constexpr uint8_t ST1_EMPTY_TUBE_MASK = 0x20;
74static constexpr uint8_t ST2_UFC_ERROR_MASK = 0x20;
75static constexpr uint8_t ST2_FLOW_DIRECTION_WRONG_MASK = 0x08;
76static constexpr uint8_t ST2_FLOW_RATE_OUT_OF_RANGE_MASK = 0x04;
77
78static_assert(SOFTWARE_VERSION_RESPONSE_SIZE <= PASSIVE_FRAME_MAX_SIZE, "software version read reuses passive_frame_");
79static constexpr size_t SOFTWARE_VERSION_CHECKSUM_INDEX = 5;
80static constexpr size_t SOFTWARE_VERSION_STOP_INDEX = 6;
81
82static float to_float(uint8_t data) { return bcd_to_uint8(data); }
83
84static bool bcd_to_digits(const uint8_t *data, size_t len, char *out) {
85 bool all_zero = true;
86 for (size_t i = 0; i < len; ++i) {
87 const uint8_t lo = data[i] & 0x0F;
88 const uint8_t hi = data[i] >> 4;
89 if (lo > 9 || hi > 9)
90 return false;
91 const size_t pos = (len - 1 - i) * 2;
92 if (hi != 0)
93 all_zero = false;
94 out[pos] = static_cast<char>('0' + hi);
95 if (lo != 0)
96 all_zero = false;
97 out[pos + 1] = static_cast<char>('0' + lo);
98 }
99 out[len * 2] = '\0';
100 return !all_zero;
101}
102
103static bool validate_software_version_response(const uint8_t data[SOFTWARE_VERSION_RESPONSE_SIZE]) {
104 if (data[0] != COMMAND_ACK || data[SOFTWARE_VERSION_STOP_INDEX] != FRAME_STOP_BYTE)
105 return false;
106 return data[SOFTWARE_VERSION_CHECKSUM_INDEX] == sum_bytes(data + 1, SOFTWARE_VERSION_CHECKSUM_INDEX - 1);
107}
108
109static bool check_byte(const uint8_t data[FRAME_SIZE], size_t index, uint8_t expected, const char *name) {
110 if (data[index] == expected)
111 return true;
112 ESP_LOGW(TAG, "%s (byte %zu) - expected 0x%02X, but was 0x%02X", name, index, expected, data[index]);
113 return false;
114}
115
116static bool validate_active_frame(const uint8_t data[FRAME_SIZE]) {
117 const uint8_t sum = sum_bytes(data, FRAME_CHECKSUM_INDEX);
118 // FrameReader already matched the start bytes
119 return check_byte(data, FRAME_INDEX_INSTANT_FLOW_FLAG, FRAME_FLAG_INSTANT_FLOW, "instant flow flag") &&
120 check_byte(data, FRAME_INDEX_RESERVED_SECTION, FRAME_FLAG_RESERVED_SECTION, "reserved section flag") &&
121 check_byte(data, FRAME_INDEX_TEMP_FLAG, FRAME_FLAG_TEMP, "temperature flag") &&
122 check_byte(data, FRAME_CHECKSUM_INDEX, sum, "checksum") &&
123 check_byte(data, FRAME_STOP_INDEX, FRAME_STOP_BYTE, "stop byte");
124}
125
126static bool validate_passive_frame(const uint8_t data[PASSIVE_FRAME_SIZE]) {
127 if (data[0] != FRAME_START_BYTE_1 || data[1] != PASSIVE_START_BYTE_2 || data[22] != FRAME_STOP_BYTE)
128 return false;
129 return data[21] == sum_bytes(data, 21);
130}
131
132#ifdef USE_UFM01_METER_ID
133static bool validate_passive_with_id_frame(const uint8_t data[PASSIVE_FRAME_WITH_ID_SIZE]) {
134 if (data[0] != FRAME_START_BYTE_1 || data[1] != PASSIVE_START_BYTE_2_WITH_ID ||
135 data[PASSIVE_WITH_ID_STOP_INDEX] != FRAME_STOP_BYTE)
136 return false;
137 return data[PASSIVE_WITH_ID_CHECKSUM_INDEX] == sum_bytes(data, PASSIVE_WITH_ID_CHECKSUM_INDEX);
138}
139#endif
140
141// Start index of each run in a passive reply; each run maps to the matching run of the active frame
142struct PassiveLayout {
143 uint8_t acc_flow; // flag + 6 bytes, active 8..14
144 uint8_t instant_flow; // flag + 5 bytes, active 15..20
145 uint8_t temperature; // flag + 3 bytes, active 24..27
146 uint8_t status; // ST1, ST2, checksum, active 28..30
147};
148static constexpr PassiveLayout PASSIVE_NO_ID_LAYOUT{2, 9, 15, 19};
149#ifdef USE_UFM01_METER_ID
150static constexpr PassiveLayout PASSIVE_WITH_ID_LAYOUT{PASSIVE_WITH_ID_ACC_FLOW_FLAG_INDEX,
151 PASSIVE_WITH_ID_INSTANT_FLOW_FLAG_INDEX,
152 PASSIVE_WITH_ID_TEMP_FLAG_INDEX, PASSIVE_WITH_ID_ST1_INDEX};
153#endif
154
155static void passive_to_active_frame(const uint8_t *passive, const PassiveLayout &layout, uint8_t active[FRAME_SIZE]) {
156 std::memset(active, 0, FRAME_SIZE);
157 active[0] = FRAME_START_BYTE_1;
158 active[1] = FRAME_START_BYTE_2;
159 std::copy_n(&passive[layout.acc_flow], 7, &active[FRAME_ACC_FLOW_FLAG_INDEX]);
160 std::copy_n(&passive[layout.instant_flow], 6, &active[FRAME_INDEX_INSTANT_FLOW_FLAG]);
161 active[FRAME_INDEX_RESERVED_SECTION] = FRAME_FLAG_RESERVED_SECTION;
162 std::copy_n(&passive[layout.temperature], 4, &active[FRAME_INDEX_TEMP_FLAG]);
163 std::copy_n(&passive[layout.status], 3, &active[FRAME_ST1_INDEX]);
164 active[FRAME_STOP_INDEX] = FRAME_STOP_BYTE;
165}
166
167static float read_accumulated_flow(const uint8_t data[FRAME_SIZE]) {
168 return (data[FRAME_ACC_FLOW_FLAG_INDEX] == ACC_FLOW_M3_FLAG ? L_PER_M3 : 1.0f) *
169 (to_float(data[14]) * 10000000.0f + to_float(data[13]) * 100000.0f + to_float(data[12]) * 1000.0f +
170 to_float(data[11]) * 10.0f + to_float(data[10]) * 0.1f + to_float(data[9]) * 0.001f);
171}
172
173static float read_flow(const uint8_t data[FRAME_SIZE]) {
174 return (data[FRAME_FLOW_SIGN_INDEX] == FLOW_NEGATIVE_SIGN ? -1.0f : 1.0f) *
175 (to_float(data[19]) * 10000.0f + to_float(data[18]) * 100.0f + to_float(data[17]) +
176 to_float(data[16]) * 0.01f) *
177 M3_PER_L;
178}
179
180static constexpr size_t LOG_HEX_MAX_SIZE = std::max(FRAME_SIZE, PASSIVE_FRAME_MAX_SIZE);
181
182static void log_hex(const uint8_t *data, size_t len) {
183 char hex_buf[format_hex_pretty_size(LOG_HEX_MAX_SIZE)];
184 ESP_LOGD(TAG, "%s", format_hex_pretty_to(hex_buf, data, len, ' '));
185}
186
187static float read_temperature(const uint8_t data[FRAME_SIZE]) {
188 // happens sometimes before getting a real reading
189 if (data[27] == 0x00 && (data[26] == 0x00 || data[26] == 0x70) && data[25] == 0x00) {
190 return NAN;
191 }
192 return to_float(data[27]) * 100.0f + to_float(data[26]) + to_float(data[25]) * 0.01f;
193}
194
195static bool read_ufc_chip_error(const uint8_t data[FRAME_SIZE]) { return data[FRAME_ST2_INDEX] & ST2_UFC_ERROR_MASK; }
196
197static bool read_flow_direction_wrong(const uint8_t data[FRAME_SIZE]) {
198 return data[FRAME_ST2_INDEX] & ST2_FLOW_DIRECTION_WRONG_MASK;
199}
200
201static bool read_empty_tube(const uint8_t data[FRAME_SIZE]) { return data[FRAME_ST1_INDEX] & ST1_EMPTY_TUBE_MASK; }
202
203static bool read_flow_rate_out_of_range(const uint8_t data[FRAME_SIZE]) {
204 return data[FRAME_ST2_INDEX] & ST2_FLOW_RATE_OUT_OF_RANGE_MASK;
205}
206
207void UFM01Component::flush_rx_() {
208 this->discard_available();
209 this->active_reader_.reset();
210}
211
212void UFM01Component::send_command_no_wait_(const std::array<uint8_t, 7> &command) {
213 this->flush_rx_();
214 this->write_array(command);
215 this->flush();
216}
217
218bool UFM01Component::consume_ack_() {
219 while (this->available()) {
220 uint8_t byte;
221 if (!this->read_byte(&byte))
222 return false;
223 if (byte == COMMAND_ACK)
224 return true;
225 ESP_LOGV(TAG, "Unexpected byte while waiting for command ACK: 0x%02X", byte);
226 }
227 return false;
228}
229
230#ifdef USE_UFM01_CLEAR_ACCUMULATED_FLOW_ACTION
231bool UFM01Component::can_start_clear_action_() const {
232 return
233#ifdef USE_UFM01_SOFTWARE_VERSION
234 !this->software_version_read_pending_ &&
235#endif
236 (this->operating_mode_ == OperatingMode::ACTIVE_STREAM ||
237 (this->operating_mode_ == OperatingMode::PASSIVE_POLL && !this->passive_read_pending_));
238}
239
240void UFM01Component::request_clear_accumulated_flow() {
241 if (this->clear_pending_) {
242 ESP_LOGD(TAG, "Clear accumulated flow already pending");
243 return;
244 }
245 this->clear_pending_ = true;
246 this->pending_clear_sent_ = false;
247 this->pending_clear_start_ms_ = App.get_loop_component_start_time();
248}
249
250void UFM01Component::finish_pending_clear_() {
251 this->clear_pending_ = false;
252 this->pending_clear_sent_ = false;
253}
254
255void UFM01Component::loop_pending_clear_action_(uint32_t now) {
256 if (!this->clear_pending_)
257 return;
258 if (!this->pending_clear_sent_) {
259 if (!this->can_start_clear_action_()) {
260 if (now - this->pending_clear_start_ms_ < CLEAR_QUEUE_TIMEOUT_MS)
261 return;
262 ESP_LOGW(TAG, "Clear accumulated flow timed out waiting for an idle UART");
263 this->finish_pending_clear_();
264 return;
265 }
266 this->pending_clear_start_ms_ = now;
267 this->pending_clear_sent_ = true;
268 this->send_command_no_wait_(CLEAR_ACCUMULATED_FLOW);
269 return;
270 }
271 if (this->consume_ack_()) {
272 ESP_LOGI(TAG, "Clear accumulated flow acknowledged");
273 this->finish_pending_clear_();
274 return;
275 }
276 if (now - this->pending_clear_start_ms_ < COMMAND_ACK_TIMEOUT_MS)
277 return;
278 ESP_LOGW(TAG, "Clear accumulated flow not acknowledged");
279 this->finish_pending_clear_();
280}
281#endif // USE_UFM01_CLEAR_ACCUMULATED_FLOW_ACTION
282
283float UFM01Component::get_setup_priority() const { return setup_priority::LATE; }
284
286 ESP_LOGI(TAG, "Setting up UFM-01...");
287 this->startup_wait_ms_ = STARTUP_DELAY_MS;
288 this->set_startup_phase_(StartupPhase::WAIT, App.get_loop_component_start_time());
289}
290
291void UFM01Component::dump_config() {
292 ESP_LOGCONFIG(TAG, "UFM-01:");
293#ifdef USE_SENSOR
294 LOG_SENSOR(" ", "Accumulated Flow", this->accumulated_flow_sensor_);
295 LOG_SENSOR(" ", "Flow", this->flow_sensor_);
296 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
297#endif
298#ifdef USE_BINARY_SENSOR
299 LOG_BINARY_SENSOR(" ", "UFC Chip Error", this->ufc_chip_error_binary_sensor_);
300 LOG_BINARY_SENSOR(" ", "Flow Direction Wrong", this->flow_direction_wrong_binary_sensor_);
301 LOG_BINARY_SENSOR(" ", "Empty Tube", this->empty_tube_binary_sensor_);
302 LOG_BINARY_SENSOR(" ", "Flow Rate Out Of Range", this->flow_rate_out_of_range_binary_sensor_);
303#endif
304#ifdef USE_UFM01_METER_ID
305 LOG_TEXT_SENSOR(" ", "Meter ID", this->meter_id_text_sensor_);
306#endif
307#ifdef USE_UFM01_SOFTWARE_VERSION
308 LOG_TEXT_SENSOR(" ", "Software Version", this->software_version_text_sensor_);
309#endif
310}
311
312// The binary sensors keep their last state while readings are stale; only flow and temperature go unknown
313void UFM01Component::publish_stale_flow_and_temperature_() {
314#ifdef USE_SENSOR
315 PUBLISH_STATE(this->flow_sensor_, NAN);
316 PUBLISH_STATE(this->temperature_sensor_, NAN);
317#endif
318}
319
320#ifdef USE_UFM01_METER_ID
321void UFM01Component::publish_meter_id_from_frame_(const uint8_t data[FRAME_SIZE]) {
322 if (this->meter_id_text_sensor_ == nullptr || this->meter_id_published_)
323 return;
324
325 char meter_id_str[DEVICE_ID_STRING_LENGTH + 1];
326 if (!bcd_to_digits(&data[FRAME_DEVICE_ID_INDEX], DEVICE_ID_LENGTH, meter_id_str)) {
327 if (!this->meter_id_invalid_logged_) {
328 ESP_LOGW(TAG, "Meter ID in frame is zero or not BCD, leaving the sensor unknown");
329 this->meter_id_invalid_logged_ = true;
330 }
331 return;
332 }
333
334 this->meter_id_text_sensor_->publish_state(meter_id_str);
335 this->meter_id_published_ = true;
336 ESP_LOGI(TAG, "UFM-01 meter ID: %s", meter_id_str);
337}
338#endif
339
340#ifdef USE_UFM01_SOFTWARE_VERSION
341void UFM01Component::start_software_version_read_(uint32_t now) {
342 this->send_command_no_wait_(GET_SOFTWARE_VERSION);
343 this->passive_index_ = 0;
344 this->passive_start_ms_ = now;
345 this->software_version_read_pending_ = true;
346}
347
348ReadResult UFM01Component::continue_software_version_read_(uint32_t now) {
349 while (this->available() && this->passive_index_ < SOFTWARE_VERSION_RESPONSE_SIZE) {
350 uint8_t byte;
351 if (!this->read_byte(&byte))
352 break;
353 // The tail of an in-flight active-stream frame can arrive before the reply
354 if (this->passive_index_ == 0 && byte != COMMAND_ACK)
355 continue;
356 this->passive_frame_[this->passive_index_++] = byte;
357 }
358
359 if (this->passive_index_ < SOFTWARE_VERSION_RESPONSE_SIZE) {
360 if (now - this->passive_start_ms_ < SOFTWARE_VERSION_READ_TIMEOUT_MS)
362 ESP_LOGD(TAG, "software version read timeout (%u/%u bytes)", this->passive_index_,
363 static_cast<unsigned>(SOFTWARE_VERSION_RESPONSE_SIZE));
365 }
366
367 if (!validate_software_version_response(this->passive_frame_)) {
368 log_hex(this->passive_frame_, SOFTWARE_VERSION_RESPONSE_SIZE);
369 ESP_LOGW(TAG, "invalid software version response");
371 }
372
373 if (this->software_version_text_sensor_ != nullptr && !this->software_version_published_) {
374 char version_str[SOFTWARE_VERSION_STRING_LENGTH + 1];
375 if (!bcd_to_digits(&this->passive_frame_[1], SOFTWARE_VERSION_LENGTH, version_str)) {
376 ESP_LOGW(TAG, "invalid BCD data in software version response");
378 }
379 this->software_version_text_sensor_->publish_state(version_str);
380 this->software_version_published_ = true;
381 ESP_LOGI(TAG, "UFM-01 software version: %s", version_str);
382 }
383
385}
386
387void UFM01Component::finish_software_version_read_(ReadResult result, uint32_t now) {
388 this->software_version_read_pending_ = false;
389 this->last_software_version_attempt_ms_ = now;
390 if (result == ReadResult::READ_RESULT_FAILURE &&
391 ++this->software_version_failures_ == SOFTWARE_VERSION_MAX_ATTEMPTS) {
392 ESP_LOGW(TAG, "Software version not read after %u attempts, giving up", SOFTWARE_VERSION_MAX_ATTEMPTS);
393 }
394}
395
396// Returns true while a software version read owns the UART, so the caller skips its own work
397bool UFM01Component::service_software_version_(uint32_t now) {
398 if (this->software_version_read_pending_) {
399 const ReadResult result = this->continue_software_version_read_(now);
401 this->finish_software_version_read_(result, now);
402 return true;
403 }
404 if (this->software_version_text_sensor_ == nullptr || this->software_version_published_ ||
405 this->software_version_failures_ >= SOFTWARE_VERSION_MAX_ATTEMPTS || this->passive_read_pending_)
406 return false;
407 if (this->last_software_version_attempt_ms_ != 0 &&
408 now - this->last_software_version_attempt_ms_ < SOFTWARE_VERSION_RETRY_MS)
409 return false;
410 this->start_software_version_read_(now);
411 return true;
412}
413#endif // USE_UFM01_SOFTWARE_VERSION
414
415void UFM01Component::on_active_frame_(const uint8_t data[FRAME_SIZE], uint32_t now) {
416#ifdef USE_UFM01_METER_ID
417 this->publish_meter_id_from_frame_(data);
418#endif
419 bool empty_tube = read_empty_tube(data);
420#ifdef USE_BINARY_SENSOR
421 PUBLISH_STATE(this->ufc_chip_error_binary_sensor_, read_ufc_chip_error(data));
422 PUBLISH_STATE(this->flow_direction_wrong_binary_sensor_, read_flow_direction_wrong(data));
423 PUBLISH_STATE(this->empty_tube_binary_sensor_, empty_tube);
424 PUBLISH_STATE(this->flow_rate_out_of_range_binary_sensor_, read_flow_rate_out_of_range(data));
425#endif
426
427#ifdef USE_SENSOR
428 // Total volume remains valid when the tube is dry; flow and temperature are not.
429 PUBLISH_STATE(this->accumulated_flow_sensor_, read_accumulated_flow(data));
430
431 if (empty_tube) {
432 this->publish_stale_flow_and_temperature_();
433 } else {
434 PUBLISH_STATE(this->flow_sensor_, read_flow(data));
435 PUBLISH_STATE(this->temperature_sensor_, read_temperature(data));
436 }
437#endif
438 this->last_valid_frame_ms_ = now;
439 this->status_clear_warning();
440 this->status_clear_error();
441}
442
443bool UFM01Component::process_active_stream_(uint32_t now) {
444 bool got_valid_frame = false;
445
446 const bool read_ok = this->read_available([this, now, &got_valid_frame](uint8_t byte) {
447 const uint8_t *frame = this->active_reader_.feed(byte);
448 if (frame == nullptr) {
449 if (this->active_reader_.length() == 0) {
450 ESP_LOGD(TAG, "not start of data (is 0x%02X)", byte);
451 }
452 return;
453 }
454 if (validate_active_frame(frame)) {
455 this->on_active_frame_(frame, now);
456 got_valid_frame = true;
457 return;
458 }
459 log_hex(frame, FRAME_SIZE);
460 ESP_LOGW(TAG, "unable to read data");
461 this->active_reader_.resync();
462 });
463 if (!read_ok) {
464 ESP_LOGW(TAG, "unable to read byte");
465 this->active_reader_.reset();
466 }
467
468 return got_valid_frame;
469}
470
471void UFM01Component::set_mode_(OperatingMode mode, uint32_t now) {
472 this->operating_mode_ = mode;
473 this->phase_start_ms_ = now;
474 this->passive_read_pending_ = false;
475#ifdef USE_UFM01_SOFTWARE_VERSION
476 this->software_version_read_pending_ = false;
477#endif
478 this->consecutive_passive_failures_ = 0;
479}
480
481void UFM01Component::set_startup_phase_(StartupPhase phase, uint32_t now) {
482 this->startup_phase_ = phase;
483 this->phase_start_ms_ = now;
484}
485
486void UFM01Component::send_reset_(const LogString *status, uint32_t now) {
487 this->status_set_warning(status);
488 this->reset_retried_ = false;
489 this->send_command_no_wait_(RESET_DEVICE);
490 this->set_startup_phase_(StartupPhase::RESET_WAIT_ACK, now);
491}
492
493void UFM01Component::enter_active_stream_(const LogString *reason, uint32_t now) {
494 ESP_LOGI(TAG, "UFM-01 active stream %s", LOG_STR_ARG(reason));
495 this->set_mode_(OperatingMode::ACTIVE_STREAM, now);
496}
497
498void UFM01Component::enter_passive_from_stale_(uint32_t now) {
499 ESP_LOGW(TAG, "Active stream stale, switching to passive polling");
500 this->publish_stale_flow_and_temperature_();
501 // Flushes leftover stream bytes first; the ACK is not awaited, the next command's flush discards it
502 this->send_command_no_wait_(PASSIVE_MODE);
503 this->set_mode_(OperatingMode::PASSIVE_POLL, now);
504 this->last_poll_ms_ = now;
505 this->status_set_warning(LOG_STR("UFM-01 passive poll"));
506}
507
508void UFM01Component::restart_startup_(const LogString *reason, uint32_t now) {
509 ESP_LOGW(TAG, "%s, re-initializing UFM-01", LOG_STR_ARG(reason));
510 this->publish_stale_flow_and_temperature_();
511 this->set_mode_(OperatingMode::STARTUP, now);
512 this->send_reset_(LOG_STR("re-initializing UFM-01"), now);
513}
514
515void UFM01Component::note_passive_poll_result_(bool success, uint32_t now) {
516 if (success) {
517 this->consecutive_passive_failures_ = 0;
518 return;
519 }
520 this->status_set_warning(LOG_STR("UFM-01 passive poll failed"));
521 if (++this->consecutive_passive_failures_ < PASSIVE_FAIL_ESCALATE_COUNT)
522 return;
523 this->restart_startup_(LOG_STR("Passive poll failed repeatedly"), now);
524}
525
526void UFM01Component::start_passive_read_(uint32_t now) {
527#ifdef USE_UFM01_METER_ID
528 if (this->meter_id_text_sensor_ != nullptr && !this->meter_id_published_) {
529 this->passive_expected_size_ = PASSIVE_FRAME_WITH_ID_SIZE;
530 this->passive_start_byte_2_ = PASSIVE_START_BYTE_2_WITH_ID;
531 this->send_command_no_wait_(READ_SENSOR_DATA_WITH_ID);
532 } else
533#endif
534 {
535 this->passive_expected_size_ = PASSIVE_FRAME_SIZE;
536 this->passive_start_byte_2_ = PASSIVE_START_BYTE_2;
537 this->send_command_no_wait_(READ_SENSOR_DATA_NO_ID);
538 }
539 this->passive_index_ = 0;
540 this->passive_start_ms_ = now;
541}
542
543ReadResult UFM01Component::continue_passive_read_(uint32_t now) {
544 const uint8_t expected_size = this->passive_expected_size_;
545
546 while (this->available() && this->passive_index_ < expected_size) {
547 uint8_t byte;
548 if (!this->read_byte(&byte))
549 break;
550
551 if (this->passive_index_ == 0 && byte != FRAME_START_BYTE_1)
552 continue;
553 if (this->passive_index_ == 1 && byte != this->passive_start_byte_2_) {
554 // The mismatched byte may itself be the start of the real frame
555 this->passive_index_ = (byte == FRAME_START_BYTE_1) ? 1 : 0;
556 continue;
557 }
558 this->passive_frame_[this->passive_index_++] = byte;
559 }
560
561 if (this->passive_index_ < expected_size) {
562 if (now - this->passive_start_ms_ < PASSIVE_READ_TIMEOUT_MS)
564 ESP_LOGD(TAG, "passive read timeout (%u/%u bytes)", this->passive_index_, expected_size);
566 }
567
568 uint8_t active_frame[FRAME_SIZE];
569#ifdef USE_UFM01_METER_ID
570 if (expected_size == PASSIVE_FRAME_WITH_ID_SIZE) {
571 if (!validate_passive_with_id_frame(this->passive_frame_)) {
572 log_hex(this->passive_frame_, PASSIVE_FRAME_WITH_ID_SIZE);
573 ESP_LOGW(TAG, "invalid passive frame with ID");
575 }
576 passive_to_active_frame(this->passive_frame_, PASSIVE_WITH_ID_LAYOUT, active_frame);
577 // Device ID and the byte after it
578 std::copy_n(&this->passive_frame_[PASSIVE_WITH_ID_DEVICE_ID_INDEX], DEVICE_ID_LENGTH + 1,
579 &active_frame[FRAME_DEVICE_ID_INDEX]);
580 } else
581#endif
582 {
583 if (!validate_passive_frame(this->passive_frame_)) {
584 log_hex(this->passive_frame_, PASSIVE_FRAME_SIZE);
585 ESP_LOGW(TAG, "invalid passive frame");
587 }
588 passive_to_active_frame(this->passive_frame_, PASSIVE_NO_ID_LAYOUT, active_frame);
589 active_frame[FRAME_DEVICE_ID_INDEX + DEVICE_ID_LENGTH] = 0x01;
590 }
591 this->on_active_frame_(active_frame, now);
593}
594
595void UFM01Component::loop_startup_(uint32_t now) {
596 const uint32_t elapsed = now - this->phase_start_ms_;
597
598 switch (this->startup_phase_) {
600 // Pick up an already-streaming device without resetting it
601 if (this->process_active_stream_(now)) {
602 this->enter_active_stream_(LOG_STR("started"), now);
603 return;
604 }
605 if (elapsed < this->startup_wait_ms_)
606 return;
607 ESP_LOGD(TAG, "Running startup sequence");
608 this->send_reset_(LOG_STR("initializing UFM-01"), now);
609 return;
610
612 if (this->consume_ack_()) {
613 this->set_startup_phase_(StartupPhase::POST_RESET_WAIT, now);
614 return;
615 }
616 if (elapsed < COMMAND_ACK_TIMEOUT_MS)
617 return;
618 if (!this->reset_retried_) {
619 ESP_LOGW(TAG, "Reset not acknowledged, retrying in %" PRIu32 " ms", RESET_RETRY_DELAY_MS);
620 this->set_startup_phase_(StartupPhase::RESET_RETRY_WAIT, now);
621 } else {
622 ESP_LOGW(TAG, "Reset failed during startup");
623 this->set_startup_phase_(StartupPhase::POST_RESET_WAIT, now);
624 }
625 return;
626
628 if (elapsed < RESET_RETRY_DELAY_MS)
629 return;
630 this->reset_retried_ = true;
631 this->send_command_no_wait_(RESET_DEVICE);
632 this->set_startup_phase_(StartupPhase::RESET_WAIT_ACK, now);
633 return;
634
636 if (elapsed < POST_RESET_DELAY_MS)
637 return;
638#ifdef USE_UFM01_SOFTWARE_VERSION
639 if (this->software_version_text_sensor_ != nullptr && !this->software_version_published_ &&
640 this->software_version_failures_ < SOFTWARE_VERSION_MAX_ATTEMPTS) {
641 this->start_software_version_read_(now);
642 this->set_startup_phase_(StartupPhase::SOFTWARE_VERSION_WAIT_REPLY, now);
643 return;
644 }
645#endif
646 this->send_command_no_wait_(ACTIVE_MODE);
647 this->set_startup_phase_(StartupPhase::ACTIVE_WAIT_FRAME, now);
648 return;
649
650#ifdef USE_UFM01_SOFTWARE_VERSION
652 const ReadResult result = this->continue_software_version_read_(now);
654 return;
655 if (result == ReadResult::READ_RESULT_SUCCESS) {
656 ESP_LOGD(TAG, "Software version read during startup");
657 } else {
658 ESP_LOGW(TAG, "Software version read failed during startup, continuing");
659 }
660 this->finish_software_version_read_(result, now);
661 this->send_command_no_wait_(ACTIVE_MODE);
662 this->set_startup_phase_(StartupPhase::ACTIVE_WAIT_FRAME, now);
663 return;
664 }
665#endif
666
668 // The command ACK (0xE5) is consumed by the frame parser as noise
669 if (this->process_active_stream_(now)) {
670 this->enter_active_stream_(LOG_STR("started"), now);
671 return;
672 }
673 if (elapsed < ACTIVE_FRAME_TIMEOUT_MS)
674 return;
675 this->send_command_no_wait_(PASSIVE_MODE);
676 this->set_startup_phase_(StartupPhase::SET_PASSIVE_WAIT_ACK, now);
677 return;
678
680 if (this->consume_ack_()) {
681 ESP_LOGD(TAG, "Passive mode acknowledged during startup");
682 } else if (elapsed < COMMAND_ACK_TIMEOUT_MS) {
683 return;
684 } else {
685 ESP_LOGW(TAG, "SET_PASSIVE_MODE not acknowledged during startup, continuing");
686 }
687 this->start_passive_read_(now);
688 this->set_startup_phase_(StartupPhase::PASSIVE_WAIT_REPLY, now);
689 return;
690
692 switch (this->continue_passive_read_(now)) {
694 return;
696 ESP_LOGI(TAG, "UFM-01 using passive polling");
697 this->set_mode_(OperatingMode::PASSIVE_POLL, now);
698 this->last_poll_ms_ = now;
699 return;
701 ESP_LOGW(TAG, "Startup failed, retrying in %" PRIu32 " ms", STARTUP_RETRY_MS);
702 this->startup_wait_ms_ = STARTUP_RETRY_MS;
703 this->set_startup_phase_(StartupPhase::WAIT, now);
704 return;
705 }
706 }
707}
708
709void UFM01Component::loop_active_stream_(uint32_t now) {
710#ifdef USE_UFM01_SOFTWARE_VERSION
711 if (this->service_software_version_(now))
712 return;
713#endif
714
715 this->process_active_stream_(now);
716
717 if (this->last_valid_frame_ms_ != 0 && now - this->last_valid_frame_ms_ > ACTIVE_STALE_MS)
718 this->enter_passive_from_stale_(now);
719}
720
721void UFM01Component::loop_passive_poll_(uint32_t now) {
722#ifdef USE_UFM01_SOFTWARE_VERSION
723 if (this->service_software_version_(now))
724 return;
725#endif
726
727 if (this->passive_read_pending_) {
728 const ReadResult result = this->continue_passive_read_(now);
730 return;
731 this->passive_read_pending_ = false;
732 this->note_passive_poll_result_(result == ReadResult::READ_RESULT_SUCCESS, now);
733 return;
734 }
735
736 if (this->process_active_stream_(now)) {
737 this->enter_active_stream_(LOG_STR("resumed"), now);
738 return;
739 }
740
741 if (now - this->last_poll_ms_ >= PASSIVE_POLL_INTERVAL_MS) {
742 this->last_poll_ms_ = now;
743 this->start_passive_read_(now);
744 this->passive_read_pending_ = true;
745 }
746}
747
748void UFM01Component::loop() {
750#ifdef USE_UFM01_CLEAR_ACCUMULATED_FLOW_ACTION
751 this->loop_pending_clear_action_(now);
752 if (this->clear_pending_ && this->pending_clear_sent_)
753 return;
754#endif
755 switch (this->operating_mode_) {
757 this->loop_startup_(now);
758 return;
760 this->loop_active_stream_(now);
761 return;
763 this->loop_passive_poll_(now);
764 return;
765 }
766}
767
768} // namespace esphome::ufm01
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
size_t length() const
Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
const uint8_t * feed(uint8_t c)
Feed one byte; returns the completed frame, header included, valid until the next call,...
void resync()
For a frame the caller rejected (bad checksum): drop its first byte and realign on a header in the re...
void reset()
Forget the partial frame and look for a header from the next byte.
UARTFlushResult flush()
Definition uart.h:96
void discard_available()
Read and drop every byte waiting in the receive buffer.
Definition uart.cpp:36
bool read_byte(uint8_t *data)
Definition uart.h:39
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
std::vector< uint8_t > & out
Definition gif.cpp:49
std::span< const uint8_t > data
constexpr float LATE
For components that should be initialized at the very end of the setup process.
Definition component.h:59
ESPHOME_LOG_TAG(TAG, "ufm01")
constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum=0)
Add up the bytes of data with size len, truncated to 8 bits: the checksum many serial and IR protocol...
Definition helpers.h:939
const void size_t len
Definition hal.h:68
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:498
size_t size_t pos
Definition helpers.h:1333
constexpr uint8_t bcd_to_uint8(uint8_t bcd)
Decode a two-digit packed BCD byte (tens in the high nibble) to its value, e.g. 0x59 to 59.
Definition helpers.h:1144
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1687
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t