# DDR-0024: Session State Machine, Timeouts, and Reconnect Strategy

Status: Approved
Date: 2025-12-22
Applies to: elkm1/elke27_lib (E27 only)

Related ADRs:
- ADR-0004: E27 Transport and Session Model
- ADR-0007: Error Handling and Recovery Philosophy

Related DDRs:
- DDR-0020: Silent Failure Behavior on Invalid Credentials
- DDR-0022: Session Lifecycle and Framed vs Unframed Traffic Handling
- DDR-0023: Provisioning Flow and Home Assistant Credential Exchange

---

Context

The Elk E27 protocol operates over TCP but does not provide explicit error responses for many failure modes. In particular:
- Invalid credentials result in no response
- Framing or encryption errors result in dropped packets
- Session expiration is implicit and time-based

A robust session state machine is required to ensure recovery without user intervention where possible.

---

Decision

The E27 implementation SHALL use an explicit session state machine managed by session.py.

Defined session states:

- DISCONNECTED
- CONNECTING
- DISCOVERING
- LINKING
- HELLO
- AUTHENTICATED
- ERROR
- PROVISIONING_REQUIRED

---

Timeout and Recovery Rules

- Each state SHALL have a bounded timeout
- On timeout:
  - DISCOVERING → reconnect
  - LINKING → transition to PROVISIONING_REQUIRED
  - HELLO → reconnect
  - AUTHENTICATED → reconnect and re-HELLO

- CRC or decryption errors SHALL NOT immediately tear down the session
- Repeated framing or crypto failures MAY trigger reconnect

---

Reconnect Strategy

- TCP reconnects SHALL use exponential backoff
- Link credentials SHALL be reused if present
- API_LINK SHALL NOT be retried automatically if credentials are known to be invalid
- Provisioning SHALL be user-driven via Home Assistant

---

Rationale

This approach:
- Prevents infinite retry loops on invalid credentials
- Minimizes unnecessary user prompts
- Allows stable long-running operation
- Matches the behavior of physical keypads and official clients

Explicit session states improve debuggability and correctness.

---

Consequences

- session.py is the single authority for connection lifecycle
- All lower layers are stateless with respect to reconnects
- Home Assistant integration can surface meaningful state to the user

This decision is binding for all E27 session management and recovery logic.
