-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient_handler.py
More file actions
91 lines (72 loc) · 3.04 KB
/
Copy pathclient_handler.py
File metadata and controls
91 lines (72 loc) · 3.04 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'''
This is a asynchronous function to handle with client requirements.
This client handler is with a strong bond to NewWalabotAppTemplate.py requirements.
Basic functions that must be:
start()
get_data()
stop()
Feel free to add your uwn function just note that you also support client-side commands.
The information is transmitted in json.
The protocol: {"Command": "", "Message": "", Params":[data]}
Two examples are attached : Breathing and Tracker
Follow TODO to add a new project
'''
import asyncio
import websockets
import json
import socket
from imp import load_source
import WalabotBreathing as breathing
import WalabotTracker as tracker
#####################################
# TODO import WalabotMyApp as my_app
#####################################
class WalabotHandler:
def __init__(self):
self.initialize = False
self.stop = False
async def commandsHandler(self ,client,path):
app = None
try:
print("Client connected..")
print(str(self.stop))
while not self.stop:
data = json.loads(await client.recv())
command = data['Command']
if command == 'BREATHING':
print(command)
app = breathing
elif command == "TRACKER":
print(command)
app = tracker
############################ ADD YOUR APP HERE ##################################
# TODO elif command == "MY_APP":
# print(command)
# app = my_app
##################################################################################
if not self.initialize:
self.initialize = True
app.start()
elif command == 'STOP':
print(command)
app.stop()
self.initialize=False
await client.send(json.dumps({"Command": "EXIT"}))
elif command == 'DATA':
try:
if self.initialize:
data = app.get_data()
res = {"Command": "DATA", "Params":[data] , "Message": ""}
await client.send(json.dumps(res))
else:
await client.send(json.dumps({"Command": "EXIT","Message": "App not initialized"}))
except:
res = {"Command": "ERROR", "Message": "App is NOT defined"}
await client.send(json.dumps(res))
else:
res = {"Command": "ERROR", "Message": "Unknown Command"}
await client.send(json.dumps(res))
except Exception as e:
print("Connection problem" + str(e))
res = {"Command": "ERROR", "Message": str(e)}
await client.send(json.dumps(res))