-
Notifications
You must be signed in to change notification settings - Fork 21
/
uat-example-server.py
executable file
·63 lines (58 loc) · 1.93 KB
/
uat-example-server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/python3
import asyncio
import websockets
import json
connected = set()
variables = [
{ "cmd": "Var", "name": "a", "value": False },
{ "cmd": "Var", "name": "b", "value": 0 },
{ "cmd": "Var", "name": "c", "value": [False,0] },
{ "cmd": "Var", "name": "Example Location 1/Example Section 1", "value": 0 },
]
async def handler(websocket, path):
"""minimalistic uat server"""
connected.add(websocket)
try:
info = {
"cmd": "Info",
"protocol": 0,
"name": "Example",
"version": "1.00"
}
await websocket.send(json.dumps([info]))
async for data in websocket:
packet = json.loads(data)
print(f"< {json.dumps(packet)}")
for command in packet:
if command["cmd"] == "Sync":
data = json.dumps(variables)
print(f"> {data}")
await websocket.send(data)
finally:
connected.remove(websocket)
async def main():
"""toggle/change variables every second one by one"""
n = 0
while True:
await asyncio.sleep(1)
if n == 0:
variables[0]["value"] = not variables[0]["value"]
elif n == 1:
variables[1]["value"] = (variables[1]["value"]+1)%100
elif n == 2:
variables[2]["value"][1] += 1
if variables[2]["value"][1] == 2:
variables[2]["value"][0] = not variables[2]["value"][0]
variables[2]["value"][1] = 0
elif n == 3:
variables[3]["value"] = int(not variables[3]["value"])
for client in connected:
data = json.dumps([variables[n]])
print(f"> {data}")
await client.send(data)
n = (n+1)%4
start_server = websockets.serve(handler, "localhost", 65399)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.create_task(main())
loop.run_forever()