homecontrol-dht: add more functionality

This commit is contained in:
Konstantin Koslowski 2019-11-03 14:00:07 +01:00
parent 8c14db6565
commit dbdf3e0207

32
main.py
View file

@ -7,8 +7,10 @@ import ujson
import wifi import wifi
CONFIG = "config.json" CONFIG = "config.json"
ADDRESS="http://192.168.11.21:5000"
TIMEOUT_UPDATE = 5
class Node: class SensorDHT:
def __init__(self): def __init__(self):
self.config = {} self.config = {}
try: try:
@ -17,10 +19,18 @@ class Node:
except Exception as ex: except Exception as ex:
print("Exception\n\ttype: %s\n\targs: %s" % (type(ex).__name__, ex.args)) print("Exception\n\ttype: %s\n\targs: %s" % (type(ex).__name__, ex.args))
if not self.config.get("nodeid"): update_config = False
self.config["nodeid"] = uuid.uuid4().hex 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: with open(CONFIG, "w") as config_file:
ujson.dump(self.config, 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)) self.d = dht.DHT22(machine.Pin(2))
@ -29,12 +39,12 @@ class Node:
t = float(self.d.temperature()) t = float(self.d.temperature())
h = float(self.d.humidity()) h = float(self.d.humidity())
print("T: %f, H: %f" % (t, h)) print("T: %f, H: %f" % (t, h))
self.send_value("temperature", t) self.send_update(self.id_t, "temperature", t)
self.send_value("humidity", h) self.send_update(self.id_h, "humidity", h)
def send_value(self, vtype, value): def send_update(self, id_s, type_s, value):
url = "http://192.168.11.21:5000/node/add_value" url = "%s/sensors/update" % ADDRESS
data = {"nodeid": self.config["nodeid"], "type": vtype, "value": value} data = {"id": id_s, "type": type_s, "value": value}
try: try:
r = requests.post(url, json=data) r = requests.post(url, json=data)
# remember to close # remember to close
@ -45,8 +55,8 @@ class Node:
if __name__ == "__main__": if __name__ == "__main__":
w = wifi.wifi() w = wifi.wifi()
w.connect() w.connect()
node = Node() sensor = SensorDHT()
while True: while True:
node.update() sensor.update()
time.sleep(5) time.sleep(TIMEOUT_UPDATE)