ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
hoermann_hcp.cpp
Go to the documentation of this file.
1#include "hoermann_hcp.h"
2
3#include <algorithm>
4#include <utility>
5
6#include "esphome/core/hal.h"
8#include "esphome/core/log.h"
9
10namespace esphome::hoermann_hcp {
11
12ESPHOME_LOG_TAG(TAG, "hoermann_hcp");
13
14// Hoermann HCP holding-register blocks.
15static constexpr uint16_t COMMAND_REG = 0x9C41; // Commands written by the bus controller
16static constexpr uint16_t STATE_REG = 0x9CB9; // Internal state read back by the bus controller
17static constexpr uint16_t BROADCAST_REG = 0x9D31; // Door status broadcast by the bus controller
18static constexpr float CLOSE_POSITION_THRESHOLD = 0.05f;
19static constexpr float OPEN_POSITION_THRESHOLD = 0.95f;
20
21static constexpr HoermannHcpCommand COMMAND_OPEN{"open", 0x0110};
22static constexpr HoermannHcpCommand COMMAND_CLOSE{"close", 0x0120};
23static constexpr HoermannHcpCommand COMMAND_IMPULSE{"impulse", 0x0140};
24static constexpr HoermannHcpCommand COMMAND_VENT{"vent", 0x0100, 0x4000};
25static constexpr HoermannHcpCommand COMMAND_HALF_OPEN{"half open", 0x0100, 0x0400};
26// Absolute, as a vendor gateway sends them, so a late or repeated one cannot switch the lamp the wrong way.
27static constexpr HoermannHcpCommand COMMAND_LIGHT_ON{"light on", 0x0880};
28static constexpr HoermannHcpCommand COMMAND_LIGHT_OFF{"light off", 0x0800, 0x0100};
29// Kept as the intent, as the same impulse starts a door at rest; only a door still moving at the fetch gets it.
30static constexpr HoermannHcpCommand COMMAND_STOP{"stop", 0x0140};
31
32// High byte of the state register and the door state it stands for. State 0x00 is decoded separately because
33// its low byte tells a plain stop from the vent position.
34struct DoorStateMapping {
35 uint8_t code;
36 DoorState state;
37};
38static constexpr DoorStateMapping DOOR_STATE_MAPPINGS[] = {
42};
43
44// The hub rejects a reply whose register count does not match the request, so an unrecognized block length
45// is padded with zeros rather than answered with an exception that would fail the controller's whole poll.
46static void push_zeros(modbus::RegisterValues &registers, uint16_t count) {
47 for (uint16_t i = 0; i < count; i++)
48 registers.push_back(0x0000);
49}
50
51// True while the door is travelling. An impulse toggles the door, so it only stops one that is moving.
52static bool is_moving(DoorState state) {
53 switch (state) {
58 return true;
59 default:
60 return false;
61 }
62}
63
64static bool at_destination(const HoermannHcpCommand &command, DoorState state) {
65 if (&command == &COMMAND_OPEN)
66 return state == DoorState::OPEN;
67 if (&command == &COMMAND_CLOSE)
68 return state == DoorState::CLOSED;
69 if (&command == &COMMAND_VENT)
70 return state == DoorState::VENT;
71 if (&command == &COMMAND_HALF_OPEN)
73 return false;
74}
75
76// Only a status poll's answer carries commands.
77static constexpr uint8_t STATUS_COMMAND = 0x03;
78// A second stop this soon after one went out is ignored, so a double press cannot restart the door.
79static constexpr uint32_t STOP_LOCK_MS = 500;
80
81#ifdef USE_HOERMANN_HCP_IDENTITY
82// A status answer with this code in the low byte of its second register asks the bus controller for a value,
83// named in the high byte of the third.
84static constexpr uint8_t ANSWER_REQUEST = 0x22;
85static constexpr uint8_t REQUEST_SERIAL = 0x05;
86static constexpr uint8_t REQUEST_FIRMWARE = 0x06;
87// Each request goes out in one answer, up to this many times, this far apart.
88static constexpr uint8_t IDENTITY_MAX_ATTEMPTS = 3;
89static constexpr uint32_t IDENTITY_RETRY_MS = 30000;
90// The value comes back as a payload transfer: this command in the low byte of the first command register, a sub
91// code in the high byte of the second, the payload from the third on.
92static constexpr uint8_t TRANSFER_COMMAND = 0x04;
93static constexpr uint8_t TRANSFER_SUB_SERIAL = 0x0C;
94static constexpr uint8_t TRANSFER_SUB_FIRMWARE = 0x0D;
95static constexpr uint8_t TRANSFER_ACK = 0xFD;
96static constexpr size_t TRANSFER_PAYLOAD_REG = 2;
97// Marks the first half of the serial number in the counter byte, and is not part of the count.
98static constexpr uint8_t COUNTER_FIRST_HALF = 0x80;
99// Older motors (index B1 seen) send the whole serial number in one frame, without the half marker. It is as long
100// as a second half, so one copy path serves both.
101static constexpr size_t SERIAL_SINGLE_FRAME_REGS = 6;
102static_assert(SERIAL_SINGLE_FRAME_REGS == SERIAL_SECOND_HALF_REGS, "one copy path serves both serial frames");
103
104// Registers hold two payload bytes each, high byte first.
105static void copy_payload(const modbus::RegisterValues &registers, size_t count, char *out) {
106 for (size_t i = 0; i < count; i++) {
107 const uint16_t value = registers[TRANSFER_PAYLOAD_REG + i];
108 out[2 * i] = static_cast<char>(value >> 8);
109 out[2 * i + 1] = static_cast<char>(value);
110 }
111}
112
113// Length of the printable text at the start, without trailing spaces. The padding after it varies.
114static size_t text_length(const char *text, size_t len) {
115 size_t at = 0;
116 while (at < len && text[at] >= 0x20 && text[at] <= 0x7E)
117 at++;
118 while (at > 0 && text[at - 1] == ' ')
119 at--;
120 return at;
121}
122
123static void terminate_text(char *text, size_t len) { text[text_length(text, len)] = '\0'; }
124
125// dump_config() is replayed to remote log clients, so they see the outcome of the exchange at boot.
126static void log_identity_value(text_sensor::TextSensor *sensor) {
127 if (sensor != nullptr) {
128 ESP_LOGCONFIG(TAG, " Value: %s",
129 sensor->has_state() ? sensor->get_state().c_str() : LOG_STR_LITERAL("not received"));
130 }
131}
132#endif
133
134void HoermannHcp::update() {
135 const uint32_t now = millis();
136 // Time out the connection flag if the bus controller stopped polling.
137 if (this->valid_ && now - this->last_response_ > this->connection_timeout_ms_)
138 this->set_valid_(false);
139 // Status broadcasts alone keep the connection alive, so a command the controller never fetches would
140 // otherwise block every later one for as long as it keeps broadcasting.
141 // A stop held for a door that has not reported its start yet is timed by the start window instead.
142 const bool stop_held = this->next_command_ == &COMMAND_STOP && this->starting_;
143 if (this->next_command_ != nullptr && !stop_held && now - this->command_queued_at_ > this->connection_timeout_ms_) {
144 ESP_LOGW(TAG, "Bus controller did not fetch '%s' command, dropping it", this->next_command_->name);
145 this->drop_command_();
146 // Children may have assumed the command would land, so let them re-derive from the door.
147 this->changed_ = true;
148 }
149 // A target the door never started towards would otherwise cut a later move short.
150 if (this->has_target_() && !this->target_started_ && now - this->target_queued_at_ > this->start_window_ms_) {
151 ESP_LOGW(TAG, "Door did not start moving towards the requested position, dropping it");
152 this->clear_target_();
153 }
154 // A door that never answers a fetched command is at rest after all.
155 if (this->starting_ && now - this->start_fetched_at_ > this->start_window_ms_) {
156 this->starting_ = false;
157 if (stop_held) {
158 ESP_LOGW(TAG, "Door did not report moving, dropping the stop");
159 this->next_command_ = nullptr;
160 } else {
161 ESP_LOGD(TAG, "Door did not start after the command");
162 }
163 }
164 // A lamp command held while the door starts or moves waits on purpose, so its deadline starts once the door rests.
165 if (this->is_moving_or_starting_() && this->light_requested_ && !this->light_command_sent_)
166 this->light_since_ = now;
167 // Neither fire late nor block the next request.
168 if (this->light_requested_ && now - this->light_since_ > this->connection_timeout_ms_) {
169 if (this->light_command_sent_) {
170 ESP_LOGW(TAG, "Door did not report the lamp changing, giving up");
171 } else {
172 ESP_LOGW(TAG, "Bus controller did not fetch the lamp command, dropping it");
173 }
174 this->clear_light_request_();
175 }
176#ifdef USE_HOERMANN_HCP_IDENTITY
177 this->publish_identity_();
178#endif
179 if (this->changed_) {
180 this->changed_ = false;
181 this->state_callback_.call();
182 }
183}
184
185void HoermannHcp::dump_config() {
186 ESP_LOGCONFIG(TAG,
187 "Hoermann HCP bridge:\n"
188 " Modbus server address: 0x%02X",
189 this->get_address());
190#ifdef USE_BINARY_SENSOR
191 LOG_BINARY_SENSOR(" ", "Actuator Error", this->actuator_error_binary_sensor_);
192#endif
193#ifdef USE_HOERMANN_HCP_IDENTITY
194 LOG_TEXT_SENSOR(" ", "Serial Number", this->serial_number_text_sensor_);
195 log_identity_value(this->serial_number_text_sensor_);
196 LOG_TEXT_SENSOR(" ", "Firmware Version", this->version_text_sensor_);
197 log_identity_value(this->version_text_sensor_);
198#endif
199}
200
201modbus::ResponseStatus HoermannHcp::on_read_holding_registers(uint16_t start_address, uint16_t number_of_registers,
202 modbus::RegisterValues &registers) {
203 if (start_address != STATE_REG) {
204 ESP_LOGW(TAG, "Unknown read address 0x%04X", start_address);
206 }
207
208 this->record_response_();
209 const bool status_poll = std::exchange(this->status_poll_pending_, false);
210
211#ifdef USE_HOERMANN_HCP_IDENTITY
212 // Acknowledge the transfer taken by the write half of this frame.
213 if (this->transfer_answer_counter_ != NO_TRANSFER_ANSWER) {
214 this->push_transfer_answer_(registers, number_of_registers);
215 return {};
216 }
217#endif
218
219 // 0x17 read half: STATE_REG is read back right after COMMAND_REG was written, so echo the stored message
220 // counter (high byte) and command (low byte). The read length identifies which internal block is requested.
221 const uint16_t counter = this->command_reg_value_ & 0xFF00;
222 const uint16_t command = static_cast<uint16_t>((this->command_reg_value_ & 0x00FF) << 8);
223
224 switch (number_of_registers) {
225 case 8:
226 // Command request: return the internal state, injecting any pending command.
227 registers.push_back(counter);
228 registers.push_back(static_cast<uint16_t>(0x0001 | command));
229 if (status_poll && static_cast<uint8_t>(this->command_reg_value_) == STATUS_COMMAND) {
230 this->push_command_registers_(registers);
231 } else {
232 push_zeros(registers, 2);
233 }
234 push_zeros(registers, 4);
235#ifdef USE_HOERMANN_HCP_IDENTITY
236 this->add_identity_request_(registers, command);
237#endif
238 break;
239 case 2:
240 // Empty command request.
241 registers.push_back(static_cast<uint16_t>(0x0004 | counter));
242 registers.push_back(command);
243 break;
244 case 5:
245 // Bus scan (the bus controller discovering us, typically at startup).
246 ESP_LOGD(TAG, "Bus scan received from bus controller");
247 registers.push_back(counter);
248 registers.push_back(static_cast<uint16_t>(0x0005 | command));
249 registers.push_back(0x0430);
250 registers.push_back(0x10FF);
251 registers.push_back(0xA845);
252 break;
253 default:
254 ESP_LOGW(TAG, "Unknown read request (read %u registers)", number_of_registers);
255 push_zeros(registers, number_of_registers);
256 break;
257 }
258
259 return {};
260}
261
262modbus::ResponseStatus HoermannHcp::on_write_registers(uint16_t start_address,
263 const modbus::RegisterValues &registers) {
264 if (start_address == COMMAND_REG) {
265 // 0x17 write half: stash the command register so the following read half can echo its message counter and
266 // command byte back from STATE_REG. The hub always runs the write before the read within one request.
267 this->record_response_();
268 this->command_reg_value_ = registers[0];
269 this->status_poll_pending_ = true;
270#ifdef USE_HOERMANN_HCP_IDENTITY
271 this->transfer_answer_counter_ = this->take_identity_transfer_(registers);
272#endif
273 return {};
274 }
275
276 if (start_address != BROADCAST_REG) {
277 // Every device sees every broadcast, so a frame meant for another node is ordinary traffic
278 ESP_LOGV(TAG, "Ignoring write to address 0x%04X", start_address);
280 }
281
282 this->record_response_();
283
284 // Door status broadcast. The state is decoded first so that a frame reporting both a new state and a new
285 // position checks the target against the new state.
286 if (registers.size() > 2)
287 this->on_state_reg_(registers[2]);
288 if (registers.size() > 1)
289 this->on_position_reg_(registers[1]);
290 if (registers.size() > 6) {
291 this->on_light_reg_(registers[6]);
292 return {};
293 }
294 // Nothing refreshes the lamp any more, so what was read before must not be commanded against.
295 this->set_light_seen_(false);
296 if (!this->short_broadcast_logged_) {
297 this->short_broadcast_logged_ = true;
298 ESP_LOGD(TAG, "Broadcast of %u registers carries no lamp state", static_cast<unsigned>(registers.size()));
299 }
300 return {};
301}
302
304 const HoermannHcpCommand *command = this->take_command_();
305 if (command == nullptr)
306 command = this->take_light_command_();
307 if (command == nullptr) {
308 push_zeros(registers, 2);
309 return;
310 }
311 ESP_LOGI(TAG, "Sending '%s' command to door", command->name);
312 registers.push_back(command->value);
313 registers.push_back(command->value_2);
314}
315
317 const HoermannHcpCommand *command = this->next_command_;
318 if (command == nullptr)
319 return nullptr;
320 const bool moving = is_moving(this->door_state_);
321 // The door was just told to start and has not said so yet, so an impulse now could start it instead.
322 if (command == &COMMAND_STOP && this->starting_ && !moving)
323 return nullptr;
324 this->next_command_ = nullptr;
325 if (moving) {
326 // The door may have been started from elsewhere since the command was queued.
327 if ((command == &COMMAND_OPEN && this->door_state_ == DoorState::OPENING) ||
328 (command == &COMMAND_CLOSE && this->door_state_ == DoorState::CLOSING)) {
329 ESP_LOGD(TAG, "Door is already moving that way, dropping '%s'", command->name);
330 return nullptr;
331 }
332 if (command != &COMMAND_STOP) {
333 ESP_LOGD(TAG, "Door is moving, stopping it instead of '%s'", command->name);
334 }
335 this->last_stop_at_ = millis();
336 this->stop_sent_ = true;
337 return &COMMAND_STOP;
338 }
339 if (command == &COMMAND_STOP) {
340 ESP_LOGD(TAG, "Door came to rest before the stop was fetched, dropping it");
341 return nullptr;
342 }
343 // Until the door answers, it still reads as at rest.
344 if (!this->door_state_seen_ || !at_destination(*command, this->door_state_)) {
345 this->starting_ = true;
346 this->start_command_ = command;
347 this->start_fetched_at_ = millis();
348 }
349 return command;
350}
351
353 // The motor ignores the lamp while its door moves and may switch it itself as it starts, so the lamp waits for rest.
354 if (!this->light_requested_ || this->light_command_sent_ || this->is_moving_or_starting_() ||
355 this->light_target_ == this->light_on_)
356 return nullptr;
357 this->light_command_sent_ = true;
358 this->light_since_ = millis();
359 return this->light_target_ ? &COMMAND_LIGHT_ON : &COMMAND_LIGHT_OFF;
360}
361
362#ifdef USE_HOERMANN_HCP_IDENTITY
364 if (static_cast<uint8_t>(this->command_reg_value_) != STATUS_COMMAND)
365 return;
366 // Like Hoermann's own bus accessory, only after one ordinary answer.
368 if (this->serial_number_text_sensor_ != nullptr || this->version_text_sensor_ != nullptr)
370 return;
371 }
372 // Uses the command registers, so it waits while a command is pending.
373 if (registers[2] != 0 || registers[3] != 0 || !this->take_identity_request_())
374 return;
375 registers[1] = static_cast<uint16_t>(ANSWER_REQUEST | command);
376 registers[2] = encode_uint16(this->identity_request_(), 0);
377}
378
380 this->identity_phase_ = phase;
381 this->identity_attempts_ = 0;
382}
383
385 const uint8_t request = this->identity_request_();
386 if (request == 0)
387 return false;
388 const uint32_t now = millis();
389 if (this->identity_attempts_ != 0 && now - this->identity_asked_at_ <= IDENTITY_RETRY_MS)
390 return false;
391 if (this->identity_attempts_ >= IDENTITY_MAX_ATTEMPTS) {
392 this->identity_unanswered_ = request;
393 if (request == REQUEST_SERIAL) {
394 // Still ask for the firmware version, and drop a leftover first half.
395 this->serial_number_[0] = '\0';
397 } else {
399 }
400 return false;
401 }
402 this->identity_attempts_++;
403 this->identity_asked_at_ = now;
404 return true;
405}
406
408 if (this->identity_phase_ == IdentityPhase::IDENTITY_PHASE_IDLE || registers.size() < TRANSFER_PAYLOAD_REG ||
409 static_cast<uint8_t>(registers[0]) != TRANSFER_COMMAND)
410 return NO_TRANSFER_ANSWER;
411 const uint8_t counter = static_cast<uint8_t>(registers[0] >> 8);
412 const uint8_t sub_code = static_cast<uint8_t>(registers[1] >> 8);
413 if (sub_code != TRANSFER_SUB_SERIAL && sub_code != TRANSFER_SUB_FIRMWARE)
414 return NO_TRANSFER_ANSWER;
415 // Acknowledged whether kept or not, as Hoermann's own bus accessory does. What was not kept is asked for again.
416 const uint8_t answer = counter & ~COUNTER_FIRST_HALF;
417 // Only an answer to the request that went out is kept.
418 const uint8_t request = sub_code == TRANSFER_SUB_SERIAL ? REQUEST_SERIAL : REQUEST_FIRMWARE;
419 if (this->identity_attempts_ == 0 || this->identity_request_() != request)
420 return answer;
421
422 const size_t payload_regs = registers.size() - TRANSFER_PAYLOAD_REG;
423 if (request == REQUEST_FIRMWARE) {
424 const size_t regs = std::min(payload_regs, FIRMWARE_REGS);
425 copy_payload(registers, regs, this->firmware_version_);
426 if (regs == FIRMWARE_REGS && text_length(this->firmware_version_, 2 * regs) != 0) {
427 terminate_text(this->firmware_version_, 2 * regs);
428 // Clear an earlier unreadable answer, so this one is shown.
429 this->firmware_unreadable_ = false;
431 return answer;
432 }
433 // Left as received for update() to log.
434 this->firmware_unreadable_ = true;
435 this->firmware_unreadable_len_ = 2 * regs;
436 // A short answer is asked for again; unreadable text would come back the same.
437 if (regs == FIRMWARE_REGS)
439 return answer;
440 }
441 if ((counter & COUNTER_FIRST_HALF) != 0) {
442 // Even a half too short to keep says the number comes in two halves; a first half already kept stays kept.
445 if (payload_regs >= SERIAL_FIRST_HALF_REGS) {
446 copy_payload(registers, SERIAL_FIRST_HALF_REGS, this->serial_number_);
448 }
449 return answer;
450 }
451 // Without a half marker seen, the frame is the whole number; after one, it can only be the second half.
452 if (this->identity_phase_ == IdentityPhase::IDENTITY_PHASE_SERIAL_SPLIT || payload_regs < SERIAL_SINGLE_FRAME_REGS)
453 return answer;
454 const size_t at =
455 this->identity_phase_ == IdentityPhase::IDENTITY_PHASE_SERIAL_SECOND_HALF ? 2 * SERIAL_FIRST_HALF_REGS : 0;
456 copy_payload(registers, SERIAL_SINGLE_FRAME_REGS, this->serial_number_ + at);
457 terminate_text(this->serial_number_, at + 2 * SERIAL_SINGLE_FRAME_REGS);
458 this->serial_unreadable_ = this->serial_number_[0] == '\0';
460 return answer;
461}
462
463void HoermannHcp::push_transfer_answer_(modbus::RegisterValues &registers, uint16_t number_of_registers) {
464 const uint16_t answer[] = {encode_uint16(this->transfer_answer_counter_, 0),
465 encode_uint16(TRANSFER_COMMAND, TRANSFER_ACK)};
466 this->transfer_answer_counter_ = NO_TRANSFER_ANSWER;
467 for (uint16_t i = 0; i < number_of_registers; i++)
468 registers.push_back(i < 2 ? answer[i] : 0x0000);
469}
470
472 // Buffers are cleared once published, so each value goes out once. The serial number is whole once the firmware
473 // version is requested.
474 if (this->serial_number_text_sensor_ != nullptr && this->identity_request_() != REQUEST_SERIAL &&
475 this->serial_number_[0] != '\0') {
476 this->serial_number_text_sensor_->publish_state(this->serial_number_);
477 this->serial_number_[0] = '\0';
478 }
479 if (this->serial_unreadable_) {
480 this->serial_unreadable_ = false;
481 ESP_LOGW(TAG, "Unreadable serial number");
482 }
483 // Checked first: the buffer then holds raw bytes, not text.
484 if (this->firmware_unreadable_) {
485 this->firmware_unreadable_ = false;
486 const uint8_t len = this->firmware_unreadable_len_;
487 // All zeros: the motor does not report a version (index B1 seen).
488 if (len == 2 * FIRMWARE_REGS &&
489 std::all_of(this->firmware_version_, this->firmware_version_ + len, [](char c) { return c == '\0'; })) {
490 ESP_LOGD(TAG, "Motor does not report its firmware version");
491 } else {
492 char hex[format_hex_size(2 * FIRMWARE_REGS)];
493 ESP_LOGW(TAG, "Unreadable firmware version (%u bytes): %s", len,
494 format_hex_to(hex, reinterpret_cast<const uint8_t *>(this->firmware_version_), len));
495 }
496 this->firmware_version_[0] = '\0';
497 }
498 if (this->version_text_sensor_ != nullptr && this->firmware_version_[0] != '\0') {
499 this->version_text_sensor_->publish_state(this->firmware_version_);
500 this->firmware_version_[0] = '\0';
501 }
502 if (this->identity_unanswered_ != 0) {
503 ESP_LOGW(TAG, "No usable %s received",
504 this->identity_unanswered_ == REQUEST_SERIAL ? LOG_STR_LITERAL("serial number")
505 : LOG_STR_LITERAL("firmware version"));
506 this->identity_unanswered_ = 0;
507 }
508}
509#endif
510
512 // Low byte: current position.
513 const uint8_t position = static_cast<uint8_t>(value);
514 if (this->position_raw_ == position)
515 return;
516
517 this->position_raw_ = position;
519 // Until the door actually travels the way it was told to, its position says nothing about the target.
520 if (!this->has_target_() || !this->target_started_)
521 return;
522
523 // The door only knows "open" and "close", so a half-open target is reached by stopping it on the way.
524 const bool reached = this->target_direction_ == DoorState::OPENING
525 ? this->current_position_ >= this->target_position_
526 : this->current_position_ <= this->target_position_;
527 if (reached)
528 this->stop_door();
529}
530
532 // The low byte is part of the state for 0x00, so the whole register has to be compared, not just the high byte.
533 const uint16_t previous = this->prev_state_reg_;
534 this->prev_state_reg_ = value;
535 if (previous == value)
536 return;
537
538 const uint8_t state = value >> 8;
539 if (state == 0x00) {
540 // Low byte 0x61 marks the door resting in the vent position, anything else a plain stop.
541 this->set_door_state_((value & 0x00FF) == 0x61 ? DoorState::VENT : DoorState::STOPPED);
542 return;
543 }
544 for (const auto &mapping : DOOR_STATE_MAPPINGS) {
545 if (mapping.code == state) {
546 this->set_door_state_(mapping.state);
547 return;
548 }
549 }
550 // The low byte can change on its own, so only report a state we cannot decode once.
551 if (state != (previous >> 8)) {
552 ESP_LOGW(TAG, "Unknown door state 0x%02X", state);
553 }
554}
555
556// Low byte of register 6: bit 0x10 is the lamp, bit 0x04 the relay. The reference implementation records
557// 0x00, 0x04, 0x10 and 0x14, so only the lamp bit decides here. In the high byte, Hoermann's own bus accessory
558// treats either bit of 0x30 as an actuator error; what sets them is not known.
560 this->set_light_seen_(true);
561 this->set_light_on_((value & 0x0010) != 0);
562 const bool actuator_error = (value & 0x3000) != 0;
563#ifdef USE_BINARY_SENSOR
564 // Unknown until first reported, then kept like the other entities here while the bus is quiet.
565 PUBLISH_STATE(this->actuator_error_binary_sensor_, actuator_error);
566#endif
567 if (this->actuator_error_ == actuator_error)
568 return;
569 this->actuator_error_ = actuator_error;
570 if (actuator_error) {
571 ESP_LOGW(TAG, "Motor reports an actuator error (0x%04X)", value);
572 } else {
573 ESP_LOGI(TAG, "Actuator error cleared");
574 }
575}
576
578 if (!this->valid_) {
579 // Queueing now would fire the command whenever the controller comes back, which may be much later.
580 ESP_LOGW(TAG, "Not connected to the bus controller, dropping '%s' command", command.name);
581 return false;
582 }
583 // A stop still waiting for a door that has come to rest would be dropped at the fetch anyway.
584 if (this->next_command_ == &COMMAND_STOP)
585 this->next_command_ = nullptr;
586 if (this->next_command_ != nullptr) {
587 ESP_LOGW(TAG, "Previous command not yet fetched by the bus controller");
588 return false;
589 }
590 // A new command supersedes any half-open target the door was still travelling to.
591 this->clear_target_();
592 this->next_command_ = &command;
593 this->command_queued_at_ = millis();
594 return true;
595}
596
597bool HoermannHcp::is_moving_or_starting_() const { return this->starting_ || is_moving(this->door_state_); }
598
600 // Only stopped, so it is never reversed at speed. take_command_() drops one queued before the door started the same
601 // way.
602 if (this->is_moving_or_starting_())
603 return this->stop_door();
604 return this->queue_command_(command);
605}
606
607bool HoermannHcp::open_door() { return this->command_door_(COMMAND_OPEN); }
608bool HoermannHcp::close_door() { return this->command_door_(COMMAND_CLOSE); }
609bool HoermannHcp::impulse_door() { return this->command_door_(COMMAND_IMPULSE); }
610bool HoermannHcp::vent_door() { return this->command_door_(COMMAND_VENT); }
611bool HoermannHcp::half_open_door() { return this->command_door_(COMMAND_HALF_OPEN); }
612bool HoermannHcp::stop_door() {
613 this->clear_target_();
614 // A stop outranks whatever is still waiting, so a door at rest does not start after the user pressed stop.
615 if (this->next_command_ != nullptr && this->next_command_ != &COMMAND_STOP) {
616 ESP_LOGD(TAG, "Stop cancels the unfetched '%s' command", this->next_command_->name);
617 this->next_command_ = nullptr;
618 }
619 if (!this->is_moving_or_starting_())
620 return true;
621 if (!this->valid_) {
622 ESP_LOGW(TAG, "Not connected to the bus controller, dropping 'stop' command");
623 return false;
624 }
625 if (this->next_command_ == &COMMAND_STOP)
626 return true;
627 if (this->stop_sent_ && millis() - this->last_stop_at_ < STOP_LOCK_MS) {
628 ESP_LOGD(TAG, "Door already stopping, ignoring stop");
629 return true;
630 }
631 this->next_command_ = &COMMAND_STOP;
632 this->command_queued_at_ = millis();
633 return true;
634}
635
636bool HoermannHcp::set_position(float position) {
637 // The first and last movement segments are inconsistent on some doors, so snap to fully open/closed.
638 if (position <= CLOSE_POSITION_THRESHOLD)
639 return this->close_door();
640 if (position >= OPEN_POSITION_THRESHOLD)
641 return this->open_door();
642 // Asking the door to travel to where it already is, or anywhere while it moves, means stopping it.
643 if (position == this->current_position_ || this->is_moving_or_starting_())
644 return this->stop_door();
645
646 // The door itself has no notion of a target, so it is started in the right direction and stopped on the way.
647 const bool opening = position > this->current_position_;
648 if (!this->queue_command_(opening ? COMMAND_OPEN : COMMAND_CLOSE))
649 return false;
651 this->target_queued_at_ = millis();
653 return true;
654}
655
657 this->last_response_ = millis();
658 this->set_valid_(true);
659}
660
662 if (this->valid_ == valid)
663 return;
664 this->valid_ = valid;
665 this->changed_ = true;
666 if (valid) {
667 ESP_LOGI(TAG, "Bus controller connected");
668 return;
669 }
670 ESP_LOGW(TAG, "Bus controller connection lost (no request for %" PRIu32 "ms)", millis() - this->last_response_);
671 // Drop what the controller never fetched, so it neither blocks later commands nor fires on reconnect.
672 this->drop_command_();
673 this->starting_ = false;
674 this->clear_light_request_();
675 // The lamp can be switched at the door while the bus is quiet, so what was last read is no longer trusted.
676 this->set_light_seen_(false);
677 // The same holds for the door. The next broadcast is decoded even if it repeats the last one.
678 this->door_state_seen_ = false;
679 this->prev_state_reg_ = 0xFFFF;
680 this->short_broadcast_logged_ = false;
681}
682
684 this->next_command_ = nullptr;
685 this->clear_target_();
686}
687
689 // The first state may equal the default, so being seen is a change of its own.
690 if (!this->door_state_seen_) {
691 this->door_state_seen_ = true;
692 this->changed_ = true;
693 }
694 // Only moving or the command's destination answers it, even as a first report that changes nothing.
695 if (this->starting_ && (is_moving(state) || at_destination(*this->start_command_, state))) {
696 // A stop held for the start is due now, so its fetch deadline starts here.
697 if (this->next_command_ == &COMMAND_STOP)
698 this->command_queued_at_ = millis();
699 this->starting_ = false;
700 }
701 if (this->door_state_ == state)
702 return;
703 this->door_state_ = state;
704 this->changed_ = true;
705 if (!is_moving(state)) {
706 // A door at rest cannot be restarted by a second stop, as stop_door() sends nothing then.
707 this->stop_sent_ = false;
708 }
710 if (!this->has_target_())
711 return;
712 if (state == this->target_direction_) {
713 this->target_started_ = true;
714 } else if (this->target_started_ && !is_moving(state)) {
715 // The door came to rest without reaching the target, so the request it belonged to is over.
716 this->clear_target_();
717 }
718}
719
721 // Doors do not always park at exactly 0 or 200, and Cover::is_fully_closed() is an exact comparison, so
722 // trust the reported end stop over the raw count.
723 float position = static_cast<float>(this->position_raw_) / 200.0f;
724 if (this->door_state_ == DoorState::CLOSED) {
725 position = 0.0f;
726 } else if (this->door_state_ == DoorState::OPEN) {
727 position = 1.0f;
728 }
729 if (this->current_position_ != position) {
730 this->current_position_ = position;
731 this->changed_ = true;
732 }
733}
734
736 this->target_position_ = 0.0f;
737 this->target_started_ = false;
738}
739
741 if (this->light_on_ == on)
742 return;
743 this->light_on_ = on;
744 this->changed_ = true;
745 if (!this->light_requested_) {
746 ESP_LOGD(TAG, "Lamp %s at the door", ONOFF(on));
747 return;
748 }
749 if (on == this->light_target_) {
750 this->clear_light_request_();
751 return;
752 }
753 // Switched away from the target while the command was out: send again.
754 this->light_command_sent_ = false;
755 this->light_since_ = millis();
756}
757
758bool HoermannHcp::set_light(bool on) {
759 // A known lamp implies a live connection.
760 if (!this->light_seen_)
761 return false;
762 this->light_target_ = on;
763 const bool was_requested = this->light_requested_;
764 // A sent command may still switch it away.
765 this->light_requested_ = on != this->light_on_ || this->light_command_sent_;
766 // The deadline belongs to the request, so more taps cannot keep it alive.
767 if (!was_requested)
768 this->light_since_ = millis();
769 this->changed_ = true;
770 return true;
771}
772
774 if (!this->light_requested_)
775 return;
776 this->light_requested_ = false;
777 this->light_command_sent_ = false;
778 this->changed_ = true;
779}
780
782 if (this->light_seen_ == seen)
783 return;
784 this->light_seen_ = seen;
785 if (!seen)
786 this->clear_light_request_();
787 // A resting door changes nothing else, so without this the light would never hear about it.
788 this->changed_ = true;
789}
790
791} // namespace esphome::hoermann_hcp
virtual void update()=0
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:304
size_t size() const
Definition helpers.h:373
void push_back(const T &value)
Definition helpers.h:343
bool command_door_(const HoermannHcpCommand &command)
void set_door_state_(DoorState state)
uint8_t take_identity_transfer_(const modbus::RegisterValues &registers)
CallbackManager< void()> state_callback_
const HoermannHcpCommand * take_command_()
void arm_identity_request_(IdentityPhase phase)
const HoermannHcpCommand * next_command_
void push_command_registers_(modbus::RegisterValues &registers)
void add_identity_request_(modbus::RegisterValues &registers, uint16_t command)
const HoermannHcpCommand * start_command_
char firmware_version_[2 *FIRMWARE_REGS+1]
void push_transfer_answer_(modbus::RegisterValues &registers, uint16_t number_of_registers)
const HoermannHcpCommand * take_light_command_()
bool queue_command_(const HoermannHcpCommand &command)
void on_position_reg_(uint16_t value)
char serial_number_[2 *(SERIAL_FIRST_HALF_REGS+SERIAL_SECOND_HALF_REGS)+1]
float position
Definition cover.h:0
bool state
Definition fan.h:2
std::vector< uint8_t > & out
Definition gif.cpp:49
unsigned count
Definition gif.cpp:51
ESPHOME_LOG_TAG(TAG, "hoermann_hcp.binary_sensor")
StaticVector< uint16_t, MAX_NUM_OF_REGISTERS_TO_READ > RegisterValues
Definition modbus.h:337
std::optional< ExceptionCode > ResponseStatus
Definition modbus.h:329
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
Definition helpers.h:1661
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
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:428
bool valid
static void uint32_t