Skip to content

Commit

Permalink
v0.7.5
Browse files Browse the repository at this point in the history
  • Loading branch information
gvigroux committed Jan 12, 2025
1 parent 002165c commit c8192cb
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 38 deletions.
19 changes: 12 additions & 7 deletions custom_components/freebox_home/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
from homeassistant.helpers import config_validation as cv, discovery
from homeassistant.core import HomeAssistant

from freebox_api.exceptions import AuthorizationError, HttpRequestError

from .const import DOMAIN, PLATFORMS
from .router import (FreeboxRouter, get_api)
from .router import (FreeboxRouter, get_api, remove_config)

_LOGGER = logging.getLogger(__name__)

Expand All @@ -28,19 +30,21 @@ async def blocking_calls(hass, api, entry):
hass.data[DOMAIN][entry.unique_id] = router
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

async def test(hass, api, entry):
await api.open(entry.data[CONF_HOST], entry.data[CONF_PORT])


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Freebox component."""

api = await get_api(hass, entry.data[CONF_HOST])
router = None
try:
await api.open(entry.data[CONF_HOST], entry.data[CONF_PORT])
api = await get_api(hass, entry.data[CONF_HOST], entry.data[CONF_PORT])
fbx_config = await api.system.get_config()
#await hass.async_add_executor_job(blocking_calls, hass, api, entry)
except HttpRequestError as err:
raise ConfigEntryNotReady from err
except:
_LOGGER.error("Unable to connect to the Freebox")

fbx_config = await api.system.get_config()
router = FreeboxRouter(hass, entry, api, fbx_config)
await router.update_all()

Expand Down Expand Up @@ -70,7 +74,8 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
)
if unload_ok:
router = hass.data[DOMAIN].pop(entry.unique_id)
# No need to remove the old file because I will clean when we recreate the entry again (and no need to get a new credential if it's working)
#await remove_config(hass, entry.data[CONF_HOST])
await router.close()
await router.remove_config(hass, entry.data[CONF_HOST])

return unload_ok
22 changes: 10 additions & 12 deletions custom_components/freebox_home/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from homeassistant.data_entry_flow import AbortFlow

from .const import DOMAIN
from .router import get_api, remove_config
from .router import get_api

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -68,13 +68,12 @@ async def async_step_link(self, user_input=None):
return self.async_show_form(step_id="link")

errors = {}
fbx = await get_api(self.hass, self._host)

try:
# Open connection and check authentication
await fbx.open(self._host, self._port)
# Open connection, check authentication and permissions
fbx = await get_api(self.hass, self._host, self._port)

# Check permissions
# Wait
await fbx.system.get_config()
await self.hass.async_block_till_done()

Expand All @@ -92,8 +91,8 @@ async def async_step_link(self, user_input=None):
except AuthorizationError as error:
# Config file may be wrong, I will delete IT.
_LOGGER.error("AuthorizationError: %s", error)
await remove_config(self.hass, self._host)
_LOGGER.error("The current configuration file is invalid. It has been deleted. Please retry")
#await remove_config(self.hass, self._host)
#_LOGGER.error("The current configuration file is invalid. It has been deleted. Please retry")
errors["base"] = "register_failed"

except HttpRequestError:
Expand All @@ -110,11 +109,9 @@ async def async_step_link(self, user_input=None):
# Ask for HOME permission
async def async_step_permission(self, user_input=None):
errors = {}
fbx = await get_api(self.hass, self._host)
try:
await fbx.open(self._host, self._port)
fbx = await get_api(self.hass, self._host, self._port)
await fbx.home.get_home_nodes()
await fbx.close()

return self.async_create_entry(
title=self._host,
Expand All @@ -128,8 +125,9 @@ async def async_step_permission(self, user_input=None):
except Exception:
_LOGGER.exception("Unknown error connecting with Freebox router at %s", self._host)
errors["base"] = "unknown"

await fbx.close()
finally:
await fbx.close()

return self.async_show_form(step_id="permission", errors=errors)


Expand Down
4 changes: 2 additions & 2 deletions custom_components/freebox_home/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
"config_flow": true,
"documentation": "https://github.com/gvigroux/freebox_home",
"issue_tracker": "https://github.com/gvigroux/freebox_home/issues",
"requirements": ["freebox-api==1.2.2"],
"requirements": ["freebox-api"],
"dependencies": ["ffmpeg"],
"after_dependencies": ["zeroconf"],
"zeroconf": ["_fbx-api._tcp.local."],
"codeowners": ["gvigroux"],
"version": "0.7.4"
"version": "0.7.5"
}
41 changes: 24 additions & 17 deletions custom_components/freebox_home/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from typing import Any, Dict, Optional

from freebox_api import Freepybox
from freebox_api.exceptions import HttpRequestError
from freebox_api.exceptions import AuthorizationError, HttpRequestError, InsufficientPermissionsError

from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.exceptions import ConfigEntryNotReady
Expand All @@ -29,10 +29,8 @@ def __init__(self, hass, entry, api, fbx_config) -> None:
self._host = entry.data[CONF_HOST]
self._port = entry.data[CONF_PORT]
self._api = api
self.mac = None

self.nodes: Dict[str, Any] = {}
#self._unsub_dispatcher = None

# System
self.mac = "FbxHome_" + fbx_config["mac"]
Expand Down Expand Up @@ -64,7 +62,12 @@ def __init__(self, hass, entry, api, fbx_config) -> None:

async def update_all(self, now: Optional[datetime] = None) -> None:
"""Update all nodes"""
fbx_nodes: Dict[str, Any] = await self._api.home.get_home_nodes()
try:
fbx_nodes: Dict[str, Any] = await self._api.home.get_home_nodes()
except InsufficientPermissionsError as error:
_LOGGER.error("InsufficientPermissionsError: You need to browse http://mafreebox.freebox.fr/#Fbx.os.app.settings.Accounts and grant the access policy: \"Gestion de l'alarme et maison connectée\"")
return

for fbx_node in fbx_nodes:
if( fbx_node["category"] not in ["pir","camera","alarm","dws","kfb","basic_shutter","shutter"] ):
_LOGGER.warning("Node not supported: \n" +str(fbx_node))
Expand All @@ -80,26 +83,30 @@ async def close(self) -> None:
self._api = None


#async def get_api(hass, host: str) -> Freepybox:
# """Get the Freebox API."""
# #freebox_path = Path(hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY).path)
# freebox_path = Path(Store(hass, STORAGE_VERSION, STORAGE_KEY).path)
# freebox_path.mkdir(exist_ok=True)
#
# token_file = Path(f"{freebox_path}/{slugify(host)}.conf")
# return Freepybox(APP_DESC, token_file, API_VERSION)


async def get_api(hass, host: str) -> Freepybox:
async def get_api(hass, host: str, port, retry = 0):
"""Get the Freebox API."""
freebox_path = Store(hass, STORAGE_VERSION, STORAGE_KEY).path

if not os.path.exists(freebox_path):
await hass.async_add_executor_job(os.makedirs, freebox_path)

token_file = Path(f"{freebox_path}/{slugify(host)}.conf")

return Freepybox(APP_DESC, token_file, api_version="latest")
api = Freepybox(APP_DESC, token_file, api_version="latest")

try:
await api.open(host, port)
await api.system.get_config()
except AuthorizationError as error:
_LOGGER.error("AuthorizationError: Please accept the application authorization on your Freebox screen")
if( retry != 0 ):
raise error
await remove_config(hass, host)
return await get_api(hass, host, port, 1)
except InsufficientPermissionsError as error:
_LOGGER.error("InsufficientPermissionsError: You need to browse http://mafreebox.freebox.fr/#Fbx.os.app.settings.Accounts and grant the access policy: \"Gestion de l'alarme et maison connectée\"")
raise error

return api


async def remove_config(hass, host: str):
Expand Down

0 comments on commit c8192cb

Please sign in to comment.