-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsensors_03.py
90 lines (64 loc) · 2.25 KB
/
sensors_03.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import time
from multipledispatch import dispatch
from sense_hat import SenseHat
SLEEP_TIME = 200 # in ms
T_SAMPLES = 10
sensors_data = {"temperature": "", "humidity": "", "pressure": ""}
sense = SenseHat()
def _read_cpu_temp():
res = os.popen("vcgencmd measure_temp").readline() # nosec
t = float(res.replace("temp=", "").replace("'C\n", ""))
return t
def _read_sense_temp():
t1 = sense.get_temperature_from_humidity()
t2 = sense.get_temperature_from_pressure()
return (t1 + t2) / 2
def _read_sense_humidity():
return sense.get_humidity()
def _read_sense_pressure():
return sense.get_pressure()
# Use moving average of 10 measures to compensate CPU heating
def _avg_temp(t):
if not hasattr(_avg_temp, "lst"):
_avg_temp.lst = [t] * 10
else:
_avg_temp.lst = _avg_temp.lst[1:]
_avg_temp.lst.insert(9, t)
return sum(_avg_temp.lst) / 10
def _estimate_temp():
for _ in range(T_SAMPLES):
t_cpu = _read_cpu_temp()
t_sense = _read_sense_temp()
t_est = _avg_temp(t_sense - ((t_cpu - t_sense) / 1.5))
time.sleep(SLEEP_TIME / 1000)
return t_est
@dispatch()
def get_sensors_data():
"""Collects temperature, humidity and pressure measures from the Sense HAT.
Returns:
JSON dictionary: temperature, humidity and pressure measures
"""
sensors_data["temperature"] = _estimate_temp()
sensors_data["humidity"] = _read_sense_humidity()
sensors_data["pressure"] = _read_sense_pressure()
return json.dumps(sensors_data, indent=2)
@dispatch(str)
def get_sensors_data(sense): # noqa: F811
"""Collects a specific sensor measure from the Sense HAT.
Args:
sense (str): name of the sensor to read
Returns:
JSON dictionary: sensor name key and measure value
"""
if sense == "temperature":
return json.dumps({"temperature": _estimate_temp()}, indent=2)
elif sense == "humidity":
return json.dumps({"humidity": _read_sense_humidity()}, indent=2)
elif sense == "pressure":
return json.dumps({"pressure": _read_sense_pressure()}, indent=2)
else:
return json.dumps({"message": "sensor not found!"}, indent=2), 404