Skip to content

Commit

Permalink
With config_flow, listen state_change, switch instead of binary_senso…
Browse files Browse the repository at this point in the history
…r, click to toggle
  • Loading branch information
Jean-Marc Collin committed Jun 17, 2023
1 parent d488808 commit aeb130a
Show file tree
Hide file tree
Showing 14 changed files with 464 additions and 153 deletions.
25 changes: 14 additions & 11 deletions .devcontainer/configuration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ input_boolean:
fake_device_i:
name: "Equipement I (20 W)"
icon: mdi:radiator
device_h_enable:
name: "Enable device H"
icon: mdi:check

switch:
- platform: template
Expand Down Expand Up @@ -138,55 +141,55 @@ solar_optimizer:
entity_id: "input_boolean.fake_device_a"
power_max: 1000
check_usable_template: "{{ True }}"
duration_sec: 20
duration_min: 0.3
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
- name: "Equipement B"
entity_id: "input_boolean.fake_device_b"
power_max: 500
check_usable_template: "{{ True }}"
duration_sec: 40
duration_min: 0.6
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
- name: "Equipement C"
entity_id: "input_boolean.fake_device_c"
power_max: 800
check_usable_template: "{{ True }}"
duration_sec: 60
duration_min: 1
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
- name: "Equipement D"
entity_id: "input_boolean.fake_device_d"
power_max: 2100
check_usable_template: "{{ True }}"
duration_sec: 30
duration_min: 0.5
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
- name: "Equipement E"
entity_id: "input_boolean.fake_device_e"
power_max: 120
check_usable_template: "{{ True }}"
duration_sec: 125
duration_min: 2
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
- name: "Equipement F"
entity_id: "input_boolean.fake_device_f"
power_max: 500
check_usable_template: "{{ True }}"
duration_sec: 10
duration_min: 0.2
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
- name: "Equipement G"
entity_id: "input_boolean.fake_device_g"
power_max: 1200
check_usable_template: "{{ True }}"
duration_sec: 90
duration_min: 90
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
Expand All @@ -197,9 +200,9 @@ solar_optimizer:
power_max: 3960
power_step: 660
# check_active_template: "{{ not is_state('input_select.fake_tesla_1', '0 A') }}"
check_usable_template: "{{ True }}"
duration_sec: 60
duration_power_sec: 10
check_usable_template: "{{ is_state('input_boolean.device_h_enable', 'on') }}"
duration_min: 1
duration_power_min: 0.1
action_mode: "service_call"
activation_service: "input_boolean/turn_on"
deactivation_service: "input_boolean/turn_off"
Expand All @@ -209,7 +212,7 @@ solar_optimizer:
entity_id: "switch.fake_switch_1"
power_max: 20
check_usable_template: "{{ True }}"
duration_sec: 10
duration_min: 0.1
action_mode: "service_call"
activation_service: "switch/turn_on"
deactivation_service: "switch/turn_off"
Expand Down
36 changes: 26 additions & 10 deletions custom_components/solar_optimizer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from .const import DOMAIN, PLATFORMS
from .coordinator import SolarOptimizerCoordinator
from .sensor import async_setup_entry as async_setup_entry_sensor
from .binary_sensor import async_setup_entry as async_setup_entry_binary_sensor
from .switch import async_setup_entry as async_setup_entry_switch

_LOGGER = logging.getLogger(__name__)

Expand All @@ -22,28 +22,44 @@ async def async_setup(
"Initializing %s integration with plaforms: %s with config: %s",
DOMAIN,
PLATFORMS,
config,
config.get(DOMAIN),
)

hass.data.setdefault(DOMAIN, {})

# L'argument config contient votre fichier configuration.yaml
solar_optimizer_config = config.get(DOMAIN)

hass.data[DOMAIN]["coordinator"] = coordinator = SolarOptimizerCoordinator(
hass.data[DOMAIN]["coordinator"] = SolarOptimizerCoordinator(
hass, solar_optimizer_config
)

await async_setup_entry_sensor(hass)
await async_setup_entry_binary_sensor(hass)
# await async_setup_entry_sensor(hass)
# await async_setup_entry_switch(hass)
#
# # refresh data on startup
# async def _internal_startup(*_):
# await coordinator.async_config_entry_first_refresh()
#
# hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _internal_startup)

# refresh data on startup
async def _internal_startup(*_):
await coordinator.async_config_entry_first_refresh()
# Return boolean to indicate that initialization was successful.
return True

hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _internal_startup)

# Return boolean to indicate that initialization was successful.
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Creation des entités à partir d'une configEntry"""

_LOGGER.debug(
"Appel de async_setup_entry entry: entry_id='%s', data='%s'",
entry.entry_id,
entry.data,
)

hass.data.setdefault(DOMAIN, {})

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True


Expand Down
88 changes: 0 additions & 88 deletions custom_components/solar_optimizer/binary_sensor.py

This file was deleted.

65 changes: 65 additions & 0 deletions custom_components/solar_optimizer/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
""" Le Config Flow """

import logging
import voluptuous as vol

from homeassistant.config_entries import ConfigFlow, FlowResult
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.input_number import DOMAIN as INPUT_NUMBER_DOMAIN
from homeassistant.helpers import selector

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

solar_optimizer_schema = {
vol.Required("refresh_period_sec", default=300): int,
vol.Required("power_consumption_entity_id"): selector.EntitySelector(
selector.EntitySelectorConfig(domain=[SENSOR_DOMAIN, INPUT_NUMBER_DOMAIN])
),
vol.Required("power_production_entity_id"): selector.EntitySelector(
selector.EntitySelectorConfig(domain=[SENSOR_DOMAIN, INPUT_NUMBER_DOMAIN])
),
vol.Required("sell_cost_entity_id"): selector.EntitySelector(
selector.EntitySelectorConfig(domain=[INPUT_NUMBER_DOMAIN])
),
vol.Required("buy_cost_entity_id"): selector.EntitySelector(
selector.EntitySelectorConfig(domain=[INPUT_NUMBER_DOMAIN])
),
vol.Required("sell_tax_percent_entity_id"): selector.EntitySelector(
selector.EntitySelectorConfig(domain=[INPUT_NUMBER_DOMAIN])
),
}


class SolarOptimizerConfigFlow(ConfigFlow, domain=DOMAIN):
"""La classe qui implémente le config flow pour notre DOMAIN.
Elle doit dériver de FlowHandler"""

# La version de notre configFlow. Va permettre de migrer les entités
# vers une version plus récente en cas de changement
VERSION = 1
_user_inputs: dict = {}

async def async_step_user(self, user_input: dict | None = None) -> FlowResult:
"""Gestion de l'étape 'user'. Point d'entrée de notre
configFlow. Cette méthode est appelée 2 fois :
1. une première fois sans user_input -> on affiche le formulaire de configuration
2. une deuxième fois avec les données saisies par l'utilisateur dans user_input -> on sauvegarde les données saisies
"""
user_form = vol.Schema(solar_optimizer_schema)

if user_input is None:
_LOGGER.debug(
"config_flow step user (1). 1er appel : pas de user_input -> on affiche le form user_form"
)
return self.async_show_form(step_id="user", data_schema=user_form)

# 2ème appel : il y a des user_input -> on stocke le résultat
self._user_inputs.update(user_input)
_LOGGER.debug(
"config_flow step2 (2). L'ensemble de la configuration est: %s",
self._user_inputs,
)

return self.async_create_entry(title="SolarOptimizer", data=self._user_inputs)
2 changes: 1 addition & 1 deletion custom_components/solar_optimizer/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from homeassistant.util import dt as dt_util

DOMAIN = "solar_optimizer"
PLATFORMS: list[Platform] = [Platform.SENSOR, Platform.BINARY_SENSOR]
PLATFORMS: list[Platform] = [Platform.SENSOR, Platform.SWITCH]

DEFAULT_REFRESH_PERIOD_SEC = 300

Expand Down
Loading

0 comments on commit aeb130a

Please sign in to comment.