source: src/mlx/fsuipc.py@ 140:7f24ede5d214

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

Reworked fuel tank handling to be more indirect

File size: 52.1 KB
Line 
1# Module handling the connection to FSUIPC
2
3#------------------------------------------------------------------------------
4
5import fs
6import const
7import util
8import acft
9
10import threading
11import os
12import time
13import calendar
14import sys
15import codecs
16
17if os.name == "nt":
18 import pyuipc
19else:
20 import pyuipc_sim as pyuipc
21
22#------------------------------------------------------------------------------
23
24# The mapping of tank types to FSUIPC offsets
25_tank2offset = { const.FUELTANK_CENTRE : 0x0b74,
26 const.FUELTANK_LEFT : 0x0b7c,
27 const.FUELTANK_RIGHT : 0x0b94,
28 const.FUELTANK_LEFT_AUX : 0x0b84,
29 const.FUELTANK_RIGHT_AUX : 0x0b9c,
30 const.FUELTANK_LEFT_TIP : 0x0b8c,
31 const.FUELTANK_RIGHT_TIP : 0x0ba4,
32 const.FUELTANK_EXTERNAL1 : 0x1254,
33 const.FUELTANK_EXTERNAL2 : 0x125c,
34 const.FUELTANK_CENTRE2 : 0x1244 }
35
36#------------------------------------------------------------------------------
37
38class Handler(threading.Thread):
39 """The thread to handle the FSUIPC requests."""
40 @staticmethod
41 def fsuipc2VS(data):
42 """Convert the given vertical speed data read from FSUIPC into feet/min."""
43 return data*60.0/const.FEETTOMETRES/256.0
44
45 @staticmethod
46 def fsuipc2radioAltitude(data):
47 """Convert the given radio altitude data read from FSUIPC into feet."""
48 return data/const.FEETTOMETRES/65536.0
49
50 @staticmethod
51 def fsuipc2Degrees(data):
52 """Convert the given data into degrees."""
53 return data * 360.0 / 65536.0 / 65536.0
54
55 @staticmethod
56 def fsuipc2PositiveDegrees(data):
57 """Convert the given data into positive degrees."""
58 degrees = Handler.fsuipc2Degrees(data)
59 if degrees<0.0: degrees += 360.0
60 return degrees
61
62 @staticmethod
63 def fsuipc2IAS(data):
64 """Convert the given data into indicated airspeed."""
65 return data / 128.0
66
67 @staticmethod
68 def _callSafe(fun):
69 """Call the given function and swallow any exceptions."""
70 try:
71 return fun()
72 except Exception, e:
73 print >> sys.stderr, str(e)
74 return None
75
76 # The number of times a read is attempted
77 NUM_READATTEMPTS = 3
78
79 # The number of connection attempts
80 NUM_CONNECTATTEMPTS = 3
81
82 # The interval between successive connect attempts
83 CONNECT_INTERVAL = 0.25
84
85 @staticmethod
86 def _performRead(data, callback, extra, validator):
87 """Perform a read request.
88
89 If there is a validator, that will be called with the return values,
90 and if the values are wrong, the request is retried at most a certain
91 number of times.
92
93 Return True if the request has succeeded, False if validation has
94 failed during all attempts. An exception may also be thrown if there is
95 some lower-level communication problem."""
96 attemptsLeft = Handler.NUM_READATTEMPTS
97 while attemptsLeft>0:
98 values = pyuipc.read(data)
99 if validator is None or \
100 Handler._callSafe(lambda: validator(values, extra)):
101 Handler._callSafe(lambda: callback(values, extra))
102 return True
103 else:
104 attemptsLeft -= 1
105 return False
106
107 class Request(object):
108 """A simple, one-shot request."""
109 def __init__(self, forWrite, data, callback, extra, validator = None):
110 """Construct the request."""
111 self._forWrite = forWrite
112 self._data = data
113 self._callback = callback
114 self._extra = extra
115 self._validator = validator
116
117 def process(self, time):
118 """Process the request.
119
120 Return True if the request has succeeded, False if data validation
121 has failed for a reading request. An exception may also be thrown
122 if there is some lower-level communication problem."""
123 if self._forWrite:
124 pyuipc.write(self._data)
125 Handler._callSafe(lambda: self._callback(True, self._extra))
126 return True
127 else:
128 return Handler._performRead(self._data, self._callback,
129 self._extra, self._validator)
130
131 def fail(self):
132 """Handle the failure of this request."""
133 if self._forWrite:
134 Handler._callSafe(lambda: self._callback(False, self._extra))
135 else:
136 Handler._callSafe(lambda: self._callback(None, self._extra))
137
138 class PeriodicRequest(object):
139 """A periodic request."""
140 def __init__(self, id, period, data, callback, extra, validator):
141 """Construct the periodic request."""
142 self._id = id
143 self._period = period
144 self._nextFire = time.time() + period
145 self._data = data
146 self._preparedData = None
147 self._callback = callback
148 self._extra = extra
149 self._validator = validator
150
151 @property
152 def id(self):
153 """Get the ID of this periodic request."""
154 return self._id
155
156 @property
157 def nextFire(self):
158 """Get the next firing time."""
159 return self._nextFire
160
161 def process(self, time):
162 """Check if this request should be executed, and if so, do so.
163
164 time is the time at which the request is being executed. If this
165 function is called too early, nothing is done, and True is
166 returned.
167
168 Return True if the request has succeeded, False if data validation
169 has failed. An exception may also be thrown if there is some
170 lower-level communication problem."""
171 if time<self._nextFire:
172 return True
173
174 if self._preparedData is None:
175 self._preparedData = pyuipc.prepare_data(self._data)
176 self._data = None
177
178 isOK = Handler._performRead(self._preparedData, self._callback,
179 self._extra, self._validator)
180
181 if isOK:
182 while self._nextFire <= time:
183 self._nextFire += self._period
184
185 return isOK
186
187 def fail(self):
188 """Handle the failure of this request."""
189 pass
190
191 def __cmp__(self, other):
192 """Compare two periodic requests. They are ordered by their next
193 firing times."""
194 return cmp(self._nextFire, other._nextFire)
195
196 def __init__(self, connectionListener,
197 connectAttempts = -1, connectInterval = 0.2):
198 """Construct the handler with the given connection listener."""
199 threading.Thread.__init__(self)
200
201 self._connectionListener = connectionListener
202 self._connectAttempts = connectAttempts
203 self._connectInterval = connectInterval
204
205 self._requestCondition = threading.Condition()
206 self._connectionRequested = False
207 self._connected = False
208
209 self._requests = []
210 self._nextPeriodicID = 1
211 self._periodicRequests = []
212
213 self.daemon = True
214
215 def requestRead(self, data, callback, extra = None, validator = None):
216 """Request the reading of some data.
217
218 data is a list of tuples of the following items:
219 - the offset of the data as an integer
220 - the type letter of the data as a string
221
222 callback is a function that receives two pieces of data:
223 - the values retrieved or None on error
224 - the extra parameter
225
226 It will be called in the handler's thread!
227 """
228 with self._requestCondition:
229 self._requests.append(Handler.Request(False, data, callback, extra,
230 validator))
231 self._requestCondition.notify()
232
233 def requestWrite(self, data, callback, extra = None):
234 """Request the writing of some data.
235
236 data is a list of tuples of the following items:
237 - the offset of the data as an integer
238 - the type letter of the data as a string
239 - the data to write
240
241 callback is a function that receives two pieces of data:
242 - a boolean indicating if writing was successful
243 - the extra data
244 It will be called in the handler's thread!
245 """
246 with self._requestCondition:
247 self._requests.append(Handler.Request(True, data, callback, extra))
248 self._requestCondition.notify()
249
250 @staticmethod
251 def _readWriteCallback(data, extra):
252 """Callback for the read() and write() calls below."""
253 extra.append(data)
254 with extra[0] as condition:
255 condition.notify()
256
257 def requestPeriodicRead(self, period, data, callback, extra = None,
258 validator = None):
259 """Request a periodic read of data.
260
261 period is a floating point number with the period in seconds.
262
263 This function returns an identifier which can be used to cancel the
264 request."""
265 with self._requestCondition:
266 id = self._nextPeriodicID
267 self._nextPeriodicID += 1
268 request = Handler.PeriodicRequest(id, period, data, callback,
269 extra, validator)
270 self._periodicRequests.append(request)
271 self._requestCondition.notify()
272 return id
273
274 def clearPeriodic(self, id):
275 """Clear the periodic request with the given ID."""
276 with self._requestCondition:
277 for i in range(0, len(self._periodicRequests)):
278 if self._periodicRequests[i].id==id:
279 del self._periodicRequests[i]
280 return True
281 return False
282
283 def connect(self):
284 """Initiate the connection to the flight simulator."""
285 with self._requestCondition:
286 if not self._connectionRequested:
287 self._connectionRequested = True
288 self._requestCondition.notify()
289
290 def disconnect(self):
291 """Disconnect from the flight simulator."""
292 with self._requestCondition:
293 self._requests = []
294 if self._connectionRequested:
295 self._connectionRequested = False
296 self._requestCondition.notify()
297
298 def clearRequests(self):
299 """Clear the outstanding one-shot requests."""
300 with self._requestCondition:
301 self._requests = []
302
303 def run(self):
304 """Perform the operation of the thread."""
305 while True:
306 self._waitConnectionRequest()
307
308 if self._connect():
309 self._handleConnection()
310
311 self._disconnect()
312
313 def _waitConnectionRequest(self):
314 """Wait for a connection request to arrive."""
315 with self._requestCondition:
316 while not self._connectionRequested:
317 self._requestCondition.wait()
318
319 def _connect(self, autoReconnection = False):
320 """Try to connect to the flight simulator via FSUIPC
321
322 Returns True if the connection has been established, False if it was
323 not due to no longer requested.
324 """
325 attempts = 0
326 while self._connectionRequested:
327 try:
328 attempts += 1
329 pyuipc.open(pyuipc.SIM_ANY)
330 description = "(FSUIPC version: 0x%04x, library version: 0x%04x, FS version: %d)" % \
331 (pyuipc.fsuipc_version, pyuipc.lib_version,
332 pyuipc.fs_version)
333 if not autoReconnection:
334 Handler._callSafe(lambda:
335 self._connectionListener.connected(const.SIM_MSFS9,
336 description))
337 self._connected = True
338 return True
339 except Exception, e:
340 print "fsuipc.Handler._connect: connection failed: " + str(e)
341 if attempts<self.NUM_CONNECTATTEMPTS:
342 time.sleep(self.CONNECT_INTERVAL)
343 else:
344 self._connectionRequested = False
345 if autoReconnection:
346 Handler._callSafe(lambda:
347 self._connectionListener.disconnected())
348 else:
349 Handler._callSafe(lambda:
350 self._connectionListener.connectionFailed())
351
352 return False
353
354 def _handleConnection(self):
355 """Handle a living connection."""
356 with self._requestCondition:
357 while self._connectionRequested:
358 self._processRequests()
359 self._waitRequest()
360
361 def _waitRequest(self):
362 """Wait for the time of the next request.
363
364 Returns also, if the connection is no longer requested.
365
366 Should be called with the request condition lock held."""
367 while self._connectionRequested:
368 timeout = None
369 if self._periodicRequests:
370 self._periodicRequests.sort()
371 timeout = self._periodicRequests[0].nextFire - time.time()
372
373 if timeout is not None and timeout <= 0.0:
374 return
375
376 self._requestCondition.wait(timeout)
377
378 def _disconnect(self):
379 """Disconnect from the flight simulator."""
380 if self._connected:
381 pyuipc.close()
382 self._connected = False
383
384 def _processRequest(self, request, time):
385 """Process the given request.
386
387 If an exception occurs or invalid data is read too many times, we try
388 to reconnect.
389
390 This function returns only if the request has succeeded, or if a
391 connection is no longer requested.
392
393 This function is called with the request lock held, but is relased
394 whole processing the request and reconnecting."""
395 self._requestCondition.release()
396
397 needReconnect = False
398 try:
399 try:
400 if not request.process(time):
401 print "fsuipc.Handler._processRequest: FSUIPC returned invalid data too many times, reconnecting"
402 needReconnect = True
403 except Exception as e:
404 print "fsuipc.Handler._processRequest: FSUIPC connection failed (" + \
405 str(e) + "), reconnecting."
406 needReconnect = True
407
408 if needReconnect:
409 with self._requestCondition:
410 self._requests.insert(0, request)
411 self._disconnect()
412 self._connect(autoReconnection = True)
413 finally:
414 self._requestCondition.acquire()
415
416 def _processRequests(self):
417 """Process any pending requests.
418
419 Will be called with the request lock held."""
420 while self._connectionRequested and self._periodicRequests:
421 self._periodicRequests.sort()
422 request = self._periodicRequests[0]
423
424 t = time.time()
425
426 if request.nextFire>t:
427 break
428
429 self._processRequest(request, t)
430
431 while self._connectionRequested and self._requests:
432 request = self._requests[0]
433 del self._requests[0]
434
435 self._processRequest(request, None)
436
437 return self._connectionRequested
438
439#------------------------------------------------------------------------------
440
441class Simulator(object):
442 """The simulator class representing the interface to the flight simulator
443 via FSUIPC."""
444 # The basic data that should be queried all the time once we are connected
445 timeData = [ (0x0240, "H"), # Year
446 (0x023e, "H"), # Number of day in year
447 (0x023b, "b"), # UTC hour
448 (0x023c, "b"), # UTC minute
449 (0x023a, "b") ] # seconds
450
451 normalData = timeData + \
452 [ (0x3d00, -256), # The name of the current aircraft
453 (0x3c00, -256), # The path of the current AIR file
454 (0x1274, "h") ] # Text display mode
455
456 flareData1 = [ (0x023a, "b"), # Seconds of time
457 (0x31e4, "d"), # Radio altitude
458 (0x02c8, "d") ] # Vertical speed
459
460 flareStartData = [ (0x0e90, "H"), # Ambient wind speed
461 (0x0e92, "H"), # Ambient wind direction
462 (0x0e8a, "H") ] # Visibility
463
464 flareData2 = [ (0x023a, "b"), # Seconds of time
465 (0x0366, "H"), # On the ground
466 (0x02c8, "d"), # Vertical speed
467 (0x030c, "d"), # Touch-down rate
468 (0x02bc, "d"), # IAS
469 (0x0578, "d"), # Pitch
470 (0x057c, "d"), # Bank
471 (0x0580, "d") ] # Heading
472
473 @staticmethod
474 def _getTimestamp(data):
475 """Convert the given data into a timestamp."""
476 timestamp = calendar.timegm(time.struct_time([data[0],
477 1, 1, 0, 0, 0, -1, 1, 0]))
478 timestamp += data[1] * 24 * 3600
479 timestamp += data[2] * 3600
480 timestamp += data[3] * 60
481 timestamp += data[4]
482
483 return timestamp
484
485 def __init__(self, connectionListener, connectAttempts = -1,
486 connectInterval = 0.2):
487 """Construct the simulator.
488
489 The aircraft object passed must provide the following members:
490 - type: one of the AIRCRAFT_XXX constants from const.py
491 - modelChanged(aircraftName, modelName): called when the model handling
492 the aircraft has changed.
493 - handleState(aircraftState): handle the given state.
494 - flareStarted(windSpeed, windDirection, visibility, flareStart,
495 flareStartFS): called when the flare has
496 started. windSpeed is in knots, windDirection is in degrees and
497 visibility is in metres. flareStart and flareStartFS are two time
498 values expressed in seconds that can be used to calculate the flare
499 time.
500 - flareFinished(flareEnd, flareEndFS, tdRate, tdRateCalculatedByFS,
501 ias, pitch, bank, heading): called when the flare has
502 finished, i.e. the aircraft is on the ground. flareEnd and flareEndFS
503 are the two time values corresponding to the touchdown time. tdRate is
504 the touch-down rate, tdRateCalculatedBySim indicates if the data comes
505 from the simulator or was calculated by the adapter. The other data
506 are self-explanatory and expressed in their 'natural' units."""
507 self._aircraft = None
508
509 self._handler = Handler(connectionListener,
510 connectAttempts = connectAttempts,
511 connectInterval = connectInterval)
512 self._handler.start()
513
514 self._scroll = False
515
516 self._normalRequestID = None
517
518 self._monitoringRequested = False
519 self._monitoring = False
520
521 self._aircraftName = None
522 self._aircraftModel = None
523
524 self._flareRequestID = None
525 self._flareRates = []
526 self._flareStart = None
527 self._flareStartFS = None
528
529 self._latin1decoder = codecs.getdecoder("iso-8859-1")
530
531 def connect(self, aircraft):
532 """Initiate a connection to the simulator."""
533 self._aircraft = aircraft
534 self._aircraftName = None
535 self._aircraftModel = None
536 self._handler.connect()
537 if self._normalRequestID is None:
538 self._startDefaultNormal()
539
540 def reconnect(self):
541 """Initiate a reconnection to the simulator.
542
543 It does not reset already set up data, just calls connect() on the
544 handler."""
545 self._handler.connect()
546
547 def requestZFW(self, callback):
548 """Send a request for the ZFW."""
549 self._handler.requestRead([(0x3bfc, "d")], self._handleZFW, extra = callback)
550
551 def requestWeights(self, callback):
552 """Request the following weights: DOW, ZFW, payload.
553
554 These values will be passed to the callback function in this order, as
555 separate arguments."""
556 self._handler.requestRead([(0x13fc, "d")], self._handlePayloadCount,
557 extra = callback)
558
559 def requestTime(self, callback):
560 """Request the time from the simulator."""
561 self._handler.requestRead(Simulator.timeData, self._handleTime,
562 extra = callback)
563
564 def startMonitoring(self):
565 """Start the periodic monitoring of the aircraft and pass the resulting
566 state to the aircraft object periodically."""
567 assert not self._monitoringRequested
568 self._monitoringRequested = True
569
570 def stopMonitoring(self):
571 """Stop the periodic monitoring of the aircraft."""
572 assert self._monitoringRequested
573 self._monitoringRequested = False
574
575 def startFlare(self):
576 """Start monitoring the flare time.
577
578 At present it is assumed to be called from the FSUIPC thread, hence no
579 protection."""
580 #self._aircraft.logger.debug("startFlare")
581 if self._flareRequestID is None:
582 self._flareRates = []
583 self._flareRequestID = self._handler.requestPeriodicRead(0.1,
584 Simulator.flareData1,
585 self._handleFlare1)
586
587 def cancelFlare(self):
588 """Cancel monitoring the flare time.
589
590 At present it is assumed to be called from the FSUIPC thread, hence no
591 protection."""
592 if self._flareRequestID is not None:
593 self._handler.clearPeriodic(self._flareRequestID)
594 self._flareRequestID = None
595
596 def sendMessage(self, message, duration = 3):
597 """Send a message to the pilot via the simulator.
598
599 duration is the number of seconds to keep the message displayed."""
600
601 if self._scroll:
602 if duration==0: duration = -1
603 elif duration == 1: duration = -2
604 else: duration = -duration
605
606 data = [(0x3380, -1 - len(message), message),
607 (0x32fa, 'h', duration)]
608
609 self._handler.requestWrite(data, self._handleMessageSent)
610
611 def disconnect(self):
612 """Disconnect from the simulator."""
613 assert not self._monitoringRequested
614
615 self._stopNormal()
616 self._handler.disconnect()
617
618 def _startDefaultNormal(self):
619 """Start the default normal periodic request."""
620 assert self._normalRequestID is None
621 self._normalRequestID = \
622 self._handler.requestPeriodicRead(1.0,
623 Simulator.normalData,
624 self._handleNormal,
625 validator = self._validateNormal)
626
627 def _stopNormal(self):
628 """Stop the normal period request."""
629 assert self._normalRequestID is not None
630 self._handler.clearPeriodic(self._normalRequestID)
631 self._normalRequestID = None
632 self._monitoring = False
633
634 def _validateNormal(self, data, extra):
635 """Validate the normal data."""
636 return data[0]!=0 and data[1]!=0 and len(data[5])>0 and len(data[6])>0
637
638 def _handleNormal(self, data, extra):
639 """Handle the reply to the normal request.
640
641 At the beginning the result consists the data for normalData. When
642 monitoring is started, it contains the result also for the
643 aircraft-specific values.
644 """
645 timestamp = Simulator._getTimestamp(data)
646
647 createdNewModel = self._setAircraftName(timestamp, data[5], data[6])
648
649 self._scroll = data[7]!=0
650
651 if self._monitoringRequested and not self._monitoring:
652 self._stopNormal()
653 self._startMonitoring()
654 elif self._monitoring and not self._monitoringRequested:
655 self._stopNormal()
656 self._startDefaultNormal()
657 elif self._monitoring and self._aircraftModel is not None and \
658 not createdNewModel:
659 aircraftState = self._aircraftModel.getAircraftState(self._aircraft,
660 timestamp, data)
661 self._aircraft.handleState(aircraftState)
662
663 def _setAircraftName(self, timestamp, name, airPath):
664 """Set the name of the aicraft and if it is different from the
665 previous, create a new model for it.
666
667 If so, also notifty the aircraft about the change.
668
669 Return if a new model was created."""
670 aircraftName = (name, airPath)
671 if aircraftName==self._aircraftName:
672 return False
673
674 self._aircraftName = aircraftName
675 needNew = self._aircraftModel is None
676 needNew = needNew or\
677 not self._aircraftModel.doesHandle(self._aircraft, aircraftName)
678 if not needNew:
679 specialModel = AircraftModel.findSpecial(self._aircraft, aircraftName)
680 needNew = specialModel is not None and \
681 specialModel is not self._aircraftModel.__class__
682
683 if needNew:
684 self._setAircraftModel(AircraftModel.create(self._aircraft, aircraftName))
685
686
687 self._aircraft.modelChanged(timestamp, self._latin1decoder(name)[0],
688 self._aircraftModel.name)
689
690 return needNew
691
692 def _setAircraftModel(self, model):
693 """Set a new aircraft model.
694
695 It will be queried for the data to monitor and the monitoring request
696 will be replaced by a new one."""
697 self._aircraftModel = model
698
699 if self._monitoring:
700 self._stopNormal()
701 self._startMonitoring()
702
703 def _startMonitoring(self):
704 """Start monitoring with the current aircraft model."""
705 data = Simulator.normalData[:]
706 self._aircraftModel.addMonitoringData(data)
707
708 self._normalRequestID = \
709 self._handler.requestPeriodicRead(1.0, data,
710 self._handleNormal,
711 validator = self._validateNormal)
712 self._monitoring = True
713
714 def _addFlareRate(self, data):
715 """Append a flare rate to the list of last rates."""
716 if len(self._flareRates)>=3:
717 del self._flareRates[0]
718 self._flareRates.append(Handler.fsuipc2VS(data))
719
720 def _handleFlare1(self, data, normal):
721 """Handle the first stage of flare monitoring."""
722 #self._aircraft.logger.debug("handleFlare1: " + str(data))
723 if Handler.fsuipc2radioAltitude(data[1])<=50.0:
724 self._flareStart = time.time()
725 self._flareStartFS = data[0]
726 self._handler.clearPeriodic(self._flareRequestID)
727 self._flareRequestID = \
728 self._handler.requestPeriodicRead(0.1,
729 Simulator.flareData2,
730 self._handleFlare2)
731 self._handler.requestRead(Simulator.flareStartData,
732 self._handleFlareStart)
733
734 self._addFlareRate(data[2])
735
736 def _handleFlareStart(self, data, extra):
737 """Handle the data need to notify the aircraft about the starting of
738 the flare."""
739 #self._aircraft.logger.debug("handleFlareStart: " + str(data))
740 if data is not None:
741 windDirection = data[1]*360.0/65536.0
742 if windDirection<0.0: windDirection += 360.0
743 self._aircraft.flareStarted(data[0], windDirection,
744 data[2]*1609.344/100.0,
745 self._flareStart, self._flareStartFS)
746
747 def _handleFlare2(self, data, normal):
748 """Handle the first stage of flare monitoring."""
749 #self._aircraft.logger.debug("handleFlare2: " + str(data))
750 if data[1]!=0:
751 flareEnd = time.time()
752 self._handler.clearPeriodic(self._flareRequestID)
753 self._flareRequestID = None
754
755 flareEndFS = data[0]
756 if flareEndFS<self._flareStartFS:
757 flareEndFS += 60
758
759 tdRate = Handler.fsuipc2VS(data[3])
760 tdRateCalculatedByFS = True
761 if tdRate==0 or tdRate>1000.0 or tdRate<-1000.0:
762 tdRate = min(self._flareRates)
763 tdRateCalculatedByFS = False
764
765 self._aircraft.flareFinished(flareEnd, flareEndFS,
766 tdRate, tdRateCalculatedByFS,
767 Handler.fsuipc2IAS(data[4]),
768 Handler.fsuipc2Degrees(data[5]),
769 Handler.fsuipc2Degrees(data[6]),
770 Handler.fsuipc2PositiveDegrees(data[7]))
771 else:
772 self._addFlareRate(data[2])
773
774 def _handleZFW(self, data, callback):
775 """Callback for a ZFW retrieval request."""
776 zfw = data[0] * const.LBSTOKG / 256.0
777 callback(zfw)
778
779 def _handleTime(self, data, callback):
780 """Callback for a time retrieval request."""
781 callback(Simulator._getTimestamp(data))
782
783 def _handlePayloadCount(self, data, callback):
784 """Callback for the payload count retrieval request."""
785 payloadCount = data[0]
786 data = [(0x3bfc, "d"), (0x30c0, "f")]
787 for i in range(0, payloadCount):
788 data.append((0x1400 + i*48, "f"))
789
790 self._handler.requestRead(data, self._handleWeights,
791 extra = callback)
792
793 def _handleWeights(self, data, callback):
794 """Callback for the weights retrieval request."""
795 zfw = data[0] * const.LBSTOKG / 256.0
796 grossWeight = data[1] * const.LBSTOKG
797 payload = sum(data[2:]) * const.LBSTOKG
798 dow = zfw - payload
799 callback(dow, payload, zfw, grossWeight)
800
801 def _handleMessageSent(self, success, extra):
802 """Callback for a message sending request."""
803 pass
804
805#------------------------------------------------------------------------------
806
807class AircraftModel(object):
808 """Base class for the aircraft models.
809
810 Aircraft models handle the data arriving from FSUIPC and turn it into an
811 object describing the aircraft's state."""
812 monitoringData = [("paused", 0x0264, "H"),
813 ("latitude", 0x0560, "l"),
814 ("longitude", 0x0568, "l"),
815 ("frozen", 0x3364, "H"),
816 ("replay", 0x0628, "d"),
817 ("slew", 0x05dc, "H"),
818 ("overspeed", 0x036d, "b"),
819 ("stalled", 0x036c, "b"),
820 ("onTheGround", 0x0366, "H"),
821 ("zfw", 0x3bfc, "d"),
822 ("grossWeight", 0x30c0, "f"),
823 ("heading", 0x0580, "d"),
824 ("pitch", 0x0578, "d"),
825 ("bank", 0x057c, "d"),
826 ("ias", 0x02bc, "d"),
827 ("mach", 0x11c6, "H"),
828 ("groundSpeed", 0x02b4, "d"),
829 ("vs", 0x02c8, "d"),
830 ("radioAltitude", 0x31e4, "d"),
831 ("altitude", 0x0570, "l"),
832 ("gLoad", 0x11ba, "H"),
833 ("flapsControl", 0x0bdc, "d"),
834 ("flapsLeft", 0x0be0, "d"),
835 ("flapsRight", 0x0be4, "d"),
836 ("lights", 0x0d0c, "H"),
837 ("pitot", 0x029c, "b"),
838 ("parking", 0x0bc8, "H"),
839 ("noseGear", 0x0bec, "d"),
840 ("spoilersArmed", 0x0bcc, "d"),
841 ("spoilers", 0x0bd0, "d"),
842 ("altimeter", 0x0330, "H"),
843 ("nav1", 0x0350, "H"),
844 ("nav2", 0x0352, "H"),
845 ("squawk", 0x0354, "H"),
846 ("windSpeed", 0x0e90, "H"),
847 ("windDirection", 0x0e92, "H"),
848 ("visibility", 0x0e8a, "H")]
849
850
851 specialModels = []
852
853 @staticmethod
854 def registerSpecial(clazz):
855 """Register the given class as a special model."""
856 AircraftModel.specialModels.append(clazz)
857
858 @staticmethod
859 def findSpecial(aircraft, aircraftName):
860 for specialModel in AircraftModel.specialModels:
861 if specialModel.doesHandle(aircraft, aircraftName):
862 return specialModel
863 return None
864
865 @staticmethod
866 def create(aircraft, aircraftName):
867 """Create the model for the given aircraft name, and notify the
868 aircraft about it."""
869 specialModel = AircraftModel.findSpecial(aircraft, aircraftName)
870 if specialModel is not None:
871 return specialModel()
872 if aircraft.type in _genericModels:
873 return _genericModels[aircraft.type]()
874 else:
875 return GenericModel()
876
877 @staticmethod
878 def convertBCD(data, length):
879 """Convert a data item encoded as BCD into a string of the given number
880 of digits."""
881 bcd = ""
882 for i in range(0, length):
883 digit = chr(ord('0') + (data&0x0f))
884 data >>= 4
885 bcd = digit + bcd
886 return bcd
887
888 @staticmethod
889 def convertFrequency(data):
890 """Convert the given frequency data to a string."""
891 bcd = AircraftModel.convertBCD(data, 4)
892 return "1" + bcd[0:2] + "." + bcd[2:4]
893
894 def __init__(self, flapsNotches):
895 """Construct the aircraft model.
896
897 flapsNotches is a list of degrees of flaps that are available on the aircraft."""
898 self._flapsNotches = flapsNotches
899
900 @property
901 def name(self):
902 """Get the name for this aircraft model."""
903 return "FSUIPC/Generic"
904
905 def doesHandle(self, aircraft, aircraftName):
906 """Determine if the model handles the given aircraft name.
907
908 This default implementation returns False."""
909 return False
910
911 def _addOffsetWithIndexMember(self, dest, offset, type, attrName = None):
912 """Add the given FSUIPC offset and type to the given array and a member
913 attribute with the given name."""
914 dest.append((offset, type))
915 if attrName is not None:
916 setattr(self, attrName, len(dest)-1)
917
918 def _addDataWithIndexMembers(self, dest, prefix, data):
919 """Add FSUIPC data to the given array and also corresponding index
920 member variables with the given prefix.
921
922 data is a list of triplets of the following items:
923 - the name of the data item. The index member variable will have a name
924 created by prepending the given prefix to this name.
925 - the FSUIPC offset
926 - the FSUIPC type
927
928 The latter two items will be appended to dest."""
929 for (name, offset, type) in data:
930 self._addOffsetWithIndexMember(dest, offset, type, prefix + name)
931
932 def addMonitoringData(self, data):
933 """Add the model-specific monitoring data to the given array."""
934 self._addDataWithIndexMembers(data, "_monidx_",
935 AircraftModel.monitoringData)
936
937 def getAircraftState(self, aircraft, timestamp, data):
938 """Get an aircraft state object for the given monitoring data."""
939 state = fs.AircraftState()
940
941 state.timestamp = timestamp
942
943 state.latitude = data[self._monidx_latitude] * \
944 90.0 / 10001750.0 / 65536.0 / 65536.0
945
946 state.longitude = data[self._monidx_longitude] * \
947 360.0 / 65536.0 / 65536.0 / 65536.0 / 65536.0
948 if state.longitude>180.0: state.longitude = 360.0 - state.longitude
949
950 state.paused = data[self._monidx_paused]!=0 or \
951 data[self._monidx_frozen]!=0 or \
952 data[self._monidx_replay]!=0
953 state.trickMode = data[self._monidx_slew]!=0
954
955 state.overspeed = data[self._monidx_overspeed]!=0
956 state.stalled = data[self._monidx_stalled]!=0
957 state.onTheGround = data[self._monidx_onTheGround]!=0
958
959 state.zfw = data[self._monidx_zfw] * const.LBSTOKG / 256.0
960 state.grossWeight = data[self._monidx_grossWeight] * const.LBSTOKG
961
962 state.heading = Handler.fsuipc2PositiveDegrees(data[self._monidx_heading])
963
964 state.pitch = Handler.fsuipc2Degrees(data[self._monidx_pitch])
965 state.bank = Handler.fsuipc2Degrees(data[self._monidx_bank])
966
967 state.ias = Handler.fsuipc2IAS(data[self._monidx_ias])
968 state.mach = data[self._monidx_mach] / 20480.0
969 state.groundSpeed = data[self._monidx_groundSpeed]* 3600.0/65536.0/1852.0
970 state.vs = Handler.fsuipc2VS(data[self._monidx_vs])
971
972 state.radioAltitude = \
973 Handler.fsuipc2radioAltitude(data[self._monidx_radioAltitude])
974 state.altitude = data[self._monidx_altitude]/const.FEETTOMETRES/65536.0/65536.0
975
976 state.gLoad = data[self._monidx_gLoad] / 625.0
977
978 numNotchesM1 = len(self._flapsNotches) - 1
979 flapsIncrement = 16383 / numNotchesM1
980 flapsControl = data[self._monidx_flapsControl]
981 flapsIndex = flapsControl / flapsIncrement
982 if flapsIndex < numNotchesM1:
983 if (flapsControl - (flapsIndex*flapsIncrement) >
984 (flapsIndex+1)*flapsIncrement - flapsControl):
985 flapsIndex += 1
986 state.flapsSet = self._flapsNotches[flapsIndex]
987
988 flapsLeft = data[self._monidx_flapsLeft]
989 state.flaps = self._flapsNotches[-1]*flapsLeft/16383.0
990
991 lights = data[self._monidx_lights]
992
993 state.navLightsOn = (lights&0x01) != 0
994 state.antiCollisionLightsOn = (lights&0x02) != 0
995 state.landingLightsOn = (lights&0x04) != 0
996 state.strobeLightsOn = (lights&0x10) != 0
997
998 state.pitotHeatOn = data[self._monidx_pitot]!=0
999
1000 state.parking = data[self._monidx_parking]!=0
1001
1002 state.gearsDown = data[self._monidx_noseGear]==16383
1003
1004 state.spoilersArmed = data[self._monidx_spoilersArmed]!=0
1005
1006 spoilers = data[self._monidx_spoilers]
1007 if spoilers<=4800:
1008 state.spoilersExtension = 0.0
1009 else:
1010 state.spoilersExtension = (spoilers - 4800) * 100.0 / (16383 - 4800)
1011
1012 state.altimeter = data[self._monidx_altimeter] / 16.0
1013
1014 state.nav1 = AircraftModel.convertFrequency(data[self._monidx_nav1])
1015 state.nav2 = AircraftModel.convertFrequency(data[self._monidx_nav2])
1016 state.squawk = AircraftModel.convertBCD(data[self._monidx_squawk], 4)
1017
1018 state.windSpeed = data[self._monidx_windSpeed]
1019 state.windDirection = data[self._monidx_windDirection]*360.0/65536.0
1020 if state.windDirection<0.0: state.windDirection += 360.0
1021
1022 state.visibility = data[self._monidx_visibility]*1609.344/100.0
1023
1024 return state
1025
1026#------------------------------------------------------------------------------
1027
1028class GenericAircraftModel(AircraftModel):
1029 """A generic aircraft model that can handle the fuel levels, the N1 or RPM
1030 values and some other common parameters in a generic way."""
1031
1032 def __init__(self, flapsNotches, fuelTanks, numEngines, isN1 = True):
1033 """Construct the generic aircraft model with the given data.
1034
1035 flapsNotches is an array of how much degrees the individual flaps
1036 notches mean.
1037
1038 fuelTanks is an array of const.FUELTANK_XXX constants about the
1039 aircraft's fuel tanks. They will be converted to offsets.
1040
1041 numEngines is the number of engines the aircraft has.
1042
1043 isN1 determines if the engines have an N1 value or an RPM value
1044 (e.g. pistons)."""
1045 super(GenericAircraftModel, self).__init__(flapsNotches = flapsNotches)
1046
1047 self._fuelTanks = fuelTanks
1048 self._fuelStartIndex = None
1049 self._numEngines = numEngines
1050 self._engineStartIndex = None
1051 self._isN1 = isN1
1052
1053 def doesHandle(self, aircraft, aircraftName):
1054 """Determine if the model handles the given aircraft name.
1055
1056 This implementation returns True."""
1057 return True
1058
1059 def addMonitoringData(self, data):
1060 """Add the model-specific monitoring data to the given array."""
1061 super(GenericAircraftModel, self).addMonitoringData(data)
1062
1063 self._addOffsetWithIndexMember(data, 0x0af4, "H", "_monidx_fuelWeight")
1064
1065 self._fuelStartIndex = len(data)
1066 for tank in self._fuelTanks:
1067 offset = _tank2offset[tank]
1068 self._addOffsetWithIndexMember(data, offset, "u") # tank level
1069 self._addOffsetWithIndexMember(data, offset+4, "u") # tank capacity
1070
1071 if self._isN1:
1072 self._engineStartIndex = len(data)
1073 for i in range(0, self._numEngines):
1074 self._addOffsetWithIndexMember(data, 0x2000 + i * 0x100, "f") # N1
1075 self._addOffsetWithIndexMember(data, 0x088c + i * 0x98, "h") # throttle lever
1076
1077 def getAircraftState(self, aircraft, timestamp, data):
1078 """Get the aircraft state.
1079
1080 Get it from the parent, and then add the data about the fuel levels and
1081 the engine parameters."""
1082 state = super(GenericAircraftModel, self).getAircraftState(aircraft,
1083 timestamp,
1084 data)
1085
1086 fuelWeight = data[self._monidx_fuelWeight]/256.0
1087 state.fuel = []
1088 for i in range(self._fuelStartIndex,
1089 self._fuelStartIndex + 2*len(self._fuelTanks), 2):
1090 fuel = data[i+1]*data[i]*fuelWeight*const.LBSTOKG/128.0/65536.0
1091 state.fuel.append(fuel)
1092
1093 state.n1 = []
1094 state.reverser = []
1095 for i in range(self._engineStartIndex,
1096 self._engineStartIndex + 2*self._numEngines, 2):
1097 state.n1.append(data[i])
1098 state.reverser.append(data[i+1]<0)
1099
1100 return state
1101
1102#------------------------------------------------------------------------------
1103
1104class GenericModel(GenericAircraftModel):
1105 """Generic aircraft model for an unknown type."""
1106 def __init__(self):
1107 """Construct the model."""
1108 super(GenericModel, self). \
1109 __init__(flapsNotches = [0, 10, 20, 30],
1110 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_RIGHT],
1111 numEngines = 2)
1112
1113 @property
1114 def name(self):
1115 """Get the name for this aircraft model."""
1116 return "FSUIPC/Generic"
1117
1118#------------------------------------------------------------------------------
1119
1120class B737Model(GenericAircraftModel):
1121 """Generic model for the Boeing 737 Classing and NG aircraft."""
1122 def __init__(self):
1123 """Construct the model."""
1124 super(B737Model, self). \
1125 __init__(flapsNotches = [0, 1, 2, 5, 10, 15, 25, 30, 40],
1126 fuelTanks = acft.Boeing737.fuelTanks,
1127 numEngines = 2)
1128
1129 @property
1130 def name(self):
1131 """Get the name for this aircraft model."""
1132 return "FSUIPC/Generic Boeing 737"
1133
1134#------------------------------------------------------------------------------
1135
1136class PMDGBoeing737NGModel(B737Model):
1137 """A model handler for the PMDG Boeing 737NG model."""
1138 @staticmethod
1139 def doesHandle(aircraft, (name, airPath)):
1140 """Determine if this model handler handles the aircraft with the given
1141 name."""
1142 return aircraft.type in [const.AIRCRAFT_B736,
1143 const.AIRCRAFT_B737,
1144 const.AIRCRAFT_B738] and \
1145 (name.find("PMDG")!=-1 or airPath.find("PMDG")!=-1) and \
1146 (name.find("737")!=-1 or airPath.find("737")!=-1) and \
1147 (name.find("600")!=-1 or airPath.find("600")!=-1 or \
1148 name.find("700")!=-1 or airPath.find("700")!=-1 or \
1149 name.find("800")!=-1 or airPath.find("800")!=-1 or \
1150 name.find("900")!=-1 or airPath.find("900")!=-1)
1151
1152 @property
1153 def name(self):
1154 """Get the name for this aircraft model."""
1155 return "FSUIPC/PMDG Boeing 737NG"
1156
1157 def addMonitoringData(self, data):
1158 """Add the model-specific monitoring data to the given array."""
1159 super(PMDGBoeing737NGModel, self).addMonitoringData(data)
1160
1161 self._addOffsetWithIndexMember(data, 0x6202, "b", "_pmdgidx_switches")
1162
1163 def getAircraftState(self, aircraft, timestamp, data):
1164 """Get the aircraft state.
1165
1166 Get it from the parent, and then check some PMDG-specific stuff."""
1167 state = super(PMDGBoeing737NGModel, self).getAircraftState(aircraft,
1168 timestamp,
1169 data)
1170 if data[self._pmdgidx_switches]&0x01==0x01:
1171 state.altimeter = 1013.25
1172
1173 return state
1174
1175#------------------------------------------------------------------------------
1176
1177class B767Model(GenericAircraftModel):
1178 """Generic model for the Boeing 767 aircraft."""
1179 def __init__(self):
1180 """Construct the model."""
1181 super(B767Model, self). \
1182 __init__(flapsNotches = [0, 1, 5, 15, 20, 25, 30],
1183 fuelTanks = acft.Boeing767.fuelTanks,
1184 numEngines = 2)
1185
1186 @property
1187 def name(self):
1188 """Get the name for this aircraft model."""
1189 return "FSUIPC/Generic Boeing 767"
1190
1191#------------------------------------------------------------------------------
1192
1193class DH8DModel(GenericAircraftModel):
1194 """Generic model for the Bombardier Dash 8-Q400 aircraft."""
1195 def __init__(self):
1196 """Construct the model."""
1197 super(DH8DModel, self). \
1198 __init__(flapsNotches = [0, 5, 10, 15, 35],
1199 fuelTanks = acft.DH8D.fuelTanks,
1200 numEngines = 2)
1201
1202 @property
1203 def name(self):
1204 """Get the name for this aircraft model."""
1205 return "FSUIPC/Generic Bombardier Dash 8-Q400"
1206
1207#------------------------------------------------------------------------------
1208
1209class DreamwingsDH8DModel(DH8DModel):
1210 """Model handler for the Dreamwings Dash 8-Q400."""
1211 @staticmethod
1212 def doesHandle(aircraft, (name, airPath)):
1213 """Determine if this model handler handles the aircraft with the given
1214 name."""
1215 return aircraft.type==const.AIRCRAFT_DH8D and \
1216 (name.find("Dreamwings")!=-1 or airPath.find("Dreamwings")!=-1) and \
1217 (name.find("Dash")!=-1 or airPath.find("Dash")!=-1) and \
1218 (name.find("Q400")!=-1 or airPath.find("Q400")!=-1) and \
1219 airPath.find("Dash8Q400")!=-1
1220
1221 @property
1222 def name(self):
1223 """Get the name for this aircraft model."""
1224 return "FSUIPC/Dreamwings Bombardier Dash 8-Q400"
1225
1226 def getAircraftState(self, aircraft, timestamp, data):
1227 """Get the aircraft state.
1228
1229 Get it from the parent, and then invert the pitot heat state."""
1230 state = super(DreamwingsDH8DModel, self).getAircraftState(aircraft,
1231 timestamp,
1232 data)
1233 state.pitotHeatOn = not state.pitotHeatOn
1234
1235 return state
1236#------------------------------------------------------------------------------
1237
1238class CRJ2Model(GenericAircraftModel):
1239 """Generic model for the Bombardier CRJ-200 aircraft."""
1240 def __init__(self):
1241 """Construct the model."""
1242 super(CRJ2Model, self). \
1243 __init__(flapsNotches = [0, 8, 20, 30, 45],
1244 fuelTanks = acft.CRJ2.fuelTanks,
1245 numEngines = 2)
1246
1247 @property
1248 def name(self):
1249 """Get the name for this aircraft model."""
1250 return "FSUIPC/Generic Bombardier CRJ-200"
1251
1252#------------------------------------------------------------------------------
1253
1254class F70Model(GenericAircraftModel):
1255 """Generic model for the Fokker F70 aircraft."""
1256 def __init__(self):
1257 """Construct the model."""
1258 super(F70Model, self). \
1259 __init__(flapsNotches = [0, 8, 15, 25, 42],
1260 fuelTanks = acft.F70.fuelTanks,
1261 numEngines = 2)
1262
1263 @property
1264 def name(self):
1265 """Get the name for this aircraft model."""
1266 return "FSUIPC/Generic Fokker 70"
1267
1268#------------------------------------------------------------------------------
1269
1270class DC3Model(GenericAircraftModel):
1271 """Generic model for the Lisunov Li-2 (DC-3) aircraft."""
1272 def __init__(self):
1273 """Construct the model."""
1274 super(DC3Model, self). \
1275 __init__(flapsNotches = [0, 15, 30, 45],
1276 fuelTanks = acft.DC3.fuelTanks,
1277 numEngines = 2)
1278
1279 @property
1280 def name(self):
1281 """Get the name for this aircraft model."""
1282 return "FSUIPC/Generic Lisunov Li-2"
1283
1284#------------------------------------------------------------------------------
1285
1286class T134Model(GenericAircraftModel):
1287 """Generic model for the Tupolev Tu-134 aircraft."""
1288 def __init__(self):
1289 """Construct the model."""
1290 super(T134Model, self). \
1291 __init__(flapsNotches = [0, 10, 20, 30],
1292 fuelTanks = acft.T134.fuelTanks,
1293 numEngines = 2)
1294
1295 @property
1296 def name(self):
1297 """Get the name for this aircraft model."""
1298 return "FSUIPC/Generic Tupolev Tu-134"
1299
1300#------------------------------------------------------------------------------
1301
1302class T154Model(GenericAircraftModel):
1303 """Generic model for the Tupolev Tu-134 aircraft."""
1304 def __init__(self):
1305 """Construct the model."""
1306 super(T154Model, self). \
1307 __init__(flapsNotches = [0, 15, 28, 45],
1308 fuelTanks = acft.T154.fuelTanks,
1309 numEngines = 3)
1310
1311 @property
1312 def name(self):
1313 """Get the name for this aircraft model."""
1314 return "FSUIPC/Generic Tupolev Tu-154"
1315
1316 def getAircraftState(self, aircraft, timestamp, data):
1317 """Get an aircraft state object for the given monitoring data.
1318
1319 This removes the reverser value for the middle engine."""
1320 state = super(T154Model, self).getAircraftState(aircraft, timestamp, data)
1321 del state.reverser[1]
1322 return state
1323
1324#------------------------------------------------------------------------------
1325
1326class YK40Model(GenericAircraftModel):
1327 """Generic model for the Yakovlev Yak-40 aircraft."""
1328 def __init__(self):
1329 """Construct the model."""
1330 super(YK40Model, self). \
1331 __init__(flapsNotches = [0, 20, 35],
1332 fuelTanks = acft.YK40.fuelTanks,
1333 numEngines = 2)
1334
1335 @property
1336 def name(self):
1337 """Get the name for this aircraft model."""
1338 return "FSUIPC/Generic Yakovlev Yak-40"
1339
1340#------------------------------------------------------------------------------
1341
1342_genericModels = { const.AIRCRAFT_B736 : B737Model,
1343 const.AIRCRAFT_B737 : B737Model,
1344 const.AIRCRAFT_B738 : B737Model,
1345 const.AIRCRAFT_B733 : B737Model,
1346 const.AIRCRAFT_B734 : B737Model,
1347 const.AIRCRAFT_B735 : B737Model,
1348 const.AIRCRAFT_DH8D : DH8DModel,
1349 const.AIRCRAFT_B762 : B767Model,
1350 const.AIRCRAFT_B763 : B767Model,
1351 const.AIRCRAFT_CRJ2 : B767Model,
1352 const.AIRCRAFT_F70 : F70Model,
1353 const.AIRCRAFT_DC3 : DC3Model,
1354 const.AIRCRAFT_T134 : T134Model,
1355 const.AIRCRAFT_T154 : T154Model,
1356 const.AIRCRAFT_YK40 : YK40Model }
1357
1358#------------------------------------------------------------------------------
1359
1360AircraftModel.registerSpecial(PMDGBoeing737NGModel)
1361AircraftModel.registerSpecial(DreamwingsDH8DModel)
1362
1363#------------------------------------------------------------------------------
Note: See TracBrowser for help on using the repository browser.