source: src/mlx/fsuipc.py@ 642:c2d51278efcd

Last change on this file since 642:c2d51278efcd was 559:54fa2efc1dc2, checked in by István Váradi <ivaradi@…>, 11 years ago

Added debug printout to see what is read from FS when the flaps settings change (re #225)

File size: 82.6 KB
Line 
1
2import fs
3import const
4import util
5import acft
6from watchdog import Watchdog
7
8import threading
9import os
10import time
11import calendar
12import sys
13import codecs
14import math
15
16if os.name == "nt" and "FORCE_PYUIPC_SIM" not in os.environ:
17 import pyuipc
18else:
19 import pyuipc_sim as pyuipc
20
21#------------------------------------------------------------------------------
22
23## @package mlx.fsuipc
24#
25# The module towards FSUIPC.
26#
27# This module implements the simulator interface to FSUIPC.
28#
29# The \ref Handler class is thread handling the FSUIPC requests. It can be
30# given read, periodic read and write, requests, that are executed
31# asynchronously, and a callback function is called with the result. This class
32# is used internally within the module.
33#
34# The \ref Simulator class is the actual interface to the flight simulator, and
35# an instance of it is returned by \ref mlx.fs.createSimulator. This object can
36# be used to connect to the simulator and disconnect from it, to query various
37# data and to start and stop the monitoring of the data.
38#
39# \ref AircraftModel is the base class of the aircraft models. A "model" is a
40# particular implementation of an aircraft, such as the PMDG Boeing 737NG in
41# Flight Simulator 2004. Since each type and each model has its peculiarities
42# (e.g. the different engine and fuel tank configurations), each aircraft type
43# has a generic model, that should work for most of the time. However, certain
44# models may implement various controls, gauges, etc. differently, and such
45# peculiarites can be handled in a specific subclass of \ref
46# AircraftModel. These subclasses should be registered as special ones, and if
47# the simulator detects that the aircraft's model became known or has changed,
48# it will check these special models before resorting to the generic ones.
49#
50# The models are responsible also for querying certain parameters, such as the
51# fuel tank configuration. While ideally it should be specific to a type only,
52# it is possible that the model contains different tanks, in which case some
53# tricks may be needed. See the \ref DC3Model "DC-3 (Li-2)" aircraft as an
54# example.
55
56#------------------------------------------------------------------------------
57
58## The mapping of tank types to FSUIPC offsets
59_tank2offset = { const.FUELTANK_CENTRE : 0x0b74,
60 const.FUELTANK_LEFT : 0x0b7c,
61 const.FUELTANK_RIGHT : 0x0b94,
62 const.FUELTANK_LEFT_AUX : 0x0b84,
63 const.FUELTANK_RIGHT_AUX : 0x0b9c,
64 const.FUELTANK_LEFT_TIP : 0x0b8c,
65 const.FUELTANK_RIGHT_TIP : 0x0ba4,
66 const.FUELTANK_EXTERNAL1 : 0x1254,
67 const.FUELTANK_EXTERNAL2 : 0x125c,
68 const.FUELTANK_CENTRE2 : 0x1244 }
69
70#------------------------------------------------------------------------------
71
72class Handler(threading.Thread):
73 """The thread to handle the FSUIPC requests."""
74 @staticmethod
75 def fsuipc2VS(data):
76 """Convert the given vertical speed data read from FSUIPC into feet/min."""
77 return data*60.0/const.FEETTOMETRES/256.0
78
79 @staticmethod
80 def fsuipc2radioAltitude(data):
81 """Convert the given radio altitude data read from FSUIPC into feet."""
82 return data/const.FEETTOMETRES/65536.0
83
84 @staticmethod
85 def fsuipc2Degrees(data):
86 """Convert the given data into degrees."""
87 return data * 360.0 / 65536.0 / 65536.0
88
89 @staticmethod
90 def fsuipc2PositiveDegrees(data):
91 """Convert the given data into positive degrees."""
92 degrees = Handler.fsuipc2Degrees(data)
93 if degrees<0.0: degrees += 360.0
94 return degrees
95
96 @staticmethod
97 def fsuipc2IAS(data):
98 """Convert the given data into indicated airspeed."""
99 return data / 128.0
100
101 @staticmethod
102 def _callSafe(fun):
103 """Call the given function and swallow any exceptions."""
104 try:
105 return fun()
106 except Exception, e:
107 print >> sys.stderr, util.utf2unicode(str(e))
108 return None
109
110 # The number of times a read is attempted
111 NUM_READATTEMPTS = 3
112
113 # The number of connection attempts
114 NUM_CONNECTATTEMPTS = 3
115
116 # The interval between successive connect attempts
117 CONNECT_INTERVAL = 0.25
118
119 @staticmethod
120 def _performRead(data, callback, extra, validator):
121 """Perform a read request.
122
123 If there is a validator, that will be called with the return values,
124 and if the values are wrong, the request is retried at most a certain
125 number of times.
126
127 Return True if the request has succeeded, False if validation has
128 failed during all attempts. An exception may also be thrown if there is
129 some lower-level communication problem."""
130 attemptsLeft = Handler.NUM_READATTEMPTS
131 while attemptsLeft>0:
132 values = pyuipc.read(data)
133 if validator is None or \
134 Handler._callSafe(lambda: validator(values, extra)):
135 Handler._callSafe(lambda: callback(values, extra))
136 return True
137 else:
138 attemptsLeft -= 1
139 return False
140
141 class Request(object):
142 """A simple, one-shot request."""
143 def __init__(self, forWrite, data, callback, extra, validator = None):
144 """Construct the request."""
145 self._forWrite = forWrite
146 self._data = data
147 self._callback = callback
148 self._extra = extra
149 self._validator = validator
150
151 def process(self, time):
152 """Process the request.
153
154 Return True if the request has succeeded, False if data validation
155 has failed for a reading request. An exception may also be thrown
156 if there is some lower-level communication problem."""
157 if self._forWrite:
158 pyuipc.write(self._data)
159 Handler._callSafe(lambda: self._callback(True, self._extra))
160 return True
161 else:
162 return Handler._performRead(self._data, self._callback,
163 self._extra, self._validator)
164
165 def fail(self):
166 """Handle the failure of this request."""
167 if self._forWrite:
168 Handler._callSafe(lambda: self._callback(False, self._extra))
169 else:
170 Handler._callSafe(lambda: self._callback(None, self._extra))
171
172 class PeriodicRequest(object):
173 """A periodic request."""
174 def __init__(self, id, period, data, callback, extra, validator):
175 """Construct the periodic request."""
176 self._id = id
177 self._period = period
178 self._nextFire = time.time()
179 self._data = data
180 self._preparedData = None
181 self._callback = callback
182 self._extra = extra
183 self._validator = validator
184
185 @property
186 def id(self):
187 """Get the ID of this periodic request."""
188 return self._id
189
190 @property
191 def nextFire(self):
192 """Get the next firing time."""
193 return self._nextFire
194
195 def process(self, time):
196 """Check if this request should be executed, and if so, do so.
197
198 time is the time at which the request is being executed. If this
199 function is called too early, nothing is done, and True is
200 returned.
201
202 Return True if the request has succeeded, False if data validation
203 has failed. An exception may also be thrown if there is some
204 lower-level communication problem."""
205 if time<self._nextFire:
206 return True
207
208 if self._preparedData is None:
209 self._preparedData = pyuipc.prepare_data(self._data)
210 self._data = None
211
212 isOK = Handler._performRead(self._preparedData, self._callback,
213 self._extra, self._validator)
214
215 if isOK:
216 while self._nextFire <= time:
217 self._nextFire += self._period
218
219 return isOK
220
221 def fail(self):
222 """Handle the failure of this request."""
223 pass
224
225 def __cmp__(self, other):
226 """Compare two periodic requests. They are ordered by their next
227 firing times."""
228 return cmp(self._nextFire, other._nextFire)
229
230 def __init__(self, connectionListener,
231 connectAttempts = -1, connectInterval = 0.2):
232 """Construct the handler with the given connection listener."""
233 threading.Thread.__init__(self)
234
235 self._connectionListener = connectionListener
236 self._connectAttempts = connectAttempts
237 self._connectInterval = connectInterval
238
239 self._requestCondition = threading.Condition()
240 self._connectionRequested = False
241 self._connected = False
242
243 self._requests = []
244 self._nextPeriodicID = 1
245 self._periodicRequests = []
246
247 self._watchdogClient = Watchdog.get().addClient(2.0, "fsuipc.Handler")
248
249 self.daemon = True
250
251 def requestRead(self, data, callback, extra = None, validator = None):
252 """Request the reading of some data.
253
254 data is a list of tuples of the following items:
255 - the offset of the data as an integer
256 - the type letter of the data as a string
257
258 callback is a function that receives two pieces of data:
259 - the values retrieved or None on error
260 - the extra parameter
261
262 It will be called in the handler's thread!
263 """
264 with self._requestCondition:
265 self._requests.append(Handler.Request(False, data, callback, extra,
266 validator))
267 self._requestCondition.notify()
268
269 def requestWrite(self, data, callback, extra = None):
270 """Request the writing of some data.
271
272 data is a list of tuples of the following items:
273 - the offset of the data as an integer
274 - the type letter of the data as a string
275 - the data to write
276
277 callback is a function that receives two pieces of data:
278 - a boolean indicating if writing was successful
279 - the extra data
280 It will be called in the handler's thread!
281 """
282 with self._requestCondition:
283 request = Handler.Request(True, data, callback, extra)
284 #print "fsuipc.Handler.requestWrite", request
285 self._requests.append(request)
286 self._requestCondition.notify()
287
288 @staticmethod
289 def _readWriteCallback(data, extra):
290 """Callback for the read() and write() calls below."""
291 extra.append(data)
292 with extra[0] as condition:
293 condition.notify()
294
295 def requestPeriodicRead(self, period, data, callback, extra = None,
296 validator = None):
297 """Request a periodic read of data.
298
299 period is a floating point number with the period in seconds.
300
301 This function returns an identifier which can be used to cancel the
302 request."""
303 with self._requestCondition:
304 id = self._nextPeriodicID
305 self._nextPeriodicID += 1
306 request = Handler.PeriodicRequest(id, period, data, callback,
307 extra, validator)
308 self._periodicRequests.append(request)
309 self._requestCondition.notify()
310 return id
311
312 def clearPeriodic(self, id):
313 """Clear the periodic request with the given ID."""
314 with self._requestCondition:
315 for i in range(0, len(self._periodicRequests)):
316 if self._periodicRequests[i].id==id:
317 del self._periodicRequests[i]
318 return True
319 return False
320
321 def connect(self):
322 """Initiate the connection to the flight simulator."""
323 with self._requestCondition:
324 if not self._connectionRequested:
325 self._connectionRequested = True
326 self._requestCondition.notify()
327
328 def disconnect(self):
329 """Disconnect from the flight simulator."""
330 with self._requestCondition:
331 self._requests = []
332 if self._connectionRequested:
333 self._connectionRequested = False
334 self._requestCondition.notify()
335
336 def clearRequests(self):
337 """Clear the outstanding one-shot requests."""
338 with self._requestCondition:
339 self._requests = []
340
341 def run(self):
342 """Perform the operation of the thread."""
343 while True:
344 self._waitConnectionRequest()
345
346 if self._connect()>0:
347 self._handleConnection()
348
349 self._disconnect()
350
351 def _waitConnectionRequest(self):
352 """Wait for a connection request to arrive."""
353 with self._requestCondition:
354 while not self._connectionRequested:
355 self._requestCondition.wait()
356
357 def _connect(self, autoReconnection = False, attempts = 0):
358 """Try to connect to the flight simulator via FSUIPC
359
360 Returns True if the connection has been established, False if it was
361 not due to no longer requested.
362 """
363 while self._connectionRequested:
364 if attempts>=self.NUM_CONNECTATTEMPTS:
365 self._connectionRequested = False
366 if autoReconnection:
367 Handler._callSafe(lambda:
368 self._connectionListener.disconnected())
369 else:
370 Handler._callSafe(lambda:
371 self._connectionListener.connectionFailed())
372 return 0
373
374 try:
375 attempts += 1
376 pyuipc.open(pyuipc.SIM_ANY)
377 description = "(FSUIPC version: 0x%04x, library version: 0x%04x, FS version: %d)" % \
378 (pyuipc.fsuipc_version, pyuipc.lib_version,
379 pyuipc.fs_version)
380 if not autoReconnection:
381 fsType = const.SIM_MSFSX \
382 if pyuipc.fs_version == pyuipc.SIM_FSX \
383 else const.SIM_MSFS9
384
385 Handler._callSafe(lambda:
386 self._connectionListener.connected(fsType,
387 description))
388 self._connected = True
389 return attempts
390 except Exception, e:
391 print "fsuipc.Handler._connect: connection failed: " + \
392 util.utf2unicode(str(e)) + \
393 " (attempts: %d)" % (attempts,)
394 if attempts<self.NUM_CONNECTATTEMPTS:
395 time.sleep(self.CONNECT_INTERVAL)
396
397 def _handleConnection(self):
398 """Handle a living connection."""
399 with self._requestCondition:
400 while self._connectionRequested:
401 self._processRequests()
402 self._waitRequest()
403
404 def _waitRequest(self):
405 """Wait for the time of the next request.
406
407 Returns also, if the connection is no longer requested.
408
409 Should be called with the request condition lock held."""
410 while self._connectionRequested:
411 timeout = None
412 if self._periodicRequests:
413 self._periodicRequests.sort()
414 timeout = self._periodicRequests[0].nextFire - time.time()
415
416 if self._requests or \
417 (timeout is not None and timeout <= 0.0):
418 return
419
420 self._requestCondition.wait(timeout)
421
422 def _disconnect(self):
423 """Disconnect from the flight simulator."""
424 print "fsuipc.Handler._disconnect"
425 if self._connected:
426 pyuipc.close()
427 self._connected = False
428
429 def _processRequest(self, request, time, attempts):
430 """Process the given request.
431
432 If an exception occurs or invalid data is read too many times, we try
433 to reconnect.
434
435 This function returns only if the request has succeeded, or if a
436 connection is no longer requested.
437
438 This function is called with the request lock held, but is relased
439 whole processing the request and reconnecting."""
440 self._requestCondition.release()
441
442 #print "fsuipc.Handler._processRequest", request
443
444 needReconnect = False
445 try:
446 self._watchdogClient.set()
447 try:
448 if not request.process(time):
449 print "fsuipc.Handler._processRequest: FSUIPC returned invalid data too many times, reconnecting"
450 needReconnect = True
451 except Exception as e:
452 print "fsuipc.Handler._processRequest: FSUIPC connection failed (" + \
453 util.utf2unicode(str(e)) + \
454 "), reconnecting (attempts=%d)." % (attempts,)
455 needReconnect = True
456
457 if needReconnect:
458 with self._requestCondition:
459 self._requests.insert(0, request)
460 self._disconnect()
461 return self._connect(autoReconnection = True, attempts = attempts)
462 else:
463 return 0
464 finally:
465 self._watchdogClient.clear()
466 self._requestCondition.acquire()
467
468 def _processRequests(self):
469 """Process any pending requests.
470
471 Will be called with the request lock held."""
472 attempts = 0
473 while self._connectionRequested and self._periodicRequests:
474 self._periodicRequests.sort()
475 request = self._periodicRequests[0]
476
477 t = time.time()
478
479 if request.nextFire>t:
480 break
481
482 attempts = self._processRequest(request, t, attempts)
483
484 while self._connectionRequested and self._requests:
485 request = self._requests[0]
486 del self._requests[0]
487
488 attempts = self._processRequest(request, None, attempts)
489
490 return self._connectionRequested
491
492#------------------------------------------------------------------------------
493
494class Simulator(object):
495 """The simulator class representing the interface to the flight simulator
496 via FSUIPC."""
497 # The basic data that should be queried all the time once we are connected
498 timeData = [ (0x0240, "H"), # Year
499 (0x023e, "H"), # Number of day in year
500 (0x023b, "b"), # UTC hour
501 (0x023c, "b"), # UTC minute
502 (0x023a, "b") ] # seconds
503
504 normalData = timeData + \
505 [ (0x3d00, -256), # The name of the current aircraft
506 (0x3c00, -256), # The path of the current AIR file
507 (0x1274, "h") ] # Text display mode
508
509 flareData1 = [ (0x023a, "b"), # Seconds of time
510 (0x31e4, "d"), # Radio altitude
511 (0x02c8, "d") ] # Vertical speed
512
513 flareStartData = [ (0x0e90, "H"), # Ambient wind speed
514 (0x0e92, "H"), # Ambient wind direction
515 (0x0e8a, "H") ] # Visibility
516
517 flareData2 = [ (0x023a, "b"), # Seconds of time
518 (0x0366, "H"), # On the ground
519 (0x02c8, "d"), # Vertical speed
520 (0x030c, "d"), # Touch-down rate
521 (0x02bc, "d"), # IAS
522 (0x0578, "d"), # Pitch
523 (0x057c, "d"), # Bank
524 (0x0580, "d") ] # Heading
525
526 TIME_SYNC_INTERVAL = 3.0
527
528 @staticmethod
529 def _getTimestamp(data):
530 """Convert the given data into a timestamp."""
531 timestamp = calendar.timegm(time.struct_time([data[0],
532 1, 1, 0, 0, 0, -1, 1, 0]))
533 timestamp += data[1] * 24 * 3600
534 timestamp += data[2] * 3600
535 timestamp += data[3] * 60
536 timestamp += data[4]
537
538 return timestamp
539
540 @staticmethod
541 def _appendHotkeyData(data, offset, hotkey):
542 """Append the data for the given hotkey to the given array, that is
543 intended to be passed to requestWrite call on the handler."""
544 data.append((offset + 0, "b", ord(hotkey.key)))
545
546 modifiers = 0
547 if hotkey.ctrl: modifiers |= 0x02
548 if hotkey.shift: modifiers |= 0x01
549 data.append((offset + 1, "b", modifiers))
550
551 data.append((offset + 2, "b", 0))
552
553 data.append((offset + 3, "b", 0))
554
555 def __init__(self, connectionListener, connectAttempts = -1,
556 connectInterval = 0.2):
557 """Construct the simulator.
558
559 The aircraft object passed must provide the following members:
560 - type: one of the AIRCRAFT_XXX constants from const.py
561 - modelChanged(aircraftName, modelName): called when the model handling
562 the aircraft has changed.
563 - handleState(aircraftState): handle the given state.
564 - flareStarted(windSpeed, windDirection, visibility, flareStart,
565 flareStartFS): called when the flare has
566 started. windSpeed is in knots, windDirection is in degrees and
567 visibility is in metres. flareStart and flareStartFS are two time
568 values expressed in seconds that can be used to calculate the flare
569 time.
570 - flareFinished(flareEnd, flareEndFS, tdRate, tdRateCalculatedByFS,
571 ias, pitch, bank, heading): called when the flare has
572 finished, i.e. the aircraft is on the ground. flareEnd and flareEndFS
573 are the two time values corresponding to the touchdown time. tdRate is
574 the touch-down rate, tdRateCalculatedBySim indicates if the data comes
575 from the simulator or was calculated by the adapter. The other data
576 are self-explanatory and expressed in their 'natural' units."""
577 self._fsType = None
578 self._aircraft = None
579
580 self._handler = Handler(self,
581 connectAttempts = connectAttempts,
582 connectInterval = connectInterval)
583 self._connectionListener = connectionListener
584 self._handler.start()
585
586 self._scroll = False
587
588 self._syncTime = False
589 self._nextSyncTime = -1
590
591 self._normalRequestID = None
592
593 self._monitoringRequested = False
594 self._monitoring = False
595
596 self._aircraftName = None
597 self._aircraftModel = None
598
599 self._flareRequestID = None
600 self._flareRates = []
601 self._flareStart = None
602 self._flareStartFS = None
603
604 self._hotkeyLock = threading.Lock()
605 self._hotkeys = None
606 self._hotkeySetID = 0
607 self._hotkeySetGeneration = 0
608 self._hotkeyOffets = None
609 self._hotkeyRequestID = None
610 self._hotkeyCallback = None
611
612 self._latin1decoder = codecs.getdecoder("iso-8859-1")
613 self._fuelCallback = None
614
615 def connect(self, aircraft):
616 """Initiate a connection to the simulator."""
617 self._aircraft = aircraft
618 self._aircraftName = None
619 self._aircraftModel = None
620 self._handler.connect()
621 if self._normalRequestID is None:
622 self._nextSyncTime = -1
623 self._startDefaultNormal()
624
625 def reconnect(self):
626 """Initiate a reconnection to the simulator.
627
628 It does not reset already set up data, just calls connect() on the
629 handler."""
630 self._handler.connect()
631
632 def requestZFW(self, callback):
633 """Send a request for the ZFW."""
634 self._handler.requestRead([(0x3bfc, "d")], self._handleZFW, extra = callback)
635
636 def requestWeights(self, callback):
637 """Request the following weights: DOW, ZFW, payload.
638
639 These values will be passed to the callback function in this order, as
640 separate arguments."""
641 self._handler.requestRead([(0x13fc, "d")], self._handlePayloadCount,
642 extra = callback)
643
644 def requestTime(self, callback):
645 """Request the time from the simulator."""
646 self._handler.requestRead(Simulator.timeData, self._handleTime,
647 extra = callback)
648
649 def startMonitoring(self):
650 """Start the periodic monitoring of the aircraft and pass the resulting
651 state to the aircraft object periodically."""
652 assert not self._monitoringRequested
653 self._monitoringRequested = True
654
655 def stopMonitoring(self):
656 """Stop the periodic monitoring of the aircraft."""
657 assert self._monitoringRequested
658 self._monitoringRequested = False
659
660 def startFlare(self):
661 """Start monitoring the flare time.
662
663 At present it is assumed to be called from the FSUIPC thread, hence no
664 protection."""
665 #self._aircraft.logger.debug("startFlare")
666 if self._flareRequestID is None:
667 self._flareRates = []
668 self._flareRequestID = self._handler.requestPeriodicRead(0.1,
669 Simulator.flareData1,
670 self._handleFlare1)
671
672 def cancelFlare(self):
673 """Cancel monitoring the flare time.
674
675 At present it is assumed to be called from the FSUIPC thread, hence no
676 protection."""
677 if self._flareRequestID is not None:
678 self._handler.clearPeriodic(self._flareRequestID)
679 self._flareRequestID = None
680
681 def sendMessage(self, message, duration = 3,
682 _disconnect = False):
683 """Send a message to the pilot via the simulator.
684
685 duration is the number of seconds to keep the message displayed."""
686
687 print "fsuipc.Simulator.sendMessage:", message
688
689 if self._scroll:
690 if duration==0: duration = -1
691 elif duration == 1: duration = -2
692 else: duration = -duration
693
694 data = [(0x3380, -1 - len(message), message),
695 (0x32fa, 'h', duration)]
696
697 #if _disconnect:
698 # print "fsuipc.Simulator.sendMessage(disconnect)", message
699
700 self._handler.requestWrite(data, self._handleMessageSent,
701 extra = _disconnect)
702
703 def getFuel(self, callback):
704 """Get the fuel information for the current model.
705
706 The callback will be called with a list of triplets with the following
707 items:
708 - the fuel tank identifier
709 - the current weight of the fuel in the tank (in kgs)
710 - the current total capacity of the tank (in kgs)."""
711 if self._aircraftModel is None:
712 self._fuelCallback = callback
713 else:
714 self._aircraftModel.getFuel(self._handler, callback)
715
716 def setFuelLevel(self, levels):
717 """Set the fuel level to the given ones.
718
719 levels is an array of two-tuples, where each tuple consists of the
720 following:
721 - the const.FUELTANK_XXX constant denoting the tank that must be set,
722 - the requested level of the fuel as a floating-point value between 0.0
723 and 1.0."""
724 if self._aircraftModel is not None:
725 self._aircraftModel.setFuelLevel(self._handler, levels)
726
727 def enableTimeSync(self):
728 """Enable the time synchronization."""
729 self._nextSyncTime = -1
730 self._syncTime = True
731
732 def disableTimeSync(self):
733 """Enable the time synchronization."""
734 self._syncTime = False
735 self._nextSyncTime = -1
736
737 def listenHotkeys(self, hotkeys, callback):
738 """Start listening to the given hotkeys.
739
740 callback is function expecting two arguments:
741 - the ID of the hotkey set as returned by this function,
742 - the list of the indexes of the hotkeys that were pressed."""
743 with self._hotkeyLock:
744 assert self._hotkeys is None
745
746 self._hotkeys = hotkeys
747 self._hotkeySetID += 1
748 self._hotkeySetGeneration = 0
749 self._hotkeyCallback = callback
750
751 self._handler.requestRead([(0x320c, "u")],
752 self._handleNumHotkeys,
753 (self._hotkeySetID,
754 self._hotkeySetGeneration))
755
756 return self._hotkeySetID
757
758 def clearHotkeys(self):
759 """Clear the current hotkey set.
760
761 Note that it is possible, that the callback function set either
762 previously or after calling this function by listenHotkeys() will be
763 called with data from the previous hotkey set.
764
765 Therefore it is recommended to store the hotkey set ID somewhere and
766 check that in the callback function. Right before calling
767 clearHotkeys(), this stored ID should be cleared so that the check
768 fails for sure."""
769 with self._hotkeyLock:
770 if self._hotkeys is not None:
771 self._hotkeys = None
772 self._hotkeySetID += 1
773 self._hotkeyCallback = None
774 self._clearHotkeyRequest()
775
776 def disconnect(self, closingMessage = None, duration = 3):
777 """Disconnect from the simulator."""
778 assert not self._monitoringRequested
779
780 print "fsuipc.Simulator.disconnect", closingMessage, duration
781
782 self._stopNormal()
783 self.clearHotkeys()
784 if closingMessage is None:
785 self._handler.disconnect()
786 else:
787 self.sendMessage(closingMessage, duration = duration,
788 _disconnect = True)
789
790 def connected(self, fsType, descriptor):
791 """Called when a connection has been established to the flight
792 simulator of the given type."""
793 self._fsType = fsType
794 with self._hotkeyLock:
795 if self._hotkeys is not None:
796 self._hotkeySetGeneration += 1
797
798 self._handler.requestRead([(0x320c, "u")],
799 self._handleNumHotkeys,
800 (self._hotkeySetID,
801 self._hotkeySetGeneration))
802 self._connectionListener.connected(fsType, descriptor)
803
804 def connectionFailed(self):
805 """Called when the connection could not be established."""
806 with self._hotkeyLock:
807 self._clearHotkeyRequest()
808 self._connectionListener.connectionFailed()
809
810 def disconnected(self):
811 """Called when a connection to the flight simulator has been broken."""
812 with self._hotkeyLock:
813 self._clearHotkeyRequest()
814 self._connectionListener.disconnected()
815
816 def _startDefaultNormal(self):
817 """Start the default normal periodic request."""
818 assert self._normalRequestID is None
819 self._normalRequestID = \
820 self._handler.requestPeriodicRead(1.0,
821 Simulator.normalData,
822 self._handleNormal,
823 validator = self._validateNormal)
824
825 def _stopNormal(self):
826 """Stop the normal period request."""
827 assert self._normalRequestID is not None
828 self._handler.clearPeriodic(self._normalRequestID)
829 self._normalRequestID = None
830 self._monitoring = False
831
832 def _validateNormal(self, data, extra):
833 """Validate the normal data."""
834 return data[0]!=0 and data[1]!=0 and len(data[5])>0 and len(data[6])>0
835
836 def _handleNormal(self, data, extra):
837 """Handle the reply to the normal request.
838
839 At the beginning the result consists the data for normalData. When
840 monitoring is started, it contains the result also for the
841 aircraft-specific values.
842 """
843 timestamp = Simulator._getTimestamp(data)
844
845 createdNewModel = self._setAircraftName(timestamp, data[5], data[6])
846 if self._fuelCallback is not None:
847 self._aircraftModel.getFuel(self._handler, self._fuelCallback)
848 self._fuelCallback = None
849
850 self._scroll = data[7]!=0
851
852 if self._monitoringRequested and not self._monitoring:
853 self._stopNormal()
854 self._startMonitoring()
855 elif self._monitoring and not self._monitoringRequested:
856 self._stopNormal()
857 self._startDefaultNormal()
858 elif self._monitoring and self._aircraftModel is not None and \
859 not createdNewModel:
860 aircraftState = self._aircraftModel.getAircraftState(self._aircraft,
861 timestamp, data)
862
863 self._checkTimeSync(aircraftState)
864
865 self._aircraft.handleState(aircraftState)
866
867 def _checkTimeSync(self, aircraftState):
868 """Check if we need to synchronize the FS time."""
869 if not self._syncTime or aircraftState.paused or \
870 self._flareRequestID is not None:
871 self._nextSyncTime = -1
872 return
873
874 now = time.time()
875 seconds = time.gmtime(now).tm_sec
876
877 if seconds>30 and seconds<59:
878 if self._nextSyncTime > (now - 0.49):
879 return
880
881 self._handler.requestWrite([(0x023a, "b", int(seconds))],
882 self._handleTimeSynced)
883
884 #print "Set the seconds to ", seconds
885
886 if self._nextSyncTime<0:
887 self._nextSyncTime = now
888
889 self._nextSyncTime += Simulator.TIME_SYNC_INTERVAL
890 else:
891 self._nextSyncTime = -1
892
893 def _handleTimeSynced(self, success, extra):
894 """Callback for the time sync result."""
895 pass
896
897 def _setAircraftName(self, timestamp, name, airPath):
898 """Set the name of the aicraft and if it is different from the
899 previous, create a new model for it.
900
901 If so, also notifty the aircraft about the change.
902
903 Return if a new model was created."""
904 name = self._latin1decoder(name)[0]
905 airPath = self._latin1decoder(airPath)[0]
906
907 aircraftName = (name, airPath)
908 if aircraftName==self._aircraftName:
909 return False
910
911 print "fsuipc.Simulator: new aircraft name and air file path: %s, %s" % \
912 (name, airPath)
913
914 self._aircraftName = aircraftName
915 needNew = self._aircraftModel is None
916 needNew = needNew or\
917 not self._aircraftModel.doesHandle(self._aircraft, aircraftName)
918 if not needNew:
919 specialModel = AircraftModel.findSpecial(self._aircraft, aircraftName)
920 needNew = specialModel is not None and \
921 specialModel is not self._aircraftModel.__class__
922
923 if needNew:
924 self._setAircraftModel(AircraftModel.create(self._aircraft,
925 aircraftName))
926
927 self._aircraft.modelChanged(timestamp, name, self._aircraftModel.name)
928
929 return needNew
930
931 def _setAircraftModel(self, model):
932 """Set a new aircraft model.
933
934 It will be queried for the data to monitor and the monitoring request
935 will be replaced by a new one."""
936 self._aircraftModel = model
937
938 if self._monitoring:
939 self._stopNormal()
940 self._startMonitoring()
941
942 def _startMonitoring(self):
943 """Start monitoring with the current aircraft model."""
944 data = Simulator.normalData[:]
945 self._aircraftModel.addMonitoringData(data, self._fsType)
946
947 self._normalRequestID = \
948 self._handler.requestPeriodicRead(1.0, data,
949 self._handleNormal,
950 validator = self._validateNormal)
951 self._monitoring = True
952
953 def _addFlareRate(self, data):
954 """Append a flare rate to the list of last rates."""
955 if len(self._flareRates)>=3:
956 del self._flareRates[0]
957 self._flareRates.append(Handler.fsuipc2VS(data))
958
959 def _handleFlare1(self, data, normal):
960 """Handle the first stage of flare monitoring."""
961 #self._aircraft.logger.debug("handleFlare1: " + str(data))
962 if Handler.fsuipc2radioAltitude(data[1])<=50.0:
963 self._flareStart = time.time()
964 self._flareStartFS = data[0]
965 self._handler.clearPeriodic(self._flareRequestID)
966 self._flareRequestID = \
967 self._handler.requestPeriodicRead(0.1,
968 Simulator.flareData2,
969 self._handleFlare2)
970 self._handler.requestRead(Simulator.flareStartData,
971 self._handleFlareStart)
972
973 self._addFlareRate(data[2])
974
975 def _handleFlareStart(self, data, extra):
976 """Handle the data need to notify the aircraft about the starting of
977 the flare."""
978 #self._aircraft.logger.debug("handleFlareStart: " + str(data))
979 if data is not None:
980 windDirection = data[1]*360.0/65536.0
981 if windDirection<0.0: windDirection += 360.0
982 self._aircraft.flareStarted(data[0], windDirection,
983 data[2]*1609.344/100.0,
984 self._flareStart, self._flareStartFS)
985
986 def _handleFlare2(self, data, normal):
987 """Handle the first stage of flare monitoring."""
988 #self._aircraft.logger.debug("handleFlare2: " + str(data))
989 if data[1]!=0:
990 flareEnd = time.time()
991 self._handler.clearPeriodic(self._flareRequestID)
992 self._flareRequestID = None
993
994 flareEndFS = data[0]
995 if flareEndFS<self._flareStartFS:
996 flareEndFS += 60
997
998 tdRate = Handler.fsuipc2VS(data[3])
999 tdRateCalculatedByFS = True
1000 if tdRate==0 or tdRate>1000.0 or tdRate<-1000.0:
1001 tdRate = min(self._flareRates)
1002 tdRateCalculatedByFS = False
1003
1004 self._aircraft.flareFinished(flareEnd, flareEndFS,
1005 tdRate, tdRateCalculatedByFS,
1006 Handler.fsuipc2IAS(data[4]),
1007 Handler.fsuipc2Degrees(data[5]),
1008 Handler.fsuipc2Degrees(data[6]),
1009 Handler.fsuipc2PositiveDegrees(data[7]))
1010 else:
1011 self._addFlareRate(data[2])
1012
1013 def _handleZFW(self, data, callback):
1014 """Callback for a ZFW retrieval request."""
1015 zfw = data[0] * const.LBSTOKG / 256.0
1016 callback(zfw)
1017
1018 def _handleTime(self, data, callback):
1019 """Callback for a time retrieval request."""
1020 callback(Simulator._getTimestamp(data))
1021
1022 def _handlePayloadCount(self, data, callback):
1023 """Callback for the payload count retrieval request."""
1024 payloadCount = data[0]
1025 data = [(0x3bfc, "d"), (0x30c0, "f")]
1026 for i in range(0, payloadCount):
1027 data.append((0x1400 + i*48, "f"))
1028
1029 self._handler.requestRead(data, self._handleWeights,
1030 extra = callback)
1031
1032 def _handleWeights(self, data, callback):
1033 """Callback for the weights retrieval request."""
1034 zfw = data[0] * const.LBSTOKG / 256.0
1035 grossWeight = data[1] * const.LBSTOKG
1036 payload = sum(data[2:]) * const.LBSTOKG
1037 dow = zfw - payload
1038 callback(dow, payload, zfw, grossWeight)
1039
1040 def _handleMessageSent(self, success, disconnect):
1041 """Callback for a message sending request."""
1042 #print "fsuipc.Simulator._handleMessageSent", disconnect
1043 if disconnect:
1044 self._handler.disconnect()
1045
1046 def _handleNumHotkeys(self, data, (id, generation)):
1047 """Handle the result of the query of the number of hotkeys"""
1048 with self._hotkeyLock:
1049 if id==self._hotkeySetID and generation==self._hotkeySetGeneration:
1050 numHotkeys = data[0]
1051 print "fsuipc.Simulator._handleNumHotkeys: numHotkeys:", numHotkeys
1052 data = [(0x3210 + i*4, "d") for i in range(0, numHotkeys)]
1053 self._handler.requestRead(data, self._handleHotkeyTable,
1054 (id, generation))
1055
1056 def _setupHotkeys(self, data):
1057 """Setup the hiven hotkeys and return the data to be written.
1058
1059 If there were hotkeys set previously, they are reused as much as
1060 possible. Any of them not reused will be cleared."""
1061 hotkeys = self._hotkeys
1062 numHotkeys = len(hotkeys)
1063
1064 oldHotkeyOffsets = set([] if self._hotkeyOffets is None else
1065 self._hotkeyOffets)
1066
1067 self._hotkeyOffets = []
1068 numOffsets = 0
1069
1070 while oldHotkeyOffsets:
1071 offset = oldHotkeyOffsets.pop()
1072 self._hotkeyOffets.append(offset)
1073 numOffsets += 1
1074
1075 if numOffsets>=numHotkeys:
1076 break
1077
1078 for i in range(0, len(data)):
1079 if numOffsets>=numHotkeys:
1080 break
1081
1082 if data[i]==0:
1083 self._hotkeyOffets.append(0x3210 + i*4)
1084 numOffsets += 1
1085
1086 writeData = []
1087 for i in range(0, numOffsets):
1088 Simulator._appendHotkeyData(writeData,
1089 self._hotkeyOffets[i],
1090 hotkeys[i])
1091
1092 for offset in oldHotkeyOffsets:
1093 writeData.append((offset, "u", long(0)))
1094
1095 return writeData
1096
1097 def _handleHotkeyTable(self, data, (id, generation)):
1098 """Handle the result of the query of the hotkey table."""
1099 with self._hotkeyLock:
1100 if id==self._hotkeySetID and generation==self._hotkeySetGeneration:
1101 writeData = self._setupHotkeys(data)
1102 self._handler.requestWrite(writeData,
1103 self._handleHotkeysWritten,
1104 (id, generation))
1105
1106 def _handleHotkeysWritten(self, success, (id, generation)):
1107 """Handle the result of the hotkeys having been written."""
1108 with self._hotkeyLock:
1109 if success and id==self._hotkeySetID and \
1110 generation==self._hotkeySetGeneration:
1111 data = [(offset + 3, "b") for offset in self._hotkeyOffets]
1112
1113 self._hotkeyRequestID = \
1114 self._handler.requestPeriodicRead(0.5, data,
1115 self._handleHotkeys,
1116 (id, generation))
1117
1118 def _handleHotkeys(self, data, (id, generation)):
1119 """Handle the hotkeys."""
1120 with self._hotkeyLock:
1121 if id!=self._hotkeySetID or generation!=self._hotkeySetGeneration:
1122 return
1123
1124 callback = self._hotkeyCallback
1125 offsets = self._hotkeyOffets
1126
1127 hotkeysPressed = []
1128 for i in range(0, len(data)):
1129 if data[i]!=0:
1130 hotkeysPressed.append(i)
1131
1132 if hotkeysPressed:
1133 data = []
1134 for index in hotkeysPressed:
1135 data.append((offsets[index]+3, "b", int(0)))
1136 self._handler.requestWrite(data, self._handleHotkeysCleared)
1137
1138 callback(id, hotkeysPressed)
1139
1140 def _handleHotkeysCleared(self, sucess, extra):
1141 """Callback for the hotkey-clearing write request."""
1142
1143 def _clearHotkeyRequest(self):
1144 """Clear the hotkey request in the handler if there is any."""
1145 if self._hotkeyRequestID is not None:
1146 self._handler.clearPeriodic(self._hotkeyRequestID)
1147 self._hotkeyRequestID = None
1148
1149#------------------------------------------------------------------------------
1150
1151class AircraftModel(object):
1152 """Base class for the aircraft models.
1153
1154 Aircraft models handle the data arriving from FSUIPC and turn it into an
1155 object describing the aircraft's state."""
1156 monitoringData = [("paused", 0x0264, "H"),
1157 ("latitude", 0x0560, "l"),
1158 ("longitude", 0x0568, "l"),
1159 ("frozen", 0x3364, "H"),
1160 ("replay", 0x0628, "d"),
1161 ("slew", 0x05dc, "H"),
1162 ("overspeed", 0x036d, "b"),
1163 ("stalled", 0x036c, "b"),
1164 ("onTheGround", 0x0366, "H"),
1165 ("zfw", 0x3bfc, "d"),
1166 ("grossWeight", 0x30c0, "f"),
1167 ("heading", 0x0580, "d"),
1168 ("pitch", 0x0578, "d"),
1169 ("bank", 0x057c, "d"),
1170 ("ias", 0x02bc, "d"),
1171 ("mach", 0x11c6, "H"),
1172 ("groundSpeed", 0x02b4, "d"),
1173 ("vs", 0x02c8, "d"),
1174 ("radioAltitude", 0x31e4, "d"),
1175 ("altitude", 0x0570, "l"),
1176 ("gLoad", 0x11ba, "H"),
1177 ("flapsControl", 0x0bdc, "d"),
1178 ("flapsLeft", 0x0be0, "d"),
1179 ("flapsRight", 0x0be4, "d"),
1180 ("flapsAxis", 0x3414, "H"),
1181 ("flapsIncrement", 0x3bfa, "H"),
1182 ("lights", 0x0d0c, "H"),
1183 ("pitot", 0x029c, "b"),
1184 ("parking", 0x0bc8, "H"),
1185 ("gearControl", 0x0be8, "d"),
1186 ("noseGear", 0x0bec, "d"),
1187 ("spoilersArmed", 0x0bcc, "d"),
1188 ("spoilers", 0x0bd0, "d"),
1189 ("altimeter", 0x0330, "H"),
1190 ("qnh", 0x0ec6, "H"),
1191 ("nav1", 0x0350, "H"),
1192 ("nav1_obs", 0x0c4e, "H"),
1193 ("nav2", 0x0352, "H"),
1194 ("nav2_obs", 0x0c5e, "H"),
1195 ("adf1_main", 0x034c, "H"),
1196 ("adf1_ext", 0x0356, "H"),
1197 ("adf2_main", 0x02d4, "H"),
1198 ("adf2_ext", 0x02d6, "H"),
1199 ("squawk", 0x0354, "H"),
1200 ("windSpeed", 0x0e90, "H"),
1201 ("windDirection", 0x0e92, "H"),
1202 ("visibility", 0x0e8a, "H"),
1203 ("cog", 0x2ef8, "f"),
1204 ("xpdrC", 0x7b91, "b"),
1205 ("apMaster", 0x07bc, "d"),
1206 ("apHeadingHold", 0x07c8, "d"),
1207 ("apHeading", 0x07cc, "H"),
1208 ("apAltitudeHold", 0x07d0, "d"),
1209 ("apAltitude", 0x07d4, "u"),
1210 ("elevatorTrim", 0x2ea0, "f"),
1211 ("eng1DeIce", 0x08b2, "H"),
1212 ("eng2DeIce", 0x094a, "H"),
1213 ("propDeIce", 0x337c, "b"),
1214 ("structDeIce", 0x337d, "b")]
1215
1216 specialModels = []
1217
1218 @staticmethod
1219 def registerSpecial(clazz):
1220 """Register the given class as a special model."""
1221 AircraftModel.specialModels.append(clazz)
1222
1223 @staticmethod
1224 def findSpecial(aircraft, aircraftName):
1225 for specialModel in AircraftModel.specialModels:
1226 if specialModel.doesHandle(aircraft, aircraftName):
1227 return specialModel
1228 return None
1229
1230 @staticmethod
1231 def create(aircraft, aircraftName):
1232 """Create the model for the given aircraft name, and notify the
1233 aircraft about it."""
1234 specialModel = AircraftModel.findSpecial(aircraft, aircraftName)
1235 if specialModel is not None:
1236 return specialModel()
1237 if aircraft.type in _genericModels:
1238 return _genericModels[aircraft.type]()
1239 else:
1240 return GenericModel()
1241
1242 @staticmethod
1243 def convertBCD(data, length):
1244 """Convert a data item encoded as BCD into a string of the given number
1245 of digits."""
1246 bcd = ""
1247 for i in range(0, length):
1248 digit = chr(ord('0') + (data&0x0f))
1249 data >>= 4
1250 bcd = digit + bcd
1251 return bcd
1252
1253 @staticmethod
1254 def convertFrequency(data):
1255 """Convert the given frequency data to a string."""
1256 bcd = AircraftModel.convertBCD(data, 4)
1257 return "1" + bcd[0:2] + "." + bcd[2:4]
1258
1259 @staticmethod
1260 def convertADFFrequency(main, ext):
1261 """Convert the given ADF frequency data to a string."""
1262 mainBCD = AircraftModel.convertBCD(main, 4)
1263 extBCD = AircraftModel.convertBCD(ext, 4)
1264
1265 return (extBCD[1] if extBCD[1]!="0" else "") + \
1266 mainBCD[1:] + "." + extBCD[3]
1267
1268 def __init__(self, flapsNotches):
1269 """Construct the aircraft model.
1270
1271 flapsNotches is a list of degrees of flaps that are available on the aircraft."""
1272 self._flapsNotches = flapsNotches
1273 self._xpdrReliable = False
1274 self._flapsSet = -1
1275
1276 @property
1277 def name(self):
1278 """Get the name for this aircraft model."""
1279 return "FSUIPC/Generic"
1280
1281 def doesHandle(self, aircraft, aircraftName):
1282 """Determine if the model handles the given aircraft name.
1283
1284 This default implementation returns False."""
1285 return False
1286
1287 def _addOffsetWithIndexMember(self, dest, offset, type, attrName = None):
1288 """Add the given FSUIPC offset and type to the given array and a member
1289 attribute with the given name."""
1290 dest.append((offset, type))
1291 if attrName is not None:
1292 setattr(self, attrName, len(dest)-1)
1293
1294 def _addDataWithIndexMembers(self, dest, prefix, data):
1295 """Add FSUIPC data to the given array and also corresponding index
1296 member variables with the given prefix.
1297
1298 data is a list of triplets of the following items:
1299 - the name of the data item. The index member variable will have a name
1300 created by prepending the given prefix to this name.
1301 - the FSUIPC offset
1302 - the FSUIPC type
1303
1304 The latter two items will be appended to dest."""
1305 for (name, offset, type) in data:
1306 self._addOffsetWithIndexMember(dest, offset, type, prefix + name)
1307
1308 def addMonitoringData(self, data, fsType):
1309 """Add the model-specific monitoring data to the given array."""
1310 self._addDataWithIndexMembers(data, "_monidx_",
1311 AircraftModel.monitoringData)
1312
1313 def getAircraftState(self, aircraft, timestamp, data):
1314 """Get an aircraft state object for the given monitoring data."""
1315 state = fs.AircraftState()
1316
1317 state.timestamp = timestamp
1318
1319 state.latitude = data[self._monidx_latitude] * \
1320 90.0 / 10001750.0 / 65536.0 / 65536.0
1321
1322 state.longitude = data[self._monidx_longitude] * \
1323 360.0 / 65536.0 / 65536.0 / 65536.0 / 65536.0
1324 if state.longitude>180.0: state.longitude = 360.0 - state.longitude
1325
1326 state.paused = data[self._monidx_paused]!=0 or \
1327 data[self._monidx_frozen]!=0 or \
1328 data[self._monidx_replay]!=0
1329 state.trickMode = data[self._monidx_slew]!=0
1330
1331 state.overspeed = data[self._monidx_overspeed]!=0
1332 state.stalled = data[self._monidx_stalled]!=0
1333 state.onTheGround = data[self._monidx_onTheGround]!=0
1334
1335 state.zfw = data[self._monidx_zfw] * const.LBSTOKG / 256.0
1336 state.grossWeight = data[self._monidx_grossWeight] * const.LBSTOKG
1337
1338 state.heading = Handler.fsuipc2PositiveDegrees(data[self._monidx_heading])
1339
1340 state.pitch = Handler.fsuipc2Degrees(data[self._monidx_pitch])
1341 state.bank = Handler.fsuipc2Degrees(data[self._monidx_bank])
1342
1343 state.ias = Handler.fsuipc2IAS(data[self._monidx_ias])
1344 state.mach = data[self._monidx_mach] / 20480.0
1345 state.groundSpeed = data[self._monidx_groundSpeed]* 3600.0/65536.0/1852.0
1346 state.vs = Handler.fsuipc2VS(data[self._monidx_vs])
1347
1348 state.radioAltitude = \
1349 Handler.fsuipc2radioAltitude(data[self._monidx_radioAltitude])
1350 state.altitude = data[self._monidx_altitude]/const.FEETTOMETRES/65536.0/65536.0
1351
1352 state.gLoad = data[self._monidx_gLoad] / 625.0
1353
1354 numNotchesM1 = len(self._flapsNotches) - 1
1355 flapsIncrement = 16383 / numNotchesM1
1356 flapsControl = data[self._monidx_flapsControl]
1357 flapsIndex = flapsControl / flapsIncrement
1358 if flapsIndex < numNotchesM1:
1359 if (flapsControl - (flapsIndex*flapsIncrement) >
1360 (flapsIndex+1)*flapsIncrement - flapsControl):
1361 flapsIndex += 1
1362 state.flapsSet = self._flapsNotches[flapsIndex]
1363 if state.flapsSet != self._flapsSet:
1364 print "flapsControl: %d, flapsLeft: %d, flapsRight: %d, flapsAxis: %d, flapsIncrement: %d, flapsSet: %d, numNotchesM1: %d" % \
1365 (flapsControl, data[self._monidx_flapsLeft],
1366 data[self._monidx_flapsRight], data[self._monidx_flapsAxis],
1367 data[self._monidx_flapsIncrement], state.flapsSet, numNotchesM1)
1368 self._flapsSet = state.flapsSet
1369
1370 flapsLeft = data[self._monidx_flapsLeft]
1371 state.flaps = self._flapsNotches[-1]*flapsLeft/16383.0
1372
1373 lights = data[self._monidx_lights]
1374
1375 state.navLightsOn = (lights&0x01) != 0
1376 state.antiCollisionLightsOn = (lights&0x02) != 0
1377 state.landingLightsOn = (lights&0x04) != 0
1378 state.strobeLightsOn = (lights&0x10) != 0
1379
1380 state.pitotHeatOn = data[self._monidx_pitot]!=0
1381
1382 state.parking = data[self._monidx_parking]!=0
1383
1384 state.gearControlDown = data[self._monidx_gearControl]==16383
1385 state.gearsDown = data[self._monidx_noseGear]==16383
1386
1387 state.spoilersArmed = data[self._monidx_spoilersArmed]!=0
1388
1389 spoilers = data[self._monidx_spoilers]
1390 if spoilers<=4800:
1391 state.spoilersExtension = 0.0
1392 else:
1393 state.spoilersExtension = (spoilers - 4800) * 100.0 / (16383 - 4800)
1394
1395 state.altimeter = data[self._monidx_altimeter] / 16.0
1396 state.altimeterReliable = True
1397 state.qnh = data[self._monidx_qnh] / 16.0
1398
1399 state.ils = None
1400 state.ils_obs = None
1401 state.ils_manual = False
1402 state.nav1 = AircraftModel.convertFrequency(data[self._monidx_nav1])
1403 state.nav1_obs = data[self._monidx_nav1_obs]
1404 state.nav1_manual = True
1405 state.nav2 = AircraftModel.convertFrequency(data[self._monidx_nav2])
1406 state.nav2_obs = data[self._monidx_nav2_obs]
1407 state.nav2_manual = True
1408 state.adf1 = \
1409 AircraftModel.convertADFFrequency(data[self._monidx_adf1_main],
1410 data[self._monidx_adf1_ext])
1411 state.adf2 = \
1412 AircraftModel.convertADFFrequency(data[self._monidx_adf2_main],
1413 data[self._monidx_adf2_ext])
1414
1415 state.squawk = AircraftModel.convertBCD(data[self._monidx_squawk], 4)
1416
1417 state.windSpeed = data[self._monidx_windSpeed]
1418 state.windDirection = data[self._monidx_windDirection]*360.0/65536.0
1419 if state.windDirection<0.0: state.windDirection += 360.0
1420
1421 state.visibility = data[self._monidx_visibility]*1609.344/100.0
1422
1423 state.cog = data[self._monidx_cog]
1424
1425 if not self._xpdrReliable:
1426 self._xpdrReliable = data[self._monidx_xpdrC]!=0
1427
1428 state.xpdrC = data[self._monidx_xpdrC]!=1 \
1429 if self._xpdrReliable else None
1430 state.autoXPDR = False
1431
1432 state.apMaster = data[self._monidx_apMaster]!=0
1433 state.apHeadingHold = data[self._monidx_apHeadingHold]!=0
1434 state.apHeading = data[self._monidx_apHeading] * 360.0 / 65536.0
1435 state.apAltitudeHold = data[self._monidx_apAltitudeHold]!=0
1436 state.apAltitude = data[self._monidx_apAltitude] / \
1437 const.FEETTOMETRES / 65536.0
1438
1439
1440 state.elevatorTrim = data[self._monidx_elevatorTrim] * 180.0 / math.pi
1441
1442 state.antiIceOn = data[self._monidx_eng1DeIce]!=0 or \
1443 data[self._monidx_eng2DeIce]!=0 or \
1444 data[self._monidx_propDeIce]!=0 or \
1445 data[self._monidx_structDeIce]!=0
1446
1447 return state
1448
1449#------------------------------------------------------------------------------
1450
1451class GenericAircraftModel(AircraftModel):
1452 """A generic aircraft model that can handle the fuel levels, the N1 or RPM
1453 values and some other common parameters in a generic way."""
1454
1455 def __init__(self, flapsNotches, fuelTanks, numEngines, isN1 = True):
1456 """Construct the generic aircraft model with the given data.
1457
1458 flapsNotches is an array of how much degrees the individual flaps
1459 notches mean.
1460
1461 fuelTanks is an array of const.FUELTANK_XXX constants about the
1462 aircraft's fuel tanks. They will be converted to offsets.
1463
1464 numEngines is the number of engines the aircraft has.
1465
1466 isN1 determines if the engines have an N1 value or an RPM value
1467 (e.g. pistons)."""
1468 super(GenericAircraftModel, self).__init__(flapsNotches = flapsNotches)
1469
1470 self._fuelTanks = fuelTanks
1471 self._fuelStartIndex = None
1472 self._numEngines = numEngines
1473 self._engineStartIndex = None
1474 self._isN1 = isN1
1475
1476 def doesHandle(self, aircraft, aircraftName):
1477 """Determine if the model handles the given aircraft name.
1478
1479 This implementation returns True."""
1480 return True
1481
1482 def addMonitoringData(self, data, fsType):
1483 """Add the model-specific monitoring data to the given array."""
1484 super(GenericAircraftModel, self).addMonitoringData(data, fsType)
1485
1486 self._fuelStartIndex = self._addFuelOffsets(data, "_monidx_fuelWeight")
1487
1488 self._engineStartIndex = len(data)
1489 for i in range(0, self._numEngines):
1490 self._addOffsetWithIndexMember(data, 0x088c + i * 0x98, "h") # throttle lever
1491 if self._isN1:
1492 self._addOffsetWithIndexMember(data, 0x2000 + i * 0x100, "f") # N1
1493 else:
1494 self._addOffsetWithIndexMember(data, 0x0898 + i * 0x98, "H") # RPM
1495 self._addOffsetWithIndexMember(data, 0x08c8 + i * 0x98, "H") # RPM scaler
1496
1497 def getAircraftState(self, aircraft, timestamp, data):
1498 """Get the aircraft state.
1499
1500 Get it from the parent, and then add the data about the fuel levels and
1501 the engine parameters."""
1502 state = super(GenericAircraftModel, self).getAircraftState(aircraft,
1503 timestamp,
1504 data)
1505
1506 (state.fuel, state.totalFuel) = \
1507 self._convertFuelData(data, index = self._monidx_fuelWeight)
1508
1509 state.n1 = [] if self._isN1 else None
1510 state.rpm = None if self._isN1 else []
1511 itemsPerEngine = 2 if self._isN1 else 3
1512
1513 state.reverser = []
1514 for i in range(self._engineStartIndex,
1515 self._engineStartIndex +
1516 itemsPerEngine*self._numEngines,
1517 itemsPerEngine):
1518 state.reverser.append(data[i]<0)
1519 if self._isN1:
1520 state.n1.append(data[i+1])
1521 else:
1522 state.rpm.append(data[i+1] * data[i+2]/65536.0)
1523
1524 return state
1525
1526 def getFuel(self, handler, callback):
1527 """Get the fuel information for this model.
1528
1529 See Simulator.getFuel for more information. This
1530 implementation simply queries the fuel tanks given to the
1531 constructor."""
1532 data = []
1533 self._addFuelOffsets(data)
1534
1535 handler.requestRead(data, self._handleFuelRetrieved,
1536 extra = callback)
1537
1538 def setFuelLevel(self, handler, levels):
1539 """Set the fuel level.
1540
1541 See the description of Simulator.setFuelLevel. This
1542 implementation simply sets the fuel tanks as given."""
1543 data = []
1544 for (tank, level) in levels:
1545 offset = _tank2offset[tank]
1546 value = long(level * 128.0 * 65536.0)
1547 data.append( (offset, "u", value) )
1548
1549 handler.requestWrite(data, self._handleFuelWritten)
1550
1551 def _addFuelOffsets(self, data, weightIndexName = None):
1552 """Add the fuel offsets to the given data array.
1553
1554 If weightIndexName is not None, it will be the name of the
1555 fuel weight index.
1556
1557 Returns the index of the first fuel tank's data."""
1558 self._addOffsetWithIndexMember(data, 0x0af4, "H", weightIndexName)
1559
1560 fuelStartIndex = len(data)
1561 for tank in self._fuelTanks:
1562 offset = _tank2offset[tank]
1563 self._addOffsetWithIndexMember(data, offset, "u") # tank level
1564 self._addOffsetWithIndexMember(data, offset+4, "u") # tank capacity
1565
1566 return fuelStartIndex
1567
1568 def _convertFuelData(self, data, index = 0, addCapacities = False):
1569 """Convert the given data into a fuel info list.
1570
1571 The list consists of two or three-tuples of the following
1572 items:
1573 - the fuel tank ID,
1574 - the amount of the fuel in kg,
1575 - if addCapacities is True, the total capacity of the tank."""
1576 fuelWeight = data[index] / 256.0
1577 index += 1
1578
1579 result = []
1580 totalFuel = 0
1581 for fuelTank in self._fuelTanks:
1582 capacity = data[index+1] * fuelWeight * const.LBSTOKG
1583 if capacity>=1.0:
1584 amount = data[index] * capacity / 128.0 / 65536.0
1585
1586 result.append( (fuelTank, amount, capacity) if addCapacities
1587 else (fuelTank, amount))
1588 totalFuel += amount
1589 index += 2
1590
1591 return (result, totalFuel)
1592
1593 def _handleFuelRetrieved(self, data, callback):
1594 """Callback for a fuel retrieval request."""
1595 (fuelData, _totalFuel) = self._convertFuelData(data,
1596 addCapacities = True)
1597 callback(fuelData)
1598
1599 def _handleFuelWritten(self, success, extra):
1600 """Callback for a fuel setting request."""
1601 pass
1602
1603#------------------------------------------------------------------------------
1604
1605class GenericModel(GenericAircraftModel):
1606 """Generic aircraft model for an unknown type."""
1607 def __init__(self):
1608 """Construct the model."""
1609 super(GenericModel, self). \
1610 __init__(flapsNotches = [0, 10, 20, 30],
1611 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_RIGHT],
1612 numEngines = 2)
1613
1614 @property
1615 def name(self):
1616 """Get the name for this aircraft model."""
1617 return "FSUIPC/Generic"
1618
1619#------------------------------------------------------------------------------
1620
1621class B737Model(GenericAircraftModel):
1622 """Generic model for the Boeing 737 Classing and NG aircraft."""
1623 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
1624
1625 def __init__(self):
1626 """Construct the model."""
1627 super(B737Model, self). \
1628 __init__(flapsNotches = [0, 1, 2, 5, 10, 15, 25, 30, 40],
1629 fuelTanks = B737Model.fuelTanks,
1630 numEngines = 2)
1631
1632 @property
1633 def name(self):
1634 """Get the name for this aircraft model."""
1635 return "FSUIPC/Generic Boeing 737"
1636
1637 # Note: the function below should be enabled if testing the speed-based
1638 # takeoff on Linux
1639 # def getAircraftState(self, aircraft, timestamp, data):
1640 # """Get the aircraft state.
1641
1642 # Get it from the parent, and then check some PMDG-specific stuff."""
1643 # state = super(B737Model, self).getAircraftState(aircraft,
1644 # timestamp,
1645 # data)
1646 # state.strobeLightsOn = None
1647 # state.xpdrC = None
1648
1649 # return state
1650
1651#------------------------------------------------------------------------------
1652
1653class PMDGBoeing737NGModel(B737Model):
1654 """A model handler for the PMDG Boeing 737NG model."""
1655 @staticmethod
1656 def doesHandle(aircraft, (name, airPath)):
1657 """Determine if this model handler handles the aircraft with the given
1658 name."""
1659 return aircraft.type in [const.AIRCRAFT_B736,
1660 const.AIRCRAFT_B737,
1661 const.AIRCRAFT_B738,
1662 const.AIRCRAFT_B738C] and \
1663 (name.find("PMDG")!=-1 or airPath.find("PMDG")!=-1) and \
1664 (name.find("737")!=-1 or airPath.find("737")!=-1) and \
1665 (name.find("600")!=-1 or airPath.find("600")!=-1 or \
1666 name.find("700")!=-1 or airPath.find("700")!=-1 or \
1667 name.find("800")!=-1 or airPath.find("800")!=-1 or \
1668 name.find("900")!=-1 or airPath.find("900")!=-1)
1669
1670 @property
1671 def name(self):
1672 """Get the name for this aircraft model."""
1673 return "FSUIPC/PMDG Boeing 737NG(X)"
1674
1675 def addMonitoringData(self, data, fsType):
1676 """Add the model-specific monitoring data to the given array."""
1677 self._fsType = fsType
1678
1679 super(PMDGBoeing737NGModel, self).addMonitoringData(data, fsType)
1680
1681 if fsType==const.SIM_MSFSX:
1682 print "FSX detected, adding PMDG 737 NGX-specific offsets"
1683 self._addOffsetWithIndexMember(data, 0x6500, "b",
1684 "_pmdgidx_lts_positionsw")
1685 self._addOffsetWithIndexMember(data, 0x6545, "b", "_pmdgidx_cmda")
1686 self._addOffsetWithIndexMember(data, 0x653f, "b", "_pmdgidx_aphdgsel")
1687 self._addOffsetWithIndexMember(data, 0x6543, "b", "_pmdgidx_apalthold")
1688 self._addOffsetWithIndexMember(data, 0x652c, "H", "_pmdgidx_aphdg")
1689 self._addOffsetWithIndexMember(data, 0x652e, "H", "_pmdgidx_apalt")
1690 self._addOffsetWithIndexMember(data, 0x65cd, "b", "_pmdgidx_xpdr")
1691 else:
1692 print "FS9 detected, adding PMDG 737 NG-specific offsets"
1693 self._addOffsetWithIndexMember(data, 0x6202, "b", "_pmdgidx_switches")
1694 self._addOffsetWithIndexMember(data, 0x6216, "b", "_pmdgidx_xpdr")
1695 self._addOffsetWithIndexMember(data, 0x6227, "b", "_pmdgidx_ap")
1696 self._addOffsetWithIndexMember(data, 0x6228, "b", "_pmdgidx_aphdgsel")
1697 self._addOffsetWithIndexMember(data, 0x622a, "b", "_pmdgidx_apalthold")
1698 self._addOffsetWithIndexMember(data, 0x622c, "H", "_pmdgidx_aphdg")
1699 self._addOffsetWithIndexMember(data, 0x622e, "H", "_pmdgidx_apalt")
1700
1701 def getAircraftState(self, aircraft, timestamp, data):
1702 """Get the aircraft state.
1703
1704 Get it from the parent, and then check some PMDG-specific stuff."""
1705 state = super(PMDGBoeing737NGModel, self).getAircraftState(aircraft,
1706 timestamp,
1707 data)
1708 if self._fsType==const.SIM_MSFS9:
1709 if data[self._pmdgidx_switches]&0x01==0x01:
1710 state.altimeter = 1013.25
1711 state.apMaster = data[self._pmdgidx_ap]&0x02==0x02
1712 state.apHeadingHold = data[self._pmdgidx_aphdgsel]==2
1713 apalthold = data[self._pmdgidx_apalthold]
1714 state.apAltitudeHold = apalthold>=3 and apalthold<=6
1715 state.xpdrC = data[self._pmdgidx_xpdr]==4
1716
1717 # Uncomment the following to test the speed-based takeoff
1718 # state.strobeLightsOn = None
1719 # state.xpdrC = None
1720 else:
1721 state.apMaster = data[self._pmdgidx_cmda]!=0
1722 state.apHeadingHold = data[self._pmdgidx_aphdgsel]!=0
1723 state.apAltitudeHold = data[self._pmdgidx_apalthold]!=0
1724
1725 # state.strobeLightsOn = data[self._pmdgidx_lts_positionsw]==0x02
1726 # state.xpdrC = data[self._pmdgidx_xpdr]==4
1727 state.strobeLightsOn = None
1728 state.xpdrC = None
1729
1730 state.apHeading = data[self._pmdgidx_aphdg]
1731 state.apAltitude = data[self._pmdgidx_apalt]
1732
1733 return state
1734
1735#------------------------------------------------------------------------------
1736
1737class B767Model(GenericAircraftModel):
1738 """Generic model for the Boeing 767 aircraft."""
1739 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
1740
1741 def __init__(self):
1742 """Construct the model."""
1743 super(B767Model, self). \
1744 __init__(flapsNotches = [0, 1, 5, 15, 20, 25, 30],
1745 fuelTanks = B767Model.fuelTanks,
1746 numEngines = 2)
1747
1748 @property
1749 def name(self):
1750 """Get the name for this aircraft model."""
1751 return "FSUIPC/Generic Boeing 767"
1752
1753#------------------------------------------------------------------------------
1754
1755class DH8DModel(GenericAircraftModel):
1756 """Generic model for the Bombardier Dash 8-Q400 aircraft."""
1757 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_RIGHT]
1758
1759 def __init__(self):
1760 """Construct the model."""
1761 super(DH8DModel, self). \
1762 __init__(flapsNotches = [0, 5, 10, 15, 35],
1763 fuelTanks = DH8DModel.fuelTanks,
1764 numEngines = 2)
1765
1766 @property
1767 def name(self):
1768 """Get the name for this aircraft model."""
1769 return "FSUIPC/Generic Bombardier Dash 8-Q400"
1770
1771#------------------------------------------------------------------------------
1772
1773class DreamwingsDH8DModel(DH8DModel):
1774 """Model handler for the Dreamwings Dash 8-Q400."""
1775 @staticmethod
1776 def doesHandle(aircraft, (name, airPath)):
1777 """Determine if this model handler handles the aircraft with the given
1778 name."""
1779 return aircraft.type==const.AIRCRAFT_DH8D and \
1780 (name.find("Dreamwings")!=-1 or airPath.find("Dreamwings")!=-1) and \
1781 (name.find("Dash")!=-1 or airPath.find("Dash")!=-1) and \
1782 (name.find("Q400")!=-1 or airPath.find("Q400")!=-1) and \
1783 airPath.find("Dash8Q400")!=-1
1784
1785 @property
1786 def name(self):
1787 """Get the name for this aircraft model."""
1788 return "FSUIPC/Dreamwings Bombardier Dash 8-Q400"
1789
1790 def addMonitoringData(self, data, fsType):
1791 """Add the model-specific monitoring data to the given array."""
1792 super(DreamwingsDH8DModel, self).addMonitoringData(data, fsType)
1793
1794 self._addOffsetWithIndexMember(data, 0x132c, "d", "_dwdh8d_navgps")
1795
1796 def getAircraftState(self, aircraft, timestamp, data):
1797 """Get the aircraft state.
1798
1799 Get it from the parent, and then invert the pitot heat state."""
1800 state = super(DreamwingsDH8DModel, self).getAircraftState(aircraft,
1801 timestamp,
1802 data)
1803 if data[self._dwdh8d_navgps]==1:
1804 state.apHeading = None
1805
1806 return state
1807
1808#------------------------------------------------------------------------------
1809
1810class CRJ2Model(GenericAircraftModel):
1811 """Generic model for the Bombardier CRJ-200 aircraft."""
1812 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
1813
1814 def __init__(self):
1815 """Construct the model."""
1816 super(CRJ2Model, self). \
1817 __init__(flapsNotches = [0, 8, 20, 30, 45],
1818 fuelTanks = CRJ2Model.fuelTanks,
1819 numEngines = 2)
1820
1821 @property
1822 def name(self):
1823 """Get the name for this aircraft model."""
1824 return "FSUIPC/Generic Bombardier CRJ-200"
1825
1826#------------------------------------------------------------------------------
1827
1828class F70Model(GenericAircraftModel):
1829 """Generic model for the Fokker F70 aircraft."""
1830 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
1831
1832 def __init__(self):
1833 """Construct the model."""
1834 super(F70Model, self). \
1835 __init__(flapsNotches = [0, 8, 15, 25, 42],
1836 fuelTanks = F70Model.fuelTanks,
1837 numEngines = 2)
1838
1839 @property
1840 def name(self):
1841 """Get the name for this aircraft model."""
1842 return "FSUIPC/Generic Fokker 70"
1843
1844#------------------------------------------------------------------------------
1845
1846class DAF70Model(F70Model):
1847 """Model for the Digital Aviation F70 implementation on FS9."""
1848 @staticmethod
1849 def doesHandle(aircraft, (name, airPath)):
1850 """Determine if this model handler handles the aircraft with the given
1851 name."""
1852 return aircraft.type == const.AIRCRAFT_F70 and \
1853 (airPath.endswith("fokker70_2k4_v4.1.air") or
1854 airPath.endswith("fokker70_2k4_v4.3.air"))
1855
1856 @property
1857 def name(self):
1858 """Get the name for this aircraft model."""
1859 return "FSUIPC/Digital Aviation Fokker 70"
1860
1861 def getAircraftState(self, aircraft, timestamp, data):
1862 """Get the aircraft state.
1863
1864 Get it from the parent, and then invert the pitot heat state."""
1865 state = super(DAF70Model, self).getAircraftState(aircraft,
1866 timestamp,
1867 data)
1868 state.navLightsOn = None
1869 state.landingLightsOn = None
1870
1871 state.altimeterReliable = False
1872
1873 state.ils = state.nav1
1874 state.ils_obs = state.nav1_obs
1875 state.ils_manual = state.nav1_manual
1876
1877 state.nav1 = state.nav2
1878 state.nav1_obs = state.nav2_obs
1879 state.nav1_manual = aircraft.flight.stage!=const.STAGE_CRUISE
1880
1881 state.nav2 = None
1882 state.nav2_obs = None
1883 state.nav2_manual = False
1884
1885 state.autoXPDR = True
1886
1887 return state
1888
1889#------------------------------------------------------------------------------
1890
1891class DC3Model(GenericAircraftModel):
1892 """Generic model for the Lisunov Li-2 (DC-3) aircraft."""
1893 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE,
1894 const.FUELTANK_RIGHT]
1895 # fuelTanks = [const.FUELTANK_LEFT_AUX, const.FUELTANK_LEFT,
1896 # const.FUELTANK_RIGHT, const.FUELTANK_RIGHT_AUX]
1897
1898 def __init__(self):
1899 """Construct the model."""
1900 super(DC3Model, self). \
1901 __init__(flapsNotches = [0, 15, 30, 45],
1902 fuelTanks = DC3Model.fuelTanks,
1903 numEngines = 2, isN1 = False)
1904 self._leftLevel = 0.0
1905 self._rightLevel = 0.0
1906
1907 @property
1908 def name(self):
1909 """Get the name for this aircraft model."""
1910 return "FSUIPC/Generic Lisunov Li-2 (DC-3)"
1911
1912 def _convertFuelData(self, data, index = 0, addCapacities = False):
1913 """Convert the given data into a fuel info list.
1914
1915 It assumes to receive the 3 fuel tanks as seen above (left,
1916 centre and right) and converts it to left aux, left, right,
1917 and right aux. The amount in the left tank goes into left aux,
1918 the amount of the right tank goes into right aux and the
1919 amount of the centre tank goes into the left and right tanks
1920 evenly distributed."""
1921 (rawFuelData, totalFuel) = \
1922 super(DC3Model, self)._convertFuelData(data, index, addCapacities)
1923
1924 centreAmount = rawFuelData[1][1]
1925 if addCapacities:
1926 centreCapacity = rawFuelData[1][2]
1927 self._leftLevel = self._rightLevel = \
1928 centreAmount / centreCapacity / 2.0
1929 fuelData = [(const.FUELTANK_LEFT_AUX,
1930 rawFuelData[0][1], rawFuelData[0][2]),
1931 (const.FUELTANK_LEFT,
1932 centreAmount/2.0, centreCapacity/2.0),
1933 (const.FUELTANK_RIGHT,
1934 centreAmount/2.0, centreCapacity/2.0),
1935 (const.FUELTANK_RIGHT_AUX,
1936 rawFuelData[2][1], rawFuelData[2][2])]
1937 else:
1938 fuelData = [(const.FUELTANK_LEFT_AUX, rawFuelData[0][1]),
1939 (const.FUELTANK_LEFT, centreAmount/2.0),
1940 (const.FUELTANK_RIGHT, centreAmount/2.0),
1941 (const.FUELTANK_RIGHT_AUX, rawFuelData[2][1])]
1942
1943 return (fuelData, totalFuel)
1944
1945 def setFuelLevel(self, handler, levels):
1946 """Set the fuel level.
1947
1948 See the description of Simulator.setFuelLevel. This
1949 implementation assumes to get the four-tank representation,
1950 as returned by getFuel()."""
1951 leftLevel = None
1952 centreLevel = None
1953 rightLevel = None
1954
1955 for (tank, level) in levels:
1956 if tank==const.FUELTANK_LEFT_AUX:
1957 leftLevel = level if leftLevel is None else (leftLevel + level)
1958 elif tank==const.FUELTANK_LEFT:
1959 level /= 2.0
1960 centreLevel = (self._rightLevel + level) \
1961 if centreLevel is None else (centreLevel + level)
1962 self._leftLevel = level
1963 elif tank==const.FUELTANK_RIGHT:
1964 level /= 2.0
1965 centreLevel = (self._leftLevel + level) \
1966 if centreLevel is None else (centreLevel + level)
1967 self._rightLevel = level
1968 elif tank==const.FUELTANK_RIGHT_AUX:
1969 rightLevel = level if rightLevel is None \
1970 else (rightLevel + level)
1971
1972 levels = []
1973 if leftLevel is not None: levels.append((const.FUELTANK_LEFT,
1974 leftLevel))
1975 if centreLevel is not None: levels.append((const.FUELTANK_CENTRE,
1976 centreLevel))
1977 if rightLevel is not None: levels.append((const.FUELTANK_RIGHT,
1978 rightLevel))
1979
1980 super(DC3Model, self).setFuelLevel(handler, levels)
1981
1982#------------------------------------------------------------------------------
1983
1984class T134Model(GenericAircraftModel):
1985 """Generic model for the Tupolev Tu-134 aircraft."""
1986 fuelTanks = [const.FUELTANK_LEFT_TIP, const.FUELTANK_EXTERNAL1,
1987 const.FUELTANK_LEFT_AUX,
1988 const.FUELTANK_CENTRE,
1989 const.FUELTANK_RIGHT_AUX,
1990 const.FUELTANK_EXTERNAL2, const.FUELTANK_RIGHT_TIP]
1991
1992 def __init__(self):
1993 """Construct the model."""
1994 super(T134Model, self). \
1995 __init__(flapsNotches = [0, 10, 20, 30],
1996 fuelTanks = T134Model.fuelTanks,
1997 numEngines = 2)
1998
1999 @property
2000 def name(self):
2001 """Get the name for this aircraft model."""
2002 return "FSUIPC/Generic Tupolev Tu-134"
2003
2004#------------------------------------------------------------------------------
2005
2006class T154Model(GenericAircraftModel):
2007 """Generic model for the Tupolev Tu-134 aircraft."""
2008 fuelTanks = [const.FUELTANK_LEFT_AUX, const.FUELTANK_LEFT,
2009 const.FUELTANK_CENTRE, const.FUELTANK_CENTRE2,
2010 const.FUELTANK_RIGHT, const.FUELTANK_RIGHT_AUX]
2011
2012 def __init__(self):
2013 """Construct the model."""
2014 super(T154Model, self). \
2015 __init__(flapsNotches = [0, 15, 28, 45],
2016 fuelTanks = T154Model.fuelTanks,
2017 numEngines = 3)
2018
2019 @property
2020 def name(self):
2021 """Get the name for this aircraft model."""
2022 return "FSUIPC/Generic Tupolev Tu-154"
2023
2024 def getAircraftState(self, aircraft, timestamp, data):
2025 """Get an aircraft state object for the given monitoring data.
2026
2027 This removes the reverser value for the middle engine."""
2028 state = super(T154Model, self).getAircraftState(aircraft, timestamp, data)
2029 del state.reverser[1]
2030 return state
2031
2032#------------------------------------------------------------------------------
2033
2034class PTT154Model(T154Model):
2035 """Project Tupolev Tu-154."""
2036 @staticmethod
2037 def doesHandle(aircraft, (name, airPath)):
2038 """Determine if this model handler handles the aircraft with the given
2039 name."""
2040 print "PTT154Model.doesHandle", aircraft.type, name, airPath
2041 return aircraft.type==const.AIRCRAFT_T154 and \
2042 (name.find("Tu-154")!=-1 or name.find("Tu154B")!=-1) and \
2043 os.path.basename(airPath).startswith("154b_")
2044
2045 def __init__(self):
2046 """Construct the model."""
2047 super(PTT154Model, self).__init__()
2048 self._fsType = None
2049
2050 @property
2051 def name(self):
2052 """Get the name for this aircraft model."""
2053 return "FSUIPC/Project Tupolev Tu-154"
2054
2055 def addMonitoringData(self, data, fsType):
2056 """Add the model-specific monitoring data to the given array.
2057
2058 It only stores the flight simulator type."""
2059 self._fsType = fsType
2060
2061 super(PTT154Model, self).addMonitoringData(data, fsType)
2062
2063 def getAircraftState(self, aircraft, timestamp, data):
2064 """Get an aircraft state object for the given monitoring data.
2065
2066 This removes the reverser value for the middle engine."""
2067 state = super(PTT154Model, self).getAircraftState(aircraft, timestamp, data)
2068
2069 if self._fsType==const.SIM_MSFSX:
2070 state.xpdrC = None
2071
2072 return state
2073
2074
2075#------------------------------------------------------------------------------
2076
2077class YK40Model(GenericAircraftModel):
2078 """Generic model for the Yakovlev Yak-40 aircraft."""
2079 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_RIGHT]
2080
2081 def __init__(self):
2082 """Construct the model."""
2083 super(YK40Model, self). \
2084 __init__(flapsNotches = [0, 20, 35],
2085 fuelTanks = YK40Model.fuelTanks,
2086 numEngines = 2)
2087
2088 @property
2089 def name(self):
2090 """Get the name for this aircraft model."""
2091 return "FSUIPC/Generic Yakovlev Yak-40"
2092
2093#------------------------------------------------------------------------------
2094
2095class B462Model(GenericAircraftModel):
2096 """Generic model for the British Aerospace BAe 146-200 aircraft."""
2097 fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE,
2098 const.FUELTANK_RIGHT]
2099
2100 def __init__(self):
2101 """Construct the model."""
2102 super(B462Model, self). \
2103 __init__(flapsNotches = [0, 18, 24, 30, 33],
2104 fuelTanks = B462Model.fuelTanks,
2105 numEngines = 4)
2106
2107 @property
2108 def name(self):
2109 """Get the name for this aircraft model."""
2110 return "FSUIPC/Generic British Aerospace 146"
2111
2112 def getAircraftState(self, aircraft, timestamp, data):
2113 """Get an aircraft state object for the given monitoring data.
2114
2115 This removes the reverser value for the middle engine."""
2116 state = super(B462Model, self).getAircraftState(aircraft, timestamp, data)
2117 state.reverser = []
2118 return state
2119
2120#------------------------------------------------------------------------------
2121
2122_genericModels = { const.AIRCRAFT_B736 : B737Model,
2123 const.AIRCRAFT_B737 : B737Model,
2124 const.AIRCRAFT_B738 : B737Model,
2125 const.AIRCRAFT_B738C : B737Model,
2126 const.AIRCRAFT_B733 : B737Model,
2127 const.AIRCRAFT_B734 : B737Model,
2128 const.AIRCRAFT_B735 : B737Model,
2129 const.AIRCRAFT_DH8D : DH8DModel,
2130 const.AIRCRAFT_B762 : B767Model,
2131 const.AIRCRAFT_B763 : B767Model,
2132 const.AIRCRAFT_CRJ2 : CRJ2Model,
2133 const.AIRCRAFT_F70 : F70Model,
2134 const.AIRCRAFT_DC3 : DC3Model,
2135 const.AIRCRAFT_T134 : T134Model,
2136 const.AIRCRAFT_T154 : T154Model,
2137 const.AIRCRAFT_YK40 : YK40Model,
2138 const.AIRCRAFT_B462 : B462Model }
2139
2140#------------------------------------------------------------------------------
2141
2142AircraftModel.registerSpecial(PMDGBoeing737NGModel)
2143AircraftModel.registerSpecial(DreamwingsDH8DModel)
2144AircraftModel.registerSpecial(DAF70Model)
2145AircraftModel.registerSpecial(PTT154Model)
2146
2147#------------------------------------------------------------------------------
Note: See TracBrowser for help on using the repository browser.