Last active
July 29, 2020 21:25
-
-
Save riston/fe28b23754403ff62d33a6373606e076 to your computer and use it in GitHub Desktop.
Capture Dallas ds18b20 sensor temperature data and post it to Home Assistant (base source https://www.mkompf.com/weather/pionewiremini.html)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo '2-57/5 * * * * HA_TOKEN=OOOO HA_HOST=tik.tok.org python3 $HOME/temperature.py >> $HOME/temperature.log 2>&1' | crontab - |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import re, os, time, json | |
import http.client | |
HA_HOST = os.environ.get('HA_HOST') | |
HA_TOKEN = os.environ.get('HA_TOKEN') | |
# function: read and parse sensor data file | |
def read_sensor(path): | |
value = "U" | |
try: | |
f = open(path, "r") | |
line = f.readline() | |
if re.match(r"([0-9a-f]{2} ){9}: crc=[0-9a-f]{2} YES", line): | |
line = f.readline() | |
m = re.match(r"([0-9a-f]{2} ){9}t=([+-]?[0-9]+)", line) | |
if m: | |
value = str(float(m.group(2)) / 1000.0) | |
f.close() | |
except IOError as e: | |
print(time.strftime("%x %X"), "Error reading", path, ": ", e) | |
return value | |
def post_sensor(value): | |
conn = http.client.HTTPSConnection(HA_HOST) | |
payload = json.JSONEncoder().encode({ | |
'state': value, | |
'attributes': { | |
'unit_of_measurement': '°C' | |
} | |
}) | |
headers = { | |
'Content-Type': 'application/json', | |
'Authorization': 'Bearer {}'.format(HA_TOKEN) | |
} | |
conn.request("POST", "/api/states/sensor.garage_temperature", payload, headers) | |
res = conn.getresponse() | |
data = res.read() | |
print(data.decode("utf-8")) | |
conn.close() | |
def main(): | |
# define pathes to 1-wire sensor data | |
sensor_path = '/sys/bus/w1/devices/28-03129779e066/w1_slave' | |
# read sensor data | |
sensor_reading = read_sensor(sensor_path) | |
post_sensor(sensor_reading) | |
print(sensor_reading) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment