50 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Python
		
	
	
	
			
		
		
	
	
			50 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Python
		
	
	
	
#!/usr/bin/python3
 | 
						|
# -*- coding: utf-8 -*-
 | 
						|
 | 
						|
import requests
 | 
						|
import json
 | 
						|
import time
 | 
						|
import Adafruit_DHT
 | 
						|
 | 
						|
config = json.load(open("/etc/dht22_sensing.json"))
 | 
						|
 | 
						|
 | 
						|
def send_to_home_assistant(temperature, humidity):
 | 
						|
    # print(f"Sending temperature {temperature}, humidity {humidity}")
 | 
						|
    headers = {
 | 
						|
        'x-ha-access': config['token'],
 | 
						|
        'Authorization': "Bearer {}".format(config['token'])
 | 
						|
    }
 | 
						|
 | 
						|
    temperature_url = "{}/api/states/sensor.{}".format(
 | 
						|
        config['ha_url'], config['ha_temp_sensor_name'])
 | 
						|
    temperatur_data = {
 | 
						|
        "state": str(temperature),
 | 
						|
        "attributes": {
 | 
						|
            "device_class": "temperature",
 | 
						|
            "friendly_name": config['ha_temp_friendly_name'],
 | 
						|
            "unit_of_measurement": "°C"
 | 
						|
        }
 | 
						|
    }
 | 
						|
    requests.post(temperature_url, json=temperatur_data, headers=headers)
 | 
						|
 | 
						|
    humidity_url = "{}/api/states/sensor.{}".format(
 | 
						|
        config['ha_url'], config['ha_humidity_sensor_name'])
 | 
						|
    humidity_data = {
 | 
						|
        "state": str(humidity),
 | 
						|
        "attributes": {
 | 
						|
            "device_class": "humidity",
 | 
						|
            "friendly_name": config['ha_humidity_friendly_name'],
 | 
						|
            "unit_of_measurement": "%"
 | 
						|
        }
 | 
						|
    }
 | 
						|
    requests.post(humidity_url, json=humidity_data, headers=headers)
 | 
						|
 | 
						|
 | 
						|
if __name__ == "__main__":
 | 
						|
    while True:
 | 
						|
        sensor = Adafruit_DHT.DHT22
 | 
						|
        humidity, temperature = Adafruit_DHT.read_retry(sensor, config['dht_pin'])
 | 
						|
        send_to_home_assistant(temperature, humidity)
 | 
						|
        time.sleep(float(config['polling_sleep_time_seconds']))
 |