2019-10-23 00:13:22 +02:00
|
|
|
import dht
|
|
|
|
import machine
|
|
|
|
import utime as time
|
|
|
|
import urequests as requests
|
|
|
|
import uuid
|
|
|
|
import ujson
|
|
|
|
import wifi
|
|
|
|
|
|
|
|
CONFIG = "config.json"
|
2019-11-06 00:03:04 +01:00
|
|
|
ADDRESS="http://192.168.11.11:5000"
|
|
|
|
TIMEOUT_UPDATE = 600
|
2019-10-23 00:13:22 +02:00
|
|
|
|
2019-11-03 14:00:07 +01:00
|
|
|
class SensorDHT:
|
2019-10-23 00:13:22 +02:00
|
|
|
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))
|
|
|
|
|
2019-11-03 14:00:07 +01:00
|
|
|
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:
|
2019-10-23 00:13:22 +02:00
|
|
|
with open(CONFIG, "w") as config_file:
|
|
|
|
ujson.dump(self.config, config_file)
|
2019-11-03 14:00:07 +01:00
|
|
|
self.id_t = self.config["id_t"]
|
|
|
|
self.id_h = self.config["id_h"]
|
2019-10-23 00:13:22 +02:00
|
|
|
|
|
|
|
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))
|
2019-11-03 14:00:07 +01:00
|
|
|
self.send_update(self.id_t, "temperature", t)
|
|
|
|
self.send_update(self.id_h, "humidity", h)
|
2019-10-23 00:13:22 +02:00
|
|
|
|
2019-11-03 14:00:07 +01:00
|
|
|
def send_update(self, id_s, type_s, value):
|
2019-11-06 00:03:04 +01:00
|
|
|
url = "%s/sensor/update" % ADDRESS
|
2019-11-03 14:00:07 +01:00
|
|
|
data = {"id": id_s, "type": type_s, "value": value}
|
2019-10-23 00:13:22 +02:00
|
|
|
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()
|
2019-11-03 14:00:07 +01:00
|
|
|
sensor = SensorDHT()
|
2019-10-23 00:13:22 +02:00
|
|
|
|
|
|
|
while True:
|
2019-11-03 14:00:07 +01:00
|
|
|
sensor.update()
|
|
|
|
time.sleep(TIMEOUT_UPDATE)
|