source: src/mlx/pirep.py@ 855:c1d387ee73d6

Last change on this file since 855:c1d387ee73d6 was 855:c1d387ee73d6, checked in by István Váradi <ivaradi@…>, 7 years ago

The PIREP message (if any) is displayed for an accepted flight (re #307)

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