ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
kamstrup_kmp.cpp
Go to the documentation of this file.
1#include "kamstrup_kmp.h"
2
4#include "esphome/core/log.h"
6
8
9ESPHOME_LOG_TAG(TAG, "kamstrup_kmp");
10
11// KMP units indexed by unit code; the empty first entry doubles as the fallback for unknown codes
12PROGMEM_STRING_TABLE(KmpUnits, "", "Wh", "kWh", "MWh", "GWh", "J", "kJ", "MJ", "GJ", "Cal", "kCal", "Mcal", "Gcal",
13 "varh", "kvarh", "Mvarh", "Gvarh", "VAh", "kVAh", "MVAh", "GVAh", "kW", "kW", "MW", "GW", "kvar",
14 "kvar", "Mvar", "Gvar", "VA", "kVA", "MVA", "GVA", "V", "A", "kV", "kA", "C", "K", "l", "m3",
15 "l/h", "m3/h", "m3xC", "ton", "ton/h", "h", "hh:mm:ss", "yy:mm:dd", "yyyy:mm:dd", "mm:dd", "",
16 "bar", "RTC", "ASCII", "m3 x 10", "ton x 10", "GJ x 10", "minutes", "Bitfield", "s", "ms", "days",
17 "RTC-Q", "Datetime");
18
20 ESP_LOGCONFIG(TAG, "kamstrup_kmp:");
21 LOG_UPDATE_INTERVAL(this);
22
23 LOG_SENSOR(" ", "Heat Energy", this->heat_energy_sensor_);
24 LOG_SENSOR(" ", "Power", this->power_sensor_);
25 LOG_SENSOR(" ", "Temperature 1", this->temp1_sensor_);
26 LOG_SENSOR(" ", "Temperature 2", this->temp2_sensor_);
27 LOG_SENSOR(" ", "Temperature Difference", this->temp_diff_sensor_);
28 LOG_SENSOR(" ", "Flow", this->flow_sensor_);
29 LOG_SENSOR(" ", "Volume", this->volume_sensor_);
30
31 for (size_t i = 0; i < this->custom_sensors_.size(); i++) {
32 LOG_SENSOR(" ", "Custom Sensor", this->custom_sensors_[i]);
33 ESP_LOGCONFIG(TAG, " Command: 0x%04X", this->custom_commands_[i]);
34 }
35}
36
38 if (this->heat_energy_sensor_ != nullptr) {
39 this->command_queue_.push(CMD_HEAT_ENERGY);
40 }
41
42 if (this->power_sensor_ != nullptr) {
43 this->command_queue_.push(CMD_POWER);
44 }
45
46 if (this->temp1_sensor_ != nullptr) {
47 this->command_queue_.push(CMD_TEMP1);
48 }
49
50 if (this->temp2_sensor_ != nullptr) {
51 this->command_queue_.push(CMD_TEMP2);
52 }
53
54 if (this->temp_diff_sensor_ != nullptr) {
55 this->command_queue_.push(CMD_TEMP_DIFF);
56 }
57
58 if (this->flow_sensor_ != nullptr) {
59 this->command_queue_.push(CMD_FLOW);
60 }
61
62 if (this->volume_sensor_ != nullptr) {
63 this->command_queue_.push(CMD_VOLUME);
64 }
65
66 for (uint16_t custom_command : this->custom_commands_) {
67 this->command_queue_.push(custom_command);
68 }
69}
70
72 if (!this->command_queue_.empty()) {
73 uint16_t command = this->command_queue_.front();
74 this->send_command_(command);
75 this->command_queue_.pop();
76 }
77}
78
80 uint32_t msg_len = 5;
81 uint8_t msg[msg_len];
82
83 msg[0] = 0x3F;
84 msg[1] = 0x10;
85 msg[2] = 0x01;
86 msg[3] = command >> 8;
87 msg[4] = command & 0xFF;
88
89 this->discard_available();
90 this->send_message_(msg, msg_len);
91 this->read_command_(command);
92}
93
94void KamstrupKMPComponent::send_message_(const uint8_t *msg, int msg_len) {
95 int buffer_len = msg_len + 2;
96 uint8_t buffer[buffer_len];
97
98 // Prepare the basic message and appand CRC
99 for (int i = 0; i < msg_len; i++) {
100 buffer[i] = msg[i];
101 }
102
103 uint16_t crc = crc16be(buffer, buffer_len - 2);
104 buffer[buffer_len - 2] = crc >> 8;
105 buffer[buffer_len - 1] = crc & 0xFF;
106
107 // Prepare actual TX message
108 uint8_t tx_msg[20];
109 int tx_msg_len = 1;
110 tx_msg[0] = 0x80; // prefix
111
112 for (int i = 0; i < buffer_len; i++) {
113 if (buffer[i] == 0x06 || buffer[i] == 0x0d || buffer[i] == 0x1b || buffer[i] == 0x40 || buffer[i] == 0x80) {
114 if (tx_msg_len + 2 >= static_cast<int>(sizeof(tx_msg))) {
115 ESP_LOGE(TAG, "TX message overflow");
116 return;
117 }
118 tx_msg[tx_msg_len++] = 0x1b;
119 tx_msg[tx_msg_len++] = buffer[i] ^ 0xff;
120 } else {
121 if (tx_msg_len + 1 >= static_cast<int>(sizeof(tx_msg))) {
122 ESP_LOGE(TAG, "TX message overflow");
123 return;
124 }
125 tx_msg[tx_msg_len++] = buffer[i];
126 }
127 }
128
129 tx_msg[tx_msg_len++] = 0x0D; // EOM
130
131 this->write_array(tx_msg, tx_msg_len);
132}
133
135 uint8_t buffer[20] = {0};
136 size_t buffer_len = 0;
137 int data;
138 int timeout = 250; // ms
139
140 // Read the data from the UART
141 while (timeout > 0 && buffer_len < sizeof(buffer)) {
142 if (this->available()) {
143 data = this->read();
144 if (data > -1) {
145 if (data == 0x40) { // start of message
146 buffer_len = 0;
147 } else if (buffer_len == 0) {
148 // Ignore request echoes until the response starts.
149 continue;
150 }
151 buffer[buffer_len++] = (uint8_t) data;
152 if (data == 0x0D) {
153 break;
154 }
155 } else {
156 ESP_LOGE(TAG, "Error while reading from UART");
157 }
158 } else {
159 delay(1);
160 timeout--;
161 }
162 }
163
164 if (timeout == 0 || buffer_len == 0) {
165 ESP_LOGE(TAG, "Request timed out");
166 return;
167 }
168
169 // Only bytes from the 0x40 start byte on are stored, so just the end of the message needs checking
170 if (buffer[buffer_len - 1] != 0x0D) {
171 ESP_LOGE(TAG, "Received invalid message (EOM mismatch received 0x%02X, expected 0x0D)", buffer[buffer_len - 1]);
172 return;
173 }
174
175 // Decode
176 uint8_t msg[20] = {0};
177 int msg_len = 0;
178 for (size_t i = 1; i < buffer_len - 1 && msg_len < (int) sizeof(msg); i++) {
179 if (buffer[i] == 0x1B) {
180 msg[msg_len++] = buffer[i + 1] ^ 0xFF;
181 i++;
182 } else {
183 msg[msg_len++] = buffer[i];
184 }
185 }
186
187 // Validate CRC; a frame shorter than the CRC itself has nothing to check
188 if (msg_len < 2 || crc16be(msg, msg_len - 2) != encode_uint16(msg[msg_len - 2], msg[msg_len - 1])) {
189 ESP_LOGE(TAG, "Received invalid message (CRC mismatch)");
190 return;
191 }
192
193 // All seems good. Now parse the message
194 this->parse_command_message_(command, msg, msg_len);
195}
196
197void KamstrupKMPComponent::parse_command_message_(uint16_t command, const uint8_t *msg, int msg_len) {
198 // Validate the message
199 if (msg_len < 8) {
200 ESP_LOGE(TAG, "Received invalid message (message too small)");
201 return;
202 }
203
204 if (msg[0] != 0x3F || msg[1] != 0x10) {
205 ESP_LOGE(TAG, "Received invalid message (invalid header received 0x%02X%02X, expected 0x3F10)", msg[0], msg[1]);
206 return;
207 }
208
209 uint16_t recv_command = encode_uint16(msg[2], msg[3]);
210 if (recv_command != command) {
211 ESP_LOGE(TAG, "Received invalid message (invalid unexpected command received 0x%04X, expected 0x%04X)",
212 recv_command, command);
213 return;
214 }
215
216 uint8_t unit_idx = msg[4];
217 uint8_t mantissa_range = msg[5];
218
219 if (mantissa_range > 4 || msg_len < 7 + mantissa_range) {
220 ESP_LOGE(TAG, "Received invalid message (mantissa size %d, msg_len %d)", mantissa_range, msg_len);
221 return;
222 }
223
224 // Calculate exponent
225 int8_t exp_val = msg[6] & 0x3F;
226 if (msg[6] & 0x40) {
227 exp_val = -exp_val;
228 }
229 float exponent = pow10_int(exp_val);
230 if (msg[6] & 0x80) {
231 exponent = -exponent;
232 }
233
234 // Calculate mantissa
235 uint32_t mantissa = 0;
236 for (int i = 0; i < mantissa_range; i++) {
237 mantissa <<= 8;
238 mantissa |= msg[i + 7];
239 }
240
241 // Calculate the actual value
242 float value = mantissa * exponent;
243
244 // Set sensor value
245 this->set_sensor_value_(command, value, unit_idx);
246}
247
248void KamstrupKMPComponent::set_sensor_value_(uint16_t command, float value, uint8_t unit_idx) {
249 // Standard sensors
250 if (command == CMD_HEAT_ENERGY && this->heat_energy_sensor_ != nullptr) {
251 this->heat_energy_sensor_->publish_state(value);
252 } else if (command == CMD_POWER && this->power_sensor_ != nullptr) {
253 this->power_sensor_->publish_state(value);
254 } else if (command == CMD_TEMP1 && this->temp1_sensor_ != nullptr) {
255 this->temp1_sensor_->publish_state(value);
256 } else if (command == CMD_TEMP2 && this->temp2_sensor_ != nullptr) {
257 this->temp2_sensor_->publish_state(value);
258 } else if (command == CMD_TEMP_DIFF && this->temp_diff_sensor_ != nullptr) {
259 this->temp_diff_sensor_->publish_state(value);
260 } else if (command == CMD_FLOW && this->flow_sensor_ != nullptr) {
261 this->flow_sensor_->publish_state(value);
262 } else if (command == CMD_VOLUME && this->volume_sensor_ != nullptr) {
263 this->volume_sensor_->publish_state(value);
264 }
265
266 // Custom sensors
267 for (size_t i = 0; i < this->custom_commands_.size(); i++) {
268 if (command == this->custom_commands_[i]) {
269 this->custom_sensors_[i]->publish_state(value);
270 }
271 }
272
273 ESP_LOGD(TAG, "Received value for command 0x%04X: %.3f [%s]", command, value,
274 LOG_STR_ARG(KmpUnits::get_log_str(unit_idx, 0)));
275}
276
277} // namespace esphome::kamstrup_kmp
virtual void dump_config()
void set_sensor_value_(uint16_t command, float value, uint8_t unit_idx)
std::vector< sensor::Sensor * > custom_sensors_
void parse_command_message_(uint16_t command, const uint8_t *msg, int msg_len)
void send_message_(const uint8_t *msg, int msg_len)
void discard_available()
Read and drop every byte waiting in the receive buffer.
Definition uart.cpp:36
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
uint32_t buffer
Definition gif.cpp:50
PROGMEM_STRING_TABLE(KmpUnits, "", "Wh", "kWh", "MWh", "GWh", "J", "kJ", "MJ", "GJ", "Cal", "kCal", "Mcal", "Gcal", "varh", "kvarh", "Mvarh", "Gvarh", "VAh", "kVAh", "MVAh", "GVAh", "kW", "kW", "MW", "GW", "kvar", "kvar", "Mvar", "Gvar", "VA", "kVA", "MVA", "GVA", "V", "A", "kV", "kA", "C", "K", "l", "m3", "l/h", "m3/h", "m3xC", "ton", "ton/h", "h", "hh:mm:ss", "yy:mm:dd", "yyyy:mm:dd", "mm:dd", "", "bar", "RTC", "ASCII", "m3 x 10", "ton x 10", "GJ x 10", "minutes", "Bitfield", "s", "ms", "days", "RTC-Q", "Datetime")
ESPHOME_LOG_TAG(TAG, "kamstrup_kmp")
uint32_t value
Definition hal.cpp:41
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:135
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
void HOT delay(uint32_t ms)
Definition hal.cpp:85
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:919
static void uint32_t