From 4e6625994f068ac2e1222f5ea1c37b4afc769ae2 Mon Sep 17 00:00:00 2001 From: Konstantin Koslowski Date: Thu, 27 Feb 2020 18:24:47 +0100 Subject: [PATCH] implement things, status updates, improve stability --- main.py | 85 ++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 69 insertions(+), 16 deletions(-) diff --git a/main.py b/main.py index a800999..b20fb5b 100644 --- a/main.py +++ b/main.py @@ -1,29 +1,82 @@ -import ujson +import ujson as json import utime as time from uwebsockets import client -HOST="ws://10.64.12.20:8100" -NODEID="esp8266-1234" +HOST="ws://10.64.12.15:8100" +ACTORID="esp8266-1234" +ACTORTYPE="neopixel" +MAXLEVEL = 100 NAME="esp8266-1234" +MAX_RETRIES = 10 def register(ws): - ret = { "command": "register", "nodeid": NODEID, "name": NAME, "ts": time.time()} - ws.send(ujson.dumps(ret)) + ret = { "command": "register", "nodeid": ACTORID, "nodetype": ACTORTYPE, "name": NAME, "maxlevel": MAXLEVEL} + ws.send(json.dumps(ret)) def listen(ws): - while (True): - msg = ws.recv() - if msg: - print("< {}".format(msg)) + retries = 0 + while (retries < MAX_RETRIES): + try: + message = ws.recv() + if message: + m = json.loads(message) + print("< {}".format(m)) + cmd = m.get("command") + if cmd == "registered": + pass + elif cmd == "get_status": + send_status(ws) + else: + print("unknown cmd: {}".format(cmd)) + + else: + retries += 1 + time.sleep(0.1) + except Exception as ex: + print("Exception fn: listen, type: {}, args: {}".format(type(ex).__name__, ex.args)) + retries += 1 + time.sleep(1) + ws.close() + +def send_status(ws): + # level = ((self.color[0] << 16) + (self.color[1] << 8) + self.color[2]) & 0xffffff + m = {"command": "status", "nodeid": ACTORID, "status": {"level": 99}} + message = json.dumps(m) + print("> {}".format(message)) + try: + ws.send(message) + except Exception as ex: + print("Exception fn: send_status, type: {}, args: {}".format(type(ex).__name__, ex.args)) def main(): - ws = client.connect(HOST) while (True): - print("register...") - register(ws) - print("listen...") - listen(ws) - time.sleep(5) + try: + print("connecting...") + ws = client.connect(HOST) + print("done.") + except Exception as ex: + print("Exception fn: main(connecting), type: {}, args: {}".format(type(ex).__name__, ex.args)) + time.sleep(3) + continue + + try: + print("registering...") + register(ws) + print("done.") + except Exception as ex: + print("Exception fn: main(registering), type: {}, args: {}".format(type(ex).__name__, ex.args)) + time.sleep(3) + continue + + try: + print("listening...") + listen(ws) + print("done.") + except Exception as ex: + print("Exception fn: main(listening), type: {}, args: {}".format(type(ex).__name__, ex.args)) + time.sleep(3) + continue + if __name__ == "__main__": - main() \ No newline at end of file + main()