Refactor sync function to be more DRY and easier to extend (#50)

Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Marius Muja 2023-09-18 11:18:13 -07:00 committed by GitHub
parent e285003944
commit d2ae60e6ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 22 additions and 18 deletions

View File

@ -436,30 +436,34 @@ namespace ratgdo {
void RATGDOComponent::sync() void RATGDOComponent::sync()
{ {
// increment rolling code counter by some amount in case we crashed without writing to flash the latest value auto sync_step = [=]() {
this->increment_rolling_code_counter(MAX_CODES_WITHOUT_FLASH_WRITE); if (*this->door_state == DoorState::UNKNOWN) {
this->send_command(Command::GET_STATUS);
return RetryResult::RETRY;
}
if (*this->openings == 0) {
this->send_command(Command::GET_OPENINGS);
return RetryResult::RETRY;
}
return RetryResult::DONE;
};
const uint8_t MAX_ATTEMPTS = 10;
set_retry( set_retry(
500, 10, [=](uint8_t r) { 500, MAX_ATTEMPTS, [=](uint8_t r) {
if (*this->door_state != DoorState::UNKNOWN) { // have status auto result = sync_step();
if (*this->openings != 0) { // have openings if (result == RetryResult::RETRY) {
return RetryResult::DONE; if (r == MAX_ATTEMPTS-2 && *this->door_state == DoorState::UNKNOWN) { // made a few attempts and no progress (door state is the first sync request)
} else { // increment rolling code counter by some amount in case we crashed without writing to flash the latest value
if (r == 0) { // failed to sync probably rolling counter is wrong, notify this->increment_rolling_code_counter(MAX_CODES_WITHOUT_FLASH_WRITE);
ESP_LOGD(TAG, "Triggering sync failed actions.");
this->sync_failed = true;
};
this->send_command(Command::GET_OPENINGS);
return RetryResult::RETRY;
} }
} else { if (r == 0) {
if (r == 0) { // failed to sync probably rolling counter is wrong, notify // this was last attempt, notify of sync failure
ESP_LOGD(TAG, "Triggering sync failed actions."); ESP_LOGD(TAG, "Triggering sync failed actions.");
this->sync_failed = true; this->sync_failed = true;
}; }
this->send_command(Command::GET_STATUS);
return RetryResult::RETRY;
} }
return result;
}, },
1.5f); 1.5f);
} }