Get values (temperature and humidity) from DH22, round the values and send it to HomeAssistant
#!/usr/bin/python3 import Adafruit_DHT import time import requests def sendData(name, sensor, value, unit): headers = { 'Authorization': 'Bearer !!!TOKEN!!!', 'Content-type': 'application/json', } data = '{"state": "' + str(value) + '", "attributes": {"unit_of_measurement": "' + str(unit) + '", "friendly_name": "' + str(name) + '"}}' response = requests.post('http://192.168.178.114:8123/api/states/sensor.' + str(sensor), headers=headers, data=data) # The sensor type sensor = Adafruit_DHT.DHT22 # The GPIO17 - Board number 3 pin = '2' humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None and temperature is not None: epoch = int(time.time()) now = time.strftime('%d-%m-%Y %H:%M:%S', time.localtime(epoch)) sendData('KitchenPi Humidity', 'kitchenpi_humidity', round(humidity, 3), '%') sendData('KitchenPi Temperature', 'kitchenpi_temperature', round(temperature, 3), 'C') print('"{0:s}","{1:0.1f}","{2:0.1f}"'.format(now, temperature, humidity)) else: print('Failed to get reading. Try again!')