-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathds18b20.py
72 lines (51 loc) · 1.7 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
63
64
65
66
67
68
69
70
71
72
# -*- coding: utf-8 -*-
# The DS18B20 sensor should be connected as follows:
#
# / GND |────────────> GND
# | DATA |─────────┬──> GPIO4
# \ VCC |─┬─[4k7]─┘
# └──────────> 5V
# DS18B20 (bottom view)
#
import os
import re
import subprocess
W1_DEVICES = '/sys/bus/w1/devices/'
W1_SENSOR_PATTERN = re.compile('(10|22|28)-.+', re.IGNORECASE)
def modprobe(module):
return subprocess.check_call(['modprobe', module])
def init_w1():
modprobe('w1-gpio')
modprobe('w1-therm')
def is_w1_sensor(path):
return \
W1_SENSOR_PATTERN.match(path) and \
os.path.isfile(sensor_full_path(path))
def sensor_full_path(sensor):
return os.path.join(W1_DEVICES, sensor, 'w1_slave')
def read_whole_file(path):
with open(path, 'r') as f:
return f.read()
class InvalidW1Address(Exception):
def __init__(self, address):
super(InvalidW1Address, self).__init__()
self.address = address
def guard_against_invalid_address(address):
if not W1_SENSOR_PATTERN.match(address):
raise InvalidW1Address(address)
class DS18b20(object):
@staticmethod
def find_all():
return [DS18b20(x)
for x in sorted(os.listdir(W1_DEVICES)) if is_w1_sensor(x)]
def __init__(self, address):
guard_against_invalid_address(address)
self.address = address
def read(self):
readings = read_whole_file(sensor_full_path(self.address))
temp_token = 't='
temp_index = readings.find(temp_token)
if temp_index < 0:
return None
temp = readings[temp_index + len(temp_token):]
return float(temp) / 1000