8static constexpr uint8_t SM300D2_RESPONSE_LENGTH = 17;
13 const uint8_t *response =
nullptr;
15 for (uint8_t c; response ==
nullptr && reader.
length() > 0 && this->
read_byte(&c);)
16 response = reader.
feed(c);
18 if (response ==
nullptr) {
19 ESP_LOGW(TAG,
"Reading data from SM300D2 failed!");
24 uint16_t calculated_checksum =
sum_bytes(response, SM300D2_RESPONSE_LENGTH - 1);
27 if ((calculated_checksum != response[SM300D2_RESPONSE_LENGTH - 1]) &&
28 (calculated_checksum - 0x80 != response[SM300D2_RESPONSE_LENGTH - 1]) &&
29 (calculated_checksum + 0x80 != response[SM300D2_RESPONSE_LENGTH - 1])) {
30 ESP_LOGW(TAG,
"SM300D2 Checksum doesn't match: 0x%02X!=0x%02X", response[SM300D2_RESPONSE_LENGTH - 1],
38 ESP_LOGD(TAG,
"Successfully read SM300D2 data");
40 const uint16_t co2 = (response[2] * 256) + response[3];
41 const uint16_t formaldehyde = (response[4] * 256) + response[5];
42 const uint16_t tvoc = (response[6] * 256) + response[7];
43 const uint16_t pm_2_5 = (response[8] * 256) + response[9];
44 const uint16_t pm_10_0 = (response[10] * 256) + response[11];
46 const float temperature = ((response[12] + (response[13] * 0.1f)) > 128)
47 ? (((response[12] + (response[13] * 0.1f)) - 128) * -1)
48 : response[12] + (response[13] * 0.1f);
49 const float humidity = response[14] + (response[15] * 0.1f);
51 ESP_LOGD(TAG,
"Received CO₂: %u ppm", co2);
52 PUBLISH_STATE(this->co2_sensor_, co2);
54 ESP_LOGD(TAG,
"Received Formaldehyde: %u µg/m³", formaldehyde);
55 PUBLISH_STATE(this->formaldehyde_sensor_, formaldehyde);
57 ESP_LOGD(TAG,
"Received TVOC: %u µg/m³", tvoc);
58 PUBLISH_STATE(this->tvoc_sensor_, tvoc);
60 ESP_LOGD(TAG,
"Received PM2.5: %u µg/m³", pm_2_5);
61 PUBLISH_STATE(this->pm_2_5_sensor_, pm_2_5);
63 ESP_LOGD(TAG,
"Received PM10: %u µg/m³", pm_10_0);
64 PUBLISH_STATE(this->pm_10_0_sensor_, pm_10_0);
66 ESP_LOGD(TAG,
"Received Temperature: %.2f °C",
temperature);
67 PUBLISH_STATE(this->temperature_sensor_,
temperature);
69 ESP_LOGD(TAG,
"Received Humidity: %.2f percent", humidity);
70 PUBLISH_STATE(this->humidity_sensor_, humidity);
73void SM300D2Sensor::dump_config() {
74 ESP_LOGCONFIG(TAG,
"SM300D2:");
75 LOG_SENSOR(
" ",
"CO2", this->co2_sensor_);
76 LOG_SENSOR(
" ",
"Formaldehyde", this->formaldehyde_sensor_);
77 LOG_SENSOR(
" ",
"TVOC", this->tvoc_sensor_);
78 LOG_SENSOR(
" ",
"PM2.5", this->pm_2_5_sensor_);
79 LOG_SENSOR(
" ",
"PM10", this->pm_10_0_sensor_);
80 LOG_SENSOR(
" ",
"Temperature", this->temperature_sensor_);
81 LOG_SENSOR(
" ",
"Humidity", this->humidity_sensor_);
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...