-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.py
159 lines (122 loc) · 3.74 KB
/
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
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
import csv
import datetime
import time
from os.path import exists
import serial
import socketio
from aiohttp import web
from Packet import ModifyPacket
port = "COM4"
ser = None
sio = socketio.AsyncServer(cors_allowed_origins='*')
app = web.Application()
sio.attach(app)
background_handler = None
shouldWriteToFile = False
fileName = ""
fileHeaders = []
fileData = []
final_buf = []
async def writeToFile():
file_exists = exists(fileName)
temp = fileHeaders.copy()
temp.insert(0, "timestamp")
if file_exists:
with open(fileName, 'a', encoding='UTF8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=temp)
writer.writerows(fileData)
else:
with open(fileName, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=temp)
writer.writeheader()
writer.writerows(fileData)
fileData.clear()
async def saveToFile(line):
if shouldWriteToFile and len(fileHeaders) > 0:
data = line.split(";")
data.pop()
tempDict = {}
tempDict["timestamp"] = str(datetime.datetime.now())
for i in data:
telemetry = i.split(":")
telemetryHeader = telemetry[0]
telemetryValue = telemetry[1]
if telemetryHeader in fileHeaders:
tempDict[telemetryHeader] = telemetryValue
fileData.append(tempDict)
if len(fileData) > 100:
await writeToFile()
async def background_task():
while ser.is_open:
await sio.sleep(0.01)
try:
line = ser.readline().decode('utf-8').strip().replace("\n", "")
if line[:4] == "CWC!":
await saveToFile(line[4:])
await sio.emit('returnData', {"data": line[4:], "time": round(time.time() * 1000)})
elif line[:5] == "CWCA!":
d = line[5:]
if len(d) > 0:
print(d)
await sio.emit("alert", line[5:])
elif line[:5] == "CWCM!":
await sio.emit("mapData", line[5:])
except UnicodeDecodeError:
print("Unicode error")
@sio.event
async def attach(sid, newPort):
global ser
global port
port = newPort
ser = serial.Serial(port, 9600, timeout=3)
global background_handler
background_handler = sio.start_background_task(background_task)
@sio.event
async def detach(sid):
ser.close()
background_handler.cancel()
@sio.event
async def saveStatus(sid, data):
global shouldWriteToFile
global fileHeaders
global fileName
shouldWriteToFile = data["status"]
if shouldWriteToFile:
fileHeaders = data["fileHeader"]
fileName = data["fileName"]
else:
await writeToFile()
@sio.event
async def newValue(sid, data):
key = data["key"]
print(key[0])
if key[0]=="F":
packet = ModifyPacket(13,key[1:], float((data["value"])), "F")
elif key[0]=="B":
if int(data["value"])==0:
packet = ModifyPacket(13,key[1:], 0, "B")
else:
packet = ModifyPacket(13,key[1:], 13107, "B")
else:
packet = ModifyPacket(13,key[1:], int((data["value"])), "I")
ser.write(packet.data)
@sio.event
async def status(sid):
await sio.emit("returnStatus", ser.is_open if ser is not None else False)
@sio.event
async def connect(sid, environ):
print("connect ", sid)
await status(sid)
@sio.event
def disconnect(sid):
print('disconnect ', sid)
async def init_app():
# global ser
# global port
# port = "COM4"
# ser = serial.Serial(port, 9600, timeout=3)
#
# background_handler = sio.start_background_task(background_task)
return app
if __name__ == '__main__':
web.run_app(init_app(), port=8080)