I use the Tuya zigbee meter PJ-1203A. that exposes the current of the two channels and the flow ( produce or consume ) as separate sensors. For automation purposes, I’m looking for the best way to combine those 2 information to end up with a signed current value ( positive if I consume / negative if I produce ).
I created a helper as per below, but the resulting sensor remains unavailable while the flow sensor changed from producing to consuming multiple times. I have no error in the logs.
Thanks in advanced for your help, I’m surprised this question didnt pop up yet, I hope it’s going to help others too !
You never need to cast a state to text, because it always is. Do check in developer tools though if these are the actual values.
Then, when you want the negative of a sensor, you need to convert it to float first. That is probably why it is unavailable. And last but not least, I’d suggest to use an availability template to make it unavailable when there’s something unexpected. Unfortunately that cannot be done in the gui, you’ll need to move this to a yaml template for that.
ps. If it works, it should also listen to the state of sensor sensor.grid_current_ss - are you sure you got the entity right? It does not resemble the entity id of the other sensor you use.
then about availability this is what the last else is supposed to take care of ( found another post ) : can you please provide pointers to the availability template : do you mean to change the code to :
{% else %}
{{ "unavailable" }}
{% endif %}
also I wonder if I shouldnt code like below with “”
{% if states('sensor.zb_meter_energy_flow_b') == "consuming" %}
if the IF conditions are never met and the “else > none” works, it would explain why I get no errors but an always “unavailable” sensor ?
As Edwin said, there’s no availability template in UI-created template sensor helpers. If you need to set availability, you’ll have to use YAML: here’s the documenation.
You should quote the string against which you are comparing the state of your (non-binary) sensor, otherwise it’ll be interpreted as a variable called consuming which doesn’t exist.
Also, if you’re setting a unit of measurement, the state must represent a numeric value unless the availability template returns false.
A full template sensor in YAML might look like this:
template:
- sensor:
- name: Current value
state: >
{{ states('sensor.grid_current_ss')|float(0)
* iif(is_state('sensor.zb_meter_energy_flow_b','producing'), -1, 1) }}
unit_of_measurement: 'A'
device_class: current
availability: "{{ states('sensor.zb_meter_energy_flow_b') in ['producing','consuming'] }}"
thank you both ! I might try again to reach the same through the helper by using the “template tool” in the development tool. but purely out of curiosity, fully happy with your “template sensor” solution in the yaml.