Skip to content

Commit

Permalink
refactoring complet
Browse files Browse the repository at this point in the history
suppression configuration via YAML
  • Loading branch information
saniho committed May 7, 2021
1 parent f5c73f6 commit 742218f
Show file tree
Hide file tree
Showing 13 changed files with 262 additions and 108 deletions.
102 changes: 95 additions & 7 deletions custom_components/apiEnedis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
CONF_SCAN_INTERVAL,
EVENT_HOMEASSISTANT_STARTED,
)
from homeassistant.core import CoreState, callback
from homeassistant.exceptions import ConfigEntryNotReady
Expand Down Expand Up @@ -62,9 +63,11 @@ def __init__(self):
__name__,
CONF_DELAY,
HEURESCREUSES_ON,
HEURES_CREUSES,
UNDO_UPDATE_LISTENER,
COORDINATOR_ENEDIS,
PLATFORMS,
DEFAULT_REPRISE_ERR,
)

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -93,24 +96,42 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up an Enedis account from a config entry."""
hass.data.setdefault(DOMAIN, {})

heurescreuses = None
heurescreuses = entry.options.get(HEURES_CREUSES, None)
if ( heurescreuses == "" ): heurescreuses = None
_LOGGER.info("**enedis**_conf heurescreuses *%s*" % heurescreuses)
#heurescreuses = None
delai_interval = entry.options.get(SCAN_INTERVAL)
token = entry.options.get(CONF_TOKEN, "")
code = str(entry.options.get(CONF_CODE, ""))
hpcost = float(entry.options.get(HP_COST, "0.0"))
hccost = float(entry.options.get(HC_COST, "0.0"))
heurescreusesON = bool(entry.options.get(HEURESCREUSES_ON, True)),

client = myClientEnedis.myClientEnedis(token, code, delai_interval,
client = myClientEnedis.myClientEnedis(token, code, delai=DEFAULT_REPRISE_ERR,
heuresCreuses=heurescreuses, heuresCreusesCost=hccost,
heuresPleinesCost=hpcost,
version=__VERSION__, heuresCreusesON=heurescreusesON)

coordinator_enedis = sensorEnedisCoordinator(hass, entry, client)
# Fetch initial data so we have data when entities subscribe
await coordinator_enedis.async_refresh()
if not coordinator_enedis.last_update_success:
raise ConfigEntryNotReady

await coordinator_enedis.async_setup()
async def _enable_scheduled_myEnedis(*_):
"""Activate the data update coordinator."""
coordinator_enedis.update_interval = timedelta(seconds=DEFAULT_SCAN_INTERVAL )
await coordinator_enedis.async_refresh()

if hass.state == CoreState.running:
await _enable_scheduled_myEnedis()
if not coordinator_enedis.last_update_success:
raise ConfigEntryNotReady

else:
# Running a speed test during startup can prevent
# integrations from being able to setup
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, _enable_scheduled_myEnedis
)

undo_listener = entry.add_update_listener(_async_update_listener)
hass.data[DOMAIN][entry.entry_id] = {
COORDINATOR_ENEDIS: coordinator_enedis,
Expand Down Expand Up @@ -166,4 +187,71 @@ async def _async_update_data_enedis():
name=f"Enedis information for {entry.title}",
update_method=_async_update_data_enedis,
update_interval=SCAN_INTERVAL,
)
)

async def async_set_options(self):
"""Set options for entry."""
_LOGGER.info("async_set_options - proc -- %s" % self.entry.options)
if not self.entry.options:
_LOGGER.info(".config_entry.options()")
data = {**self.entry.data}
options = {
CONF_SCAN_INTERVAL: data.pop(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),
CONF_TOKEN: data.pop(CONF_TOKEN, ""),
CONF_CODE: str(data.pop(CONF_CODE, "")),
HP_COST: str(data.pop(HP_COST, "0.0")),
HC_COST: str(data.pop(HC_COST, "0.0")),
HEURESCREUSES_ON: bool(data.pop(HEURESCREUSES_ON, True)),
HEURES_CREUSES: str(data.pop(HEURES_CREUSES, "")),
}
self.hass.config_entries.async_update_entry(
self.entry, data=data, options=options
)
_LOGGER.info(".config_entry.options() - done")
_LOGGER.info("async_set_options - proc -- done ")

def update_OptionsMyEnedis(self):
_LOGGER.info("update_MyEnedis pre-getini for %s" % (self.entry.options['token']))
_LOGGER.info("getInit()")
hccost = float(self.entry.options.get(HC_COST, "0.0"))
hpcost = float(self.entry.options.get(HP_COST, "0.0"))
token, code = self.entry.options[CONF_TOKEN], self.entry.options[CONF_CODE]
heurescreusesON = self.entry.options[HEURESCREUSES_ON]
heurescreuses = eval(self.entry.options[HEURES_CREUSES])
_LOGGER.info("options - proc -- %s %s %s %s %s %s" % (token, code, hccost, hpcost, heurescreusesON, heurescreuses))

self.clientEnedis = myClientEnedis.myClientEnedis(token, code, delai=DEFAULT_REPRISE_ERR,
heuresCreuses=heurescreuses, heuresCreusesCost=hccost,
heuresPleinesCost=hpcost,
version=__VERSION__, heuresCreusesON=heurescreusesON)

async def async_setup(self):
#Set up myEnedis.
try:
_LOGGER.info("run my First Extension")
# ne sert plus normalement ...
# self.myEnedis = await self.hass.async_add_executor_job(self.clientEnedis.getData)
_LOGGER.info("run my First Extension - done -- ")
except Exception as inst:
raise Exception(inst)

async def request_update(call):
# Request update.
await self.async_request_refresh()

#await self.async_set_options()
#await self.hass.async_add_executor_job(self.clientEnedis.getData)
await self.async_set_options()
await self.hass.async_add_executor_job(self.update_OptionsMyEnedis)
self._unsub_update_listener = self.entry.add_update_listener(
options_updated_listener
)
""" """


async def options_updated_listener(hass, entry):
"""Handle options update. suite modification options"""
_LOGGER.info("options_updated_listener ")
#hass.data[DOMAIN][entry.entry_id].update_interval = timedelta(seconds=DEFAULT_SENSOR_INTERVAL)
#await hass.data[DOMAIN][entry.entry_id].async_request_refresh()
_LOGGER.info("options_updated_listener - done -- ")
21 changes: 18 additions & 3 deletions custom_components/apiEnedis/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
HC_COST,
HP_COST,
HEURESCREUSES_ON,
HEURES_CREUSES
)

import logging
Expand Down Expand Up @@ -43,6 +44,7 @@ def _show_setup_form(self, user_input=None, errors=None):
code = ""
val_hc_cost = "0.0"
val_hp_cost = "0.0"
val_heures_creuses = ""
val_heurescreuses_on = True

data_schema = vol.Schema(
Expand Down Expand Up @@ -71,7 +73,12 @@ def _show_setup_form(self, user_input=None, errors=None):
default=user_input.get(
HEURESCREUSES_ON, val_heurescreuses_on
)
): cv.boolean
): cv.boolean,
vol.Optional(HEURES_CREUSES,
default=user_input.get(
HEURES_CREUSES, val_heures_creuses
)
): cv.string,
}
)
return self.async_show_form(
Expand All @@ -90,6 +97,7 @@ async def async_step_user(self, user_input=None): # pylint: disable=unused-arg
hc_cost = user_input.get(HC_COST)
hp_cost = user_input.get(HP_COST)
heures_creuses_on = user_input.get(HEURESCREUSES_ON)
heures_creuses = user_input.get(HEURES_CREUSES)

# Check if already configured
await self.async_set_unique_id(f"{code}")
Expand All @@ -99,7 +107,8 @@ async def async_step_user(self, user_input=None): # pylint: disable=unused-arg
title=code,
data={CONF_TOKEN: token, CONF_CODE: code,
HC_COST: hc_cost, HP_COST: hp_cost,
HEURESCREUSES_ON : heures_creuses_on},
HEURESCREUSES_ON : heures_creuses_on,
HEURES_CREUSES : heures_creuses},
)

async def async_step_import(self, user_input):
Expand All @@ -119,6 +128,7 @@ async def async_step_init(self, user_input=None):
return self.async_create_entry(title="", data=user_input)
token = "monToken"
code = "monCode"
val_heures_creuses = ""
data_schema = vol.Schema(
{
vol.Required(CONF_TOKEN,
Expand All @@ -145,7 +155,12 @@ async def async_step_init(self, user_input=None):
default=self.config_entry.options.get(
HEURESCREUSES_ON, True
),
): cv.boolean
): cv.boolean,
vol.Optional(HEURES_CREUSES,
default=self.config_entry.options.get(
HEURES_CREUSES, val_heures_creuses
)
): cv.string,
}
)
return self.async_show_form(step_id="init", data_schema=data_schema)
8 changes: 5 additions & 3 deletions custom_components/apiEnedis/const.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
""" Constants """

__VERSION__ = "1.1.4.4rc3" # attention updater aussi manifest.json
__VERSION__ = "1.2.0.0rc1" # attention updater aussi manifest.json
__name__ = "myEnedis"

try:
Expand Down Expand Up @@ -31,10 +31,12 @@ def __init__(self):

HP_COST = "hp_cout"
HC_COST = "hc_cout"
HEURES_CREUSES = "heures_creuses"

CONF_DELAY = 60 * 60 * 6 # verification enedis toutes les 6 heures
DEFAULT_SCAN_INTERVAL = 60*30 # verification enedis toutes les 30 minutes, si dernier ok, alors verifie selon conf_delay
#DEFAULT_SCAN_INTERVAL = 60*2 # verification enedis toutes les 30 minutes, si dernier ok, alors verifie selon conf_delay
DEFAULT_SCAN_INTERVAL = 60 * 30 # verification enedis toutes les 30 minutes
DEFAULT_REPRISE_ERR = 60 * 60 # verification enedis toutes les heures
#DEFAULT_SCAN_INTERVAL = 60 # verification enedis toutes les 60 secondes
DEFAULT_SENSOR_INTERVAL = 60 # 60 secondes verifications du coordinator
DEFAULT_SCAN_INTERVAL_HISTORIQUE = 60*10 # 1 fois toutes les 10 minutes

Expand Down
2 changes: 1 addition & 1 deletion custom_components/apiEnedis/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"name": "myEnedis sensor",
"documentation": "https://github.com/saniho/apiEnedis/",
"config_flow": true,
"version": "1.1.4.4rc3",
"version": "1.2.0.0rc1",
"requirements": [
],
"dependencies": [],
Expand Down
3 changes: 2 additions & 1 deletion custom_components/apiEnedis/myCall.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ def post_and_get_json(self, url, params=None, data=None, headers=None):
response.raise_for_status()
dataAnswer = response.json()
self.setLastAnswer(dataAnswer)
print("ici", params, headers, data)
#print("ici", params, headers, data)
#raise(requests.exceptions.Timeout) # pour raiser un timeout de test ;)
return dataAnswer
except requests.exceptions.Timeout as error:
response = {"enedis_return": {"error": "UNKERROR_002"}}
Expand Down
Loading

0 comments on commit 742218f

Please sign in to comment.