|
19 | 19 | GUIDE_PRESETS_F = (180, 195, 200, 205, 212) |
20 | 20 |
|
21 | 21 |
|
| 22 | +class KettleTimeoutError(Exception): |
| 23 | + """Raised when the kettle's HTTP server doesn't respond in time. |
| 24 | +
|
| 25 | + The kettle briefly stops answering HTTP requests when it transitions |
| 26 | + to Off (and occasionally at other points), so callers can treat this |
| 27 | + as a transient condition rather than a hard failure. |
| 28 | + """ |
| 29 | + |
| 30 | + |
22 | 31 | @dataclass |
23 | 32 | class KettleState: |
24 | 33 | """Represents the current state of the kettle""" |
@@ -89,17 +98,39 @@ def __init__(self, host: str = "10.1.1.177", port: int = 80): |
89 | 98 | self.session = requests.Session() |
90 | 99 | self.session.headers.update({'User-Agent': 'StaggEKG-HA/1.0'}) |
91 | 100 |
|
92 | | - def _send_command(self, cmd: str) -> str: |
93 | | - """Send a CLI command to the kettle""" |
| 101 | + def _send_command(self, cmd: str, retries: int = 2) -> str: |
| 102 | + """Send a CLI command to the kettle, retrying on timeout. |
| 103 | +
|
| 104 | + The kettle's HTTP server goes unresponsive for several seconds |
| 105 | + during mode transitions (especially when turning off), so a single |
| 106 | + read timeout is not a reliable signal that anything is wrong. |
| 107 | + Retries swallow that window; if the kettle is still unresponsive |
| 108 | + after the final attempt, raise KettleTimeoutError so callers can |
| 109 | + distinguish it from other request failures. |
| 110 | + """ |
94 | 111 | url = f"{self.base_url}/cli" |
95 | 112 | params = {"cmd": cmd} |
96 | 113 |
|
97 | | - try: |
98 | | - response = self.session.get(url, params=params, timeout=10) |
99 | | - response.raise_for_status() |
100 | | - return response.text |
101 | | - except requests.exceptions.RequestException as e: |
102 | | - raise Exception(f"Failed to send command '{cmd}': {e}") |
| 114 | + last_timeout: Optional[Exception] = None |
| 115 | + for attempt in range(retries + 1): |
| 116 | + try: |
| 117 | + response = self.session.get(url, params=params, timeout=10) |
| 118 | + response.raise_for_status() |
| 119 | + return response.text |
| 120 | + except requests.exceptions.Timeout as e: |
| 121 | + last_timeout = e |
| 122 | + if attempt < retries: |
| 123 | + _LOGGER.debug( |
| 124 | + "Kettle timeout on '%s' (attempt %d/%d), retrying", |
| 125 | + cmd, attempt + 1, retries + 1, |
| 126 | + ) |
| 127 | + time.sleep(0.5) |
| 128 | + except requests.exceptions.RequestException as e: |
| 129 | + raise Exception(f"Failed to send command '{cmd}': {e}") |
| 130 | + |
| 131 | + raise KettleTimeoutError( |
| 132 | + f"Kettle did not respond to '{cmd}' after {retries + 1} attempts: {last_timeout}" |
| 133 | + ) |
103 | 134 |
|
104 | 135 | def get_state(self) -> KettleState: |
105 | 136 | """Get the current state of the kettle""" |
|
0 commit comments