forked from kinkintama/Deneyap-Kart-Web-Agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSerialMonitorWebsocket.py
213 lines (170 loc) · 7.05 KB
/
SerialMonitorWebsocket.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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import asyncio
import json
import traceback
from utils import Data
import serial
import logging
import config
import websockets
class aobject(object):
"""
Inheriting this class allows you to define an async __init__.
So you can create objects by doing something like `await MyClass(params)`
credit:https://stackoverflow.com/questions/33128325/how-to-set-class-attribute-with-await-in-init
"""
async def __new__(cls, *a, **kw):
instance = super().__new__(cls)
await instance.__init__(*a, **kw)
return instance
async def __init__(self):
pass
class SerialMonitorWebsocket(aobject):
"""
For serial monitor communication, for every front-end connection, one object is created
"""
async def __init__(self, websocket:websockets.legacy.server.WebSocketServerProtocol, path:str):
"""
:param websocket: websocket connection to front-end
:type websocket: websockets.legacy.server.WebSocketServerProtocol
:param path: need for websockets library to work. not used in this project
:type path: str
"""
logging.info(f"SerialMonitorWebsocket is object created")
self.websocket = websocket
self.serialOpen = False
self.ser = None
await self.mainLoop()
async def commandParser(self, body:dict) -> None:
"""
message send from front-end is first comes to here to redirect appropriate function
messages related to serial monitor comes to this class. other messages goes to Websocket class.
upload message is sent both this class and Websocket class. when new code is uploading serial monitor has to be closed.
:param body: data that sent from front-end. %100 has 'command' other keys are depended on command
:type body: dict
"""
command = body['command']
if command == None:
return
else:
await self.sendResponse()
if command == "upload":
await self.closeSerialMonitor()
elif command == "openSerialMonitor":
self.openSerialMontor(body["port"], body["baudRate"])
elif command == "closeSerialMonitor":
await self.closeSerialMonitor()
elif command == "serialWrite":
self.serialWrite(body["text"])
def serialWrite(self, text:str) -> None:
"""
simulates arduino's serial write function
:param text: string that will be send to Deneyap kart/mini.
:type text: str
"""
if self.serialOpen:
logging.info(f"Writing to serial, data:{text}")
self.ser.write(text.encode("utf-8"))
def openSerialMontor(self, port:str, baudRate:int) -> None:
"""
opens serial monitor to communicate with deneyap kart/mini
:param port: port that board is on, like COM4
:type port: str
:param baudRate: baud rate that serial monitor will be opened 9600, 115200 etc.
:type baudRate: int
"""
logging.info(f"Opening serial monitor")
if not self.serialOpen:
self.serialOpen = True
self.ser = serial.Serial()
self.ser.baudrate = baudRate
self.ser.port = port
if Data.boards[port] == config.deneyapKart:
self.ser.setDTR(False)
self.ser.setRTS(False)
self.ser.open()
elif Data.boards[port] == config.deneyapKart1A:
self.ser.setDTR(False)
self.ser.setRTS(False)
self.ser.open()
elif Data.boards[port] == config.deneyapKartG:
self.ser.setDTR(True)
self.ser.setRTS(True)
self.ser.open()
elif Data.boards[port] == config.deneyapMini:
self.ser.setDTR(True)
self.ser.setRTS(True)
self.ser.open()
elif Data.boards[port] == config.deneyapMiniv2:
self.ser.setDTR(True)
self.ser.setRTS(True)
self.ser.open()
elif Data.boards[port] == config.deneyapKart1Av2:
self.ser.setDTR(True)
self.ser.setRTS(True)
self.ser.open()
else:
self.ser.setDTR(True)
self.ser.setRTS(True)
self.ser.open()
async def sendResponse(self) -> None:
"""
send message back to front-end to say that message is received succesfully if this message is not send, front-end send message again.
"""
bodyToSend = {"command": "response"}
bodyToSend = json.dumps(bodyToSend)
logging.info(f"SerialMonitorWebsocket sending response back")
await self.websocket.send(bodyToSend)
async def closeSerialMonitor(self) -> None:
"""
closes serial monitor.
"""
logging.info(f"Closing serial monitor")
if self.serialOpen and self.ser != None:
self.ser.close()
bodyToSend = {"command":"closeSerialMonitor"}
bodyToSend = json.dumps(bodyToSend)
await self.websocket.send(bodyToSend)
self.serialOpen = False
async def serialLog(self) -> None:
"""
Reads whatever serial monitor has and sends to front-end
if there is no delay at code, front-end fails to keep up lags
"""
if self.serialOpen and self.ser != None:
try:
waiting = self.ser.in_waiting
line = self.ser.read(waiting).decode("utf-8")
except serial.SerialException:
await self.closeSerialMonitor()
return
except:
return
if line == "":
return
bodyToSend = {"command":"serialLog", "log":line}
bodyToSend = json.dumps(bodyToSend)
await self.websocket.send(bodyToSend)
async def mainLoop(self) -> None:
"""
main loop for serial monitor. checks if there is a message send my front-end if there is sends it to commandParser function.
priorities commands over serial read from board.
if there is no command, then it reads serial, if it is opened.
"""
while True:
try:
if not self.serialOpen:
await asyncio.sleep(.3)
body = {"command":None}
try:
message= await asyncio.wait_for(self.websocket.recv(), timeout=0.000001)
logging.info(f"SerialMonitorWebsocket received {message}")
body = json.loads(message)
except (asyncio.TimeoutError, ConnectionRefusedError):
if self.serialOpen:
await self.serialLog()
await self.commandParser(body)
except Exception as e:
logging.exception("Serial Monitor Error: ")
bodyToSend = {"command": "serialLog", "log": str(e)+"\n"}
bodyToSend = json.dumps(bodyToSend)
await self.websocket.send(bodyToSend)