Skip to content

Instantly share code, notes, and snippets.

@matr1xp
Last active February 12, 2017 08:57
Show Gist options
  • Save matr1xp/032e31419be53cbcc379857a27403838 to your computer and use it in GitHub Desktop.
Save matr1xp/032e31419be53cbcc379857a27403838 to your computer and use it in GitHub Desktop.
Push DHT11/DS18B20 sensor data to Loopback API
#!/usr/bin/python
import os, time, datetime, glob
import sys
import requests
import Adafruit_DHT as DHT
dht_sensor = DHT.DHT11
dht_pin = 4
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
device_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(device_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
api_url = 'http://0.0.0.0:3000/api/'
# Get DHT11 sensor reading
def read_dht():
humidity, temperature = DHT.read_retry(dht_sensor, dht_pin)
return temperature, humidity
# Get DS18b20 raw sensor reading
def read_raw_temp():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
# Format raw sensor reading to get temperature
def read_ds_temp():
lines = read_raw_temp()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.5)
lines = read_raw_temp()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_str = lines[1][equals_pos+2:]
temp_c = float(temp_str) / 1000.0
return temp_c
def cleanup():
# Do sensor cleanup code
sys.exit(0)
try:
while True:
temp1, humidity = read_dht()
temp2 = read_ds_temp()
timestamp = "{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now())
dht11_payload = {'temperature': temp1, 'humidity': humidity, 'timestamp': timestamp}
ds18b20_payload = {'temperature': temp2, 'timestamp': timestamp}
# Do POST requrest to API url
requests.post(api_url+'DHT11', dht11_payload)
requests.post(api_url+'DS18B20', ds18b20_payload)
time.sleep(10)
except KeyboardInterrupt:
cleanup()
except IOError:
print("Error")
cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment