# Erro em cálculo de custos

**URL:** <https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729>\
**Category:** Dúvidas\
**Created:** [11 Julho , 2019 14:58 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729 "2019-07-11T14:58:15Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [11 Julho , 2019 14:58 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/1 "2019-07-11T14:58:15Z")

</div>

Boas!

Vinha pedir ajuda aos mais entendidos.  
Tenho uns erros no log devido às formulas usadas no cálculo do custo:

```auto
2019-07-11 15:34:27 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.casa_today_cost fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 220, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 375, in async_device_update
    await self.async_update()
  File "/usr/src/homeassistant/homeassistant/components/template/sensor.py", line 191, in async_update
    self._state = self._template.async_render()
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 191, in async_render
    return self._compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
TypeError: can't multiply sequence by non-int of type 'float'
2019-07-11 15:34:27 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.casa_yesterday_cost fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 220, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 375, in async_device_update
    await self.async_update()
  File "/usr/src/homeassistant/homeassistant/components/template/sensor.py", line 191, in async_update
    self._state = self._template.async_render()
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 191, in async_render
    return self._compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
TypeError: can't multiply sequence by non-int of type 'float'
2019-07-11 15:34:27 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.casa_anual_cost fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 220, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 375, in async_device_update
    await self.async_update()
  File "/usr/src/homeassistant/homeassistant/components/template/sensor.py", line 191, in async_update
    self._state = self._template.async_render()
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 191, in async_render
    return self._compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
TypeError: can't multiply sequence by non-int of type 'float'

```

O código é o seguinte:

```auto
  - platform: template
    sensors:
    
      casa_today_cost:
        friendly_name: Custo de hoje
        entity_id: sensor.casa_energy_today
        unit_of_measurement: "€"
        value_template: "{{ float((float(states.sensor.casa_energy_today.state) * 0.1513 + 0.3715 + 0.094) * 1.23 ) | round(2) }}"

      casa_yesterday_cost:
        friendly_name: Custo de ontem
        entity_id: sensor.casa_energy_yesterday
        unit_of_measurement: "€"

        value_template: "{{ float((float(states.sensor.casa_energy_yesterday.state) * 0.1513 + 0.3715 + 0.094) * 1.23 ) | round(2) }}"

      casa_mensal_cost:
        friendly_name: Custo mensal
        entity_id: sensor.energia_casa_mensal
        unit_of_measurement: "€"
        value_template: "{{ ((float(states.sensor.energia_casa_mensal.state) * 0.1513 + now().day * 0.3715 + 2.85) * 1.23 ) | round(2) }}"

      casa_anual_cost:
        friendly_name: Custo anual
        entity_id: sensor.energia_casa_anual
        unit_of_measurement: "€"
        value_template: "{{ (float(states.sensor.energia_casa_anual.state) * 0.1513 + float(states.sensor.dias_apos_inicio_2019.state) * 0.3715 * 1.23 + float(states.sensor.dias_apos_inicio_2019.state) * 0.0937 * 1.06) | round(2) }}"

```

Antes que perguntem por que não juntar os valores todos em vez de os ter em separado, serve apenas para caso haja alguma alteração seja mais fácil fazê-lo pois como até pode ser daqui a uma ano, posso já nem me lembrar disto…

Sei que tem a ver com o tipo de dados (float vs int) mas como ainda pesco pouco disto não tenho tido muita sorte a resolver isto…

sensor.dias\_apos\_inicio\_2019.state:

```auto
  - platform: template
    sensors:
      dias_apos_inicio_2019:
        value_template: '{{ ((as_timestamp(now()) - (states.input_datetime.inicio_ano_2019.attributes.timestamp)) | int /60/1440) | round(0) }}'
        unit_of_measurement: 'Days'
        entity_id: input_datetime.inicio_ano_2019,sensor.time

```

Desde já obrigado…

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [11 Julho , 2019 15:06 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/2 "2019-07-11T15:06:20Z")

</div>

E já experimentaste usar a opção Templates do Dev Tools :templates: para validar a formula?

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [11 Julho , 2019 19:35 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/3 "2019-07-11T19:35:04Z")

</div>

Esqueci-me de referir que com as formulas dão o resultado no entanto aparecem os erros no log…

Sobre a tua pergunta, estás a referir-te a isto?

 ![image](https://forum.cpha.pt/uploads/default/original/2X/c/c5394c2b645e5321517cddcee358a81d2e2e53a6.png)

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [11 Julho , 2019 19:53 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/4 "2019-07-11T19:53:02Z")

</div>

Sim, era isso mesmo. Penso que o problema aí é teres um float a mais e não usarem as prioridades nas contas (multiplicações e divisões primeiro, adições e subtrações depois).

Mais logo já faço um teste para veres como fica.

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [13 Julho , 2019 11:34 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/5 "2019-07-13T11:34:23Z")

</div>

Acho que já estou aperceber qual é o problema…

Alterei o código para isto:

`value_template: "{{ ((float(states.sensor.casa_energy_today.state) * 0.1513 + 0.3715 + 0.094) * 1.23 ) | round(2) }}"`

O problema parece ser porque no arranque os valores do sensor “sensor.casa\_energy\_today” é “unknown” pelo que só quando actualiza para o valor é que aparece o valor de custo…

Na página de ajuda do Template sensor do Home assistant aparece isto:

> ## Considerations
> 
> ### STARTUP
> 
> If you are using the state of a platform that takes extra time to load, the Template Sensor may get an `unknown` state during startup. To avoid this (and the resulting error messages in your log file), you can use `is_state()` function in your template. For example, you would replace `{{ is_state('switch.source', 'on') }}` with this equivalent that returns `true` / `false` and never gives an `unknown` result:
> 
> `{{ is_state('switch.source', 'on') }}`

A questão agora é como fazer o que aqui diz ou então dar a volta a isto e colocar tipo um delay…

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [13 Julho , 2019 12:02 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/6 "2019-07-13T12:02:44Z")

</div>

Isso que está na página do template sensor só funciona para valores binários (on/off, true/false, etc).

No template não podes usar wait nem delay.

A única solução é esperar um pouco até os valores aparecerem.

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [13 Julho , 2019 12:04 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/7 "2019-07-13T12:04:16Z")

</div>

era o que pensava, mas assim os erros no log mantêm-se… ☹  
Se criar um bínary sensor que fique on após por exemplo 1 minuto a seguir ao arranque do HA não dará para dar a volta a isto?

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [13 Julho , 2019 12:07 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/8 "2019-07-13T12:07:02Z")

</div>

Só aparecem até teres valores. Os valores vêm de onde?

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [13 Julho , 2019 12:12 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/9 "2019-07-13T12:12:06Z")

</div>

```auto
  - platform: mqtt
    name: "Casa energy today"
    state_topic: "tele/bhpzem/SENSOR"
    value_template: "{{ value_json.ENERGY.Today | round(1) }}"
    unit_of_measurement: "kWh"
    icon: mdi:power-socket-eu

  - platform: mqtt
    name: "Casa energy yesterday"
    state_topic: "tele/bhpzem/SENSOR"
    value_template: "{{ value_json.ENERGY.Yesterday | round(1) }}"
    unit_of_measurement: "kWh"
    icon: mdi:power-socket-eu

```

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [13 Julho , 2019 12:14 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/10 "2019-07-13T12:14:12Z")

</div>

Ahhh… MQTT…

Então isso é muito fácil de resolver. Basta adicionar `retain: true` em cada sensor. O que o retain faz e memorizar o último valor recebido e mantém-o até receber novo valor.

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [13 Julho , 2019 12:15 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/11 "2019-07-13T12:15:03Z")

</div>

simples… lol

Nem tal coisa me passou pela cabeça…

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [13 Julho , 2019 12:15 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/12 "2019-07-13T12:15:22Z")

</div>

Testa e diz se resolve o problema.

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [13 Julho , 2019 12:17 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/13 "2019-07-13T12:17:20Z")

</div>

Não resolve porque ao colocar o retain dá erro:

> Configuração inválidaVERIFICAR A CONFIGURAÇÃO
> 
> Invalid config for [sensor.mqtt]: [retain] is an invalid option for [sensor.mqtt]. Check: sensor.mqtt-\>retain. (See ?, line ?). Please check the docs at [https://home-assistant.io/components/sensor.mqtt/](https://home-assistant.io/components/sensor.mqtt/) Invalid config for [sensor.mqtt]: [retain] is an invalid option for [sensor.mqtt]. Check: sensor.mqtt-\>retain. (See ?, line ?). Please check the docs at [https://home-assistant.io/components/sensor.mqtt/](https://home-assistant.io/components/sensor.mqtt/)

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [13 Julho , 2019 12:18 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/14 "2019-07-13T12:18:50Z")

</div>

Mostra como ficou o código.

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [13 Julho , 2019 12:19 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/15 "2019-07-13T12:19:50Z")

</div>

```auto
  - platform: mqtt
    name: "Casa energy today"
    state_topic: "tele/bhpzem/SENSOR"
    value_template: "{{ value_json.ENERGY.Today | round(1) }}"
    unit_of_measurement: "kWh"
    icon: mdi:power-socket-eu
    retain: true

```

Seria assim, certo?

---

<div class="post-metadata">

**Author:** ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)\
**Post date:** [13 Julho , 2019 12:23 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/16 "2019-07-13T12:23:02Z")

</div>

Sim mas aparentemente foi descontinuadao o retain.

> **[MQTT Sensor](https://www.home-assistant.io/integrations/sensor.mqtt)**
>
> Instructions on how to integrate MQTT sensors within Home Assistant.

Experimenta usar o `force_update`.

---

<div class="post-metadata">

**Author:** ![fsilva80](https://forum.cpha.pt/user_avatar/forum.cpha.pt/fsilva80/32/4484_2.png) [@fsilva80](https://forum.cpha.pt/u/fsilva80)\
**Post date:** [13 Julho , 2019 12:28 UTC](https://forum.cpha.pt/t/erro-em-calculo-de-custos/2729/17 "2019-07-13T12:28:14Z")

</div>

não funciona, demora sempre um pouco a dar o valores…  
Paciência, parece que vou ter de viver com esses erros no log…
