-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemperature_probe.py
59 lines (44 loc) · 1.66 KB
/
temperature_probe.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
import time
from pathlib import Path
from typing import Optional
import requests
from standalone_modules.shed_pi_module_utils.data_submission import (
ReadingSubmissionService,
)
# TODO: Remove the submission_service from the component, it's an anti pattern
class TempProbe:
def __init__(self, submission_service: ReadingSubmissionService):
self.device_id: int = None
base_dir = "/sys/bus/w1/devices/"
device_folder = Path.glob(base_dir + "28*")[0]
self.device_file = device_folder + "/w1_slave"
self.submission_service = submission_service
def read_temp_raw(self) -> list[str]:
with open(self.device_file, "r") as f:
lines = f.readlines()
f.close()
return lines
def is_data_available(self, lines: list) -> bool:
return lines[0].strip()[-3:] != "YES"
def read_temp(self) -> Optional[float]:
lines = self.read_temp_raw()
while self.is_data_available(lines):
time.sleep(0.2)
lines = self.read_temp_raw()
equals_pos = lines[1].find("t=")
if equals_pos != -1:
temp_string = lines[1][equals_pos + 2 :]
temp_c = float(temp_string) / 1000.0
return temp_c
def submit_reading(self) -> requests.Response:
"""
Submits a reading to an external endpoint
:return:
"""
probe_1_temp = self.read_temp()
# FIXME: Should this be a float or a string? Broke the test
data = {"temperature": str(probe_1_temp)}
response = self.submission_service.submit(
device_module_id=self.device_id, data=data
)
return response