# Sample code to request the state fron JSON service.
API_PASSWORD = 'YOUR_PASSWORD'
URL = 'http://x.x.x.x:xxxx/api/states/'
ENTITY = 'sensor'
TIMEOUT = 30
PIN = 5
def get_data():
import urequests
url = '{}{}'.format(URL, ENTITY)
headers = {'x-ha-access': API_PASSWORD,
'content-type': 'application/json'}
resp = urequests.get(URL, headers=headers)
return resp.json()['state']
def main():
import machine
import time
pin = machine.Pin(PIN, machine.Pin.OUT)
while True:
try:
if int(get_data()) >= 20:
pin.high()
else:
pin.low()
except TypeError:
pass
time.sleep(TIMEOUT)
if __name__ == '__main__':
print('Get the state of {}'.format(ENTITY))
main()