I am trying to write a simple Python script to modify a state based on the value of a different state. I based my code on various examples online and it updates the UI but does not update the connected device. Changing the state with an entity card does update the connected device. As far as I can tell I need to trigger a state_changed event but could not get that to work. Here is my code so far:
def run():
rate = hass.states.get("sensor.inverter_battery_state_of_charge")
if not rate:
return
rate = float(rate.state)
# logger.info(rate)
rate=rate - 20
if(rate < 0):
rate = 0
stateName = "number.inverter_timed_discharge_current"
current=hass.states.get(stateName)
if not current:
return
oldVal=float(current.state)
if(oldVal == rate):
return
hass.states.set(stateName, rate, current.attributes.copy())
# evtData={"entity_id":stateName,"old_state":oldState, "new_state":current}
# logger.info(evtData)
# hass.bus.fire("state_changed", evtData)
run()
The commented out stuff at the end is my attempt to fire an event but I could not find any way to copy the old state. Can anyone give me some pointers on where I am going wrong? I could not find any relevant Home Assistant documentation.