Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ homeassistant/components/notify/* @home-assistant/core
homeassistant/components/notion/* @bachya
homeassistant/components/nsw_fuel_station/* @nickw444
homeassistant/components/nsw_rural_fire_service_feed/* @exxamalte
homeassistant/components/nuheat/* @bdraco
homeassistant/components/nuki/* @pvizeli
homeassistant/components/nws/* @MatthewFlamm
homeassistant/components/nzbget/* @chriscla
Expand Down
25 changes: 25 additions & 0 deletions homeassistant/components/nuheat/.translations/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"config" : {
"error" : {
"unknown" : "Unexpected error",
"cannot_connect" : "Failed to connect, please try again",
"invalid_auth" : "Invalid authentication",
"invalid_thermostat" : "The thermostat serial number is invalid."
},
"title" : "NuHeat",
"abort" : {
"already_configured" : "The thermostat is already configured"
},
"step" : {
"user" : {
"title" : "Connect to the NuHeat",
"description": "You will need to obtain your thermostat’s numeric serial number or ID by logging into https://MyNuHeat.com and selecting your thermostat(s).",
"data" : {
"username" : "Username",
"password" : "Password",
"serial_number" : "Serial number of the thermostat."
}
}
}
}
}
94 changes: 82 additions & 12 deletions homeassistant/components/nuheat/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
"""Support for NuHeat thermostats."""
import asyncio
import logging

import nuheat
import requests
import voluptuous as vol

from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_DEVICES, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import config_validation as cv, discovery
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv

_LOGGER = logging.getLogger(__name__)
from .const import CONF_SERIAL_NUMBER, DOMAIN, PLATFORMS

DOMAIN = "nuheat"
_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
{
Expand All @@ -27,16 +32,81 @@
)


def setup(hass, config):
"""Set up the NuHeat thermostat component."""
conf = config[DOMAIN]
username = conf.get(CONF_USERNAME)
password = conf.get(CONF_PASSWORD)
devices = conf.get(CONF_DEVICES)
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the NuHeat component."""
hass.data.setdefault(DOMAIN, {})
conf = config.get(DOMAIN)
if not conf:
return True

for serial_number in conf[CONF_DEVICES]:
# Since the api currently doesn't permit fetching the serial numbers
# and they have to be specified we create a separate config entry for
# each serial number. This won't increase the number of http
# requests as each thermostat has to be updated anyways.
# This also allows us to validate that the entered valid serial
# numbers and do not end up with a config entry where half of the
# devices work.
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_USERNAME: conf[CONF_USERNAME],
CONF_PASSWORD: conf[CONF_PASSWORD],
CONF_SERIAL_NUMBER: serial_number,
},
)
)

return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up NuHeat from a config entry."""

conf = entry.data

username = conf[CONF_USERNAME]
password = conf[CONF_PASSWORD]
serial_number = conf[CONF_SERIAL_NUMBER]

api = nuheat.NuHeat(username, password)
api.authenticate()
hass.data[DOMAIN] = (api, devices)

discovery.load_platform(hass, "climate", DOMAIN, {}, config)
try:
await hass.async_add_executor_job(api.authenticate)
except requests.exceptions.Timeout:
raise ConfigEntryNotReady
except requests.exceptions.HTTPError as ex:
if ex.request.status_code > 400 and ex.request.status_code < 500:
_LOGGER.error("Failed to login to nuheat: %s", ex)
return False
raise ConfigEntryNotReady
except Exception as ex: # pylint: disable=broad-except
_LOGGER.error("Failed to login to nuheat: %s", ex)
return False

hass.data[DOMAIN][entry.entry_id] = (api, serial_number)

for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)

return unload_ok
67 changes: 22 additions & 45 deletions homeassistant/components/nuheat/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import logging

from nuheat.config import SCHEDULE_HOLD, SCHEDULE_RUN, SCHEDULE_TEMPORARY_HOLD
import voluptuous as vol

from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
Expand All @@ -14,16 +13,10 @@
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_TEMPERATURE,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.util import Throttle

from . import DOMAIN
from .const import DOMAIN, MANUFACTURER

_LOGGER = logging.getLogger(__name__)

Expand All @@ -49,55 +42,29 @@
value: key for key, value in PRESET_MODE_TO_SCHEDULE_MODE_MAP.items()
}

SERVICE_RESUME_PROGRAM = "resume_program"

RESUME_PROGRAM_SCHEMA = vol.Schema({vol.Optional(ATTR_ENTITY_ID): cv.entity_ids})

SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE


def setup_platform(hass, config, add_entities, discovery_info=None):
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the NuHeat thermostat(s)."""
if discovery_info is None:
return
api, serial_number = hass.data[DOMAIN][config_entry.entry_id]

temperature_unit = hass.config.units.temperature_unit
api, serial_numbers = hass.data[DOMAIN]
thermostats = [
NuHeatThermostat(api, serial_number, temperature_unit)
for serial_number in serial_numbers
]
add_entities(thermostats, True)

def resume_program_set_service(service):
"""Resume the program on the target thermostats."""
entity_id = service.data.get(ATTR_ENTITY_ID)
if entity_id:
target_thermostats = [
device for device in thermostats if device.entity_id in entity_id
]
else:
target_thermostats = thermostats
thermostat = await hass.async_add_executor_job(api.get_thermostat, serial_number)
entity = NuHeatThermostat(thermostat, temperature_unit)

for thermostat in target_thermostats:
thermostat.resume_program()
# No longer need a service as set_hvac_mode to auto does this
# since climate 1.0 has been implemented

thermostat.schedule_update_ha_state(True)

hass.services.register(
DOMAIN,
SERVICE_RESUME_PROGRAM,
resume_program_set_service,
schema=RESUME_PROGRAM_SCHEMA,
)
async_add_entities([entity], True)


class NuHeatThermostat(ClimateDevice):
"""Representation of a NuHeat Thermostat."""

def __init__(self, api, serial_number, temperature_unit):
def __init__(self, thermostat, temperature_unit):
"""Initialize the thermostat."""
self._thermostat = api.get_thermostat(serial_number)
self._thermostat = thermostat
self._temperature_unit = temperature_unit
self._force_update = False

Expand Down Expand Up @@ -140,8 +107,9 @@ def available(self):
def set_hvac_mode(self, hvac_mode):
"""Set the system mode."""

# This is the same as what res
if hvac_mode == HVAC_MODE_AUTO:
self._thermostat.schedule_mode = SCHEDULE_RUN
self._thermostat.resume_schedule()
elif hvac_mode == HVAC_MODE_HEAT:
self._thermostat.schedule_mode = SCHEDULE_HOLD

Expand Down Expand Up @@ -251,3 +219,12 @@ def update(self):
def _throttled_update(self, **kwargs):
"""Get the latest state from the thermostat with a throttle."""
self._thermostat.get_data()

@property
def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, self._thermostat.serial_number)},
"name": self._thermostat.room,
"manufacturer": MANUFACTURER,
}
104 changes: 104 additions & 0 deletions homeassistant/components/nuheat/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Config flow for NuHeat integration."""
import logging

import nuheat
import requests.exceptions
import voluptuous as vol

from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME

from .const import CONF_SERIAL_NUMBER
from .const import DOMAIN # pylint:disable=unused-import

_LOGGER = logging.getLogger(__name__)

DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(CONF_SERIAL_NUMBER): str,
}
)


async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.

Data has the keys from DATA_SCHEMA with values provided by the user.
"""
api = nuheat.NuHeat(data[CONF_USERNAME], data[CONF_PASSWORD])

try:
await hass.async_add_executor_job(api.authenticate)
except requests.exceptions.Timeout:
raise CannotConnect
except requests.exceptions.HTTPError as ex:
if ex.request.status_code > 400 and ex.request.status_code < 500:
raise InvalidAuth
raise CannotConnect
#
# The underlying module throws a generic exception on login failure
#
except Exception: # pylint: disable=broad-except
raise InvalidAuth

try:
thermostat = await hass.async_add_executor_job(
api.get_thermostat, data[CONF_SERIAL_NUMBER]
)
except requests.exceptions.HTTPError:
raise InvalidThermostat

return {"title": thermostat.room, "serial_number": thermostat.serial_number}


class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for NuHeat."""

VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL

async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except InvalidThermostat:
errors["base"] = "invalid_thermostat"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"

if "base" not in errors:
await self.async_set_unique_id(info["serial_number"])
self._abort_if_unique_id_configured()
return self.async_create_entry(title=info["title"], data=user_input)

return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)

async def async_step_import(self, user_input):
"""Handle import."""
await self.async_set_unique_id(user_input[CONF_SERIAL_NUMBER])
self._abort_if_unique_id_configured()

return await self.async_step_user(user_input)


class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""


class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth."""


class InvalidThermostat(exceptions.HomeAssistantError):
"""Error to indicate there is invalid thermostat."""
9 changes: 9 additions & 0 deletions homeassistant/components/nuheat/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Constants for NuHeat thermostats."""

DOMAIN = "nuheat"

PLATFORMS = ["climate"]

CONF_SERIAL_NUMBER = "serial_number"

MANUFACTURER = "NuHeat"
13 changes: 7 additions & 6 deletions homeassistant/components/nuheat/manifest.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
{
"domain": "nuheat",
"name": "NuHeat",
"documentation": "https://www.home-assistant.io/integrations/nuheat",
"requirements": ["nuheat==0.3.0"],
"dependencies": [],
"codeowners": []
"domain": "nuheat",
"name": "NuHeat",
"documentation": "https://www.home-assistant.io/integrations/nuheat",
"requirements": ["nuheat==0.3.0"],
"dependencies": [],
"codeowners": ["@bdraco"],
"config_flow": true
}
Loading