ce2c71011df57b2a2fe5aa0c81c332ff180c3182
[EVA-2020-02.git] / exec / temperature / DS18B20..temp_poll.py
1 #!/usr/bin/env python3
2 # Desc: Prints time and temperature reading
3 # Output: [date (ISO-8601)],[date (Unix Epoch)],[temp (°C)]
4 # Depends: python 3.3
5 # Ref/Attrib: Raspberry Pi Temprature Sensor using the DS18B20; https://pimylifeup.com/raspberry-pi-temperature-sensor/
6
7 import os
8 import glob
9 import time
10 from time import strftime
11 import socket
12
13 os.system('modprobe w1-gpio')
14 os.system('modprobe w1-therm')
15
16 base_dir = '/sys/bus/w1/devices/'
17 device_folder = glob.glob(base_dir + '28*')[0]
18 device_file = device_folder + '/w1_slave'
19
20 def read_temp_raw():
21 f = open(device_file, 'r')
22 lines = f.readlines()
23 f.close()
24 return lines
25
26 def read_temp():
27 lines = read_temp_raw()
28 while lines[0].strip()[-3:] != 'YES':
29 time.sleep(0.2)
30 lines = read_temp_raw()
31 equals_pos = lines[1].find('t=')
32 if equals_pos != -1:
33 temp_string = lines[1][equals_pos+2:]
34 temp_c = float(temp_string) / 1000.0
35 temp_f = temp_c * 9.0 / 5.0 + 32.0
36 temp_c_2dec = f"{temp_c:.5f}" # https://stackoverflow.com/a/15263885/10850071
37 #return temp_c, temp_f
38 return temp_c_2dec
39
40
41 myHostname = socket.gethostname()
42
43 while True:
44 nowTimeIso8601 = strftime("%Y%m%dT%H%M%S%z")
45 nowTimeUE = strftime("%s")
46 nowTemp = read_temp()
47 print(str(nowTimeIso8601) + ',' + str(nowTimeUE) + ',' + str(myHostname) + ',' + str(nowTemp), flush=True) # flush to stdout continuously (e.g. without buffer) https://stackoverflow.com/a/14729823
48 time.sleep(10)