-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtemperature.py
More file actions
executable file
·66 lines (48 loc) · 1.67 KB
/
temperature.py
File metadata and controls
executable file
·66 lines (48 loc) · 1.67 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
#!/usr/bin/env python3
import os
from os import path
from settings import UR
class TemperatureInterface:
"""
DS18B20 interface.
"""
bus_devices_path = '/sys/bus/w1/devices'
family_code = 0x28
@classmethod
def discover_devices(cls):
prefix = '{:02x}-'.format(cls.family_code)
bus_devices = os.listdir(cls.bus_devices_path)
return [x for x in bus_devices if x.startswith(prefix)]
def __init__(self, device_id):
self.device_id = device_id
self.file_path = path.join('/sys/bus/w1/devices', device_id, 'w1_slave')
if not path.isfile(self.file_path):
raise Exception('File %s does not exist' % self.file_path)
def get_temperature(self):
lines = [line.strip() for line in open(self.file_path)]
if len(lines) != 2:
raise Exception('Invalid lines count')
if not lines[0].endswith(' YES'):
raise Exception('CRC check failed')
value = lines[1][lines[1].rindex('=') + 1:]
temp_C = int(value) / 1000.0
return temp_C * UR.degC
class ConstTemperatureInterface:
def __init__(self, value):
self.value = value
def get_temperature(self):
return self.value
def main():
devices = TemperatureInterface.discover_devices()
if len(devices) == 0:
raise Exception('No devices found')
sensors = [TemperatureInterface(id) for id in devices]
while True:
try:
for s in sensors:
temperature = s.get_temperature()
print('{} {}'.format(s.device_id, temperature))
except Exception as e:
print(e)
if __name__ == '__main__':
main()