52 lines
No EOL
1.4 KiB
Python
52 lines
No EOL
1.4 KiB
Python
import dht
|
|
import machine
|
|
import utime as time
|
|
import urequests as requests
|
|
import uuid
|
|
import ujson
|
|
import wifi
|
|
|
|
CONFIG = "config.json"
|
|
|
|
class Node:
|
|
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))
|
|
|
|
if not self.config.get("nodeid"):
|
|
self.config["nodeid"] = uuid.uuid4().hex
|
|
with open(CONFIG, "w") as config_file:
|
|
ujson.dump(self.config, config_file)
|
|
|
|
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_value("temperature", t)
|
|
self.send_value("humidity", h)
|
|
|
|
def send_value(self, vtype, value):
|
|
url = "http://192.168.11.21:5000/node/add_value"
|
|
data = {"nodeid": self.config["nodeid"], "type": vtype, "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()
|
|
node = Node()
|
|
|
|
while True:
|
|
node.update()
|
|
time.sleep(5) |