source: src/mlx/pirep.py@ 955:d98b211d32fa

python3
Last change on this file since 955:d98b211d32fa was 955:d98b211d32fa, checked in by István Váradi <ivaradi@…>, 5 years ago

Fixed pickling of PIREPs saved with Python 2 (re #347).

File size: 14.7 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_OLDTIMER : "OT",
45 const.FLIGHTTYPE_VIP : "VIP",
46 const.FLIGHTTYPE_CHARTER : "CHARTER" }
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 "numCrew" not in dir(pirep):
119 pirep.numCrew = pirep.bookedFlight.numCrew
120 if "numPassengers" not in dir(pirep):
121 pirep.numPassengers = pirep.bookedFlight.numPassengers
122 if "bagWeight" not in dir(pirep):
123 pirep.bagWeight = pirep.bookedFlight.bagWeight
124 if "mailWeight" not in dir(pirep):
125 pirep.mailWeight = pirep.bookedFlight.mailWeight
126 return pirep
127 except Exception as e:
128 print("Failed loading PIREP from %s: %s" % (path,
129 utf2unicode(str(e))))
130 return None
131
132 def __init__(self, flight):
133 """Initialize the PIREP from the given flight."""
134 if flight is None:
135 return
136
137 self.bookedFlight = flight.bookedFlight
138
139 self.numCrew = flight.numCrew
140 self.numPassengers = flight.numPassengers
141 self.bagWeight = flight.bagWeight
142 self.cargoWeight = flight.cargoWeight
143 self.mailWeight = flight.mailWeight
144
145 self.filedCruiseAltitude = flight.filedCruiseAltitude
146 self.cruiseAltitude = flight.cruiseAltitude
147 self.route = flight.route
148
149 self.departureMETAR = flight.departureMETAR.upper()
150 self.arrivalMETAR = flight.arrivalMETAR.upper()
151
152 self.departureRunway = flight.departureRunway.upper()
153 self.sid = flight.sid.upper()
154
155 self.star = flight.star
156 self.transition = flight.transition
157 self.approachType = flight.approachType.upper()
158 self.arrivalRunway = flight.arrivalRunway.upper()
159
160 self.flightType = flight.flightType
161 self.online = flight.online
162
163 self.comments = flight.comments
164 self.flightDefects = flight.flightDefects
165 self.delayCodes = flight.delayCodes
166
167 self.blockTimeStart = flight.blockTimeStart
168 self.flightTimeStart = flight.flightTimeStart
169 self.flightTimeEnd = flight.flightTimeEnd
170 self.blockTimeEnd = flight.blockTimeEnd
171 self.flownDistance = flight.flownDistance
172 self.fuelUsed = flight.startFuel - flight.endFuel
173
174 logger = flight.logger
175 self.rating = logger.getRating()
176 self.logLines = logger.lines
177 self.faultLineIndexes = logger.faultLineIndexes
178
179 self.messages = []
180
181 def setupFromPIREPData(self, pirepData, bookedFlight):
182
183 self.bookedFlight = bookedFlight
184
185 self.numCrew = int(pirepData["numCrew"])
186 self.numPassengers = int(pirepData["numPassengers"])
187 self.bagWeight = int(pirepData["bagWeight"])
188 self.cargoWeight = int(pirepData["cargoWeight"])
189 self.mailWeight = int(pirepData["mailWeight"])
190
191 filedCruiseLevel = pirepData["filedCruiseLevel"].strip()
192 if filedCruiseLevel:
193 if filedCruiseLevel.startswith("FL"):
194 filedCruiseLevel = filedCruiseLevel[2:]
195 if filedCruiseLevel:
196 self.filedCruiseAltitude = int(filedCruiseLevel)*100
197 else:
198 self.filedCruiseAltitude = 10000;
199
200 cruiseLevel = pirepData["cruiseLevel"].strip()
201 if cruiseLevel:
202 if cruiseLevel.startswith("FL"):
203 cruiseLevel = cruiseLevel[2:]
204 if cruiseLevel:
205 self.cruiseAltitude = int(cruiseLevel[2:])*100
206 else:
207 self.cruiseAltitude = self.filedCruiseAltitude
208 self.route = pirepData["route"]
209
210 self.departureMETAR = pirepData["departureMETAR"]
211 self.arrivalMETAR = pirepData["arrivalMETAR"]
212
213 self.departureRunway = pirepData["departureRunway"]
214 self.sid = pirepData["sid"]
215
216 star = pirepData["star"].split(",")
217 self.star = star[0]
218 self.star.strip()
219
220 if len(star)>1:
221 self.transition = star[1]
222 self.transition.strip()
223 else:
224 self.transition = ""
225 self.approachType = pirepData["approachType"]
226 self.arrivalRunway = pirepData["arrivalRunway"]
227
228 self.flightType = PIREP.decodeFlightTypeText(pirepData["flightType"])
229 self.online = int(pirepData["online"])!=0
230
231 self.comments = pirepData["comments"]
232 self.flightDefects = pirepData["flightDefects"]
233 self.delayCodes = pirepData["timeComment"]
234 if self.delayCodes=="UTC":
235 self.delayCodes = []
236 else:
237 self.delayCodes = self.delayCodes.split(", ")
238
239 flightDate = pirepData["flightDate"] + " "
240
241 self.blockTimeStart = \
242 PIREP.parseTimestampFromRPC(flightDate + pirepData["blockTimeStart"])
243 self.flightTimeStart = \
244 PIREP.parseTimestampFromRPC(flightDate + pirepData["flightTimeStart"])
245 self.flightTimeEnd = \
246 PIREP.parseTimestampFromRPC(flightDate + pirepData["flightTimeEnd"])
247 self.blockTimeEnd = \
248 PIREP.parseTimestampFromRPC(flightDate + pirepData["blockTimeEnd"])
249 self.flownDistance = float(pirepData["flownDistance"])
250 self.fuelUsed = float(pirepData["fuelUsed"])
251
252 # logger = flight.logger
253 self.rating = float(pirepData["rating"])
254
255 log = pirepData["log"]
256
257 self.logLines = PIREP.parseLogFromRPC(log)[1:]
258 if self.logLines and \
259 (self.logLines[0][0]=="LOGGER NG LOG" or
260 self.logLines[0][0]=="MAVA LOGGER X"):
261 self.logLines = self.logLines[1:]
262 numLogLines = len(self.logLines)
263
264 lastFaultLineIndex = 0
265 self.faultLineIndexes = []
266 for ratingText in pirepData["ratingText"].splitlines()[:-1]:
267 faultLines = PIREP.parseLogFromRPC(ratingText)
268 for (timeStr, entry) in faultLines:
269 for i in range(lastFaultLineIndex, numLogLines-1):
270 if timeStr>=self.logLines[i][0] and \
271 timeStr<self.logLines[i+1][0]:
272 self.logLines = self.logLines[:i+1] + \
273 [(timeStr, entry)] + self.logLines[i+1:]
274 self.faultLineIndexes.append(i+1)
275 lastFaultLineIndex = i+1
276 numLogLines += 1
277 break
278
279 self.messages = []
280 for messageData in pirepData["messages"]:
281 self.messages.append(PIREP.Message.fromMessageData(messageData))
282
283 @property
284 def flightDateText(self):
285 """Get the text version of the booked flight's departure time."""
286 return self.bookedFlight.departureTime.strftime("%Y-%m-%d")
287
288 @property
289 def flightTypeText(self):
290 """Get the text representation of the flight type."""
291 return PIREP._flightTypes[self.flightType]
292
293 @property
294 def blockTimeStartText(self):
295 """Get the beginning of the block time in string format."""
296 return PIREP.formatTimestampForRPC(self.blockTimeStart)
297
298 @property
299 def flightTimeStartText(self):
300 """Get the beginning of the flight time in string format."""
301 return PIREP.formatTimestampForRPC(self.flightTimeStart)
302
303 @property
304 def flightTimeEndText(self):
305 """Get the end of the flight time in string format."""
306 return PIREP.formatTimestampForRPC(self.flightTimeEnd)
307
308 @property
309 def blockTimeEndText(self):
310 """Get the end of the block time in string format."""
311 return PIREP.formatTimestampForRPC(self.blockTimeEnd)
312
313 def getACARSText(self):
314 """Get the ACARS text.
315
316 This is a specially formatted version of the log without the faults."""
317 text = "[MAVA LOGGER X LOG]-[%s]" % (const.VERSION,)
318 for index in range(0, len(self.logLines)):
319 if index not in self.faultLineIndexes:
320 (timeStr, line) = self.logLines[index]
321 if timeStr is not None:
322 text += PIREP._formatLine(timeStr, line)
323 return text
324
325 def getRatingText(self):
326 """Get the rating text.
327
328 This is a specially formatted version of the lines containing the
329 faults."""
330 text = ""
331 for index in self.faultLineIndexes:
332 (timeStr, line) = self.logLines[index]
333 if timeStr is not None:
334 text += PIREP._formatLine(timeStr, line)
335 text += "\n"
336
337 text += "\n[Flight Rating: %.1f]" % (max(0.0, self.rating),)
338
339 return text
340
341 def getTimeComment(self):
342 """Get the time comment.
343
344 This is basically a collection of the delay codes, if any."""
345 if not self.delayCodes:
346 return "UTC"
347 else:
348 s = ""
349 for code in self.delayCodes:
350 if s: s += ", "
351 s += code
352 return s
353
354 def getSTAR(self):
355 """Get the STAR and/or the transition."""
356 star = self.star if self.star is not None else ""
357 if self.transition is not None:
358 if star: star += ", "
359 star += self.transition
360 return star.upper()
361
362 def save(self, path):
363 """Save the PIREP to the given file.
364
365 Returns whether the saving has succeeded."""
366 try:
367 with open(path, "wb") as f:
368 pickle.dump(self, f)
369 return None
370 except Exception as e:
371 error = utf2unicode(str(e))
372 print("Failed saving PIREP to %s: %s" % (path, error))
373 return error
374
375 def _serialize(self):
376 """Serialize the PIREP for JSON-RPC."""
377 attrs = {}
378 attrs["log"] = self.getACARSText()
379 attrs["flightDate"] = self.flightDateText
380 attrs["callsign"] = self.bookedFlight.callsign
381 attrs["departureICAO"] = self.bookedFlight.departureICAO
382 attrs["arrivalICAO"] = self.bookedFlight.arrivalICAO
383 attrs["numPassengers"] = self.numPassengers
384 attrs["numCrew"] = self.numCrew
385 attrs["cargoWeight"] = self.cargoWeight
386 attrs["bagWeight"] = self.bagWeight
387 attrs["mailWeight"] = self.mailWeight
388 attrs["flightType"] = self.flightTypeText
389 attrs["online"] = 1 if self.online else 0
390 attrs["blockTimeStart"] = self.blockTimeStartText
391 attrs["blockTimeEnd"] = self.blockTimeEndText
392 attrs["flightTimeStart"] = self.flightTimeStartText
393 attrs["flightTimeEnd"] = self.flightTimeEndText
394 attrs["timeComment"] = self.getTimeComment()
395 attrs["fuelUsed"] = self.fuelUsed
396 attrs["departureRunway"] = self.departureRunway
397 attrs["arrivalRunway"] = self.arrivalRunway
398 attrs["departureMETAR"] = self.departureMETAR
399 attrs["arrivalMETAR"] = self.arrivalMETAR
400 attrs["filedCruiseLevel"] = self.filedCruiseAltitude / 100.0
401 attrs["cruiseLevel"] = self.cruiseAltitude / 100.0
402 attrs["sid"] = self.sid
403 attrs["route"] = self.route
404 attrs["star"] = self.star
405 attrs["approachType"] = self.approachType
406 attrs["comments"] = self.comments
407 attrs["flightDefects"] = self.flightDefects
408 attrs["ratingText"] = self.getRatingText()
409 attrs["rating"] = max(0.0, self.rating)
410 attrs["flownDistance"] = "%.2f" % (self.flownDistance,)
411 # FIXME: it should be stored in the PIREP when it is sent later
412 attrs["performDate"] = datetime.date.today().strftime("%Y-%m-%d")
413
414 return ([], attrs)
415
416 def __setstate__(self, state):
417 """Set the state from the given unpickled dictionary."""
418 self.__dict__.update(fixUnpickled(state))
Note: See TracBrowser for help on using the repository browser.