Skip to content

Commit 09db5b0

Browse files
authored
Merge pull request #233 from CoMPaTech/dnsdebug
DNS Debugging
2 parents ebd5f22 + 1910a7b commit 09db5b0

File tree

6 files changed

+42
-12
lines changed

6 files changed

+42
-12
lines changed

custom_components/stromer/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from .const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, DOMAIN, LOGGER
1212
from .coordinator import StromerDataUpdateCoordinator
13-
from .stromer import ApiError, Stromer
13+
from .stromer import ApiError, NextLocationError, Stromer
1414

1515
SCAN_INTERVAL = timedelta(minutes=10)
1616

@@ -42,6 +42,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
4242
await stromer.stromer_connect()
4343
except ApiError as ex:
4444
raise ConfigEntryNotReady("Error while communicating to Stromer API") from ex
45+
except NextLocationError as ex:
46+
raise ConfigEntryNotReady("Error while getting authentication location %s", ex) from ex
4547

4648
# Ensure migration from v3 single bike
4749
if "bike_id" not in entry.data:

custom_components/stromer/config_flow.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from homeassistant.exceptions import HomeAssistantError
1313

1414
from .const import BIKE_DETAILS, CONF_CLIENT_ID, CONF_CLIENT_SECRET, DOMAIN, LOGGER
15-
from .stromer import Stromer
15+
from .stromer import ApiError, NextLocationError, Stromer
1616

1717
STEP_USER_DATA_SCHEMA = vol.Schema(
1818
{
@@ -32,9 +32,17 @@ async def validate_input(_: HomeAssistant, data: dict[str, Any]) -> dict:
3232
client_secret = data.get(CONF_CLIENT_SECRET, None)
3333

3434
# Initialize connection to stromer to validate credentials
35-
stromer = Stromer(username, password, client_id, client_secret)
36-
if not await stromer.stromer_connect():
35+
try:
36+
stromer = Stromer(username, password, client_id, client_secret)
37+
connected: bool = await stromer.stromer_connect()
38+
except ApiError as ex:
39+
raise CannotConnect("Error while connecting to Stromer API %s", ex) from ex
40+
except NextLocationError as ex:
41+
raise CannotConnect("Error while getting authentication location %s", ex) from ex
42+
43+
if not connected:
3744
raise InvalidAuth
45+
3846
LOGGER.debug("Credentials validated successfully")
3947

4048
# All bikes information available

custom_components/stromer/coordinator.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
77

88
from .const import DOMAIN, LOGGER
9-
from .stromer import ApiError, Stromer
9+
from .stromer import ApiError, NextLocationError, Stromer
1010

1111

1212
class StromerData(NamedTuple):
@@ -42,8 +42,10 @@ async def _async_update_data(self) -> StromerData:
4242
data = [bike_data, self.stromer.bike_id, self.stromer.bike_name]
4343
LOGGER.debug("Stromer data %s updated", data)
4444

45-
except ApiError as err:
46-
raise UpdateFailed(f"Error communicating with API: {err}") from err
47-
except Exception as err:
48-
raise ConfigEntryAuthFailed from err
45+
except ApiError as ex:
46+
raise UpdateFailed(f"Error communicating with API: {ex}") from ex
47+
except NextLocationError as ex:
48+
raise UpdateFailed("Error while getting authentication location %s", ex) from ex
49+
except Exception as ex:
50+
raise ConfigEntryAuthFailed from ex
4951
return StromerData(*data) # type: ignore [arg-type]

custom_components/stromer/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@
88
"iot_class": "cloud_polling",
99
"issue_tracker": "https://github.com/CoMPaTech/stromer/issues",
1010
"requirements": [],
11-
"version": "0.4.2"
11+
"version": "0.4.3"
1212
}

custom_components/stromer/stromer.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,23 @@ async def stromer_get_code(self) -> None:
170170
url, data=data, headers={"Referer": url}, allow_redirects=False
171171
)
172172
next_loc = res.headers.get("Location")
173+
if not next_loc:
174+
LOGGER.debug("No next location returned from Stromer API. Full response details:")
175+
LOGGER.debug(" **DONT DOX BY SHARING** Full Request-Data: %s", data)
176+
LOGGER.debug(" **SHARE RESPONSIBLY ** Full Partial-Data: %s", data["next"])
177+
LOGGER.debug(" Status: %s", res.status)
178+
LOGGER.debug(" Headers: %s", dict(res.headers))
179+
try:
180+
body_text = await res.text()
181+
LOGGER.debug(" Body: %s", body_text)
182+
except Exception as err:
183+
raise NextLocationError("Unable to provide body information from Stromer API") from err
184+
raise NextLocationError("No next location returned from Stromer API") from None
185+
173186
next_url = f"{self.base_url}{next_loc}"
187+
if not (next_loc.startswith("/") or next_loc.startswith("?")):
188+
raise NextLocationError(f"Invalid next location: '{next_loc}'. Expected start with '/' or '?'.")
189+
174190
res = await self._websession.get(next_url, allow_redirects=False)
175191
self._code = res.headers.get("Location")
176192
self._code = self._code.split("=")[1] # type: ignore[union-attr]
@@ -258,3 +274,6 @@ async def stromer_call_api(self, endpoint: str, full=False) -> Any:
258274

259275
class ApiError(Exception):
260276
"""Error to indicate something wrong with the API."""
277+
278+
class NextLocationError(Exception):
279+
"""Error to indicate something wrong returned in next location."""

pyproject.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ lint.select = [
6969
"TID251", # Banned imports
7070
"TRY004", # Prefer TypeError exception for invalid type
7171
"B904", # Use raise from to specify exception cause # warning: `TRY200` has been remapped to `B904`.
72-
"TRY302", # Remove exception handler; error is immediately re-raised
72+
"TRY203", # Remove exception handler; error is immediately re-raised
7373
"UP", # pyupgrade
7474
"W", # pycodestyle
7575
]
@@ -93,7 +93,6 @@ lint.ignore = [
9393
"UP006", # keep type annotation style as is
9494
"UP007", # keep type annotation style as is
9595
# Ignored due to performance: https://github.com/charliermarsh/ruff/issues/2923
96-
"UP038", # Use `X | Y` in `isinstance` call instead of `(X, Y)`
9796
]
9897

9998
[tool.ruff.lint.flake8-import-conventions.extend-aliases]

0 commit comments

Comments
 (0)