@gpbenton & other people who know a little python or Jinja2
I am using the arduino component to bring in analog sensor values. These values are scaled differently then the needed outcome. With a sensor connected to the arduino I get a range of ~190 to 965 but the required scale is 4 to 20.
My script below uses the homeassistant.remote module to read the current values and create a new entity with the correct state.
As you can see from the image there are 8 total inputs that need to be handled but right now my script is only taking care of one of them sensor.A0 creates sensor.analog…
My question is: What is the most efficient way to handle 8-16 sensors in this fashion?
It would be nice to make the transaction occur only when a A* sensor changes state.
It should also be possible to create a single function with the equation and then pass the state of the changed entity through that function. Correct?
Or would be best thing be to repeat my script for every A* sensor?
*Side note: I tried a template sensor in the beginning but I couldn’t figure out how to accomplish the math with Jinja2. I am open to other resolutions…
Regards,
Mike
import string
import math
import time
from decimal import getcontext, Decimal
getcontext().prec = 4
import homeassistant.remote as remote
api = remote.API('127.0.0.1')
while True:
# get state of arduino analog sensor
a0 = int(remote.get_state(api, 'sensor.a0').state)
# perform scale equation
iMin = int(190)
iMax = int(965)
oMin = int(4)
oMax = int(20)
ispan = int(iMax - iMin)
ospan = int(oMax - oMin)
a0_scaled = Decimal((a0 - iMin) / ispan)
a0_output = Decimal(oMin + (a0_scaled * ospan))
#update state of new entity with scaled values between 4 and 20 "mA"
if a0_output <= 4:
remote.set_state(api, 'sensor.analog', new_state=str(4.0), attributes={'unit_of_measurement': 'mA'})
time.sleep(30)
elif a0_output >= 20:
remote.set_state(api, 'sensor.analog', new_state=str(20.0), attributes={'unit_of_measurement': 'mA'})
time.sleep(30)
else:
remote.set_state(api, 'sensor.analog', new_state=str(a0_output), attributes={'unit_of_measurement': 'mA'})
time.sleep(30)