Skip to content
This repository has been archived by the owner on Jun 20, 2022. It is now read-only.

Commit

Permalink
Merge pull request #48 from DCSBL/development
Browse files Browse the repository at this point in the history
Release 0.9.0
  • Loading branch information
DCSBL authored Aug 12, 2021
2 parents 76fd167 + f49611d commit 2d3a53d
Show file tree
Hide file tree
Showing 10 changed files with 276 additions and 179 deletions.
27 changes: 27 additions & 0 deletions .github/helpers/update_manifest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Update the manifest file."""
"""Idea from https://github.com/hacs/integration/blob/main/manage/update_manifest.py"""

import sys
import json
import os


def update_manifest():
"""Update the manifest file."""
version = "0.0.0"
for index, value in enumerate(sys.argv):
if value in ["--version", "-V"]:
version = sys.argv[index + 1]

with open(f"{os.getcwd()}/custom_components/homewizard_energy/manifest.json") as manifestfile:
manifest = json.load(manifestfile)

manifest["version"] = version

with open(
f"{os.getcwd()}/custom_components/homewizard_energy/manifest.json", "w"
) as manifestfile:
manifestfile.write(json.dumps(manifest, indent=4, sort_keys=True))


update_manifest()
85 changes: 69 additions & 16 deletions custom_components/homewizard_energy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,44 @@
"""The Homewizard Energy integration."""
import asyncio
from homeassistant.const import CONF_API_VERSION, CONF_ID, CONF_STATE
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
import logging
from datetime import timedelta
import re
from datetime import timedelta
from enum import unique

import aiohwenergy
import async_timeout
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_VERSION, CONF_ID, CONF_STATE
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import entity_registry
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import slugify

from .const import (
ATTR_BRIGHTNESS,
ATTR_POWER_ON,
ATTR_SWITCHLOCK,
CONF_API,
CONF_NAME,
CONF_MODEL,
CONF_DATA,
CONF_MODEL,
CONF_NAME,
CONF_SW_VERSION,
CONF_OVERRIDE_POLL_INTERVAL,
CONF_POLL_INTERVAL_SECONDS,
CONF_UNLOAD_CB,
COORDINATOR,
DEFAULT_OVERRIDE_POLL_INTERVAL,
DEFAULT_POLL_INTERVAL_SECONDS,
DOMAIN,
MODEL_KWH_1,
MODEL_KWH_3,
MODEL_P1,
MODEL_SOCKET,
PLATFORMS,
)

Logger = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA)

PLATFORMS = ["sensor"]


async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Homewizard Energy component."""
Expand Down Expand Up @@ -132,7 +135,35 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):

# Get api and do a initialization
energy_api = aiohwenergy.HomeWizardEnergy(entry.data.get("host"))
await energy_api.initialize()

# Validate connection
initialized = False
try:
with async_timeout.timeout(10):
await energy_api.initialize()
initialized = True

except (asyncio.TimeoutError, aiohwenergy.RequestError):
Logger.error(
"Error connecting to the Energy device at %s",
energy_api._host,
)
raise ConfigEntryNotReady

except aiohwenergy.AioHwEnergyException:
Logger.exception("Unknown Energy API error occurred")
raise ConfigEntryNotReady

except Exception: # pylint: disable=broad-except
Logger.exception(
"Unknown error connecting with Energy Device at %s",
energy_api._host["host"],
)
return False

finally:
if not initialized:
await energy_api.close()

# Create coordinator
coordinator = hass.data[DOMAIN][entry.data["unique_id"]][
Expand Down Expand Up @@ -196,9 +227,31 @@ def __init__(
) -> None:
self.api = api

update_interval = timedelta(seconds=10)
update_interval = self.get_update_interval()
super().__init__(hass, Logger, name="", update_interval=update_interval)

def get_update_interval(self) -> timedelta:

try:
product_type = self.api.device.product_type
except AttributeError:
product_type = "Unknown"

if product_type == MODEL_P1:
try:
smr_version = self.api.data.smr_version
if smr_version == 50:
return timedelta(seconds=1)
else:
return timedelta(seconds=5)
except AttributeError:
pass

elif product_type in [MODEL_KWH_1, MODEL_KWH_3, MODEL_SOCKET]:
return timedelta(seconds=5)

return timedelta(seconds=10)

async def _async_update_data(self) -> dict:
"""Fetch all device and sensor data from api."""
try:
Expand All @@ -224,9 +277,9 @@ async def _async_update_data(self) -> dict:

if self.api.state is not None:
data[CONF_STATE] = {
"power_on": self.api.state.power_on,
"switch_lock": self.api.state.switch_lock,
"brightness": self.api.state.brightness,
ATTR_POWER_ON: self.api.state.power_on,
ATTR_SWITCHLOCK: self.api.state.switch_lock,
ATTR_BRIGHTNESS: self.api.state.brightness,
}

except Exception as ex:
Expand Down
52 changes: 2 additions & 50 deletions custom_components/homewizard_energy/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,7 @@
from voluptuous import All, Length, Required, Schema
from voluptuous.util import Lower

from .const import (
CONF_IP_ADDRESS,
CONF_OVERRIDE_POLL_INTERVAL,
CONF_POLL_INTERVAL_SECONDS,
DEFAULT_OVERRIDE_POLL_INTERVAL,
DEFAULT_POLL_INTERVAL_SECONDS,
DOMAIN,
)
from .const import CONF_IP_ADDRESS, DOMAIN

Logger = logging.getLogger(__name__)

Expand All @@ -33,12 +26,6 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL

@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return HWEnergyConfigFlowHandler(config_entry)

def __init__(self):
"""Set up the instance."""
Logger.debug("config_flow __init__")
Expand Down Expand Up @@ -155,7 +142,7 @@ async def async_step_check(self, entry_info):
# return self.async_abort(reason="device_not_supported")

if entry_info["api_enabled"] != "1":
# Logger.warning("API not enabled, please enable API in app")
Logger.warning("API not enabled, please enable API in app")
return self.async_abort(reason="api_not_enabled")

Logger.debug(f"entry_info: {entry_info}")
Expand Down Expand Up @@ -245,38 +232,3 @@ async def async_step_discovery_confirm(self, user_input=None):
title=title,
data=self.context,
)


class HWEnergyConfigFlowHandler(config_entries.OptionsFlow):
"""Handle options."""

def __init__(self, config_entry):
"""Initialize Hue options flow."""
self.config_entry = config_entry

async def async_step_init(
self, user_input: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""Manage Energy options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)

return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
CONF_OVERRIDE_POLL_INTERVAL,
default=self.config_entry.options.get(
CONF_OVERRIDE_POLL_INTERVAL, DEFAULT_OVERRIDE_POLL_INTERVAL
),
): bool,
vol.Required(
CONF_POLL_INTERVAL_SECONDS,
default=self.config_entry.options.get(
CONF_POLL_INTERVAL_SECONDS, DEFAULT_POLL_INTERVAL_SECONDS
),
): vol.All(cv.positive_int, vol.Range(min=1)),
}
),
)
19 changes: 11 additions & 8 deletions custom_components/homewizard_energy/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
DOMAIN = "homewizard_energy"
COORDINATOR = "coordinator"
MANUFACTURER_NAME = "HomeWizard"
PLATFORMS = ["sensor"]
PLATFORMS = ["sensor", "switch"]

# Platform config.
CONF_ENTITY_ID = const.CONF_ENTITY_ID
Expand Down Expand Up @@ -38,14 +38,17 @@
ATTR_TOTAL_GAS_M3 = "total_gas_m3"
ATTR_GAS_TIMESTAMP = "gas_timestamp"

# State attributes
ATTR_POWER_ON = "power_on"
ATTR_SWITCHLOCK = "switch_lock"
ATTR_BRIGHTNESS = "brightness"

# Default values.
DEFAULT_STR_VALUE = "undefined"
DEVICE_DEFAULT_NAME = "P1 Meter"


# Config
CONF_OVERRIDE_POLL_INTERVAL = "override_poll_interval"
DEFAULT_OVERRIDE_POLL_INTERVAL = False

CONF_POLL_INTERVAL_SECONDS = "poll_interval_seconds"
DEFAULT_POLL_INTERVAL_SECONDS = 10
# Device models
MODEL_P1 = "HWE-P1"
MODEL_KWH_1 = "SDM230-wifi"
MODEL_KWH_3 = "SDM630-wifi"
MODEL_SOCKET = "HWE-SKT"
4 changes: 2 additions & 2 deletions custom_components/homewizard_energy/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"domain": "homewizard_energy",
"name": "HomeWizard Energy",
"version": "0.8.2",
"version": "0.0.0",
"documentation": "https://github.com/DCSBL/ha-homewizard-energy",
"issue_tracker": "https://github.com/DCSBL/ha-homewizard-energy/issues",
"codeowners": [
Expand All @@ -11,7 +11,7 @@
"zeroconf"
],
"requirements": [
"aiohwenergy==0.1.1"
"aiohwenergy==0.2.3"
],
"zeroconf": [
"_hwenergy._tcp.local."
Expand Down
Loading

0 comments on commit 2d3a53d

Please sign in to comment.