Skip to content

Commit

Permalink
- Posibilidad de cambiar la configuración
Browse files Browse the repository at this point in the history
- Añadida la opción por tramos de 15 mins
- Añadido offset configurable
  • Loading branch information
MiguelAngelLV committed Dec 15, 2023
1 parent 170b0ff commit 8590949
Show file tree
Hide file tree
Showing 8 changed files with 281 additions and 154 deletions.
81 changes: 81 additions & 0 deletions README-en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
([Ver en español](README.md))

# Net Balance Component for Home Assistant

## What is net balance?

In Spain and other countries, users of photovoltaic panels with surplus compensation have net balance, which calculates the final result of import and export every hour and bills accordingly.

To put it simply: If you export 3 kWh and import 1 kWh in one hour, it will simply be considered that you have exported 2 kWh.

Since exporting is always cheaper than importing, this represents significant savings for the user.

### Example:

Let's assume that importing costs €0.15/kWh, and exporting gives a discount of €0.11/kWh. In the first case, we export 3 kWh and import 1 kWh, and in the second case, it's the opposite.

#### Without Balance
`1 * €0.15 - 3 * €0.11 = -€0.18`

`3 * €0.15 - 1 * €0.11 = €0.34`

#### With Balance
`1 - 3 = -2 => -2 * €0.11 = -€0.22`

`3 - 1 = 2 => 2 * €0.15 = €0.30`

As we can see, in both cases, net balance benefits the user.

## What does this component do?

This component calculates your current hourly balance as well as the result at the end of the hour.

To do this, you need to provide the total imported and exported kWh from your inverter, and the component will create three new entities:

- Net Import
- Net Export
- Current Net Balance

You can then use Net Import and Net Export in the Energy panel for Home Assistant to perform calculations correctly.

### Without net metering

![Without Balance](img/sin%20balance.png)

### With Balance

![With Balance](img/balance.png)

## Installation

You can install the component using HACS. To do this, simply add this repository to your custom repositories and search for "balance neto".

## Configuration

Once installed, go to _Devices and Services -> Add Integration_ and search for _Balance_.

The assistant will ask for 2 entities: total import from grid kWh and total exported to grid kWh.


Additionally, it will request the time period, which can be hourly (as is the case in Spain) or every quarter of an hour.

Finally, you can select a safety offset since Home Assistant may take a moment to perform the calculations; it will carry them out 5 seconds before the end of the period, but this can be modified if necessary.

## Usage

Once the component is configured, use "Net Import" as the sensor for _network consumption_ and "Net Export" for _network feed_.

>#### :warning: If you already have historical data in HA, changing the sensors will stop displaying old data. If you want to keep the data, you will need to connect to the database and copy/update the old import/export records to the net import and net export records.
## Activating Devices When There Are Surpluses

Thanks to the Current Hourly Balance entity, you can activate and deactivate high-consumption devices, such as electric water heaters, to make the most of the surpluses.

Instead of using power regulators to adjust consumption to your current production, you can turn the device on and off based on the balance value. For example, turn on the water heater/AC when the net balance is greater than 0.2 kWh and turn it off when it's less than -0.05 kWh.

This way, we can avoid reducing power when a cloud passes by temporarily or never turning on a 1500W device if our surpluses are 750W when we could have it on for half an hour without any issues.


## Videotutorial

[![Videotutorial](https://img.youtube.com/vi/tG9T1NYv2Cs/0.jpg)](https://www.youtube.com/watch?v=tG9T1NYv2Cs "Videotutorial")
83 changes: 0 additions & 83 deletions README-es.md

This file was deleted.

88 changes: 50 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,74 +1,86 @@
([Ver en español](README-es.md))
# Componente Balance Neto para Home Assistant

# Net Balance Component for Home Assistant
([English version](README-en.md))

## What is net balance?
## ¿Qué es el balance neto?

In Spain and other countries, users of photovoltaic panels with surplus compensation have hourly net balance, which calculates the final result of import and export every hour and bills accordingly.
En España, los usuarios de placas fotovoltáicas con compensación de excedentes disponen del balance neto horario en España (en otros paises es puede ser cada 15 min), el cual
calcula el resultado final de importación y exportación cada hora y en base a este se le factura.

To put it simply: If you export 3 kWh and import 1 kWh in one hour, it will simply be considered that you have exported 2 kWh.
Dicho más sencillo: Si en una hora exportas 3kWh e importas 1kWh, simplemente se considerará que has exportado 2kWh.

Since exporting is always cheaper than importing, this represents significant savings for the user.
Dado que la exportación siempre será más barata que la importación, esto supone un ahorro importante para el usuario.

### Example:
### Ejemplo:

Let's assume that importing costs €0.15/kWh, and exporting gives a discount of €0.11/kWh. In the first case, we export 3 kWh and import 1 kWh, and in the second case, it's the opposite.
Supongamos que importar cuesta 0.15/kWh y exportar nos descuenta 0.11/kWh, en el primer caso exportamos 3 e importamos 1, en el segundo al revés.

#### Without Balance
`1 * 0.15 - 3 * 0.11 = -0.18`
#### Sin Balance
`1 * 0.15 - 3 * 0.11 = -0.18`

`3 * 0.15 - 1 * 0.11 = 0.34`
`3 * 0.15 - 1 * 0.11 = 0.34`

#### With Balance
`1 - 3 = -2 => -2 * 0.11 = -0.22`
#### Con balance
`1 - 3 = -2 => -2 * 0.11 = -0.22`

`3 - 1 = 2 => 2 * 0.15 = 0.30`
`3 - 1 = 2 => 2 * 0.15 = 0.30`

As we can see, in both cases, net balance benefits the user.

## What does this component do?
Como vemos, en ambos casos el balance neto beneficia al usuario.

This component calculates your current hourly balance as well as the result at the end of the hour.

To do this, you need to provide the total imported and exported kWh from your inverter, and the component will create three new entities:
## ¿Qué hace este componente?

- Net Import
- Net Export
- Current Hourly Balance
Este componente va calculando tu balance net actual así como el resultado al final del periodo.

You can then use Net Import and Net Export in the Energy panel for Home Assistant to perform calculations correctly.
Para ello, debes indicar los kWh totales importados y exportados de tu inversor y el componente creará tres entidades nuevas:

### Without net metering
- Importación Neta
- Exportación Neta
- Balance Neto Actual

![Without Balance](img/sin%20balance.png)
Después podrás usar Importación Neta y Exportación Neta en el panel de Energía para que Home Assistant haga los calculos correctamente.

### With Balance

![With Balance](img/balance.png)
### Sin balance neto

## Installation
![Sin Balance](img/sin%20balance.png)

You can install the component using HACS. To do this, simply add this repository to your custom repositories and search for "balance neto".
### Con Balance

## Configuration
![Con Balance](img/balance.png)

Once installed, go to _Devices and Services -> Add Integration_ and search for _Balance_.

The assistant will ask for 2 entities: total import from grid kWh and total exported to grid kWh.

## Usage
## Instalación
Puedes instalar el componente usando HACS, para ello basta con añadir este repositorio a los repositorios personalizados y buscarlo escribiendo «balance».

Once the component is configured, use "Net Import" as the sensor for _network consumption_ and "Net Export" for _network feed_.
## Configuración

>#### :warning: If you already have historical data in HA, changing the sensors will stop displaying old data. If you want to keep the data, you will need to connect to the database and copy/update the old import/export records to the net import and net export records.
Una vez instalado, ve a _Dispositivos y Servicios -> Añadir Integración_ y busca _Balance_.

## Activating Devices When There Are Surpluses
El asistente te solicitará 2 entidades: kWh totales importados de la red y kWh totales exportados a la red.

Thanks to the Current Hourly Balance entity, you can activate and deactivate high-consumption devices, such as electric water heaters, to make the most of the surpluses.
Adicionalmente solicitará el periodo, que puede ser Horario (como es el caso de España) o cada cuarto de hora.

Instead of using power regulators to adjust consumption to your current production, you can turn the device on and off based on the balance value. For example, turn on the water heater/AC when the net balance is greater than 0.2 kWh and turn it off when it's less than -0.05 kWh.
Finalmente, puedes seleccionar un desfase de seguridad puesto que Home Assistant puede tardar un poco en realizar los cálculos, los realizará 5 segundos
antes de terminar el periodo, pero puede ser modificado si fuese necesario.

This way, we can avoid reducing power when a cloud passes by temporarily or never turning on a 1500W device if our surpluses are 750W when we could have it on for half an hour without any issues.

## Uso
Una vez configurado el componente, usa como sensor de _consumo de red_ «Importación Neta» y _volcar a la red_ «Expotación Neta».

>#### :warning: Si ya tienes histórico de datos en HA, al cambiar los sensores los datos antiguos dejarán de mostrarse. Si quieres mantener los datos tendrás que conectarse a la base de datos y copiar/actualizar los registros antiguos de importación/exportación a los de importación neta y exportación neta.

## Activar dispositivos cuando hay excedentes

Gracias a la entidad de Balance Horario Actual podrás activar y desactivar dispositivos de alto consumo, como termos eléctricos, para aprovechar al máximo los excedentes.

En vez de usar reguladores de potencia para adaptar el consumo a tu producción actual, puedes encender y apagar el dispositivo según el valor
del balance. Por ejemplo encender el termo/AC cuando el balance neto sea superior a 0.2kWh y apagarlo cuando sea inferior a -0.05kWh.

De esta forma evitamos bajar la potencia al pasar una nube de forma puntual o no encender nunca un dispositivo de 1500W si nuestros excedentes son de 750W cuando podríamos tenerlo media hora encendido sin problema.


## Videotutorial
Expand Down
26 changes: 23 additions & 3 deletions custom_components/balance_neto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,27 @@

_LOGGER = logging.getLogger(__name__)

from .const import DOMAIN
from .const import DOMAIN, PERIOD, HOURLY, OFFSET

PLATFORMS: list[Platform] = [Platform.SENSOR]


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(_async_update_options))

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return True
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS)


async def _async_update_options(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Handle options update."""
# update entry replacing data with new options
hass.config_entries.async_update_entry(config_entry, data={**config_entry.data, **config_entry.options})
await hass.config_entries.async_reload(config_entry.entry_id)


async def async_migrate_entry(hass: HomeAssistant, config_entry):
Expand All @@ -45,4 +53,16 @@ def _async_migrator(entity_entry: er.RegistryEntry):
await er.async_migrate_entries(hass, config_entry.entry_id, _async_migrator)
config_entry.version = 2

if version == 2:

data = {
**config_entry.data,
PERIOD: HOURLY,
OFFSET: 5,
}

hass.config_entries.async_update_entry(config_entry, data=data)

config_entry.version = 3

return True
Loading

0 comments on commit 8590949

Please sign in to comment.