Skip to content

Instantly share code, notes, and snippets.

@d-ng

d-ng/WriteTemp.py

Created Nov 12, 2015
Embed
What would you like to do?
Gets data from a DS18B20 digital temperature sensor conntected to a Raspberry Pi and write to the PI System via PI Web API.
import requests
import time
import os
import glob
import re
base_url = 'https://<PI Web API server>/piwebapi'
webId = '<WebId to PI tag>'
base_dir = '/sys/bus/w1/devices/'
yes_pattern = re.compile(r'YES')
temp_pattern = re.compile('t=(\d+)')
def initialize_sensor():
os.system('sudo modprobe w1-gpio')
os.system('sudo modprobe w1-therm')
def get_sensor_file():
device_folder = glob.glob(base_dir + '28-*')[0]
return device_folder + '/w1_slave'
def read_temp_raw(file):
f = open(device_file,'r')
lines = f.read()
f.close()
return lines
def read_temp(file):
lines = read_temp_raw(file)
while not yes_pattern.search(lines):
time.sleep(0.2)
lines = read_temp_raw(file)
temp_string = temp_pattern.search(lines).group(1)
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_f
def post_pi_value(value):
data = {'Value': value}
headers = {'Content-Type': 'application/json'}
response = requests.post(base_url + '/streams/' + webId + '/value', json=data, headers=headers, verify=False)
return response
if __name__ == '__main__':
initialize_sensor()
device_file = get_sensor_file()
while True:
value = read_temp(device_file)
response = post_pi_value(value)
print(response)
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.