Skip to content

Instantly share code, notes, and snippets.

@bkbilly
Last active June 19, 2020 17:26
Show Gist options
  • Save bkbilly/149599350fb6a02a8955e41537531a7c to your computer and use it in GitHub Desktop.
Save bkbilly/149599350fb6a02a8955e41537531a7c to your computer and use it in GitHub Desktop.
[Unit]
Description=Home assistant service for Temperature/Humidity
[Service]
ExecStart=/usr/bin/python3 /opt/remotehomeassistant_dht11.py
WorkingDirectory=/opt/
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi
[Install]
WantedBy=multi-user.target
#!/usr/bin/env python3
import time
import Adafruit_DHT
import requests
# Initial the dht device, with data pin connected to:
gpio = 14
url = 'https://homeassistanturl:8123'
name = 'raspberry'
key = 'Bearer ........................'
refreshrate = 30
force_count = 60
count = 0
old_humidity = 0
old_temperature = 0
sensor=Adafruit_DHT.DHT11
while True:
try:
humidity, temperature_c = Adafruit_DHT.read_retry(sensor, gpio)
if old_temperature != temperature_c or count == 0:
requests.post('{}/api/states/sensor.{}_temperature'.format(url, name),
headers={'Authorization': key},
json={"state": temperature_c,
"attributes": {
"unit_of_measurement": "°C",
"device_class": "temperature",
}
}
)
old_temperature = temperature_c
print('sent new temp data')
if old_humidity != humidity or count == 0:
requests.post('{}/api/states/sensor.{}_humidity'.format(url, name),
headers={'Authorization': key},
json={"state": humidity,
"attributes": {
"unit_of_measurement": "%",
"device_class": "humidity",
}
}
)
old_humidity = humidity
print('sent new humidity data')
if count == 0:
count = force_count
count -= 1
print("Temp: {:.1f} C Humidity: {}% ".format(temperature_c, humidity))
except Exception as error:
print(error.args[0])
time.sleep(refreshrate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment