Smart Meter Texas integration (#37966)

* Run scaffold script

* Update version

* Bump version

* Initial commit

* Move meter and ESIID to device attributes

* Update internal to hourly due to api limit

* Format with Black

* Fix typo

* Update tests

* Update description

* Disable Pylint error

* Don't commit translations

* Remove meter number from sensor name

* Allow multiple meters per account

* Move data updates to a DataUpdateCoordinator

* Use setdefault to setup the component

* Move strings to const.py

* Fix tests

* Remove meter last updated attribute

* Bump smart-meter-texas version

* Fix logger call

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove unneeded manifest keys

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon property

Co-authored-by: J. Nick Koston <nick@koston.org>

* Handle instance where user already setup an account

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon constant

* Fix indentation

* Handle config flow errors better

* Use ESIID + meter number as unique ID for sensor

* Update config flow tests to reach 100% coverage

* Avoid reading meters on startup

Cherrypick @bdraco's suggestion

* Run scaffold script

* Update version

* Bump version

* Initial commit

* Move meter and ESIID to device attributes

* Update internal to hourly due to api limit

* Format with Black

* Fix typo

* Update tests

* Update description

* Disable Pylint error

* Don't commit translations

* Remove meter number from sensor name

* Allow multiple meters per account

* Move data updates to a DataUpdateCoordinator

* Use setdefault to setup the component

* Move strings to const.py

* Fix tests

* Remove meter last updated attribute

* Bump smart-meter-texas version

* Fix logger call

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove unneeded manifest keys

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon property

Co-authored-by: J. Nick Koston <nick@koston.org>

* Handle instance where user already setup an account

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon constant

* Fix indentation

* Handle config flow errors better

* Use ESIID + meter number as unique ID for sensor

* Update config flow tests to reach 100% coverage

* Remove unnecessary try/except block

This checks for the same exception just prior in execution on L51.

* Remove unused return values

* Add tests

* Improve tests and coverage

* Use more pythonic control flow

* Remove all uses of hass.data

Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Graham WetzlerandJ. Nick Koston authored and GitHub committed 2020-08-19 13:16:45 -05:00
1 parent e626937147
commit bb164bb32c
17 files changed
+780

No files matched your search

@@ -0,0 +1,133 @@
"""The Smart Meter Texas integration."""
import asyncio
import logging
from smart_meter_texas import Account, Client
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
Debouncer,
UpdateFailed,
)
from .const import (
DATA_COORDINATOR,
DATA_SMART_METER,
DEBOUNCE_COOLDOWN,
DOMAIN,
SCAN_INTERVAL,
)
_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["sensor"]
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Smart Meter Texas component."""
hass.data.setdefault(DOMAIN, {})
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Smart Meter Texas from a config entry."""
username = entry.data[CONF_USERNAME]
password = entry.data[CONF_PASSWORD]
account = Account(username, password)
smartmetertexas = SmartMeterTexasData(hass, entry, account)
try:
await smartmetertexas.client.authenticate()
except SmartMeterTexasAuthError:
_LOGGER.error("Username or password was not accepted")
return False
except asyncio.TimeoutError:
raise ConfigEntryNotReady
await smartmetertexas.setup()
async def async_update_data():
_LOGGER.debug("Fetching latest data")
await smartmetertexas.read_meters()
return smartmetertexas
# Use a DataUpdateCoordinator to manage the updates. This is due to the
# Smart Meter Texas API which takes around 30 seconds to read a meter.
# This avoids Home Assistant from complaining about the component taking
# too long to update.
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
name="Smart Meter Texas",
update_method=async_update_data,
update_interval=SCAN_INTERVAL,
request_refresh_debouncer=Debouncer(
hass, _LOGGER, cooldown=DEBOUNCE_COOLDOWN, immediate=True
),
)
hass.data[DOMAIN][entry.entry_id] = {
DATA_COORDINATOR: coordinator,
DATA_SMART_METER: smartmetertexas,
}
asyncio.create_task(coordinator.async_refresh())
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True
class SmartMeterTexasData:
"""Manages coordinatation of API data updates."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry, account: Account):
"""Initialize the data coordintator."""
self._entry = entry
self.account = account
websession = aiohttp_client.async_get_clientsession(hass)
self.client = Client(websession, account)
self.meters = []
async def setup(self):
"""Fetch all of the user's meters."""
self.meters = await self.account.fetch_meters(self.client)
_LOGGER.debug("Discovered %s meter(s)", len(self.meters))
async def read_meters(self):
"""Read each meter."""
for meter in self.meters:
try:
await meter.read_meter(self.client)
except (SmartMeterTexasAPIError, SmartMeterTexasAuthError) as error:
raise UpdateFailed(error)
return self.meters
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
@@ -0,0 +1,91 @@
"""Config flow for Smart Meter Texas integration."""
import asyncio
import logging
from aiohttp import ClientError
from smart_meter_texas import Account, Client
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import aiohttp_client
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}
)
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.
"""
client_session = aiohttp_client.async_get_clientsession(hass)
account = Account(data["username"], data["password"])
client = Client(client_session, account)
try:
await client.authenticate()
except (asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError):
raise CannotConnect
except SmartMeterTexasAuthError as error:
raise InvalidAuth(error)
# Return info that you want to store in the config entry.
return {"title": account.username}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Smart Meter Texas."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
def _account_already_configured(self, account):
existing_accounts = {
entry.data[CONF_USERNAME]
for entry in self._async_current_entries()
if CONF_USERNAME in entry.data
}
return account in existing_accounts
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 Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if not errors:
if self._account_already_configured(user_input[CONF_USERNAME]):
return self.async_abort(reason="already_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
)
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth."""
@@ -0,0 +1,15 @@
"""Constants for the Smart Meter Texas integration."""
from datetime import timedelta
SCAN_INTERVAL = timedelta(hours=1)
DEBOUNCE_COOLDOWN = 1800 # Seconds
DATA_COORDINATOR = "coordinator"
DATA_SMART_METER = "smart_meter_data"
DOMAIN = "smart_meter_texas"
METER_NUMBER = "meter_number"
ESIID = "electric_service_identifier"
LAST_UPDATE = "last_updated"
ELECTRIC_METER = "Electric Meter"
@@ -0,0 +1,8 @@
{
"domain": "smart_meter_texas",
"name": "Smart Meter Texas",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/smart_meter_texas",
"requirements": ["smart-meter-texas==0.4.0"],
"codeowners": ["@grahamwetzler"]
}
@@ -0,0 +1,112 @@
"""Support for Smart Meter Texas sensors."""
import logging
from smart_meter_texas import Meter
from homeassistant.const import CONF_ADDRESS, ENERGY_KILO_WATT_HOUR
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import (
DATA_COORDINATOR,
DATA_SMART_METER,
DOMAIN,
ELECTRIC_METER,
ESIID,
METER_NUMBER,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Smart Meter Texas sensors."""
coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]
meters = hass.data[DOMAIN][config_entry.entry_id][DATA_SMART_METER].meters
async_add_entities(
[SmartMeterTexasSensor(meter, coordinator) for meter in meters], False
)
class SmartMeterTexasSensor(RestoreEntity, Entity):
"""Representation of an Smart Meter Texas sensor."""
def __init__(self, meter: Meter, coordinator: DataUpdateCoordinator):
"""Initialize the sensor."""
self.meter = meter
self.coordinator = coordinator
self._state = None
self._available = False
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return ENERGY_KILO_WATT_HOUR
@property
def name(self):
"""Device Name."""
return f"{ELECTRIC_METER} {self.meter.meter}"
@property
def unique_id(self):
"""Device Uniqueid."""
return f"{self.meter.esiid}_{self.meter.meter}"
@property
def available(self):
"""Return True if entity is available."""
return self._available
@property
def state(self):
"""Get the latest reading."""
return self._state
@property
def device_state_attributes(self):
"""Return the device specific state attributes."""
attributes = {
METER_NUMBER: self.meter.meter,
ESIID: self.meter.esiid,
CONF_ADDRESS: self.meter.address,
}
return attributes
@property
def should_poll(self):
"""Return False, updates are controlled via coordinator."""
return False
async def async_update(self):
"""Update the entity.
Only used by the generic entity update service.
"""
await self.coordinator.async_request_refresh()
@callback
def _state_update(self):
"""Call when the coordinator has an update."""
self._available = self.coordinator.last_update_success
if self._available:
self._state = self.meter.reading
self.async_write_ha_state()
async def async_added_to_hass(self):
"""Subscribe to updates."""
self.async_on_remove(self.coordinator.async_add_listener(self._state_update))
# If the background update finished before
# we added the entity, there is no need to restore
# state.
if self.coordinator.last_update_success:
return
last_state = await self.async_get_last_state()
if last_state:
self._state = last_state.state
self._available = True
@@ -0,0 +1,22 @@
{
"title": "Smart Meter Texas",
"config": {
"step": {
"user": {
"description": "Provide your username and password for Smart Meter Texas.",
"data": {
"username": "[%key:common::config_flow::data::username%]",
"password": "[%key:common::config_flow::data::password%]"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
}
}
}
+1
View File
@@ -151,6 +151,7 @@ FLOWS = [
"shopping_list",
"simplisafe",
"smappee",
"smart_meter_texas",
"smarthab",
"smartthings",
"smhi",