jsn_sr04t component: AJ_SR04M compatibility mode in checksum calculation (#7044)

Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
This commit is contained in:
soeffi 2024-07-11 23:30:45 +02:00 committed by GitHub
parent 99cba0ae7f
commit 7f83bcfdd9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 38 additions and 2 deletions

View File

@ -31,7 +31,16 @@ void Jsnsr04tComponent::loop() {
}
void Jsnsr04tComponent::check_buffer_() {
uint8_t checksum = this->buffer_[0] + this->buffer_[1] + this->buffer_[2];
uint8_t checksum = 0;
switch (this->model_) {
case JSN_SR04T:
checksum = this->buffer_[0] + this->buffer_[1] + this->buffer_[2];
break;
case AJ_SR04M:
checksum = this->buffer_[1] + this->buffer_[2];
break;
}
if (this->buffer_[3] == checksum) {
uint16_t distance = encode_uint16(this->buffer_[1], this->buffer_[2]);
if (distance > 250) {
@ -49,6 +58,14 @@ void Jsnsr04tComponent::check_buffer_() {
void Jsnsr04tComponent::dump_config() {
LOG_SENSOR("", "JST_SR04T Sensor", this);
switch (this->model_) {
case JSN_SR04T:
ESP_LOGCONFIG(TAG, " sensor model: jsn_sr04t");
break;
case AJ_SR04M:
ESP_LOGCONFIG(TAG, " sensor model: aj_sr04m");
break;
}
LOG_UPDATE_INTERVAL(this);
}

View File

@ -9,9 +9,14 @@
namespace esphome {
namespace jsn_sr04t {
enum Model {
JSN_SR04T,
AJ_SR04M,
};
class Jsnsr04tComponent : public sensor::Sensor, public PollingComponent, public uart::UARTDevice {
public:
// Nothing really public.
void set_model(Model model) { this->model_ = model; }
// ========== INTERNAL METHODS ==========
void update() override;
@ -20,6 +25,7 @@ class Jsnsr04tComponent : public sensor::Sensor, public PollingComponent, public
protected:
void check_buffer_();
Model model_;
std::vector<uint8_t> buffer_;
};

View File

@ -5,6 +5,7 @@ from esphome.const import (
STATE_CLASS_MEASUREMENT,
UNIT_METER,
ICON_ARROW_EXPAND_VERTICAL,
CONF_MODEL,
)
CODEOWNERS = ["@Mafus1"]
@ -14,6 +15,11 @@ jsn_sr04t_ns = cg.esphome_ns.namespace("jsn_sr04t")
Jsnsr04tComponent = jsn_sr04t_ns.class_(
"Jsnsr04tComponent", sensor.Sensor, cg.PollingComponent, uart.UARTDevice
)
Model = jsn_sr04t_ns.enum("Model")
MODEL = {
"jsn_sr04t": Model.JSN_SR04T,
"aj_sr04m": Model.AJ_SR04M,
}
CONFIG_SCHEMA = (
sensor.sensor_schema(
@ -25,6 +31,11 @@ CONFIG_SCHEMA = (
)
.extend(cv.polling_component_schema("60s"))
.extend(uart.UART_DEVICE_SCHEMA)
.extend(
{
cv.Optional(CONF_MODEL, default="jsn_sr04t"): cv.enum(MODEL, upper=False),
}
)
)
FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema(
@ -42,3 +53,5 @@ async def to_code(config):
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
await uart.register_uart_device(var, config)
cg.add(var.set_model(config[CONF_MODEL]))