Last active
November 25, 2020 18:31
-
-
Save quicklywilliam/f2efafbbbcb94932ba8528d361f01526 to your computer and use it in GitHub Desktop.
Flask Server for Temperature Sensor and Binary Temperature Threshold Sensor
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
# Use this along with Home Assistant's RESTful Sensor Platform (https://home-assistant.io/components/sensor.rest/) | |
# to create a temperature sensor using a Raspberry Pi and a DS18B20 probe. | |
# | |
# In my case this was being used in a sauna (using a waterproof probe https://www.sparkfun.com/products/11050) | |
# so I also wanted a binary sensor that indicated whether the temperature had reached a certain threshold or not. | |
import os | |
import glob | |
import time | |
from flask import Flask, Response, json | |
app = Flask(__name__) | |
os.system('modprobe w1-gpio') | |
os.system('modprobe w1-therm') | |
base_dir = '/sys/bus/w1/devices/' | |
device_folder = glob.glob(base_dir + '28*')[0] | |
device_file = device_folder + '/w1_slave' | |
@app.route("/temp") | |
def read_temp(): | |
lines = read_temp_raw() | |
while lines[0].strip()[-3:] != 'YES': | |
time.sleep(0.2) | |
lines = read_temp_raw() | |
equals_pos = lines[1].find('t=') | |
if equals_pos != -1: | |
temp_string = lines[1][equals_pos+2:] | |
temp_c = float(temp_string) / 1000.0 | |
temp_f = temp_c * 9.0 / 5.0 + 32.0 | |
d = {'temp_c': temp_c, 'temp_f': temp_f, 'hot': ('true' if temp_f>160 else 'false')} | |
return Response(json.dumps(d), mimetype='application/json') | |
def read_temp_raw(): | |
f = open(device_file, 'r') | |
lines = f.readlines() | |
f.close() | |
return lines | |
app.run(host='0.0.0.0') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment