82 lines
2.4 KiB
Python
82 lines
2.4 KiB
Python
import ujson as json
|
|
import utime as time
|
|
from uwebsockets import client
|
|
|
|
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": ACTORID, "nodetype": ACTORTYPE, "name": NAME, "maxlevel": MAXLEVEL}
|
|
ws.send(json.dumps(ret))
|
|
|
|
def listen(ws):
|
|
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():
|
|
while (True):
|
|
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()
|