forked from thomaseichhorn/fhlthermorasp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ds18b20.py
62 lines (46 loc) · 1.5 KB
/
ds18b20.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
from os.path import join, exists
from collections import namedtuple
DS18B20Result = namedtuple("DS18B20Result", ("sensor_name", "is_valid", "temp"))
import os
import glob
import math
import time
import sys
class DS18B20:
def __init__(self, gpio):
self.gpio = gpio
master_map = {16:1,17:2,26:3,27:4}
master = master_map[gpio]
self.master = master
self.base_dir=f'/sys/bus/w1/devices/w1_bus_master{master}/'
self.device_folder = glob.glob(self.base_dir + '28*')[0]
self.device_file = self.device_folder + '/w1_slave'
def read_temp_raw(self):
with open(self.device_file, 'r') as f:
lines = f.readlines()
return lines
def read(self):
lines = self.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:]
self.temperature = float(temp_string) / 1000.0
return DS18B20Result(self.get_sensor_name(), True, self.temperature)
def get_sensor_type_name(self):
return "DS18B20"
def get_sensor_name(self):
return "DS18B20_w1_gpio-%i" % (self.gpio)
def get_sensor_fields(self):
return ["temp"]
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--gpio', type = int, default = 16)
args = parser.parse_args()
mydevice = DS18B20(args.gpio)
result = mydevice.read()
print("%s - is_valid:%r temperature:%.2f" % (result.sensor_name,result.is_valid, result.temp))