Skip to content

Commit

Permalink
Merge pull request #14 from frlequ/config-flow
Browse files Browse the repository at this point in the history
Config flow update
  • Loading branch information
frlequ authored Oct 16, 2024
2 parents 9beed6d + 25918c2 commit 9860c0f
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 53 deletions.
22 changes: 10 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,19 @@ This custom component for Home Assistant calculates the current network fee tari

## Configuration

After installation, you need to add the component to your Home Assistant configuration. Edit your `configuration.yaml` file and add the following configuration:
After installation, go to Settings -> Add Integration and search for `Elektro Network Tariff`

```yaml
sensor:
- platform: elektro_network_tariff
```

Or if you want a custom name and entity_id use this:
## Upgrading

> [!IMPORTANT]
> If you are upgrading from an older version, please **remove** platform sensor from `configuration.yaml`, you don't need it anymore.
>
>```yaml
>sensor:
> - platform: elektro_network_tariff
>```
```yaml
sensor:
- platform: elektro_network_tariff
name: "Custom Tariff Sensor"
entity_id: "sensor.custom_tariff_sensor"
```
## Report any issues
Expand Down
28 changes: 27 additions & 1 deletion custom_components/elektro_network_tariff/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,27 @@
from .sensor import ElektroNetworkTariffSensor
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers import config_validation as cv
from .const import DOMAIN

# Define the config schema
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)

async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Elektro Network Tariff component."""
return True

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Elektro Network Tariff from a config entry."""
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = entry

# Forward the setup to the sensor platform
await hass.config_entries.async_forward_entry_setups(entry, ["sensor"])

return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload an Elektro Network Tariff config entry."""
await hass.config_entries.async_forward_entry_unload(entry, "sensor")
hass.data[DOMAIN].pop(entry.entry_id)
return True
45 changes: 45 additions & 0 deletions custom_components/elektro_network_tariff/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import callback
from .const import DOMAIN # Make sure DOMAIN is defined in const.py

class ElektroNetworkTariffConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Elektro Network Tariff."""

VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL

async def async_step_user(self, user_input=None):
"""Handle the initial step."""
# Automatically create an entry with default values
return self.async_create_entry(
title="Elektro Network Tariff",
data={
"name": "Elektro Network Tariff",
"entity_id": "sensor.elektro_network_tariff"
}
)

@staticmethod
@callback
def async_get_options_flow(config_entry):
return ElektroNetworkTariffOptionsFlowHandler(config_entry)

class ElektroNetworkTariffOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle Elektro Network Tariff options."""

def __init__(self, config_entry):
self.config_entry = config_entry

async def async_step_init(self, user_input=None):
"""Manage the 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("name", default=self.config_entry.data.get("name")): str,
vol.Required("entity_id", default=self.config_entry.data.get("entity_id")): str,
})
)
1 change: 1 addition & 0 deletions custom_components/elektro_network_tariff/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DOMAIN = "elektro_network_tariff"
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,5 @@ def calculate_tariff():

# Now return the current tariff and the blocks
current_tariff = blocks[date.hour] # Get the tariff for the current hour
return current_tariff, blocks # Return both the current tariff and the blocks
return current_tariff, blocks # Return both the current tariff and the blocks

6 changes: 3 additions & 3 deletions custom_components/elektro_network_tariff/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
"domain": "elektro_network_tariff",
"name": "Elektro Network Tariff",
"codeowners": ["@frlequ"],
"config_flow": true,
"dependencies": [],
"documentation": "https://github.com/frlequ/elektro_network_tariff",
"integration_type": "entity",
"iot_class": "local_polling",
"issue_tracker": "https://github.com/frlequ/elektro_network_tariff/issues",
"requirements": [],
"version": "0.1.4"
"requirements": ["requests>=2.25.1"],
"version": "0.1.5"
}
56 changes: 20 additions & 36 deletions custom_components/elektro_network_tariff/sensor.py
Original file line number Diff line number Diff line change
@@ -1,68 +1,52 @@
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from datetime import timedelta
import voluptuous as vol
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
from .elektro_network_tariff import calculate_tariff
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

# Extend PLATFORM_SCHEMA with optional name and entity_id, and provide defaults
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional("name", default="Elektro Network Tariff"): cv.string,
vol.Optional("entity_id", default="sensor.elektro_network_tariff"): cv.string,
})
SCAN_INTERVAL = timedelta(seconds=5)

SCAN_INTERVAL = timedelta(seconds=30) # Adjust the interval as needed

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Elektro Network Tariff Sensor."""
# Retrieve name and entity_id from configuration, with defaults
name = config.get("name")
entity_id = config.get("entity_id")
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities):
"""Set up the Elektro Network Tariff Sensor from a config entry."""
name = config_entry.data["name"]
entity_id = config_entry.data["entity_id"]
async_add_entities([ElektroNetworkTariffSensor(name, entity_id)])

class ElektroNetworkTariffSensor(Entity):
class ElektroNetworkTariffSensor(SensorEntity):
"""Representation of an Elektro Network Tariff Sensor."""

def __init__(self, name, entity_id):
"""Initialize the sensor."""
self._name = name
self._entity_id = entity_id
self._attr_name = name
self._attr_unique_id = entity_id # Set a unique ID for the entity
self._state = None
self._blocks = None
self.update()

@property
def name(self):
"""Return the name of the sensor."""
return self._name

@property
def entity_id(self):
"""Return the entity_id."""
return self._entity_id

@property
def state(self):
"""Return the state of the sensor."""
return self._state

@property
def state_attributes(self):
def extra_state_attributes(self):
"""Return the state attributes."""
blocks_str = ','.join(map(str, self._blocks)) if self._blocks else ''
return {
"state_class": "measurement",
"blocks": blocks_str
"blocks": ','.join(map(str, self._blocks)) if self._blocks else ''
}

@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:transmission-tower"

def update(self):
"""Fetch new state data for the sensor."""
self._state, self._blocks = calculate_tariff() # Update both state and blocks
async def async_update(self):
"""Fetch new state data for the sensor asynchronously."""
try:
self._state, self._blocks = calculate_tariff() # Fetch data asynchronously if needed
except Exception as e:
_LOGGER.error(f"Error updating Elektro Network Tariff Sensor: {e}")

0 comments on commit 9860c0f

Please sign in to comment.