-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDS18B20.py
More file actions
79 lines (59 loc) · 1.62 KB
/
DS18B20.py
File metadata and controls
79 lines (59 loc) · 1.62 KB
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
73
74
75
76
77
78
79
# coding:utf-8
from __future__ import division
import os
import logging
# os.system('modprobe w1-gpio')
# os.system('modprobe w1-therm')
class SensorException(Exception):
"""
Sensor exception
"""
pass
# class SensorNotFound(SensorException):
# """
# there is no sensors
# """
# pass
class NotReady(SensorException):
"""
sensor not ready to get temperature value
"""
pass
class DS18B20():
BASE_DIRECTORY = "/sys/bus/w1/devices"
def __init__(self, sensor_name):
self.sensor_name = sensor_name
@classmethod
def get_sensors(cls):
"""
maybe multi sensor
"""
return [cls(s) for s in os.listdir(cls.BASE_DIRECTORY)
if s.startswith("28")]
def get_temperature(self):
try:
origin = self.get_origin()
except NotReady, e:
logging.error(e.message)
raise e
else:
degrees_c = origin / 1000
degrees_f = origin * 9 / 5000 + 32
return origin, degrees_c, degrees_f
def get_origin(self):
"""
get origin value
"""
with open(self.sensor_path) as f:
lines = f.readlines()
if lines[0].strip()[-3:] != "YES":
raise NotReady("temperature value not ready")
return float(lines[1].split("=")[1])
@property
def sensor_path(self):
return os.path.join(self.BASE_DIRECTORY, self.sensor_name, 'w1_slave')
if __name__ == "__main__":
sensors = DS18B20.get_sensors()
if sensors:
# "\u00B0"
print(sensors[0].get_temperature())