source: src/mlx/pirep.py@ 1104:efcef6ab0610

python3
Last change on this file since 1104:efcef6ab0610 was 1034:4836f52b49cd, checked in by István Váradi <ivaradi@…>, 3 years ago

Updated the flight type handling (re #357)

File size: 15.2 KB
Line 
1
2from .util import utf2unicode
3from .flight import Flight
4from .common import fixUnpickled
5
6from . import const
7import pickle as pickle
8import calendar
9import datetime
10import time
11
12#------------------------------------------------------------------------------
13
14## @package mlx.pirep
15#
16# The PIREP module.
17#
18# This module defines only one class, \ref PIREP. It is used to extract and
19# store the information needed for a PIREP. The saved PIREPs are pickled
20# instances of this class.
21
22#------------------------------------------------------------------------------
23
24class PIREP(object):
25 """A pilot's report of a flight."""
26 class Message(object):
27 """A message belonging to the PIREP."""
28 @staticmethod
29 def fromMessageData(messageData):
30 """Construct a message from a JSON message data."""
31 message = messageData["message"]
32 senderPID = messageData["senderPID"]
33 senderName = messageData["senderName"]
34
35 return PIREP.Message(message, senderPID, senderName)
36
37 def __init__(self, message, senderPID, senderName):
38 """Construct the message object."""
39 self.message = message
40 self.senderPID = senderPID
41 self.senderName = senderName
42
43 _flightTypes = { const.FLIGHTTYPE_SCHEDULED : "SCHEDULED",
44 const.FLIGHTTYPE_VIP : "VIP",
45 const.FLIGHTTYPE_CHARTER : "CHARTER",
46 const.FLIGHTTYPE_OLDTIMER : "OT" }
47
48 @staticmethod
49 def _formatLine(timeStr, line):
50 """Format the given time string and line as needed for the ACARS and
51 some other things."""
52 return "[" + timeStr + "]-[" + line + "]"
53
54 @staticmethod
55 def formatTimestampForRPC(t):
56 """Format the given timestamp for RPC."""
57 return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t))
58
59 @staticmethod
60 def parseTimestampFromRPC(s):
61 """Format the given timestamp for RPC."""
62 dt = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
63 return calendar.timegm(dt.utctimetuple())
64
65 @staticmethod
66 def decodeFlightTypeText(s):
67 """Decode the given flight type text."""
68 for (flighType, text) in PIREP._flightTypes.items():
69 if s==text:
70 return flighType
71 return const.FLIGHTTYPE_SCHEDULED
72
73 @staticmethod
74 def parseLogFromRPC(log):
75 """Parse the given log coming from the RPC."""
76 index = 0
77 entries = []
78
79 inTimeStr = False
80 inEntry = False
81
82 timestr = ""
83 entry = ""
84
85 while index<len(log):
86 c = log[index]
87 index += 1
88
89 if c==']':
90 if inEntry:
91 entries.append((timestr, entry))
92 timestr = ""
93 entry = ""
94
95 inTimeStr = False
96 inEntry = False
97 elif not inTimeStr and not inEntry:
98 if c=='[':
99 if timestr:
100 inEntry = True
101 else:
102 inTimeStr = True
103 elif inTimeStr:
104 timestr += c
105 elif inEntry:
106 entry += c
107
108 return entries
109
110 @staticmethod
111 def load(path):
112 """Load a PIREP from the given path.
113
114 Returns the PIREP object, or None on error."""
115 try:
116 with open(path, "rb") as f:
117 pirep = pickle.load(f, fix_imports = True, encoding = "bytes")
118 if "numCabinCrew" not in dir(pirep):
119 if "numCrew" not in dir(pirep):
120 pirep.numCabinCrew = pirep.bookedFlight.numCabinCrew
121 else:
122 pirep.numCabinCrew = pirep.bookedFlight.numCrew
123 if "numPassengers" not in dir(pirep):
124 pirep.numPassengers = pirep.bookedFlight.numPassengers
125 if "numChildren" not in dir(pirep):
126 pirep.numChildren = 0
127 if "numInfants" not in dir(pirep):
128 pirep.numInfants = 0
129 if "bagWeight" not in dir(pirep):
130 pirep.bagWeight = pirep.bookedFlight.bagWeight
131 if "mailWeight" not in dir(pirep):
132 pirep.mailWeight = pirep.bookedFlight.mailWeight
133 return pirep
134 except Exception as e:
135 print("Failed loading PIREP from %s: %s" % (path,
136 utf2unicode(str(e))))
137 return None
138
139 def __init__(self, flight):
140 """Initialize the PIREP from the given flight."""
141 if flight is None:
142 return
143
144 self.bookedFlight = flight.bookedFlight
145
146 self.numCabinCrew = flight.numCabinCrew
147 self.numPassengers = flight.numPassengers
148 self.numChildren = flight.numChildren
149 self.numInfants = flight.numInfants
150 self.bagWeight = flight.bagWeight
151 self.cargoWeight = flight.cargoWeight
152 self.mailWeight = flight.mailWeight
153
154 self.filedCruiseAltitude = flight.filedCruiseAltitude
155 self.cruiseAltitude = flight.cruiseAltitude
156 self.route = flight.route
157
158 self.departureMETAR = flight.departureMETAR.upper()
159 self.arrivalMETAR = flight.arrivalMETAR.upper()
160
161 self.departureRunway = flight.departureRunway.upper()
162 self.sid = flight.sid.upper()
163
164 self.star = flight.star
165 self.transition = flight.transition
166 self.approachType = flight.approachType.upper()
167 self.arrivalRunway = flight.arrivalRunway.upper()
168
169 self.online = flight.online
170
171 self.comments = flight.comments
172 self.flightDefects = flight.flightDefects
173 self.delayCodes = flight.delayCodes
174
175 self.blockTimeStart = flight.blockTimeStart
176 self.flightTimeStart = flight.flightTimeStart
177 self.flightTimeEnd = flight.flightTimeEnd
178 self.blockTimeEnd = flight.blockTimeEnd
179 self.flownDistance = flight.flownDistance
180 self.fuelUsed = flight.startFuel - flight.endFuel
181
182 logger = flight.logger
183 self.rating = logger.getRating()
184 self.logLines = logger.lines
185 self.faultLineIndexes = logger.faultLineIndexes
186
187 self.messages = []
188
189 def setupFromPIREPData(self, pirepData, bookedFlight):
190
191 self.bookedFlight = bookedFlight
192
193 self.numCabinCrew = int(pirepData["numCabinCrew"])
194 self.numPassengers = int(pirepData["numPassengers"])
195 self.numChildren = int(pirepData["numChildren"])
196 self.numInfants = int(pirepData["numInfants"])
197 self.bagWeight = int(pirepData["bagWeight"])
198 self.cargoWeight = int(pirepData["cargoWeight"])
199 self.mailWeight = int(pirepData["mailWeight"])
200
201 filedCruiseLevel = pirepData["filedCruiseLevel"].strip()
202 if filedCruiseLevel:
203 if filedCruiseLevel.startswith("FL"):
204 filedCruiseLevel = filedCruiseLevel[2:]
205 if filedCruiseLevel:
206 self.filedCruiseAltitude = int(filedCruiseLevel)*100
207 else:
208 self.filedCruiseAltitude = 10000;
209
210 cruiseLevel = pirepData["cruiseLevel"].strip()
211 if cruiseLevel:
212 if cruiseLevel.startswith("FL"):
213 cruiseLevel = cruiseLevel[2:]
214 if cruiseLevel:
215 self.cruiseAltitude = int(cruiseLevel[2:])*100
216 else:
217 self.cruiseAltitude = self.filedCruiseAltitude
218 self.route = pirepData["route"]
219
220 self.departureMETAR = pirepData["departureMETAR"]
221 self.arrivalMETAR = pirepData["arrivalMETAR"]
222
223 self.departureRunway = pirepData["departureRunway"]
224 self.sid = pirepData["sid"]
225
226 star = pirepData["star"].split(",")
227 self.star = star[0]
228 self.star.strip()
229
230 if len(star)>1:
231 self.transition = star[1]
232 self.transition.strip()
233 else:
234 self.transition = ""
235 self.approachType = pirepData["approachType"]
236 self.arrivalRunway = pirepData["arrivalRunway"]
237
238 self.online = int(pirepData["online"])!=0
239
240 self.comments = pirepData["comments"]
241 self.flightDefects = pirepData["flightDefects"]
242 self.delayCodes = pirepData["timeComment"]
243 if self.delayCodes=="UTC":
244 self.delayCodes = []
245 else:
246 self.delayCodes = self.delayCodes.split(", ")
247
248 flightDate = pirepData["flightDate"] + " "
249
250 self.blockTimeStart = \
251 PIREP.parseTimestampFromRPC(flightDate + pirepData["blockTimeStart"])
252 self.flightTimeStart = \
253 PIREP.parseTimestampFromRPC(flightDate + pirepData["flightTimeStart"])
254 self.flightTimeEnd = \
255 PIREP.parseTimestampFromRPC(flightDate + pirepData["flightTimeEnd"])
256 self.blockTimeEnd = \
257 PIREP.parseTimestampFromRPC(flightDate + pirepData["blockTimeEnd"])
258 self.flownDistance = float(pirepData["flownDistance"])
259 self.fuelUsed = float(pirepData["fuelUsed"])
260
261 # logger = flight.logger
262 self.rating = float(pirepData["rating"])
263
264 log = pirepData["log"]
265
266 self.logLines = PIREP.parseLogFromRPC(log)[1:]
267 if self.logLines and \
268 (self.logLines[0][0]=="LOGGER NG LOG" or
269 self.logLines[0][0]=="MAVA LOGGER X"):
270 self.logLines = self.logLines[1:]
271 numLogLines = len(self.logLines)
272
273 lastFaultLineIndex = 0
274 self.faultLineIndexes = []
275 for ratingText in pirepData["ratingText"].splitlines()[:-1]:
276 faultLines = PIREP.parseLogFromRPC(ratingText)
277 for (timeStr, entry) in faultLines:
278 for i in range(lastFaultLineIndex, numLogLines-1):
279 if timeStr>=self.logLines[i][0] and \
280 timeStr<self.logLines[i+1][0]:
281 self.logLines = self.logLines[:i+1] + \
282 [(timeStr, entry)] + self.logLines[i+1:]
283 self.faultLineIndexes.append(i+1)
284 lastFaultLineIndex = i+1
285 numLogLines += 1
286 break
287
288 self.messages = []
289 for messageData in pirepData["messages"]:
290 self.messages.append(PIREP.Message.fromMessageData(messageData))
291
292 @property
293 def flightDateText(self):
294 """Get the text version of the booked flight's departure time."""
295 return self.bookedFlight.departureTime.strftime("%Y-%m-%d")
296
297 @property
298 def flightTypeText(self):
299 """Get the text representation of the flight type."""
300 return PIREP._flightTypes[self.bookedFlight.flightType]
301
302 @property
303 def blockTimeStartText(self):
304 """Get the beginning of the block time in string format."""
305 return PIREP.formatTimestampForRPC(self.blockTimeStart)
306
307 @property
308 def flightTimeStartText(self):
309 """Get the beginning of the flight time in string format."""
310 return PIREP.formatTimestampForRPC(self.flightTimeStart)
311
312 @property
313 def flightTimeEndText(self):
314 """Get the end of the flight time in string format."""
315 return PIREP.formatTimestampForRPC(self.flightTimeEnd)
316
317 @property
318 def blockTimeEndText(self):
319 """Get the end of the block time in string format."""
320 return PIREP.formatTimestampForRPC(self.blockTimeEnd)
321
322 def getACARSText(self):
323 """Get the ACARS text.
324
325 This is a specially formatted version of the log without the faults."""
326 text = "[MAVA LOGGER X LOG]-[%s]" % (const.VERSION,)
327 for index in range(0, len(self.logLines)):
328 if index not in self.faultLineIndexes:
329 (timeStr, line) = self.logLines[index]
330 if timeStr is not None:
331 text += PIREP._formatLine(timeStr, line)
332 return text
333
334 def getRatingText(self):
335 """Get the rating text.
336
337 This is a specially formatted version of the lines containing the
338 faults."""
339 text = ""
340 for index in self.faultLineIndexes:
341 (timeStr, line) = self.logLines[index]
342 if timeStr is not None:
343 text += PIREP._formatLine(timeStr, line)
344 text += "\n"
345
346 text += "\n[Flight Rating: %.1f]" % (max(0.0, self.rating),)
347
348 return text
349
350 def getTimeComment(self):
351 """Get the time comment.
352
353 This is basically a collection of the delay codes, if any."""
354 if not self.delayCodes:
355 return "UTC"
356 else:
357 s = ""
358 for code in self.delayCodes:
359 if s: s += ", "
360 s += code
361 return s
362
363 def getSTAR(self):
364 """Get the STAR and/or the transition."""
365 star = self.star if self.star is not None else ""
366 if self.transition is not None:
367 if star: star += ", "
368 star += self.transition
369 return star.upper()
370
371 def save(self, path):
372 """Save the PIREP to the given file.
373
374 Returns whether the saving has succeeded."""
375 try:
376 with open(path, "wb") as f:
377 pickle.dump(self, f)
378 return None
379 except Exception as e:
380 error = utf2unicode(str(e))
381 print("Failed saving PIREP to %s: %s" % (path, error))
382 return error
383
384 def _serialize(self):
385 """Serialize the PIREP for JSON-RPC."""
386 attrs = {}
387 attrs["log"] = self.getACARSText()
388 attrs["flightDate"] = self.flightDateText
389 attrs["callsign"] = self.bookedFlight.callsign
390 attrs["departureICAO"] = self.bookedFlight.departureICAO
391 attrs["arrivalICAO"] = self.bookedFlight.arrivalICAO
392 attrs["numPassengers"] = self.numPassengers
393 attrs["numChildren"] = self.numChildren
394 attrs["numInfants"] = self.numInfants
395 attrs["numCabinCrew"] = self.numCabinCrew
396 attrs["cargoWeight"] = self.cargoWeight
397 attrs["bagWeight"] = self.bagWeight
398 attrs["mailWeight"] = self.mailWeight
399 attrs["online"] = 1 if self.online else 0
400 attrs["blockTimeStart"] = self.blockTimeStartText
401 attrs["blockTimeEnd"] = self.blockTimeEndText
402 attrs["flightTimeStart"] = self.flightTimeStartText
403 attrs["flightTimeEnd"] = self.flightTimeEndText
404 attrs["timeComment"] = self.getTimeComment()
405 attrs["fuelUsed"] = self.fuelUsed
406 attrs["departureRunway"] = self.departureRunway
407 attrs["arrivalRunway"] = self.arrivalRunway
408 attrs["departureMETAR"] = self.departureMETAR
409 attrs["arrivalMETAR"] = self.arrivalMETAR
410 attrs["filedCruiseLevel"] = self.filedCruiseAltitude / 100.0
411 attrs["cruiseLevel"] = self.cruiseAltitude / 100.0
412 attrs["sid"] = self.sid
413 attrs["route"] = self.route
414 attrs["star"] = self.star
415 attrs["approachType"] = self.approachType
416 attrs["comments"] = self.comments
417 attrs["flightDefects"] = self.flightDefects
418 attrs["ratingText"] = self.getRatingText()
419 attrs["rating"] = max(0.0, self.rating)
420 attrs["flownDistance"] = "%.2f" % (self.flownDistance,)
421 # FIXME: it should be stored in the PIREP when it is sent later
422 attrs["performDate"] = datetime.date.today().strftime("%Y-%m-%d")
423
424 return ([], attrs)
425
426 def __setstate__(self, state):
427 """Set the state from the given unpickled dictionary."""
428 self.__dict__.update(fixUnpickled(state))
Note: See TracBrowser for help on using the repository browser.