ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
dfrobot_sen0465_base.cpp
Go to the documentation of this file.
2#include "esphome/core/log.h"
3
4#include <cmath>
5
7
8ESPHOME_LOG_TAG(TAG, "dfrobot_sen0465");
9
10// Protocol from https://github.com/DFRobot/DFRobot_MultiGasSensor
11// Request: FF 01 command argument 00 00 00 00 checksum
12// Response: FF command conc_high conc_low gas_type decimals temp_high temp_low checksum
13static constexpr uint8_t FRAME_ADDRESS = 0x01;
14
15static constexpr uint8_t NO_COMMAND = 0x00;
16static constexpr uint8_t CMD_CHANGE_ACQUIRE_MODE = 0x78;
17static constexpr uint8_t CMD_GET_ALL_DATA = 0x88;
18static constexpr uint8_t CMD_SET_THRESHOLD_ALARM = 0x89;
19static constexpr uint8_t ACQUIRE_MODE_PASSIVE = 0x04;
20static constexpr uint8_t ALARM_SWITCH_OFF = 0x00;
21static constexpr uint8_t ALARM_SWITCH_ON = 0x01;
22static constexpr uint8_t ALARM_LOW_THRESHOLD = 0x00;
23static constexpr uint8_t ALARM_HIGH_THRESHOLD = 0x01;
24// Byte 2 of the answer to a setting command is 1 when the sensor accepted it
25static constexpr uint8_t RESULT_OK = 0x01;
26
27// The DFRobot examples wait this long after changing the acquire mode
28static constexpr uint32_t MODE_CHANGE_DELAY_MS = 1000;
29static constexpr uint32_t RETRY_DELAY_MS = 1000;
30static constexpr uint8_t MAX_ATTEMPTS = 3;
31
32// Like FucCheckSum() in the DFRobot library, the checksum covers bytes 1 to 6 only, not byte 7
33static uint8_t frame_checksum(const uint8_t *frame) {
34 // Two's complement of the byte sum between the head and the checksum
35 return static_cast<uint8_t>(~sum16_bytes(frame + 1, FRAME_SIZE - 3) + 1);
36}
37
38static const LogString *step_name(SetupStep step) {
39 return step == SetupStep::SETUP_STEP_ACQUIRE_MODE ? LOG_STR("Passive mode") : LOG_STR("Alarm setting");
40}
41
42void DFRobotSEN0465Component::setup() {
43 // Answer only when asked, instead of sending a reading every second
45 if (!this->send_step_request_())
46 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
47}
48
49void DFRobotSEN0465Component::update() {
50 // The first reading is requested when the setup steps are done
52 return;
53 // A new request would replace the wait for the answer to the previous one
54 if (this->pending_command_ != NO_COMMAND) {
55 ESP_LOGV(TAG, "Previous request still waiting for an answer, skipping update");
56 return;
57 }
58 if (!this->send_command_(CMD_GET_ALL_DATA)) {
59 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
60 this->status_set_warning();
61 }
62}
63
64void DFRobotSEN0465Component::dump_config() {
65 ESP_LOGCONFIG(TAG,
66 "DFRobot SEN0465 series gas sensor:\n"
67 " Gas: %s (type 0x%02X)",
68 this->gas_name_, this->gas_type_);
69#ifdef USE_DFROBOT_SEN0465_TEMPERATURE_COMPENSATION
70 ESP_LOGCONFIG(TAG, " Temperature compensation: %s", YESNO(!this->compensation_.empty()));
71#endif
73 ESP_LOGCONFIG(TAG, " Alarm: off");
74 } else {
75 const float threshold = this->alarm_threshold_ / pow10_int(this->alarm_decimals_);
76 ESP_LOGCONFIG(TAG, " Alarm: %s %.*f",
77 this->alarm_type_ == AlarmType::ALARM_TYPE_HIGH ? LOG_STR_LITERAL("above") : LOG_STR_LITERAL("below"),
78 this->alarm_decimals_, threshold);
79 }
80 if (this->setup_incomplete_) {
81 ESP_LOGCONFIG(TAG, " Setup incomplete: yes");
82 }
83 LOG_UPDATE_INTERVAL(this);
84 LOG_SENSOR(" ", "Concentration", this->concentration_sensor_);
85 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
86}
87
88bool DFRobotSEN0465Component::send_command_(uint8_t command, uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t arg3) {
89 uint8_t frame[FRAME_SIZE] = {FRAME_HEAD, FRAME_ADDRESS, command, arg0, arg1, arg2, arg3};
90 frame[FRAME_SIZE - 1] = frame_checksum(frame);
91 if (!this->write_frame(frame))
92 return false;
93 this->pending_command_ = command;
94 this->read_response();
95 return true;
96}
97
100 return this->send_command_(CMD_CHANGE_ACQUIRE_MODE, ACQUIRE_MODE_PASSIVE);
102 // Switch the alarm off explicitly, the sensor may still have one from an earlier configuration
103 return this->send_command_(CMD_SET_THRESHOLD_ALARM, ALARM_SWITCH_OFF);
104 }
105 return this->send_command_(
106 CMD_SET_THRESHOLD_ALARM, ALARM_SWITCH_ON, static_cast<uint8_t>(this->alarm_threshold_ >> 8),
107 static_cast<uint8_t>(this->alarm_threshold_),
108 this->alarm_type_ == AlarmType::ALARM_TYPE_HIGH ? ALARM_HIGH_THRESHOLD : ALARM_LOW_THRESHOLD);
109}
110
112 if (!this->send_step_request_())
113 this->step_failed_(LOG_STR("request not sent"));
114}
115
116void DFRobotSEN0465Component::step_failed_(const LogString *reason) {
117 this->attempts_++;
118 ESP_LOGW(TAG, "%s failed: %s (attempt %u of %u)", LOG_STR_ARG(step_name(this->step_)), LOG_STR_ARG(reason),
119 this->attempts_, MAX_ATTEMPTS);
120 if (this->attempts_ < MAX_ATTEMPTS) {
121 this->set_timeout(STEP_TIMEOUT_ID, RETRY_DELAY_MS, [this]() { this->retry_step_request_(); });
122 return;
123 }
124 // Carry on: readings may still work, but the warning stays because the sensor is not set up as configured
125 this->setup_incomplete_ = true;
126 this->status_set_warning();
127 this->next_step_();
128}
129
131 this->attempts_ = 0;
134 this->set_timeout(STEP_TIMEOUT_ID, MODE_CHANGE_DELAY_MS, [this]() { this->retry_step_request_(); });
135 return;
136 }
138 this->update();
139}
140
142 this->pending_command_ = NO_COMMAND;
143 if (this->step_ != SetupStep::SETUP_STEP_DONE) {
144 this->step_failed_(LOG_STR("no response"));
145 return;
146 }
147 ESP_LOGW(TAG, "No response from the sensor");
148 this->fail_reading_();
149}
150
152 // A frozen gas reading would hide a rising concentration, so the entities go unknown
153 PUBLISH_STATE(this->concentration_sensor_, NAN);
154 PUBLISH_STATE(this->temperature_sensor_, NAN);
155 this->status_set_warning();
156}
157
159 // Reject a late answer to an earlier request or a reading sent before passive mode was set
160 const bool expected = frame[0] == FRAME_HEAD && frame[1] == this->pending_command_;
161 this->pending_command_ = NO_COMMAND;
162
163 if (this->step_ == SetupStep::SETUP_STEP_DONE) {
164 if (!expected) {
165 char hex[format_hex_pretty_size(FRAME_SIZE)];
166 ESP_LOGW(TAG, "Unexpected response: %s", format_hex_pretty_to(hex, frame, FRAME_SIZE));
167 this->fail_reading_();
168 return;
169 }
170 this->handle_data_(frame);
171 return;
172 }
173
174 ESP_LOGD_HEX(TAG, frame, FRAME_SIZE, FRAME_SIZE, "%s response: %s", LOG_STR_ARG(step_name(this->step_)));
175 if (!expected) {
176 this->step_failed_(LOG_STR("unexpected response"));
177 return;
178 }
179 // Like the DFRobot library, the answer to the mode change is accepted without a checksum check
180 if (this->step_ == SetupStep::SETUP_STEP_ALARM && frame[FRAME_SIZE - 1] != frame_checksum(frame)) {
181 this->step_failed_(LOG_STR("invalid checksum"));
182 return;
183 }
184 if (frame[2] != RESULT_OK) {
185 this->step_failed_(LOG_STR("not confirmed"));
186 return;
187 }
188 ESP_LOGD(TAG, "%s confirmed", LOG_STR_ARG(step_name(this->step_)));
189 this->next_step_();
190}
191
192void DFRobotSEN0465Component::handle_data_(const uint8_t *frame) {
193 if (frame[FRAME_SIZE - 1] != frame_checksum(frame)) {
194 char hex[format_hex_pretty_size(FRAME_SIZE)];
195 ESP_LOGW(TAG, "Invalid checksum: %s", format_hex_pretty_to(hex, frame, FRAME_SIZE));
196 this->fail_reading_();
197 return;
198 }
199
200 // On-board 10 kOhm NTC (B = 3380) read by a 10-bit ADC at 3 V, as converted by the DFRobot library
201 float temperature = NAN;
202 const uint16_t temperature_raw = encode_uint16(frame[6], frame[7]);
203 if (temperature_raw > 0 && temperature_raw < 1024) {
204 const float voltage = 3.0f * temperature_raw / 1024.0f;
205 const float resistance = voltage * 10000.0f / (3.0f - voltage);
206 temperature = 1.0f / (1.0f / 298.15f + std::log(resistance / 10000.0f) / 3380.13f) - 273.15f;
207 } else {
208 // 0 is a disconnected thermistor, 1024 and above a bad frame
209 ESP_LOGW(TAG, "Temperature reading %u is out of range", temperature_raw);
210 }
211 PUBLISH_STATE(this->temperature_sensor_, temperature);
212
213 if (frame[4] != this->gas_type_) {
214 ESP_LOGW(TAG, "Probe reports gas type 0x%02X, expected %s (0x%02X); check the configured model", frame[4],
215 this->gas_name_, this->gas_type_);
216 PUBLISH_STATE(this->concentration_sensor_, NAN);
217 this->status_set_warning();
218 return;
219 }
220
221 if (frame[5] > 2) {
222 ESP_LOGW(TAG, "Invalid number of decimal places: %u", frame[5]);
223 PUBLISH_STATE(this->concentration_sensor_, NAN);
224 this->status_set_warning();
225 return;
226 }
227 float concentration = encode_uint16(frame[2], frame[3]) * pow10_int(-frame[5]);
228
229#ifdef USE_DFROBOT_SEN0465_TEMPERATURE_COMPENSATION
230 if (!this->compensation_.empty())
231 concentration = this->compensate_(concentration, temperature);
232#endif
233 if (concentration < 0.0f)
234 concentration = 0.0f;
235
236 PUBLISH_STATE(this->concentration_sensor_, concentration);
237 this->status_comm_result(!std::isnan(concentration) && !std::isnan(temperature) && !this->setup_incomplete_, nullptr);
238}
239
240#ifdef USE_DFROBOT_SEN0465_TEMPERATURE_COMPENSATION
241float DFRobotSEN0465Component::compensate_(float concentration, float temperature) const {
242 for (const auto &range : this->compensation_) {
243 if (temperature > range.low && temperature <= range.high)
244 return concentration / (range.a * temperature + range.b) - (range.c * temperature + range.d);
245 }
246 ESP_LOGW(TAG, "Temperature %.1f C is outside the compensation range", temperature);
247 return NAN;
248}
249#endif
250
251} // namespace esphome::dfrobot_sen0465_base
void mark_failed()
Mark this component as failed.
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
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
StaticVector< CompensationRange, DFROBOT_SEN0465_COMPENSATION_RANGES > compensation_
bool send_step_request_()
Sends the request of the current step.
virtual void read_response()=0
Waits for the answer to a request, then calls either handle_response_() or handle_no_response_(),...
void retry_step_request_()
Sends the request again from a scheduled callback; a failed write counts as a failed attempt.
bool setup_incomplete_
A setup step gave up, so the alarm or the mode may not be what was configured.
virtual bool write_frame(const uint8_t *frame)=0
Sends one complete request frame.
uint8_t pending_command_
Command whose answer is awaited, 0 when no request is outstanding.
bool send_command_(uint8_t command, uint8_t arg0=0, uint8_t arg1=0, uint8_t arg2=0, uint8_t arg3=0)
Sends a request and waits for its answer; returns false when the request could not be sent.
float compensate_(float concentration, float temperature) const
Returns NAN when the temperature is outside every range.
void fail_reading_()
Publish unknown on both sensors and set the warning when a reading cannot be used.
Range range
Definition msa3xx.h:0
ESPHOME_LOG_TAG(TAG, "dfrobot_sen0465")
SetupStep
Settings sent once after boot, before the first reading.
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
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
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1043
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:919
static void uint32_t
uint16_t temperature
Definition sun_gtil2.cpp:12