-
Notifications
You must be signed in to change notification settings - Fork 0
/
cscmuVatsimapi.py
273 lines (236 loc) · 9.12 KB
/
cscmuVatsimapi.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
from asyncore import write
from datetime import date
import calendar
from mimetypes import init
from cmu_graphics import *
import requests
import math
import json
import time
import os
import csv
from ccvaClasses import *
app.ticksPerSecond = 60
app.background = rgb(125,157,189)
app.currentRefreshTick = 0
refreshTick = 1200
vatsimID = 0
logNo = 0
response = requests.get("https://api.vatsim.net/api/")
baseLink = "https://api.vatsim.net/api/"
curDT = str(time.time_ns())
curfile = "./data/datafile"+curDT+".csv"
initGroup = Group()
routeGroup = Group()
curDate = ((str(time.asctime())).replace(":","-")).replace(" ","_")
print(curDate)
#Labels that display changable values from the fp
squawkG = Label("0000",375,15,bold=True)
squawkD = Label("Squawk:",335,15)
altitudeG = Label("0000",375,30,bold=True)
altitudeD = Label("Filed Alt:",330,30)
callsign = Label("-----",370,45,bold=True)
callsignD = Label("Callsign:",315,45)
cruisespdG = Label("000"+"kts",375,60,bold=True)
cruisespdD = Label("Cruise Speed:",315,60)
arrow = Line(75,350,325,350,lineWidth=5,arrowEnd=True)
dep = Label("----",20,350,bold=True,size=24,align='left')
arr = Label("----",380,350,bold=True,size=24,align='right')
altD = Label("Alt",200,365,size=12.5)
alt = Label("----",200,385,bold=True,size=15)
routeLabel = Label("Route:",10,25,size=20,bold=True,align='left')
weightD = Label('Weight Catagory:',305,75)
weightG = Label('----',370,75,bold=True)
guiGroup = Group(squawkG,altitudeG,squawkD,altitudeD,
callsign,callsignD,cruisespdD,cruisespdG,arrow,
dep,arr,alt,altD,weightD,weightG)
guiGroup.visible = False
routeGroup.visible = False
#ignore these, just the dicts and lists for the FTF and route list
FTF = {}
text = ""
routeList = []
log = {}
#Just asks if the gui is being shown, kinda unecessary because we can just call guiGroup.visible and use an If statement
guiUp = False
#prints any given JSON
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
#finds the vatsim CID from the txt file
CID = open('vatsimcid.txt','r')
vatsimID = CID.read().split('\n')[1]
CID.close()
def writeSomethingCSV(file,subj,body,notes):
csvCur = CurCSV(file)
curt = str(time.time_ns())
csvCur.writeFile(curt,subj,body,notes)
'''
This is the juicy stuff*. Val must be a JSON and what it does is it grabs the info from
the "result" entry in the main dict. The result from that is a list containing the
sub-dicts that outline each flight.
Eg: printResult(main JSON of fp) = [{fp1:'fp1'},{fp2_info:'fp2_data'}]
'''
def printResult(val):
filterToFlights = val['results']
FTF = filterToFlights.pop(0)
for i in FTF:
print(i,'->',FTF[i])
return FTF
def separateRoute(val):
route = val['route']
print("Filed Route Below:")
routeList = route.split()
mstrRouteList = route
routeLength = len(routeList)
for x in range(routeLength):
routeSnippet = routeList.pop(0)
print(routeSnippet)
return mstrRouteList
def initRoute(val):
route = val['route']
routeList = route.split()
routeLength = len(routeList)
lS2 = 50
for x in range(routeLength):
routeSnippet = routeList.pop(0)
line = Label(routeSnippet,15,lS2,bold=True,size=15,align='left')
routeGroup.add(line)
lS2 += 20
def stdLogUpt(subj):
route = ('./logs/log' + curDate + '.txt')
with open(route, 'a') as f:
f.write('( /// Time /// -' + curDate + ")\n")
f.write(f"({subj})\n\n")
f.write("(>~<)\n\n")
def initLogDir():
try:
open = open('./logs/logs.txt','r')
except FileNotFoundError:
os.mkdir("./logs/")
stdLogUpt("DIR UPD","'logs' dir not found. Creating new logs dir.")
try:
os.mkdir("./data/")
except:
pass
def uptLogPiece(subj):
route = ('./logs/log' + curDate + '.txt')
with open(route, 'a') as f:
f.write(subj)
def uptLog(subj,notes):
curTime = str(time.asctime())
uptLogPiece(f'/// Time /// - {curTime}\n')
uptLogPiece(f'Subject {subj}\n')
uptLogPiece(f'Notes: {notes}\n\n')
uptLogPiece("-------------------------|-------------------------\n\n")
'''
Initial text, virtually invisible. Just spits stuff out as it tests the connection.
It also grabs the current fp when opening to use as the base of the gui. This all gets
updated later, just so that we have info for the GUI off the bat
'''
def testSample(lS):
r1 = requests.get((baseLink+"ratings/"+str(vatsimID)+"/flight_plans/")) #My Id in Vatsim is 1669884
rr1 = r1.json()
FTFF = printResult(rr1)
routeFF = FTFF['route']
flPln = Label(("Current Flight Plan:"),5,lS,align="left",font="calibri",size=15,bold=True)
lS += 25
actFlPln = Label(routeFF,5,lS,align="left",font="calibri",size=15,bold=True)
lS += 25
allInfo = Label(FTFF,200,lS,align="left",font="calibri",size=7.5,bold=True)
lS += 25
initGroup.add(flPln,actFlPln,allInfo)
time.sleep(1.5)
return FTFF
connectAttempt = response.status_code
initGroupLineMaker = 25
if (connectAttempt == 200):
writeSomethingCSV(curfile,'Subject','Body Info','Notes(post scriptum)')
print("Return", connectAttempt)
print("Connection success.")
sucCon = Label("Connected to Vatsim API.",5,initGroupLineMaker,align="left",font="calibri",size=15,bold=True)
initGroupLineMaker += 25
initGroup.add(sucCon)
uptLog('INIT APP','App opened and is running properly.')
FTFF = testSample(initGroupLineMaker)
writeSomethingCSV(curfile,'INIT APP','App opened and is running properly.','Below is data recorded from SimConnect.')
else:
print("Error",connectAttempt)
erCon = Label(("Error",connectAttempt),5,initGroupLineMaker,align="left",font="calibri",size=15,bold=True)
initGroup.add(erCon)
initGroupLineMaker += 25
print("An unknown error has occured.")
uptLog("XX -|- FATAL ERROR -|- XX","An unknown error has occured. Network error No.",connectAttempt)
writeSomethingCSV(curfile,'FATAL ERROR','An unknown network error has occured.',f'Error code: {connectAttempt}')
erCon2 = Label("An unknown error has occured.",5,initGroupLineMaker,align="left",font="calibri",size=15,bold=True)
initGroup.add(erCon2)
initGroupLineMaker += 25
stopApp = Label("Stopping the App.",5,initGroupLineMaker,align="left",font="calibri",size=15,bold=True)
writeSomethingCSV(curfile,'APP STOP COMMAND','App is stopping.','This is the end of the file.')
app.stop()
eUI = "yes" # app.getTextInput("Enter GUI?").lower()
if (eUI == "yes"):
initGroup.visible = False
guiUp = True
guiGroup.visible = True
routeGroup.visible = True
uptLog("GUI START","GUI has been entered, exiting startup stage.")
elif (eUI == "no"):
clA = app.getTextInput("Close Program?").lower()
if (clA == "yes"):
print("App stopped intentionally. Closing the program.")
uptLog("APP STOP", "App stopped intentionally.")
writeSomethingCSV(curfile,'APP STOP COMMAND','App is stopping.','This is the end of the file.')
app.stop()
else:
pass
app.currentRefreshTick = 1200
def refreshRoute():
routeGroup.clear()
initRoute(FTFF)
def updateData():
writeSomethingCSV(curfile,'----','DATA PACKET START','----')
writeSomethingCSV(curfile,'NO DATA','No data is available to display.','This feature is not available, however if you see this it works :)')
writeSomethingCSV(curfile,'----','DATA PACKET END','----')
pass
def logMasterUpdate(alt,aspd,squawk,notes=None):
mstrRoute = separateRoute(FTFF)
routeString = str(mstrRoute)
print(routeString)
stdLogUpt(f'Route Fetch: {routeString})\n(Altitude Assg {alt})\n(Airspeed assg {aspd})\n(Squawk Assigned {squawk})')
def getWeight():
global FTFF
aircraftFull = FTFF['aircraft']
print(f'Aircraft Type: {aircraftFull}')
weightClass = aircraftFull[-2]
print(f'Weight Class: {weightClass}')
if weightClass == 'L':
weightG.value = "Light"
elif weightClass == 'M':
weightG.value = 'Medium'
elif weightClass == 'H':
weightG.value = 'Heavy'
callsign.value += 'Heavy'
elif weightClass == 'S':
weightG.value = 'Super'
callsign.value += 'Super'
def onStep():
if (guiUp == False):
pass
elif (guiUp == True):
if (app.currentRefreshTick >= refreshTick):
app.currentRefreshTick = 0
FTFF = testSample(0)
squawkG.value = FTFF['assignedsquawk'] # note - maybe make an alert to show a change in code? Alteration etc
altitudeG.value = FTFF['altitude']
callsign.value = FTFF['callsign']
cruisespdG.value = FTFF['cruisespeed']+"kts"
dep.value = FTFF['dep']
arr.value = FTFF['arr']
alt.value = FTFF['alt']
getWeight()
logMasterUpdate(altitudeG.value, cruisespdG, squawkG, notes="Assigned")
refreshRoute()
updateData()
app.currentRefreshTick += 1
cmu_graphics.run()