source: src/mlx/pirep.py@ 851:b98050aeebf9

Last change on this file since 851:b98050aeebf9 was 839:4eba04af7683, checked in by István Váradi <ivaradi@…>, 8 years ago

The flown distance is serialized with 2 decimal places

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 else:
206 self.delayCodes = self.delayCodes.split(", ")
207
208 flightDate = pirepData["flightDate"] + " "
209
210 self.blockTimeStart = \
211 PIREP.parseTimestampFromRPC(flightDate + pirepData["blockTimeStart"])
212 self.flightTimeStart = \
213 PIREP.parseTimestampFromRPC(flightDate + pirepData["flightTimeStart"])
214 self.flightTimeEnd = \
215 PIREP.parseTimestampFromRPC(flightDate + pirepData["flightTimeEnd"])
216 self.blockTimeEnd = \
217 PIREP.parseTimestampFromRPC(flightDate + pirepData["blockTimeEnd"])
218 self.flownDistance = float(pirepData["flownDistance"])
219 self.fuelUsed = float(pirepData["fuelUsed"])
220
221 # logger = flight.logger
222 self.rating = float(pirepData["rating"])
223
224 log = pirepData["log"]
225
226 self.logLines = PIREP.parseLogFromRPC(log)[1:]
227 if self.logLines and \
228 (self.logLines[0][0]=="LOGGER NG LOG" or
229 self.logLines[0][0]=="MAVA LOGGER X"):
230 self.logLines = self.logLines[1:]
231 numLogLines = len(self.logLines)
232
233 lastFaultLineIndex = 0
234 self.faultLineIndexes = []
235 for ratingText in pirepData["ratingText"].splitlines()[:-1]:
236 faultLines = PIREP.parseLogFromRPC(ratingText)
237 for (timeStr, entry) in faultLines:
238 for i in range(lastFaultLineIndex, numLogLines-1):
239 if timeStr>=self.logLines[i][0] and \
240 timeStr<self.logLines[i+1][0]:
241 self.logLines = self.logLines[:i+1] + \
242 [(timeStr, entry)] + self.logLines[i+1:]
243 self.faultLineIndexes.append(i+1)
244 lastFaultLineIndex = i+1
245 numLogLines += 1
246 break
247
248 @property
249 def flightDateText(self):
250 """Get the text version of the booked flight's departure time."""
251 return self.bookedFlight.departureTime.strftime("%Y-%m-%d")
252
253 @property
254 def flightTypeText(self):
255 """Get the text representation of the flight type."""
256 return PIREP._flightTypes[self.flightType]
257
258 @property
259 def blockTimeStartText(self):
260 """Get the beginning of the block time in string format."""
261 return PIREP.formatTimestampForRPC(self.blockTimeStart)
262
263 @property
264 def flightTimeStartText(self):
265 """Get the beginning of the flight time in string format."""
266 return PIREP.formatTimestampForRPC(self.flightTimeStart)
267
268 @property
269 def flightTimeEndText(self):
270 """Get the end of the flight time in string format."""
271 return PIREP.formatTimestampForRPC(self.flightTimeEnd)
272
273 @property
274 def blockTimeEndText(self):
275 """Get the end of the block time in string format."""
276 return PIREP.formatTimestampForRPC(self.blockTimeEnd)
277
278 def getACARSText(self):
279 """Get the ACARS text.
280
281 This is a specially formatted version of the log without the faults."""
282 text = "[MAVA LOGGER X LOG]-[%s]" % (const.VERSION,)
283 for index in range(0, len(self.logLines)):
284 if index not in self.faultLineIndexes:
285 (timeStr, line) = self.logLines[index]
286 if timeStr is not None:
287 text += PIREP._formatLine(timeStr, line)
288 return text
289
290 def getRatingText(self):
291 """Get the rating text.
292
293 This is a specially formatted version of the lines containing the
294 faults."""
295 text = ""
296 for index in self.faultLineIndexes:
297 (timeStr, line) = self.logLines[index]
298 if timeStr is not None:
299 text += PIREP._formatLine(timeStr, line)
300 text += "\n"
301
302 text += "\n[Flight Rating: %.1f]" % (max(0.0, self.rating),)
303
304 return text
305
306 def getTimeComment(self):
307 """Get the time comment.
308
309 This is basically a collection of the delay codes, if any."""
310 if not self.delayCodes:
311 return "UTC"
312 else:
313 s = ""
314 for code in self.delayCodes:
315 if s: s += ", "
316 s += code
317 return s
318
319 def getSTAR(self):
320 """Get the STAR and/or the transition."""
321 star = self.star if self.star is not None else ""
322 if self.transition is not None:
323 if star: star += ", "
324 star += self.transition
325 return star.upper()
326
327 def save(self, path):
328 """Save the PIREP to the given file.
329
330 Returns whether the saving has succeeded."""
331 try:
332 with open(path, "wb") as f:
333 pickle.dump(self, f)
334 return None
335 except Exception, e:
336 error = utf2unicode(str(e))
337 print u"Failed saving PIREP to %s: %s" % (path, error)
338 return error
339
340 def _serialize(self):
341 """Serialize the PIREP for JSON-RPC."""
342 attrs = {}
343 attrs["log"] = self.getACARSText()
344 attrs["flightDate"] = self.flightDateText
345 attrs["callsign"] = self.bookedFlight.callsign
346 attrs["departureICAO"] = self.bookedFlight.departureICAO
347 attrs["arrivalICAO"] = self.bookedFlight.arrivalICAO
348 attrs["numPassengers"] = self.numPassengers
349 attrs["numCrew"] = self.numCrew
350 attrs["cargoWeight"] = self.cargoWeight
351 attrs["bagWeight"] = self.bagWeight
352 attrs["mailWeight"] = self.mailWeight
353 attrs["flightType"] = self.flightTypeText
354 attrs["online"] = 1 if self.online else 0
355 attrs["blockTimeStart"] = self.blockTimeStartText
356 attrs["blockTimeEnd"] = self.blockTimeEndText
357 attrs["flightTimeStart"] = self.flightTimeStartText
358 attrs["flightTimeEnd"] = self.flightTimeEndText
359 attrs["timeComment"] = self.getTimeComment()
360 attrs["fuelUsed"] = self.fuelUsed
361 attrs["departureRunway"] = self.departureRunway
362 attrs["arrivalRunway"] = self.arrivalRunway
363 attrs["departureMETAR"] = self.departureMETAR
364 attrs["arrivalMETAR"] = self.arrivalMETAR
365 attrs["filedCruiseLevel"] = self.filedCruiseAltitude / 100.0
366 attrs["cruiseLevel"] = self.cruiseAltitude / 100.0
367 attrs["sid"] = self.sid
368 attrs["route"] = self.route
369 attrs["star"] = self.star
370 attrs["approachType"] = self.approachType
371 attrs["comments"] = self.comments
372 attrs["flightDefects"] = self.flightDefects
373 attrs["ratingText"] = self.getRatingText()
374 attrs["rating"] = max(0.0, self.rating)
375 attrs["flownDistance"] = "%.2f" % (self.flownDistance,)
376 # FIXME: it should be stored in the PIREP when it is sent later
377 attrs["performDate"] = datetime.date.today().strftime("%Y-%m-%d")
378
379 return ([], attrs)
Note: See TracBrowser for help on using the repository browser.