This section was part of the blog post. As of today there are limitations in the urequest library which will not allow you to use HTTP POSTs with Home Assistant, Micropython, and an ESP8266.
A HTTP sensor would be the perfect starting point because there is no configuration needed for Home Assistant. The sensor’s name in the samples below is sensor.kitchen_temperature
which will give us the endpoint http://IP_ADDRESS:8123/api/states/sensor.kitchen_temperature
.
This curl
command will update the temperature or create the HTTP sensor.
$ curl -X POST -H "x-ha-access: YOUR_PASSWORD" \
-H "Content-Type: application/json" \
-d '{"state": "23", "attributes": {"friendly_name": "Kitchen Temperature", "unit_of_measurement": "°C"}}' \
http://IP_ADDRESS:8123/api/states/sensor.kitchen_temperature
If your ESP8266 is still running with the code from the blog post then the LED should be set to high.
Let’s do a HTTP POST with MicroPython. The conversion of the curl
command to use with urequests
is very simple. Basically it’s a one-liner but splitted to be easier to read and identical to Python’s Requests module.
>>> import urequests
>>> url = 'http://IP_ADDRESS:8123/api/states/sensor.kitchen_temperature'
>>> headers = {'x-ha-access': API_PASSWORD, 'content-type': 'application/json'}
>>> data = '{"state": "15", "attributes": {"friendly_name": "Kitchen Temperature", "unit_of_measurement": "°C"}}'
>>> resp = urequests.post(url, data=data, headers=headers)
>>> print(resp.json())
For this to work you need to comment out one line in api.py.
For additional information check the Home Assistant RESTful API documentation.