Changeset 330:ae65c735022a


Ignore:
Timestamp:
11/11/12 14:44:58 (11 years ago)
Author:
István Váradi <ivaradi@…>
Branch:
default
Phase:
public
Message:

Removed some superfluous spaces

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/mlx/fsuipc.py

    r321 r330  
    146146            self._extra = extra
    147147            self._validator = validator
    148            
     148
    149149        def process(self, time):
    150150            """Process the request.
     
    152152            Return True if the request has succeeded, False if data validation
    153153            has failed for a reading request. An exception may also be thrown
    154             if there is some lower-level communication problem."""           
     154            if there is some lower-level communication problem."""
    155155            if self._forWrite:
    156156                pyuipc.write(self._data)
     
    180180            self._extra = extra
    181181            self._validator = validator
    182            
     182
    183183        @property
    184184        def id(self):
     
    203203            if time<self._nextFire:
    204204                return True
    205            
     205
    206206            if self._preparedData is None:
    207207                self._preparedData = pyuipc.prepare_data(self._data)
     
    214214                while self._nextFire <= time:
    215215                    self._nextFire += self._period
    216            
     216
    217217            return isOK
    218218
     
    237237        self._requestCondition = threading.Condition()
    238238        self._connectionRequested = False
    239         self._connected = False       
     239        self._connected = False
    240240
    241241        self._requests = []
     
    321321                self._connectionRequested = True
    322322                self._requestCondition.notify()
    323        
     323
    324324    def disconnect(self):
    325325        """Disconnect from the flight simulator."""
     
    327327            self._requests = []
    328328            if self._connectionRequested:
    329                 self._connectionRequested = False               
     329                self._connectionRequested = False
    330330                self._requestCondition.notify()
    331331
     
    339339        while True:
    340340            self._waitConnectionRequest()
    341            
     341
    342342            if self._connect()>0:
    343343                self._handleConnection()
    344344
    345345            self._disconnect()
    346            
     346
    347347    def _waitConnectionRequest(self):
    348348        """Wait for a connection request to arrive."""
     
    350350            while not self._connectionRequested:
    351351                self._requestCondition.wait()
    352            
     352
    353353    def _connect(self, autoReconnection = False, attempts = 0):
    354354        """Try to connect to the flight simulator via FSUIPC
     
    361361                self._connectionRequested = False
    362362                if autoReconnection:
    363                     Handler._callSafe(lambda:     
     363                    Handler._callSafe(lambda:
    364364                                      self._connectionListener.disconnected())
    365365                else:
    366                     Handler._callSafe(lambda:     
     366                    Handler._callSafe(lambda:
    367367                                      self._connectionListener.connectionFailed())
    368368                return 0
    369                
     369
    370370            try:
    371371                attempts += 1
    372372                pyuipc.open(pyuipc.SIM_ANY)
    373373                description = "(FSUIPC version: 0x%04x, library version: 0x%04x, FS version: %d)" % \
    374                     (pyuipc.fsuipc_version, pyuipc.lib_version, 
     374                    (pyuipc.fsuipc_version, pyuipc.lib_version,
    375375                     pyuipc.fs_version)
    376376                if not autoReconnection:
     
    378378                             if pyuipc.fs_version == pyuipc.SIM_FSX \
    379379                             else const.SIM_MSFS9
    380                
    381                     Handler._callSafe(lambda:     
     380
     381                    Handler._callSafe(lambda:
    382382                                      self._connectionListener.connected(fsType,
    383383                                                                         description))
     
    389389                if attempts<self.NUM_CONNECTATTEMPTS:
    390390                    time.sleep(self.CONNECT_INTERVAL)
    391                
     391
    392392    def _handleConnection(self):
    393393        """Handle a living connection."""
     
    412412               (timeout is not None and timeout <= 0.0):
    413413                return
    414            
     414
    415415            self._requestCondition.wait(timeout)
    416                
     416
    417417    def _disconnect(self):
    418418        """Disconnect from the flight simulator."""
     
    421421            pyuipc.close()
    422422            self._connected = False
    423            
     423
    424424    def _processRequest(self, request, time, attempts):
    425         """Process the given request. 
     425        """Process the given request.
    426426
    427427        If an exception occurs or invalid data is read too many times, we try
     
    457457        finally:
    458458            self._requestCondition.acquire()
    459        
     459
    460460    def _processRequests(self):
    461461        """Process any pending requests.
     
    471471            if request.nextFire>t:
    472472                break
    473            
     473
    474474            attempts = self._processRequest(request, t, attempts)
    475475
     
    493493                 (0x023c, "b"),            # UTC minute
    494494                 (0x023a, "b") ]           # seconds
    495    
     495
    496496    normalData = timeData + \
    497497                 [ (0x3d00, -256),           # The name of the current aircraft
     
    502502                   (0x31e4, "d"),            # Radio altitude
    503503                   (0x02c8, "d") ]           # Vertical speed
    504                    
     504
    505505    flareStartData = [ (0x0e90, "H"),        # Ambient wind speed
    506506                       (0x0e92, "H"),        # Ambient wind direction
    507507                       (0x0e8a, "H") ]       # Visibility
    508                        
     508
    509509    flareData2 = [ (0x023a, "b"),            # Seconds of time
    510510                   (0x0366, "H"),            # On the ground
     
    526526        timestamp += data[2] * 3600
    527527        timestamp += data[3] * 60
    528         timestamp += data[4]       
     528        timestamp += data[4]
    529529
    530530        return timestamp
     
    542542
    543543        data.append((offset + 2, "b", 0))
    544        
    545         data.append((offset + 3, "b", 0))       
     544
     545        data.append((offset + 3, "b", 0))
    546546
    547547    def __init__(self, connectionListener, connectAttempts = -1,
    548548                 connectInterval = 0.2):
    549549        """Construct the simulator.
    550        
     550
    551551        The aircraft object passed must provide the following members:
    552552        - type: one of the AIRCRAFT_XXX constants from const.py
     
    559559          visibility is in metres. flareStart and flareStartFS are two time
    560560          values expressed in seconds that can be used to calculate the flare
    561           time. 
     561          time.
    562562       - flareFinished(flareEnd, flareEndFS, tdRate, tdRateCalculatedByFS,
    563563                       ias, pitch, bank, heading): called when the flare has
     
    580580        self._syncTime = False
    581581        self._nextSyncTime = -1
    582        
     582
    583583        self._normalRequestID = None
    584584
     
    630630
    631631        These values will be passed to the callback function in this order, as
    632         separate arguments."""       
     632        separate arguments."""
    633633        self._handler.requestRead([(0x13fc, "d")], self._handlePayloadCount,
    634634                                  extra = callback)
     
    638638        self._handler.requestRead(Simulator.timeData, self._handleTime,
    639639                                  extra = callback)
    640                                                            
     640
    641641    def startMonitoring(self):
    642642        """Start the periodic monitoring of the aircraft and pass the resulting
    643643        state to the aircraft object periodically."""
    644         assert not self._monitoringRequested         
     644        assert not self._monitoringRequested
    645645        self._monitoringRequested = True
    646646
    647647    def stopMonitoring(self):
    648648        """Stop the periodic monitoring of the aircraft."""
    649         assert self._monitoringRequested 
     649        assert self._monitoringRequested
    650650        self._monitoringRequested = False
    651651
     
    721721        self._nextSyncTime = -1
    722722        self._syncTime = True
    723            
     723
    724724    def disableTimeSync(self):
    725725        """Enable the time synchronization."""
     
    740740            self._hotkeySetGeneration = 0
    741741            self._hotkeyCallback = callback
    742            
     742
    743743            self._handler.requestRead([(0x320c, "u")],
    744744                                      self._handleNumHotkeys,
     
    765765                self._hotkeyCallback = None
    766766                self._clearHotkeyRequest()
    767            
     767
    768768    def disconnect(self, closingMessage = None, duration = 3):
    769769        """Disconnect from the simulator."""
    770         assert not self._monitoringRequested 
     770        assert not self._monitoringRequested
    771771
    772772        print "fsuipc.Simulator.disconnect", closingMessage, duration
    773        
     773
    774774        self._stopNormal()
    775775        self.clearHotkeys()
     
    787787            if self._hotkeys is not None:
    788788                self._hotkeySetGeneration += 1
    789            
     789
    790790                self._handler.requestRead([(0x320c, "u")],
    791791                                          self._handleNumHotkeys,
     
    850850        elif self._monitoring and self._aircraftModel is not None and \
    851851             not createdNewModel:
    852             aircraftState = self._aircraftModel.getAircraftState(self._aircraft, 
     852            aircraftState = self._aircraftModel.getAircraftState(self._aircraft,
    853853                                                                 timestamp, data)
    854854
    855855            self._checkTimeSync(aircraftState)
    856        
     856
    857857            self._aircraft.handleState(aircraftState)
    858858
     
    870870            if self._nextSyncTime > (now - 0.49):
    871871                return
    872            
     872
    873873            self._handler.requestWrite([(0x023a, "b", int(seconds))],
    874874                                       self._handleTimeSynced)
    875            
     875
    876876            #print "Set the seconds to ", seconds
    877877
    878878            if self._nextSyncTime<0:
    879879                self._nextSyncTime = now
    880                
     880
    881881            self._nextSyncTime += Simulator.TIME_SYNC_INTERVAL
    882882        else:
     
    886886        """Callback for the time sync result."""
    887887        pass
    888        
     888
    889889    def _setAircraftName(self, timestamp, name, airPath):
    890890        """Set the name of the aicraft and if it is different from the
    891891        previous, create a new model for it.
    892        
     892
    893893        If so, also notifty the aircraft about the change.
    894894
     
    912912        if needNew:
    913913            self._setAircraftModel(AircraftModel.create(self._aircraft, aircraftName))
    914  
    915        
     914
     915
    916916        self._aircraft.modelChanged(timestamp, self._latin1decoder(name)[0],
    917                                     self._aircraftModel.name)       
     917                                    self._aircraftModel.name)
    918918
    919919        return needNew
     
    925925        will be replaced by a new one."""
    926926        self._aircraftModel = model
    927        
     927
    928928        if self._monitoring:
    929929            self._stopNormal()
    930930            self._startMonitoring()
    931            
     931
    932932    def _startMonitoring(self):
    933933        """Start monitoring with the current aircraft model."""
    934934        data = Simulator.normalData[:]
    935935        self._aircraftModel.addMonitoringData(data, self._fsType)
    936        
     936
    937937        self._normalRequestID = \
    938             self._handler.requestPeriodicRead(1.0, data, 
     938            self._handler.requestPeriodicRead(1.0, data,
    939939                                              self._handleNormal,
    940940                                              validator = self._validateNormal)
     
    955955            self._handler.clearPeriodic(self._flareRequestID)
    956956            self._flareRequestID = \
    957                 self._handler.requestPeriodicRead(0.1, 
     957                self._handler.requestPeriodicRead(0.1,
    958958                                                  Simulator.flareData2,
    959959                                                  self._handleFlare2)
    960960            self._handler.requestRead(Simulator.flareStartData,
    961961                                      self._handleFlareStart)
    962                
     962
    963963        self._addFlareRate(data[2])
    964964
     
    10051005        zfw = data[0] * const.LBSTOKG / 256.0
    10061006        callback(zfw)
    1007                                                  
     1007
    10081008    def _handleTime(self, data, callback):
    10091009        """Callback for a time retrieval request."""
     
    10161016        for i in range(0, payloadCount):
    10171017            data.append((0x1400 + i*48, "f"))
    1018        
     1018
    10191019        self._handler.requestRead(data, self._handleWeights,
    10201020                                  extra = callback)
     
    10401040                numHotkeys = data[0]
    10411041                print "fsuipc.Simulator._handleNumHotkeys: numHotkeys:", numHotkeys
    1042                 data = [(0x3210 + i*4, "d") for i in range(0, numHotkeys)]       
     1042                data = [(0x3210 + i*4, "d") for i in range(0, numHotkeys)]
    10431043                self._handler.requestRead(data, self._handleHotkeyTable,
    10441044                                          (id, generation))
     
    10931093                                           self._handleHotkeysWritten,
    10941094                                           (id, generation))
    1095            
     1095
    10961096    def _handleHotkeysWritten(self, success, (id, generation)):
    10971097        """Handle the result of the hotkeys having been written."""
    1098         with self._hotkeyLock:           
     1098        with self._hotkeyLock:
    10991099            if success and id==self._hotkeySetID and \
    11001100            generation==self._hotkeySetGeneration:
    11011101                data = [(offset + 3, "b") for offset in self._hotkeyOffets]
    1102        
     1102
    11031103                self._hotkeyRequestID = \
    11041104                    self._handler.requestPeriodicRead(0.5, data,
     
    11071107
    11081108    def _handleHotkeys(self, data, (id, generation)):
    1109         """Handle the hotkeys."""       
     1109        """Handle the hotkeys."""
    11101110        with self._hotkeyLock:
    11111111            if id!=self._hotkeySetID or generation!=self._hotkeySetGeneration:
     
    11291129
    11301130    def _handleHotkeysCleared(self, sucess, extra):
    1131         """Callback for the hotkey-clearing write request."""       
     1131        """Callback for the hotkey-clearing write request."""
    11321132
    11331133    def _clearHotkeyRequest(self):
     
    11361136            self._handler.clearPeriodic(self._hotkeyRequestID)
    11371137            self._hotkeyRequestID = None
    1138                                                  
     1138
    11391139#------------------------------------------------------------------------------
    11401140
     
    12411241        return (extBCD[1] if extBCD[1]!="0" else "") + \
    12421242               mainBCD[1:] + "." + extBCD[3]
    1243    
     1243
    12441244    def __init__(self, flapsNotches):
    12451245        """Construct the aircraft model.
    1246        
     1246
    12471247        flapsNotches is a list of degrees of flaps that are available on the aircraft."""
    12481248        self._flapsNotches = flapsNotches
    1249    
     1249
    12501250    @property
    12511251    def name(self):
    12521252        """Get the name for this aircraft model."""
    12531253        return "FSUIPC/Generic"
    1254    
     1254
    12551255    def doesHandle(self, aircraft, aircraftName):
    12561256        """Determine if the model handles the given aircraft name.
    1257        
     1257
    12581258        This default implementation returns False."""
    12591259        return False
     
    12611261    def _addOffsetWithIndexMember(self, dest, offset, type, attrName = None):
    12621262        """Add the given FSUIPC offset and type to the given array and a member
    1263         attribute with the given name."""       
     1263        attribute with the given name."""
    12641264        dest.append((offset, type))
    12651265        if attrName is not None:
     
    12751275        - the FSUIPC offset
    12761276        - the FSUIPC type
    1277        
     1277
    12781278        The latter two items will be appended to dest."""
    12791279        for (name, offset, type) in data:
    12801280            self._addOffsetWithIndexMember(dest, offset, type, prefix + name)
    1281            
     1281
    12821282    def addMonitoringData(self, data, fsType):
    12831283        """Add the model-specific monitoring data to the given array."""
    12841284        self._addDataWithIndexMembers(data, "_monidx_",
    12851285                                      AircraftModel.monitoringData)
    1286    
     1286
    12871287    def getAircraftState(self, aircraft, timestamp, data):
    12881288        """Get an aircraft state object for the given monitoring data."""
    12891289        state = fs.AircraftState()
    1290        
     1290
    12911291        state.timestamp = timestamp
    12921292
     
    12971297                          360.0 / 65536.0 / 65536.0 / 65536.0 / 65536.0
    12981298        if state.longitude>180.0: state.longitude = 360.0 - state.longitude
    1299        
     1299
    13001300        state.paused = data[self._monidx_paused]!=0 or \
    13011301            data[self._monidx_frozen]!=0 or \
     
    13091309        state.zfw = data[self._monidx_zfw] * const.LBSTOKG / 256.0
    13101310        state.grossWeight = data[self._monidx_grossWeight] * const.LBSTOKG
    1311        
     1311
    13121312        state.heading = Handler.fsuipc2PositiveDegrees(data[self._monidx_heading])
    13131313
     
    13251325
    13261326        state.gLoad = data[self._monidx_gLoad] / 625.0
    1327        
     1327
    13281328        numNotchesM1 = len(self._flapsNotches) - 1
    13291329        flapsIncrement = 16383 / numNotchesM1
     
    13351335                flapsIndex += 1
    13361336        state.flapsSet = self._flapsNotches[flapsIndex]
    1337        
     1337
    13381338        flapsLeft = data[self._monidx_flapsLeft]
    13391339        state.flaps = self._flapsNotches[-1]*flapsLeft/16383.0
    1340        
     1340
    13411341        lights = data[self._monidx_lights]
    1342        
     1342
    13431343        state.navLightsOn = (lights&0x01) != 0
    13441344        state.antiCollisionLightsOn = (lights&0x02) != 0
    13451345        state.landingLightsOn = (lights&0x04) != 0
    13461346        state.strobeLightsOn = (lights&0x10) != 0
    1347        
     1347
    13481348        state.pitotHeatOn = data[self._monidx_pitot]!=0
    13491349
     
    13541354
    13551355        state.spoilersArmed = data[self._monidx_spoilersArmed]!=0
    1356        
     1356
    13571357        spoilers = data[self._monidx_spoilers]
    13581358        if spoilers<=4800:
     
    13621362
    13631363        state.altimeter = data[self._monidx_altimeter] / 16.0
    1364            
     1364
    13651365        state.nav1 = AircraftModel.convertFrequency(data[self._monidx_nav1])
    13661366        state.nav1_obs = data[self._monidx_nav1_obs]
     
    13821382
    13831383        state.visibility = data[self._monidx_visibility]*1609.344/100.0
    1384        
     1384
    13851385        state.cog = data[self._monidx_cog]
    1386        
     1386
    13871387        return state
    13881388
     
    13921392    """A generic aircraft model that can handle the fuel levels, the N1 or RPM
    13931393    values and some other common parameters in a generic way."""
    1394    
     1394
    13951395    def __init__(self, flapsNotches, fuelTanks, numEngines, isN1 = True):
    13961396        """Construct the generic aircraft model with the given data.
     
    14161416    def doesHandle(self, aircraft, aircraftName):
    14171417        """Determine if the model handles the given aircraft name.
    1418        
     1418
    14191419        This implementation returns True."""
    14201420        return True
     
    14231423        """Add the model-specific monitoring data to the given array."""
    14241424        super(GenericAircraftModel, self).addMonitoringData(data, fsType)
    1425        
     1425
    14261426        self._fuelStartIndex = self._addFuelOffsets(data, "_monidx_fuelWeight")
    14271427
     
    14341434                self._addOffsetWithIndexMember(data, 0x0898 + i * 0x98, "H")  # RPM
    14351435                self._addOffsetWithIndexMember(data, 0x08c8 + i * 0x98, "H")  # RPM scaler
    1436        
     1436
    14371437    def getAircraftState(self, aircraft, timestamp, data):
    14381438        """Get the aircraft state.
    14391439
    1440         Get it from the parent, and then add the data about the fuel levels and 
     1440        Get it from the parent, and then add the data about the fuel levels and
    14411441        the engine parameters."""
    14421442        state = super(GenericAircraftModel, self).getAircraftState(aircraft,
     
    14501450        state.rpm = None if self._isN1 else []
    14511451        itemsPerEngine = 2 if self._isN1 else 3
    1452        
     1452
    14531453        state.reverser = []
    14541454        for i in range(self._engineStartIndex,
     
    15031503            self._addOffsetWithIndexMember(data, offset, "u")    # tank level
    15041504            self._addOffsetWithIndexMember(data, offset+4, "u")  # tank capacity
    1505        
     1505
    15061506        return fuelStartIndex
    15071507
     
    15231523            amount = data[index] * capacity / 128.0 / 65536.0
    15241524            index += 2
    1525            
    1526             result.append( (fuelTank, amount, capacity) if addCapacities 
     1525
     1526            result.append( (fuelTank, amount, capacity) if addCapacities
    15271527                           else (fuelTank, amount))
    15281528            totalFuel += amount
    15291529
    1530         return (result, totalFuel)       
     1530        return (result, totalFuel)
    15311531
    15321532    def _handleFuelRetrieved(self, data, callback):
    15331533        """Callback for a fuel retrieval request."""
    1534         (fuelData, _totalFuel) = self._convertFuelData(data, 
     1534        (fuelData, _totalFuel) = self._convertFuelData(data,
    15351535                                                       addCapacities = True)
    15361536        callback(fuelData)
    1537                                                          
     1537
    15381538    def _handleFuelWritten(self, success, extra):
    15391539        """Callback for a fuel setting request."""
     
    15541554    def name(self):
    15551555        """Get the name for this aircraft model."""
    1556         return "FSUIPC/Generic"   
     1556        return "FSUIPC/Generic"
    15571557
    15581558#------------------------------------------------------------------------------
     
    15601560class B737Model(GenericAircraftModel):
    15611561    """Generic model for the Boeing 737 Classing and NG aircraft."""
    1562     fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]   
    1563    
     1562    fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
     1563
    15641564    def __init__(self):
    15651565        """Construct the model."""
     
    16011601        """Add the model-specific monitoring data to the given array."""
    16021602        self._fsType = fsType
    1603        
     1603
    16041604        super(PMDGBoeing737NGModel, self).addMonitoringData(data, fsType)
    1605                
     1605
    16061606        self._addOffsetWithIndexMember(data, 0x6202, "b", "_pmdgidx_switches")
    16071607
     
    16301630class B767Model(GenericAircraftModel):
    16311631    """Generic model for the Boeing 767 aircraft."""
    1632     fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]   
     1632    fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
    16331633
    16341634    def __init__(self):
     
    16481648class DH8DModel(GenericAircraftModel):
    16491649    """Generic model for the Bombardier  Dash 8-Q400 aircraft."""
    1650     fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_RIGHT]   
    1651    
     1650    fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_RIGHT]
     1651
    16521652    def __init__(self):
    16531653        """Construct the model."""
     
    16961696class CRJ2Model(GenericAircraftModel):
    16971697    """Generic model for the Bombardier CRJ-200 aircraft."""
    1698     fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]   
     1698    fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
    16991699
    17001700    def __init__(self):
     
    17141714class F70Model(GenericAircraftModel):
    17151715    """Generic model for the Fokker F70 aircraft."""
    1716     fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]   
     1716    fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE, const.FUELTANK_RIGHT]
    17171717
    17181718    def __init__(self):
     
    17621762    """Generic model for the Lisunov Li-2 (DC-3) aircraft."""
    17631763    fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_CENTRE,
    1764                  const.FUELTANK_RIGHT]   
     1764                 const.FUELTANK_RIGHT]
    17651765    # fuelTanks = [const.FUELTANK_LEFT_AUX, const.FUELTANK_LEFT,
    17661766    #              const.FUELTANK_RIGHT, const.FUELTANK_RIGHT_AUX]
     
    17971797            self._leftLevel = self._rightLevel = \
    17981798                centreAmount / centreCapacity / 2.0
    1799             fuelData = [(const.FUELTANK_LEFT_AUX, 
     1799            fuelData = [(const.FUELTANK_LEFT_AUX,
    18001800                         rawFuelData[0][1], rawFuelData[0][2]),
    18011801                        (const.FUELTANK_LEFT,
     
    18221822        centreLevel = None
    18231823        rightLevel = None
    1824        
     1824
    18251825        for (tank, level) in levels:
    18261826            if tank==const.FUELTANK_LEFT_AUX:
     
    19051905    """Generic model for the Yakovlev Yak-40 aircraft."""
    19061906    fuelTanks = [const.FUELTANK_LEFT, const.FUELTANK_RIGHT]
    1907    
     1907
    19081908    def __init__(self):
    19091909        """Construct the model."""
Note: See TracChangeset for help on using the changeset viewer.