11import asyncio
22import json
3- import sys
4- import time
3+ import traceback
54
65import serial
76import logging
@@ -34,7 +33,7 @@ async def __init__(self, websocket, path):
3433
3534 self .websocket = websocket
3635 self .serialOpen = False
37-
36+ self . ser = None
3837 await self .mainLoop ()
3938
4039 async def commandParser (self , body ):
@@ -84,7 +83,6 @@ def openSerialMontor(self, port, baudRate):
8483 """
8584 logging .info (f"Opening serial monitor" )
8685 if not self .serialOpen :
87-
8886 self .serialOpen = True
8987 self .ser = serial .Serial (
9088 port = port ,
@@ -108,34 +106,34 @@ def closeSerialMonitor(self):
108106 Serial monitörü kapatır
109107 """
110108 logging .info (f"Closing serial monitor" )
111- if self .serialOpen :
109+ if self .serialOpen and self . ser != None :
112110 self .ser .close ()
113111 self .serialOpen = False
114112
115113 async def serialLog (self ):
116114 """
117115 Serial monitörü okur ve websocket aracılığı ile web tarafına gönderir
118116 """
119- waiting = self .ser .in_waiting
120- try :
121- line = self .ser .read (waiting ).decode ("utf-8" )
122- except :
123- return
124- if line == "" :
125- return
126- # print(line, end="")"
127- bodyToSend = {"command" :"serialLog" , "log" :line }
128- bodyToSend = json .dumps (bodyToSend )
129- await self .websocket .send (bodyToSend )
117+ if self .serialOpen and self .ser != None :
118+ waiting = self .ser .in_waiting
119+ try :
120+ line = self .ser .read (waiting ).decode ("utf-8" )
121+ except :
122+ return
123+ if line == "" :
124+ return
125+ # print(line, end="")"
126+ bodyToSend = {"command" :"serialLog" , "log" :line }
127+ bodyToSend = json .dumps (bodyToSend )
128+ await self .websocket .send (bodyToSend )
130129
131130 async def mainLoop (self ):
132131 """
133132 Ana döngü, her döngüde, web tarafından mesaj gelip gelmediğini kontrol eder, veri geldiyse commandParser()'a gönderir,
134133 aksi halde serial monitör açık ise serialLog()'u çalıştırır
135134 """
136- try :
137- while True :
138-
135+ while True :
136+ try :
139137 if not self .serialOpen :
140138 await asyncio .sleep (.3 )
141139
@@ -151,7 +149,11 @@ async def mainLoop(self):
151149 await self .serialLog ()
152150
153151 await self .commandParser (body )
154- except :
155- logging .info ("Closing Serial Monitor." )
156- finally :
157- sys .exit ()
152+
153+ except Exception as e :
154+ logging .info ("Serial Monitor Error" )
155+ logging .exception ("Because!: " )
156+ traceback .print_exc ()
157+ bodyToSend = {"command" : "serialLog" , "log" : str (e )+ "\n " }
158+ bodyToSend = json .dumps (bodyToSend )
159+ await self .websocket .send (bodyToSend )
0 commit comments