2019-11-03 14:56:56 +01:00
|
|
|
import machine
|
|
|
|
import utime as time
|
|
|
|
import urequests as requests
|
|
|
|
import uuid
|
|
|
|
import ujson
|
|
|
|
import wifi
|
|
|
|
import bh1750
|
|
|
|
|
|
|
|
CONFIG = "config.json"
|
2019-11-06 00:03:29 +01:00
|
|
|
ADDRESS="http://192.168.11.11:5000"
|
|
|
|
TIMEOUT_UPDATE = 600
|
2019-11-03 14:56:56 +01:00
|
|
|
|
|
|
|
class SensorBH1750:
|
|
|
|
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"):
|
|
|
|
update_config = True
|
|
|
|
self.config["id"] = uuid.uuid4().hex
|
|
|
|
if update_config:
|
|
|
|
with open(CONFIG, "w") as config_file:
|
|
|
|
ujson.dump(self.config, config_file)
|
|
|
|
self.id_s = self.config["id"]
|
|
|
|
|
|
|
|
self.i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
|
|
|
|
self.s = bh1750.BH1750(self.i2c)
|
|
|
|
self.s.on()
|
|
|
|
|
|
|
|
def update(self):
|
|
|
|
mode=bh1750.BH1750.ONCE_HIRES_1
|
|
|
|
l = float(self.s.luminance(mode))
|
|
|
|
print("luminance: %f" % l)
|
|
|
|
self.send_update(self.id_s, "luminance", l)
|
|
|
|
|
|
|
|
def send_update(self, id_s, type_s, value):
|
2019-11-06 00:03:29 +01:00
|
|
|
url = "%s/sensor/update" % ADDRESS
|
2019-11-03 14:56:56 +01:00
|
|
|
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 = SensorBH1750()
|
|
|
|
|
|
|
|
while True:
|
|
|
|
sensor.update()
|
|
|
|
time.sleep(TIMEOUT_UPDATE)
|