homecontrol-dht/main.py

62 lines
No EOL
1.8 KiB
Python

import dht
import machine
import utime as time
import urequests as requests
import uuid
import ujson
import wifi
CONFIG = "config.json"
ADDRESS="http://192.168.11.11:5000"
TIMEOUT_UPDATE = 600
class SensorDHT:
def __init__(self):
self.config = {}
try:
config_file = open(CONFIG, "r")
self.config = ujson.load(config_file)
except Exception as ex:
print("Exception\n\ttype: %s\n\targs: %s" % (type(ex).__name__, ex.args))
update_config = False
if not self.config.get("id_t"):
update_config = True
self.config["id_t"] = uuid.uuid4().hex
if not self.config.get("id_h"):
update_config = True
self.config["id_h"] = uuid.uuid4().hex
if update_config:
with open(CONFIG, "w") as config_file:
ujson.dump(self.config, config_file)
self.id_t = self.config["id_t"]
self.id_h = self.config["id_h"]
self.d = dht.DHT22(machine.Pin(2))
def update(self):
self.d.measure()
t = float(self.d.temperature())
h = float(self.d.humidity())
print("T: %f, H: %f" % (t, h))
self.send_update(self.id_t, "temperature", t)
self.send_update(self.id_h, "humidity", h)
def send_update(self, id_s, type_s, value):
url = "%s/sensor/update" % ADDRESS
data = {"id": id_s, "type": type_s, "value": value}
try:
r = requests.post(url, json=data)
# remember to close
r.close()
except Exception as ex:
print("Exception\n\tdata: %s\n\ttype: %s\n\targs: %s" % (data, type(ex).__name__, ex.args))
if __name__ == "__main__":
w = wifi.wifi()
w.connect()
sensor = SensorDHT()
while True:
sensor.update()
time.sleep(TIMEOUT_UPDATE)