source: src/mlx/pirep.py@ 835:253df5ee72c5

Last change on this file since 835:253df5ee72c5 was 834:5651e303daa9, checked in by István Váradi <ivaradi@…>, 8 years ago

Backed out changeset f300ebc45a7f

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