The client can automatically restore the connection if the TCP link drops unexpectedly. When enabled, it retries with exponential backoff, re-discovers entities, and re-registers any active state subscription — with no code changes required in your application.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/richard87/esphome-apiclient/llms.txt
Use this file to discover all available pages before exploring further.
Enabling auto-reconnect
PassWithReconnect to Dial or DialWithContext with a base retry interval:
Backoff behaviour
The reconnect loop starts at the given interval, doubles after each failed attempt, and caps at 5 minutes:| Attempt | Wait (base = 10s) |
|---|---|
| 1 | 10 s |
| 2 | 20 s |
| 3 | 40 s |
| 4 | 80 s |
| … | … |
| cap | 5 min |
What happens on reconnect
- The entity registry is cleared.
- A new TCP connection is established (plain or Noise, using the original options).
ListEntitiesis called to re-populate the registry.- If a state handler was registered before the disconnect,
SubscribeStatesis called automatically with the saved handler. - The
WithOnConnectcallback fires.
Calling
Disconnect() intentionally disables the reconnect loop. The method sets the reconnect interval to zero before sending the DisconnectRequest, so the client will not attempt to reconnect after a graceful shutdown.Connection callbacks
RegisterWithOnConnect and WithOnDisconnect to react to connection state changes:
WithOnConnect fires after the initial connection and after every successful reconnect. WithOnDisconnect fires only on unexpected drops, not on intentional Disconnect() calls.
Keepalive
The client sendsPingRequest messages on a ticker to detect dead connections that the TCP layer has not yet reported as closed. This ensures the reconnect loop triggers promptly even when the network silently drops packets.
| Option | Default | Description |
|---|---|---|
WithKeepalive(interval) | 20 s | How often to send a ping. Set to 0 to disable. |
WithKeepaliveTimeout(timeout) | 10 s | How long to wait for the ping response before treating the connection as dead. |
Clean shutdown with context
UseDialWithContext with a cancellable context to stop all background goroutines (read loop, keepalive, reconnect) cleanly when your application exits: