Skip to content

Commit

Permalink
Added UX Config Flow and Cleanip
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffSteinbok committed Jun 27, 2023
1 parent a27a109 commit bb76450
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 166 deletions.
65 changes: 9 additions & 56 deletions custom_components/dreo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,43 +11,22 @@

from .const import (
DOMAIN,
SERVICE_UPDATE_DEVS,
DREO_DISCOVERY,
DREO_FANS,
DREO_MANAGER
)

_LOGGER = logging.getLogger("dreo")


DOMAIN = "dreo"
COMPONENT_DOMAIN = "dreo"
COMPONENT_DATA = "dreo-data"
COMPONENT_ATTRIBUTION = "Data provided by Dreo servers."
COMPONENT_BRAND = "Dreo"

CONFIG_SCHEMA = vol.Schema(
{
COMPONENT_DOMAIN: vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_REGION, default='us'): cv.string
}
),
},
extra=vol.ALLOW_EXTRA
)

async def async_setup(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:

_LOGGER.debug("async_setup")

"""Set up dreo as config entry."""
username = config_entry[COMPONENT_DOMAIN].get(CONF_USERNAME)
password = config_entry[COMPONENT_DOMAIN].get(CONF_PASSWORD)
region = config_entry[COMPONENT_DOMAIN].get(CONF_REGION)
_LOGGER.debug(username)
_LOGGER.debug(config_entry.data.get(CONF_USERNAME))
username = config_entry.data.get(CONF_USERNAME)
password = config_entry.data.get(CONF_PASSWORD)
region = "us"

from .pydreo import PyDreo
manager = PyDreo(username, password, region)
Expand All @@ -64,15 +43,11 @@ async def async_setup(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
_LOGGER.error("Unable to load devices from the dreo server")
return False

# TODO: What's the difference?
#device_dict = await hass.async_add_executor_job(async_process_devices, hass, manager)
device_dict = await async_process_devices(hass, manager)
device_dict = process_devices(manager)

# TODO: Move all of this into the manager init?
manager.start_monitoring()

#forward_setup = hass.config_entries.async_forward_entry_setup
hass.data[COMPONENT_DATA] = manager
forward_setup = hass.config_entries.async_forward_entry_setup
hass.data[DOMAIN] = {}
hass.data[DOMAIN][DREO_MANAGER] = manager

Expand All @@ -84,32 +59,10 @@ async def async_setup(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
fans.extend(device_dict[DREO_FANS])
platforms.append(Platform.FAN)

#await hass.config_entries.async_forward_entry_setups(config_entry, platforms)

async def async_new_device_discovery(service: ServiceCall) -> None:
"""Discover if new devices should be added."""
manager = hass.data[DOMAIN][DREO_MANAGER]
fans = hass.data[DOMAIN][DREO_FANS]

dev_dict = await async_process_devices(hass, manager)
fan_devs = dev_dict.get(DREO_FANS, [])

fan_set = set(fan_devs)
new_fans = list(fan_set.difference(fans))
if new_fans and fans:
fans.extend(new_fans)
async_dispatcher_send(hass, DREO_DISCOVERY.format(DREO_FANS), new_fans)
return
if new_fans and not fans:
fans.extend(new_fans)
hass.async_create_task(forward_setup(config_entry, Platform.FAN))


manager.start_monitoring()

await hass.config_entries.async_forward_entry_setups(config_entry, platforms)
return True

async def async_process_devices(hass, manager):
def process_devices(manager) -> dict:
"""Assign devices to proper component."""
devices = {}
devices[DREO_FANS] = []
Expand Down
68 changes: 68 additions & 0 deletions custom_components/dreo/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import logging
from typing import Any, Dict, Optional
from collections import OrderedDict

from homeassistant import config_entries, core
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, CONF_REGION
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_registry import (
async_entries_for_config_entry
)
from homeassistant.helpers.selector import (
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
import voluptuous as vol
from .const import *

from .pydreo import PyDreo

_LOGGER = logging.getLogger("dreo")

class DreoFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Dreo Custom config flow."""

# The schema version of the entries that it creates
# Home Assistant will call your migrate method if the version changes
VERSION = 1

def __init__(self) -> None:
"""Instantiate config flow."""
self._username = None
self._password = None
self.data_schema = OrderedDict()
self.data_schema[vol.Required(CONF_USERNAME)] = str
self.data_schema[vol.Required(CONF_PASSWORD)] = str

@callback
def _show_form(self, errors=None):
"""Show form to the user."""
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(self.data_schema),
errors=errors if errors else {},
)

async def async_step_user(self, user_input=None):
"""Handle a flow start."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")

if not user_input:
return self._show_form()

self._username = user_input[CONF_USERNAME]
self._password = user_input[CONF_PASSWORD]

manager = PyDreo(self._username, self._password, "us")
login = await self.hass.async_add_executor_job(manager.login)
if not login:
return self._show_form(errors={"base": "invalid_auth"})

return self.async_create_entry(
title=self._username,
data={CONF_USERNAME: self._username, CONF_PASSWORD: self._password},
)
16 changes: 4 additions & 12 deletions custom_components/dreo/fan.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,13 @@
)

from .basedevice import DreoBaseDeviceHA
from .const import (DOMAIN, DREO_DISCOVERY, DREO_FANS)
from .const import (DOMAIN, DREO_DISCOVERY, DREO_FANS, DREO_MANAGER)
from .pydreo.constant import *
from .pydreo.pydreofan import PyDreoFan

_LOGGER = logging.getLogger("dreo")

DEV_TYPE_TO_HA = {
"DR-HTF008S": "fan",
}

from . import (
COMPONENT_DATA
)

async def async_setup_platform(
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
Expand All @@ -41,10 +33,10 @@ async def async_setup_platform(
_LOGGER.info("Starting Dreo Fan Platform")
_LOGGER.debug("Dreo Fan:async_setup_platform")

dreoData = hass.data[COMPONENT_DATA]
manager = hass.data[DOMAIN][DREO_MANAGER]

fansHAs = []
for fanEntity in dreoData.fans:
for fanEntity in manager.fans:
fansHAs.append(DreoFanHA(fanEntity))

async_add_entities(fansHAs)
Expand Down
3 changes: 1 addition & 2 deletions custom_components/dreo/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@
"domain": "dreo",
"name": "Dreo",
"codeowners": ["@jeffsteinbok"],
"config_flow": false,
"config_flow": true,
"dependencies": [],
"documentation": "https://github.com/jeffsteinbok/hass-dreo/blob/master/README.md",
"integration_type": "hub",
"iot_class": "cloud_push",
"issue_tracker": "https://github.com/jeffsteinbok/hass-dreo/issues",
"requirements": ["websockets"],
Expand Down
Loading

0 comments on commit bb76450

Please sign in to comment.