import machine import neopixel import utime as time import urequests as requests import uuid import ujson import math import wifi CONFIG = "config.json" NUM_PIXEL = 24 ADDRESS = "http://192.168.11.11:5000" TIMEOUT_UPDATE = 5 class ActorNP: 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 not self.config.get("type"): update_config = True self.config["type"] = "neopixel" if not self.config.get("maxLevel"): update_config = True self.config["maxLevel"] = 0xffffff if update_config: with open(CONFIG, "w") as config_file: ujson.dump(self.config, config_file) self.id_a = self.config["id"] self.type_a = self.config["type"] self.maxLevel = self.config["maxLevel"] self.color = (0, 0, 0) self.np = neopixel.NeoPixel(machine.Pin(2), NUM_PIXEL) def update(self): url = "%s/actor/update" % ADDRESS level = ((self.color[0] << 16) + (self.color[1] << 8) + self.color[2]) & 0xffffff data = {"id": self.id_a, "type": self.type_a, "maxLevel": self.maxLevel, "level": level} try: res = requests.post(url, json=data) content = res.json() if "command" in content: command = content["command"] if command == "set_level": data = content["data"] level = int(data["level"]) self.set_level(level) # remember to close res.close() except Exception as ex: print("Exception\n\tdata: %s\n\ttype: %s\n\targs: %s" % (data, type(ex).__name__, ex.args)) def set_level(self, level): print("set_level: level: 0x%06x" % (level)) t = 1 steps = 25 t_step = t/steps br_step = 1/steps # turn off br = 1 r = self.color[0] g = self.color[1] b = self.color[2] if (r or g or b): for i in range(steps): br = br - br_step self.np.fill(self.col(r, g, b, br)) self.np.write() time.sleep(t_step) # turn on r = (level >> 16) & 0xff g = (level >> 8) & 0xff b = level & 0xff br = 0 if (r or g or b): for i in range(steps): br = br + br_step self.np.fill(self.col(r, g, b, br)) self.np.write() time.sleep(t_step) self.color = (r, g, b) def col(self, r, g, b, br): rr = int(math.ceil(r * br)) gg = int(math.ceil(g * br)) bb = int(math.ceil(b * br)) c = (rr, gg, bb) return(c) if __name__ == "__main__": w = wifi.wifi() w.connect() np = ActorNP() while True: np.update() time.sleep(TIMEOUT_UPDATE)