DebenOldert 6 mesi fa
parent
commit
6a91260217

+ 3 - 4
custom_components/odido_klikklaar/__init__.py

@@ -44,12 +44,11 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: RouterConfigEntry
 
     # Perform an initial data load from api.
     # async_config_entry_first_refresh() is special in that it does not log errors if it fails
-    if not await coordinator.api.async_login():
-        raise ConfigEntryNotReady
+    await coordinator.async_config_entry_first_refresh()
     
     # Create the device
-    di = await coordinator.api.async_query_api(oid=EP_DEVICESTATUS)
-    coordinator.device_info = DeviceInfo()
+    # di = await coordinator.api.async_query_api(oid=EP_DEVICESTATUS)
+    # coordinator.device_info = DeviceInfo()
 
     # Initialise a listener for config flow options changes.
     # This will be removed automatically if the integration is unloaded.

+ 41 - 27
custom_components/odido_klikklaar/api.py

@@ -44,18 +44,28 @@ class RouterAPI:
             self.pwd.encode('utf-8')).decode('utf-8')
         
         _LOGGER.warning(str(payload))
+        _LOGGER.warning(f'{API_SCHEMA}://{self.host}{API_LOGIN_PATH}')
 
-        response = await self.session.post(
-            f'{API_SCHEMA}://{self.host}{API_LOGIN_PATH}',
-            json=payload)
+        try:
+
+            response = await self.session.post(
+                f'{API_SCHEMA}://{self.host}{API_LOGIN_PATH}',
+                json=payload)
         
-        if response.ok:
-            _LOGGER.warning(await response.text)
+        except Exception as e:
+            _LOGGER.error(f'Could not connect to router. {e}')
+            raise RouterAPIConnectionError(
+                f'Error connecting to router. {e}')
             
+        if response.status == 401:
+            raise RouterAPIAuthError('Username or password incorrect.')
+
+        if response.ok:
+            _LOGGER.warning(await response.text())
+
             try:
                 data = await response.json()
 
-
                 if 'result' in data:
                     if data['result'] == VAL_SUCCES:
                         return True
@@ -67,38 +77,42 @@ class RouterAPI:
             except Exception as json_exception:
                 raise RouterAPIInvalidResponse(f'Unable to decode login response') \
                     from json_exception
-            
-        raise RouterAPIConnectionError(
-            f'Error connecting to router. Status: {response.status}')
+        else:
+            raise RouterAPIInvalidResponse(f'Unknown status {response.status}')
     
     async def async_query_api(self,
                               oid: str) -> dict:
         """Query an authenticated API endpoint"""
-        try:
-            async with asyncio.timeout(API_TIMEOUT):
+        async with asyncio.timeout(API_TIMEOUT):
+            try:
                 response = await self.session.get(
                     f'{API_SCHEMA}://{self.host}{API_BASE_PATH}',
                     params={'oid': oid})
+            except Exception as exception:
+                raise RouterAPIConnectionError('Unable to connect to router API') \
+                    from exception
+            
+            if response.status == 401:
+                raise RouterAPIAuthError('Unauthenticated request. Did the username or password change')
 
-                if response.ok:
-                    try:
-                        data: dict = await response.json()
+            if response.ok:
+                try:
+                    data: dict = await response.json()
 
-                        if data.get(KEY_RESULT, None) == VAL_SUCCES:
-                            return data.get(KEY_OBJECT, [{}])[0]
-                        else:
-                            raise RouterAPIInvalidResponse(f'Response returned error')
+                    if data.get(KEY_RESULT, None) == VAL_SUCCES:
+                        _LOGGER.warning(data.get(KEY_OBJECT, [{}]))
+                        return data.get(KEY_OBJECT, [{}])[0]
+                    else:
+                        raise RouterAPIInvalidResponse(f'Response returned error')
 
-                    except Exception as json_exception:
-                        raise RouterAPIInvalidResponse(f'Unable to decode JSON') \
-                            from json_exception
-                else:
-                    raise RouterAPIConnectionError(
-                        f'Error retrieving API. Status: {response.status}')
+                except Exception as json_exception:
+                    raise RouterAPIInvalidResponse(f'Unable to decode JSON') \
+                        from json_exception
+            else:
+                raise RouterAPIConnectionError(
+                    f'Error retrieving API. Status: {response.status}')
 
-        except Exception as exception:
-            raise RouterAPIConnectionError('Unable to connect to router API') \
-                from exception
+        
 
 
     @property

+ 1 - 1
custom_components/odido_klikklaar/config_flow.py

@@ -73,7 +73,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,
     except RouterAPIConnectionError as err:
         raise CannotConnect from err
     
-    return {"title": f"Odido Klik & Klaar router - {data[CONF_HOST]}"}
+    return {"title": data[CONF_HOST]}
 
 
 class RouterConfigFlow(ConfigFlow, domain=DOMAIN):

+ 5 - 0
custom_components/odido_klikklaar/coordinator.py

@@ -98,11 +98,15 @@ class RouterCoordinator(DataUpdateCoordinator):
                     *[self.api.async_query_api(oid=endpoint) for endpoint in endpoints],
                     return_exceptions=True)
                 
+                _LOGGER.debug(results)
+                
                 data = {
                     endpoints[i]: results[i]
                     for i in len(endpoints)
                 }
 
+                _LOGGER.debug(data)
+                
                 info = data[EP_DEVICESTATUS]['DeviceInfo']
 
                 self.device_info = DeviceInfo(
@@ -124,6 +128,7 @@ class RouterCoordinator(DataUpdateCoordinator):
             raise UpdateFailed(err) from err
         except Exception as err:
             # This will show entities as unavailable by raising UpdateFailed exception
+            _LOGGER.error(err)
             raise UpdateFailed(f"Error communicating with API: {err}") from err
 
         # # What is returned here is stored in self.data by the DataUpdateCoordinator