homecontrol-bh1750/main.py

58 lines
No EOL
1.7 KiB
Python

import machine
import utime as time
import urequests as requests
import uuid
import ujson
import wifi
import bh1750
CONFIG = "config.json"
ADDRESS="http://192.168.11.11:5000"
TIMEOUT_UPDATE = 600
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):
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 = SensorBH1750()
while True:
sensor.update()
time.sleep(TIMEOUT_UPDATE)