Hello,
So I created a custom component that calls an API and sets custom states to be the values retrieved from that API.
The issue is that after the first run of this script, the states do not get updated with new values. I have to keep restarting home assistant to update the states.
I’m sure there is a better solution, but I cant figure it out. Any input is appreciated.
Edit:
Here is the code that retrieves and sets the state. It’s in init.py of a custom component. I created another automation in the UI to run this script at 12am each day. But the states are set on the first run only. They don’t get updated after that.
async def async_setup(hass, config):
"""Set up is called when Home Assistant is loading our component."""
times = await hass.async_add_executor_job(get_times)
def handle_times(call):
"""Handle the service call."""
time1 = convertTime(times['time1'], 0)
time2= convertTime(times['time2'], 0)
"""This sets the state in hass"""
hass.states.set('input_datetime.time1', time1)
hass.states.set('input_datetime.time2', time2)
async def async_handle_times(call):
await hass.async_add_executor_job(handle_times call)
hass.services.async_register(DOMAIN, "times", handle_times)
# Return boolean to indicate that initialization was successful.
return True
def get_times():
location = "xxxx"
apiKey = "xxxx"
url = "xxxx"
req = Request(url)
req.add_header('Accept', 'application/json')
req.add_header('Content-Type', 'application/json')
req.add_header('User-Agent', 'Mozilla/5.0 (X11; CrOS armv7l 13597.84.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.57 Safari/537.36')
response = urlopen(req).read().decode('utf-8')
jsonStr = json.loads(response)
times = jsonStr['items'][0]
return times
def convertTime(aTime, offset):
aTime = datetime.strptime(aTime, '%I:%M %p')
aTime = aTime + timedelta(hours=0, minutes=offset)
aTime = datetime.strftime(aTime, '%H:%M')
return aTime