ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
sml_text_sensor.cpp
Go to the documentation of this file.
2#include "esphome/core/log.h"
3#include "sml_text_sensor.h"
4#include "../sml_parser.h"
5#include <cinttypes>
6
7namespace esphome::sml {
8
9static const char *const TAG = "sml_text_sensor";
10
11SmlTextSensor::SmlTextSensor(std::string server_id, std::string obis_code, SmlType format)
12 : SmlListener(std::move(server_id), std::move(obis_code)), format_(format) {}
13
14void SmlTextSensor::publish_val(const ObisInfo &obis_info) {
15 uint8_t value_type;
16 if (this->format_ == SML_UNDEFINED) {
17 value_type = obis_info.value_type;
18 } else {
19 value_type = this->format_;
20 }
21
22 switch (value_type) {
23 case SML_HEX: {
24 // Buffer for "0x" + up to 32 bytes as hex + null
25 char buf[67];
26 // Max 32 bytes of data fit in buffer ((67-3)/2)
27 size_t hex_bytes = std::min(obis_info.value.size(), size_t(32));
28 format_hex_prefixed_to(buf, obis_info.value.begin(), hex_bytes);
29 publish_state(buf, 2 + hex_bytes * 2);
30 break;
31 }
32 case SML_INT: {
33 char buf[21]; // Enough for int64_t (-9223372036854775808)
34 int len = snprintf(buf, sizeof(buf), "%" PRId64, bytes_to_int(obis_info.value));
35 publish_state(buf, static_cast<size_t>(len));
36 break;
37 }
38 case SML_BOOL:
39 publish_state(bytes_to_uint(obis_info.value) ? "True" : "False");
40 break;
41 case SML_UINT: {
42 char buf[21]; // Enough for uint64_t (18446744073709551615)
43 int len = snprintf(buf, sizeof(buf), "%" PRIu64, bytes_to_uint(obis_info.value));
44 publish_state(buf, static_cast<size_t>(len));
45 break;
46 }
47 case SML_OCTET: {
48 publish_state(reinterpret_cast<const char *>(obis_info.value.begin()), obis_info.value.size());
49 break;
50 }
51 }
52}
53
55 LOG_TEXT_SENSOR("", "SML", this);
56 if (!this->server_id.empty()) {
57 ESP_LOGCONFIG(TAG, " Server ID: %s", this->server_id.c_str());
58 }
59 ESP_LOGCONFIG(TAG, " OBIS Code: %s", this->obis_code.c_str());
60}
61
62} // namespace esphome::sml
const uint8_t * begin() const noexcept
Definition sml_parser.h:34
size_t size() const noexcept
Definition sml_parser.h:22
std::string server_id
Definition sml.h:14
std::string obis_code
Definition sml.h:15
SmlTextSensor(std::string server_id, std::string obis_code, SmlType format)
void publish_val(const ObisInfo &obis_info) override
void publish_state(const std::string &state)
int64_t bytes_to_int(const BytesView &buffer)
uint64_t bytes_to_uint(const BytesView &buffer)
const char int const __FlashStringHelper * format
Definition log.h:74
const void size_t len
Definition hal.h:64
char * format_hex_prefixed_to(char(&buffer)[N], T val)
Format an unsigned integer as "0x" prefixed lowercase hex to buffer.
Definition helpers.h:1367