]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/models/propulsion/FGPiston.cpp
Merge branch 'next' of git://gitorious.org/fg/flightgear into next
[flightgear.git] / src / FDM / JSBSim / models / propulsion / FGPiston.cpp
1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
3  Module:       FGPiston.cpp
4  Author:       Jon S. Berndt, JSBSim framework
5                Dave Luff, Piston engine model
6                Ronald Jensen, Piston engine model
7  Date started: 09/12/2000
8  Purpose:      This module models a Piston engine
9
10  ------------- Copyright (C) 2000  Jon S. Berndt (jon@jsbsim.org) --------------
11
12  This program is free software; you can redistribute it and/or modify it under
13  the terms of the GNU Lesser General Public License as published by the Free Software
14  Foundation; either version 2 of the License, or (at your option) any later
15  version.
16
17  This program is distributed in the hope that it will be useful, but WITHOUT
18  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
20  details.
21
22  You should have received a copy of the GNU Lesser General Public License along with
23  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
24  Place - Suite 330, Boston, MA  02111-1307, USA.
25
26  Further information about the GNU Lesser General Public License can also be found on
27  the world wide web at http://www.gnu.org.
28
29 FUNCTIONAL DESCRIPTION
30 --------------------------------------------------------------------------------
31
32 This class descends from the FGEngine class and models a Piston engine based on
33 parameters given in the engine config file for this class
34
35 HISTORY
36 --------------------------------------------------------------------------------
37 09/12/2000  JSB  Created
38
39 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40 INCLUDES
41 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
42
43 #include <sstream>
44
45 #include "FGPiston.h"
46 #include "models/FGAtmosphere.h"
47 #include "models/FGAuxiliary.h"
48 #include "models/FGPropulsion.h"
49 #include "FGPropeller.h"
50 #include <iostream>
51
52 using namespace std;
53
54 namespace JSBSim {
55
56 static const char *IdSrc = "$Id: FGPiston.cpp,v 1.53 2010/08/21 17:13:48 jberndt Exp $";
57 static const char *IdHdr = ID_PISTON;
58
59 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
60 CLASS IMPLEMENTATION
61 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
62
63 FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number)
64   : FGEngine(exec, el, engine_number),
65   R_air(287.3),                  // Gas constant for air J/Kg/K
66   rho_fuel(800),                 // estimate
67   calorific_value_fuel(47.3e6),
68   Cp_air(1005),                  // Specific heat (constant pressure) J/Kg/K
69   Cp_fuel(1700),
70   standard_pressure(101320.73)
71 {
72   string token;
73
74   // Defaults and initializations
75
76   Type = etPiston;
77   dt = FDMExec->GetDeltaT();
78
79   // These items are read from the configuration file
80   // Defaults are from a Lycoming O-360, more or less
81
82   Cycles = 4;
83   IdleRPM = 600;
84   MaxRPM = 2800;
85   Displacement = 360;
86   SparkFailDrop = 1.0;
87   MaxHP = 200;
88   MinManifoldPressure_inHg = 6.5;
89   MaxManifoldPressure_inHg = 28.5;
90   ISFC = -1;
91   volumetric_efficiency = 0.85;
92   Bore = 5.125;
93   Stroke = 4.375;
94   Cylinders = 4;
95   CompressionRatio = 8.5;
96   Z_airbox = -999;
97   Ram_Air_Factor = 1;
98   PeakMeanPistonSpeed_fps = 100;
99   FMEPDynamic= 18400;
100   FMEPStatic = 46500;
101
102
103   // These are internal program variables
104
105   crank_counter = 0;
106   Magnetos = 0;
107   minMAP = 21950;
108   maxMAP = 96250;
109
110   ResetToIC();
111
112   // Supercharging
113   BoostSpeeds = 0;  // Default to no supercharging
114   BoostSpeed = 0;
115   Boosted = false;
116   BoostOverride = 0;
117   BoostManual = 0;
118   bBoostOverride = false;
119   bTakeoffBoost = false;
120   TakeoffBoost = 0.0;   // Default to no extra takeoff-boost
121   int i;
122   for (i=0; i<FG_MAX_BOOST_SPEEDS; i++) {
123     RatedBoost[i] = 0.0;
124     RatedPower[i] = 0.0;
125     RatedAltitude[i] = 0.0;
126     BoostMul[i] = 1.0;
127     RatedMAP[i] = 100000;
128     RatedRPM[i] = 2500;
129     TakeoffMAP[i] = 100000;
130   }
131   for (i=0; i<FG_MAX_BOOST_SPEEDS-1; i++) {
132     BoostSwitchAltitude[i] = 0.0;
133     BoostSwitchPressure[i] = 0.0;
134   }
135
136   // First column is thi, second is neta (combustion efficiency)
137   Lookup_Combustion_Efficiency = new FGTable(12);
138   *Lookup_Combustion_Efficiency << 0.00 << 0.980;
139   *Lookup_Combustion_Efficiency << 0.90 << 0.980;
140   *Lookup_Combustion_Efficiency << 1.00 << 0.970;
141   *Lookup_Combustion_Efficiency << 1.05 << 0.950;
142   *Lookup_Combustion_Efficiency << 1.10 << 0.900;
143   *Lookup_Combustion_Efficiency << 1.15 << 0.850;
144   *Lookup_Combustion_Efficiency << 1.20 << 0.790;
145   *Lookup_Combustion_Efficiency << 1.30 << 0.700;
146   *Lookup_Combustion_Efficiency << 1.40 << 0.630;
147   *Lookup_Combustion_Efficiency << 1.50 << 0.570;
148   *Lookup_Combustion_Efficiency << 1.60 << 0.525;
149   *Lookup_Combustion_Efficiency << 2.00 << 0.345;
150
151   Mixture_Efficiency_Correlation = new FGTable(15);
152   *Mixture_Efficiency_Correlation << 0.05000 << 0.00000;
153   *Mixture_Efficiency_Correlation << 0.05137 << 0.00862;
154   *Mixture_Efficiency_Correlation << 0.05179 << 0.21552;
155   *Mixture_Efficiency_Correlation << 0.05430 << 0.48276;
156   *Mixture_Efficiency_Correlation << 0.05842 << 0.70690;
157   *Mixture_Efficiency_Correlation << 0.06312 << 0.83621;
158   *Mixture_Efficiency_Correlation << 0.06942 << 0.93103;
159   *Mixture_Efficiency_Correlation << 0.07786 << 1.00000;
160   *Mixture_Efficiency_Correlation << 0.08845 << 1.00000;
161   *Mixture_Efficiency_Correlation << 0.09270 << 0.98276;
162   *Mixture_Efficiency_Correlation << 0.10120 << 0.93103;
163   *Mixture_Efficiency_Correlation << 0.11455 << 0.72414;
164   *Mixture_Efficiency_Correlation << 0.12158 << 0.45690;
165   *Mixture_Efficiency_Correlation << 0.12435 << 0.23276;
166   *Mixture_Efficiency_Correlation << 0.12500 << 0.00000;
167
168
169   // Read inputs from engine data file where present.
170
171   if (el->FindElement("minmp")) // Should have ELSE statement telling default value used?
172     MinManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("minmp","INHG");
173   if (el->FindElement("maxmp"))
174     MaxManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("maxmp","INHG");
175   if (el->FindElement("displacement"))
176     Displacement = el->FindElementValueAsNumberConvertTo("displacement","IN3");
177   if (el->FindElement("maxhp"))
178     MaxHP = el->FindElementValueAsNumberConvertTo("maxhp","HP");
179   if (el->FindElement("sparkfaildrop"))
180     SparkFailDrop = Constrain(0, 1 - el->FindElementValueAsNumber("sparkfaildrop"), 1);
181   if (el->FindElement("cycles"))
182     Cycles = el->FindElementValueAsNumber("cycles");
183   if (el->FindElement("idlerpm"))
184     IdleRPM = el->FindElementValueAsNumber("idlerpm");
185   if (el->FindElement("maxrpm"))
186     MaxRPM = el->FindElementValueAsNumber("maxrpm");
187   if (el->FindElement("maxthrottle"))
188     MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
189   if (el->FindElement("minthrottle"))
190     MinThrottle = el->FindElementValueAsNumber("minthrottle");
191   if (el->FindElement("bsfc"))
192     ISFC = el->FindElementValueAsNumberConvertTo("bsfc", "LBS/HP*HR");
193   if (el->FindElement("volumetric-efficiency"))
194     volumetric_efficiency = el->FindElementValueAsNumber("volumetric-efficiency");
195   if (el->FindElement("compression-ratio"))
196     CompressionRatio = el->FindElementValueAsNumber("compression-ratio");
197   if (el->FindElement("bore"))
198     Bore = el->FindElementValueAsNumberConvertTo("bore","IN");
199   if (el->FindElement("stroke"))
200     Stroke = el->FindElementValueAsNumberConvertTo("stroke","IN");
201   if (el->FindElement("cylinders"))
202     Cylinders = el->FindElementValueAsNumber("cylinders");
203   if (el->FindElement("air-intake-impedance-factor"))
204     Z_airbox = el->FindElementValueAsNumber("air-intake-impedance-factor");
205   if (el->FindElement("ram-air-factor"))
206     Ram_Air_Factor  = el->FindElementValueAsNumber("ram-air-factor");
207   if (el->FindElement("dynamic-fmep"))
208     FMEPDynamic= el->FindElementValueAsNumberConvertTo("dynamic-fmep","PA");
209   if (el->FindElement("static-fmep"))
210     FMEPStatic = el->FindElementValueAsNumberConvertTo("static-fmep","PA");
211   if (el->FindElement("peak-piston-speed"))
212     PeakMeanPistonSpeed_fps  = el->FindElementValueAsNumber("peak-piston-speed");
213   if (el->FindElement("numboostspeeds")) { // Turbo- and super-charging parameters
214     BoostSpeeds = (int)el->FindElementValueAsNumber("numboostspeeds");
215     if (el->FindElement("boostoverride"))
216       BoostOverride = (int)el->FindElementValueAsNumber("boostoverride");
217     if (el->FindElement("boostmanual"))
218       BoostManual = (int)el->FindElementValueAsNumber("boostmanual");
219     if (el->FindElement("takeoffboost"))
220       TakeoffBoost = el->FindElementValueAsNumberConvertTo("takeoffboost", "PSI");
221     if (el->FindElement("ratedboost1"))
222       RatedBoost[0] = el->FindElementValueAsNumberConvertTo("ratedboost1", "PSI");
223     if (el->FindElement("ratedboost2"))
224       RatedBoost[1] = el->FindElementValueAsNumberConvertTo("ratedboost2", "PSI");
225     if (el->FindElement("ratedboost3"))
226       RatedBoost[2] = el->FindElementValueAsNumberConvertTo("ratedboost3", "PSI");
227     if (el->FindElement("ratedpower1"))
228       RatedPower[0] = el->FindElementValueAsNumberConvertTo("ratedpower1", "HP");
229     if (el->FindElement("ratedpower2"))
230       RatedPower[1] = el->FindElementValueAsNumberConvertTo("ratedpower2", "HP");
231     if (el->FindElement("ratedpower3"))
232       RatedPower[2] = el->FindElementValueAsNumberConvertTo("ratedpower3", "HP");
233     if (el->FindElement("ratedrpm1"))
234       RatedRPM[0] = el->FindElementValueAsNumber("ratedrpm1");
235     if (el->FindElement("ratedrpm2"))
236       RatedRPM[1] = el->FindElementValueAsNumber("ratedrpm2");
237     if (el->FindElement("ratedrpm3"))
238       RatedRPM[2] = el->FindElementValueAsNumber("ratedrpm3");
239     if (el->FindElement("ratedaltitude1"))
240       RatedAltitude[0] = el->FindElementValueAsNumberConvertTo("ratedaltitude1", "FT");
241     if (el->FindElement("ratedaltitude2"))
242       RatedAltitude[1] = el->FindElementValueAsNumberConvertTo("ratedaltitude2", "FT");
243     if (el->FindElement("ratedaltitude3"))
244       RatedAltitude[2] = el->FindElementValueAsNumberConvertTo("ratedaltitude3", "FT");
245   }
246
247   StarterHP = sqrt(MaxHP) * 0.4;
248   displacement_SI = Displacement * in3tom3;
249   RatedMeanPistonSpeed_fps =  ( MaxRPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
250
251   // Create IFSC to match the engine if not provided
252   if (ISFC < 0) {
253       double pmep = 29.92 - MaxManifoldPressure_inHg;
254       pmep *= inhgtopa  * volumetric_efficiency;
255       double fmep = (FMEPDynamic * RatedMeanPistonSpeed_fps * fttom + FMEPStatic);
256       double hp_loss = ((pmep + fmep) * displacement_SI * MaxRPM)/(Cycles*22371);
257       ISFC = ( 1.1*Displacement * MaxRPM * volumetric_efficiency *(MaxManifoldPressure_inHg / 29.92) ) / (9411 * (MaxHP+hp_loss));
258 // cout <<"FMEP: "<< fmep <<" PMEP: "<< pmep << " hp_loss: " <<hp_loss <<endl;
259   }
260   if ( MaxManifoldPressure_inHg > 29.9 ) {   // Don't allow boosting with a bogus number
261       MaxManifoldPressure_inHg = 29.9;
262   }
263   minMAP = MinManifoldPressure_inHg * inhgtopa;  // inHg to Pa
264   maxMAP = MaxManifoldPressure_inHg * inhgtopa;
265
266 // For throttle
267 /*
268  * Pm = ( Ze / ( Ze + Zi + Zt ) ) * Pa
269  * Where:
270  * Pm = Manifold Pressure
271  * Pa = Ambient Pressre
272  * Ze = engine impedance, Ze is effectively 1 / Mean Piston Speed
273  * Zi = airbox impedance
274  * Zt = throttle impedance
275  *
276  * For the calculation below throttle is fully open or Zt = 0
277  *
278  *
279  *
280  */
281
282   if(Z_airbox < 0.0){
283     double Ze=PeakMeanPistonSpeed_fps/RatedMeanPistonSpeed_fps; // engine impedence
284     Z_airbox = (standard_pressure *Ze / maxMAP) - Ze; // impedence of airbox
285   }
286   // Constant for Throttle impedence
287   Z_throttle=(PeakMeanPistonSpeed_fps/((IdleRPM * Stroke) / 360))*(standard_pressure/minMAP - 1) - Z_airbox; 
288   //  Z_throttle=(MaxRPM/IdleRPM )*(standard_pressure/minMAP+2); // Constant for Throttle impedence
289
290   string property_name, base_property_name;
291   base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
292   property_name = base_property_name + "/power-hp";
293   PropertyManager->Tie(property_name, &HP);
294   property_name = base_property_name + "/bsfc-lbs_hphr";
295   PropertyManager->Tie(property_name, &ISFC);
296   property_name = base_property_name + "/volumetric-efficiency";
297   PropertyManager->Tie(property_name, &volumetric_efficiency);
298   property_name = base_property_name + "/map-pa";
299   PropertyManager->Tie(property_name, &MAP);
300   property_name = base_property_name + "/map-inhg";
301   PropertyManager->Tie(property_name, &ManifoldPressure_inHg);
302   property_name = base_property_name + "/air-intake-impedance-factor";
303   PropertyManager->Tie(property_name, &Z_airbox);
304   property_name = base_property_name + "/ram-air-factor";
305   PropertyManager->Tie(property_name, &Ram_Air_Factor);
306   property_name = base_property_name + "/boost-speed";
307   PropertyManager->Tie(property_name, &BoostSpeed);
308
309   // Set up and sanity-check the turbo/supercharging configuration based on the input values.
310   if (TakeoffBoost > RatedBoost[0]) bTakeoffBoost = true;
311   for (i=0; i<BoostSpeeds; ++i) {
312     bool bad = false;
313     if (RatedBoost[i] <= 0.0) bad = true;
314     if (RatedPower[i] <= 0.0) bad = true;
315     if (RatedAltitude[i] < 0.0) bad = true;  // 0.0 is deliberately allowed - this corresponds to unregulated supercharging.
316     if (i > 0 && RatedAltitude[i] < RatedAltitude[i - 1]) bad = true;
317     if (bad) {
318       // We can't recover from the above - don't use this supercharger speed.
319       BoostSpeeds--;
320       // TODO - put out a massive error message!
321       break;
322     }
323     // Now sanity-check stuff that is recoverable.
324     if (i < BoostSpeeds - 1) {
325       if (BoostSwitchAltitude[i] < RatedAltitude[i]) {
326         // TODO - put out an error message
327         // But we can also make a reasonable estimate, as below.
328         BoostSwitchAltitude[i] = RatedAltitude[i] + 1000;
329       }
330       BoostSwitchPressure[i] = Atmosphere->GetPressure(BoostSwitchAltitude[i]) * psftopa;
331       //cout << "BoostSwitchAlt = " << BoostSwitchAltitude[i] << ", pressure = " << BoostSwitchPressure[i] << '\n';
332       // Assume there is some hysteresis on the supercharger gear switch, and guess the value for now
333       BoostSwitchHysteresis = 1000;
334     }
335     // Now work out the supercharger pressure multiplier of this speed from the rated boost and altitude.
336     RatedMAP[i] = Atmosphere->GetPressureSL() * psftopa + RatedBoost[i] * 6895;  // psi*6895 = Pa.
337     // Sometimes a separate BCV setting for takeoff or extra power is fitted.
338     if (TakeoffBoost > RatedBoost[0]) {
339       // Assume that the effect on the BCV is the same whichever speed is in use.
340       TakeoffMAP[i] = RatedMAP[i] + ((TakeoffBoost - RatedBoost[0]) * 6895);
341       bTakeoffBoost = true;
342     } else {
343       TakeoffMAP[i] = RatedMAP[i];
344       bTakeoffBoost = false;
345     }
346     BoostMul[i] = RatedMAP[i] / (Atmosphere->GetPressure(RatedAltitude[i]) * psftopa);
347
348   }
349
350   if (BoostSpeeds > 0) {
351     Boosted = true;
352     BoostSpeed = 0;
353   }
354   bBoostOverride = (BoostOverride == 1 ? true : false);
355   bBoostManual   = (BoostManual   == 1 ? true : false);
356   Debug(0); // Call Debug() routine from constructor if needed
357 }
358
359 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
360
361 FGPiston::~FGPiston()
362 {
363   delete Lookup_Combustion_Efficiency;
364   delete Mixture_Efficiency_Correlation;
365   Debug(1); // Call Debug() routine from constructor if needed
366 }
367
368 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
369
370 void FGPiston::ResetToIC(void)
371 {
372   FGEngine::ResetToIC();
373
374   ManifoldPressure_inHg = Atmosphere->GetPressure() * psftoinhg; // psf to in Hg
375   MAP = Atmosphere->GetPressure() * psftopa;
376   TMAP = MAP;
377   double airTemperature_degK = RankineToKelvin(Atmosphere->GetTemperature());
378   OilTemp_degK = airTemperature_degK;
379   CylinderHeadTemp_degK = airTemperature_degK;
380   ExhaustGasTemp_degK = airTemperature_degK;
381   EGT_degC = ExhaustGasTemp_degK - 273;
382   Thruster->SetRPM(0.0);
383   RPM = 0.0;
384   OilPressure_psi = 0.0;
385 }
386
387 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
388 void FGPiston::Calculate(void)
389 {
390   RunPreFunctions();
391
392   if (FuelFlow_gph > 0.0) ConsumeFuel();
393
394   Throttle = FCS->GetThrottlePos(EngineNumber);
395   Mixture = FCS->GetMixturePos(EngineNumber);
396
397   // Input values.
398
399   p_amb = Atmosphere->GetPressure() * psftopa;
400   double p = Auxiliary->GetTotalPressure() * psftopa;
401   p_ram = (p - p_amb) * Ram_Air_Factor + p_amb;
402   T_amb = RankineToKelvin(Atmosphere->GetTemperature());
403
404   RPM = Thruster->GetRPM() * Thruster->GetGearRatio();
405   MeanPistonSpeed_fps =  ( RPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
406
407   IAS = Auxiliary->GetVcalibratedKTS();
408
409   doEngineStartup();
410   if (Boosted) doBoostControl();
411   doMAP();
412   doAirFlow();
413   doFuelFlow();
414
415   //Now that the fuel flow is done check if the mixture is too lean to run the engine
416   //Assume lean limit at 22 AFR for now - thats a thi of 0.668
417   //This might be a bit generous, but since there's currently no audiable warning of impending
418   //cutout in the form of misfiring and/or rough running its probably reasonable for now.
419
420   //  if (equivalence_ratio < 0.668)
421   //    Running = false;
422
423   doEnginePower();
424   if (IndicatedHorsePower < 0.1250) Running = false;
425
426   doEGT();
427   doCHT();
428   doOilTemperature();
429   doOilPressure();
430
431   if (Thruster->GetType() == FGThruster::ttPropeller) {
432     ((FGPropeller*)Thruster)->SetAdvance(FCS->GetPropAdvance(EngineNumber));
433     ((FGPropeller*)Thruster)->SetFeather(FCS->GetPropFeather(EngineNumber));
434   }
435
436   PowerAvailable = (HP * hptoftlbssec) - Thruster->GetPowerRequired();
437   Thruster->Calculate(PowerAvailable);
438
439   RunPostFunctions();
440 }
441
442 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
443
444 double FGPiston::CalcFuelNeed(void)
445 {
446   double dT = FDMExec->GetDeltaT() * Propulsion->GetRate();
447   FuelExpended = FuelFlowRate * dT;
448   return FuelExpended;
449 }
450
451 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
452
453 int FGPiston::InitRunning(void) {
454   Magnetos=3;
455   p_amb = Atmosphere->GetPressure() * psftopa;
456   double mix= p_amb / (101325.0*1.3);
457   FCS->SetMixturePos(EngineNumber, mix);
458   Thruster->SetRPM( 2.*IdleRPM/Thruster->GetGearRatio() );
459   //Thruster->SetRPM( 1000 );
460   Running=true;
461 // cout <<"Set Running in FGPiston. RPM:" << Thruster->GetRPM()*Thruster->GetGearRatio() <<" Pressure:"<<p_amb<<" Mixture:"<< mix <<endl;
462   return 1;
463 }
464
465 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
466 /**
467  * Start or stop the engine.
468  */
469
470 void FGPiston::doEngineStartup(void)
471 {
472   // Check parameters that may alter the operating state of the engine.
473   // (spark, fuel, starter motor etc)
474   bool spark;
475   bool fuel;
476   // Check for spark
477   Magneto_Left = false;
478   Magneto_Right = false;
479   // Magneto positions:
480   // 0 -> off
481   // 1 -> left only
482   // 2 -> right only
483   // 3 -> both
484   if (Magnetos != 0) {
485     spark = true;
486   } else {
487     spark = false;
488   }  // neglects battery voltage, master on switch, etc for now.
489
490   if ((Magnetos == 1) || (Magnetos > 2)) Magneto_Left = true;
491   if (Magnetos > 1)  Magneto_Right = true;
492
493   // Assume we have fuel for now
494   fuel = !Starved;
495
496   // Check if we are turning the starter motor
497   if (Cranking != Starter) {
498     // This check saves .../cranking from getting updated every loop - they
499     // only update when changed.
500     Cranking = Starter;
501     crank_counter = 0;
502   }
503
504   if (Cranking) crank_counter++;  //Check mode of engine operation
505
506   if (!Running && spark && fuel) {  // start the engine if revs high enough
507     if (Cranking) {
508       if ((RPM > IdleRPM*0.8) && (crank_counter > 175)) // Add a little delay to startup
509         Running = true;                         // on the starter
510     } else {
511       if (RPM > IdleRPM*0.8)                            // This allows us to in-air start
512         Running = true;                         // when windmilling
513     }
514   }
515
516   // Cut the engine *power* - Note: the engine may continue to
517   // spin if the prop is in a moving airstream
518
519   if ( Running && (!spark || !fuel) ) Running = false;
520
521   // Check for stalling (RPM = 0).
522   if (Running) {
523     if (RPM == 0) {
524       Running = false;
525     } else if ((RPM <= IdleRPM *0.8 ) && (Cranking)) {
526       Running = false;
527     }
528   }
529 }
530
531 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
532
533 /**
534  * Calculate the Current Boost Speed
535  *
536  * This function calculates the current turbo/supercharger boost speed
537  * based on altitude and the (automatic) boost-speed control valve configuration.
538  *
539  * Inputs: p_amb, BoostSwitchPressure, BoostSwitchHysteresis
540  *
541  * Outputs: BoostSpeed
542  */
543
544 void FGPiston::doBoostControl(void)
545 {
546   if(BoostManual) {
547     if(BoostSpeed > BoostSpeeds-1) BoostSpeed = BoostSpeeds-1;
548     if(BoostSpeed < 0) BoostSpeed = 0;
549   } else {
550     if(BoostSpeed < BoostSpeeds - 1) {
551       // Check if we need to change to a higher boost speed
552       if(p_amb < BoostSwitchPressure[BoostSpeed] - BoostSwitchHysteresis) {
553         BoostSpeed++;
554       }
555     } if(BoostSpeed > 0) {
556       // Check if we need to change to a lower boost speed
557       if(p_amb > BoostSwitchPressure[BoostSpeed - 1] + BoostSwitchHysteresis) {
558         BoostSpeed--;
559       }
560     }
561   }
562 }
563
564 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
565
566 /**
567  * Calculate the manifold absolute pressure (MAP) in inches hg
568  *
569  * This function calculates manifold absolute pressure (MAP)
570  * from the throttle position, turbo/supercharger boost control
571  * system, engine speed and local ambient air density.
572  *
573  * Inputs: p_amb, Throttle,
574  *         MeanPistonSpeed_fps, dt
575  *
576  * Outputs: MAP, ManifoldPressure_inHg, TMAP
577  */
578
579 void FGPiston::doMAP(void)
580 {
581   double Zt = (1-Throttle)*(1-Throttle)*Z_throttle; // throttle impedence
582   double Ze= MeanPistonSpeed_fps > 0 ? PeakMeanPistonSpeed_fps/MeanPistonSpeed_fps : 999999; // engine impedence
583
584   double map_coefficient = Ze/(Ze+Z_airbox+Zt);
585
586   // Add a one second lag to manifold pressure changes
587   double dMAP = (TMAP - p_ram * map_coefficient) * dt;
588   TMAP -=dMAP;
589
590   // Find the mean effective pressure required to achieve this manifold pressure
591   // Fixme: determine the HP consumed by the supercharger
592
593   PMEP = (TMAP - p_amb) * volumetric_efficiency; // Fixme: p_amb should be exhaust manifold pressure
594
595   if (Boosted) {
596     // If takeoff boost is fitted, we currently assume the following throttle map:
597     // (In throttle % - actual input is 0 -> 1)
598     // 99 / 100 - Takeoff boost
599     // In real life, most planes would be fitted with a mechanical 'gate' between
600     // the rated boost and takeoff boost positions.
601
602     bool bTakeoffPos = false;
603     if (bTakeoffBoost) {
604       if (Throttle > 0.98) {
605         bTakeoffPos = true;
606       }
607     }
608     // Boost the manifold pressure.
609     double boost_factor = (( BoostMul[BoostSpeed] - 1 ) / RatedRPM[BoostSpeed] ) * RPM + 1;
610     MAP = TMAP * boost_factor;
611     // Now clip the manifold pressure to BCV or Wastegate setting.
612     if (bTakeoffPos) {
613       if (MAP > TakeoffMAP[BoostSpeed]) MAP = TakeoffMAP[BoostSpeed];
614     } else {
615       if (MAP > RatedMAP[BoostSpeed]) MAP = RatedMAP[BoostSpeed];
616     }
617   } else {
618       MAP = TMAP;
619   }
620
621   // And set the value in American units as well
622   ManifoldPressure_inHg = MAP / inhgtopa;
623 }
624
625 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
626 /**
627  * Calculate the air flow through the engine.
628  * Also calculates ambient air density
629  * (used in CHT calculation for air-cooled engines).
630  *
631  * Inputs: p_amb, R_air, T_amb, MAP, Displacement,
632  *   RPM, volumetric_efficiency,
633  *
634  * TODO: Model inlet manifold air temperature.
635  *
636  * Outputs: rho_air, m_dot_air
637  */
638
639 void FGPiston::doAirFlow(void)
640 {
641   double gamma = 1.3; // specific heat constants
642 // loss of volumentric efficiency due to difference between MAP and exhaust pressure
643 // Eq 6-10 from The Internal Combustion Engine - Charles Taylor Vol 1
644   double ve =((gamma-1)/gamma) +( CompressionRatio -(p_amb/MAP))/(gamma*( CompressionRatio - 1));
645
646   rho_air = p_amb / (R_air * T_amb);
647   double swept_volume = (displacement_SI * (RPM/60)) / 2;
648   double v_dot_air = swept_volume * volumetric_efficiency *ve;
649
650   double rho_air_manifold = MAP / (R_air * T_amb);
651   m_dot_air = v_dot_air * rho_air_manifold;
652
653 }
654
655 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
656 /**
657  * Calculate the fuel flow into the engine.
658  *
659  * Inputs: Mixture, thi_sea_level, p_amb, m_dot_air
660  *
661  * Outputs: equivalence_ratio, m_dot_fuel
662  */
663
664 void FGPiston::doFuelFlow(void)
665 {
666   double thi_sea_level = 1.3 * Mixture; // Allows an AFR of infinity:1 to 11.3075:1
667   equivalence_ratio = thi_sea_level * 101325.0 / p_amb;
668 //  double AFR = 10+(12*(1-Mixture));// mixture 10:1 to 22:1
669 //  m_dot_fuel = m_dot_air / AFR;
670   m_dot_fuel = (m_dot_air * equivalence_ratio) / 14.7;
671   FuelFlowRate =  m_dot_fuel * 2.2046;  // kg to lb
672   FuelFlow_pph = FuelFlowRate  * 3600;  // seconds to hours
673   FuelFlow_gph = FuelFlow_pph / 6.0;    // Assumes 6 lbs / gallon
674 }
675
676 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
677 /**
678  * Calculate the power produced by the engine.
679  *
680  * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb, ISFC,
681  *   Mixture_Efficiency_Correlation, Cycles, MaxHP, PMEP,
682  *   MeanPistonSpeed_fps
683  *
684  * Outputs: PctPower, HP, FMEP, IndicatedHorsePower
685  */
686
687 void FGPiston::doEnginePower(void)
688 {
689   IndicatedHorsePower = 0;
690   FMEP = 0;
691   if (Running) {
692     // FIXME: this needs to be generalized
693     double ME, percent_RPM, power;  // Convienience term for use in the calculations
694     ME = Mixture_Efficiency_Correlation->GetValue(m_dot_fuel/m_dot_air);
695
696     percent_RPM = RPM/MaxRPM;
697 // Guestimate engine friction losses from Figure 4.4 of "Engines: An Introduction", John Lumley
698     FMEP = (-FMEPDynamic * MeanPistonSpeed_fps * fttom - FMEPStatic);
699
700     power = 1;
701
702     if ( Magnetos != 3 ) power *= SparkFailDrop;
703
704
705     IndicatedHorsePower = (FuelFlow_pph / ISFC )* ME * power;
706
707   } else {
708     // Power output when the engine is not running
709     if (Cranking) {
710       if (RPM < 10) {
711         IndicatedHorsePower = StarterHP;
712       } else if (RPM < IdleRPM*0.8) {
713         IndicatedHorsePower = StarterHP + ((IdleRPM*0.8 - RPM) / 8.0);
714         // This is a guess - would be nice to find a proper starter moter torque curve
715       } else {
716         IndicatedHorsePower = StarterHP;
717       }
718     }
719   }
720
721   // Constant is (1/2) * 60 * 745.7
722   // (1/2) convert cycles, 60 minutes to seconds, 745.7 watts to hp.
723   double pumping_hp = ((PMEP + FMEP) * displacement_SI * RPM)/(Cycles*22371);
724
725   HP = IndicatedHorsePower + pumping_hp - 1.5; //FIXME 1.5 static friction should depend on oil temp and configuration
726 //  cout << "pumping_hp " <<pumping_hp << FMEP << PMEP <<endl;
727   PctPower = HP / MaxHP ;
728 //  cout << "Power = " << HP << "  RPM = " << RPM << "  Running = " << Running << "  Cranking = " << Cranking << endl;
729 }
730
731 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
732 /**
733  * Calculate the exhaust gas temperature.
734  *
735  * Inputs: equivalence_ratio, m_dot_fuel, calorific_value_fuel,
736  *   Cp_air, m_dot_air, Cp_fuel, m_dot_fuel, T_amb, PctPower
737  *
738  * Outputs: combustion_efficiency, ExhaustGasTemp_degK
739  */
740
741 void FGPiston::doEGT(void)
742 {
743   double delta_T_exhaust;
744   double enthalpy_exhaust;
745   double heat_capacity_exhaust;
746   double dEGTdt;
747
748   if ((Running) && (m_dot_air > 0.0)) {  // do the energy balance
749     combustion_efficiency = Lookup_Combustion_Efficiency->GetValue(equivalence_ratio);
750     enthalpy_exhaust = m_dot_fuel * calorific_value_fuel *
751                               combustion_efficiency * 0.33;
752     heat_capacity_exhaust = (Cp_air * m_dot_air) + (Cp_fuel * m_dot_fuel);
753     delta_T_exhaust = enthalpy_exhaust / heat_capacity_exhaust;
754     ExhaustGasTemp_degK = T_amb + delta_T_exhaust;
755     ExhaustGasTemp_degK *= 0.444 + ((0.544 - 0.444) * PctPower);
756   } else {  // Drop towards ambient - guess an appropriate time constant for now
757     combustion_efficiency = 0;
758     dEGTdt = (RankineToKelvin(Atmosphere->GetTemperature()) - ExhaustGasTemp_degK) / 100.0;
759     delta_T_exhaust = dEGTdt * dt;
760     ExhaustGasTemp_degK += delta_T_exhaust;
761   }
762 }
763
764 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
765 /**
766  * Calculate the cylinder head temperature.
767  *
768  * Inputs: T_amb, IAS, rho_air, m_dot_fuel, calorific_value_fuel,
769  *   combustion_efficiency, RPM, MaxRPM, Displacement
770  *
771  * Outputs: CylinderHeadTemp_degK
772  */
773
774 void FGPiston::doCHT(void)
775 {
776   double h1 = -95.0;
777   double h2 = -3.95;
778   double h3 = -140.0; // -0.05 * 2800 (default maxrpm)
779
780   double arbitary_area = Displacement/360.0;
781   double CpCylinderHead = 800.0;
782   double MassCylinderHead = 8.0;
783
784   double temperature_difference = CylinderHeadTemp_degK - T_amb;
785   double v_apparent = IAS * 0.5144444;
786   double v_dot_cooling_air = arbitary_area * v_apparent;
787   double m_dot_cooling_air = v_dot_cooling_air * rho_air;
788   double dqdt_from_combustion =
789     m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
790   double dqdt_forced = (h2 * m_dot_cooling_air * temperature_difference) +
791     (h3 * RPM * temperature_difference / MaxRPM);
792   double dqdt_free = h1 * temperature_difference;
793   double dqdt_cylinder_head = dqdt_from_combustion + dqdt_forced + dqdt_free;
794
795   double HeatCapacityCylinderHead = CpCylinderHead * MassCylinderHead;
796
797   CylinderHeadTemp_degK +=
798     (dqdt_cylinder_head / HeatCapacityCylinderHead) * dt;
799 }
800
801 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
802 /**
803  * Calculate the oil temperature.
804  *
805  * Inputs: CylinderHeadTemp_degK, T_amb, OilPressure_psi.
806  *
807  * Outputs: OilTemp_degK
808  */
809
810 void FGPiston::doOilTemperature(void)
811 {
812   double target_oil_temp;        // Steady state oil temp at the current engine conditions
813   double time_constant;          // The time constant for the differential equation
814   double efficiency = 0.667;     // The aproximate oil cooling system efficiency // FIXME: may vary by engine
815
816 //  Target oil temp is interpolated between ambient temperature and Cylinder Head Tempurature
817 //  target_oil_temp = ( T_amb * efficiency ) + (CylinderHeadTemp_degK *(1-efficiency)) ;
818   target_oil_temp = CylinderHeadTemp_degK + efficiency * (T_amb - CylinderHeadTemp_degK) ;
819
820   if (OilPressure_psi > 5.0 ) {
821     time_constant = 5000 / OilPressure_psi; // Guess at a time constant for circulated oil.
822                                             // The higher the pressure the faster it reaches
823                                             // target temperature.  Oil pressure should be about
824                                             // 60 PSI yielding a TC of about 80.
825   } else {
826     time_constant = 1000;  // Time constant for engine-off; reflects the fact
827                            // that oil is no longer getting circulated
828   }
829
830   double dOilTempdt = (target_oil_temp - OilTemp_degK) / time_constant;
831
832   OilTemp_degK += (dOilTempdt * dt);
833 }
834
835 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
836 /**
837  * Calculate the oil pressure.
838  *
839  * Inputs: RPM, MaxRPM, OilTemp_degK
840  *
841  * Outputs: OilPressure_psi
842  */
843
844 void FGPiston::doOilPressure(void)
845 {
846   double Oil_Press_Relief_Valve = 60; // FIXME: may vary by engine
847   double Oil_Press_RPM_Max = MaxRPM * 0.75;    // 75% of max rpm FIXME: may vary by engine
848   double Design_Oil_Temp = 358;          // degK; FIXME: may vary by engine
849   double Oil_Viscosity_Index = 0.25;
850
851   OilPressure_psi = (Oil_Press_Relief_Valve / Oil_Press_RPM_Max) * RPM;
852
853   if (OilPressure_psi >= Oil_Press_Relief_Valve) {
854     OilPressure_psi = Oil_Press_Relief_Valve;
855   }
856
857   OilPressure_psi += (Design_Oil_Temp - OilTemp_degK) * Oil_Viscosity_Index * OilPressure_psi / Oil_Press_Relief_Valve;
858 }
859
860 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
861
862 string FGPiston::GetEngineLabels(const string& delimiter)
863 {
864   std::ostringstream buf;
865
866   buf << Name << " Power Available (engine " << EngineNumber << " in HP)" << delimiter
867       << Name << " HP (engine " << EngineNumber << ")" << delimiter
868       << Name << " equivalent ratio (engine " << EngineNumber << ")" << delimiter
869       << Name << " MAP (engine " << EngineNumber << " in inHg)" << delimiter
870       << Thruster->GetThrusterLabels(EngineNumber, delimiter);
871
872   return buf.str();
873 }
874
875 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
876
877 string FGPiston::GetEngineValues(const string& delimiter)
878 {
879   std::ostringstream buf;
880
881   buf << PowerAvailable << delimiter << HP << delimiter
882       << equivalence_ratio << delimiter << ManifoldPressure_inHg << delimiter
883       << Thruster->GetThrusterValues(EngineNumber, delimiter);
884
885   return buf.str();
886 }
887
888 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
889 //
890 //    The bitmasked value choices are as follows:
891 //    unset: In this case (the default) JSBSim would only print
892 //       out the normally expected messages, essentially echoing
893 //       the config files as they are read. If the environment
894 //       variable is not set, debug_lvl is set to 1 internally
895 //    0: This requests JSBSim not to output any messages
896 //       whatsoever.
897 //    1: This value explicity requests the normal JSBSim
898 //       startup messages
899 //    2: This value asks for a message to be printed out when
900 //       a class is instantiated
901 //    4: When this value is set, a message is displayed when a
902 //       FGModel object executes its Run() method
903 //    8: When this value is set, various runtime state variables
904 //       are printed out periodically
905 //    16: When set various parameters are sanity checked and
906 //       a message is printed out when they go out of bounds
907
908 void FGPiston::Debug(int from)
909 {
910   if (debug_lvl <= 0) return;
911
912   if (debug_lvl & 1) { // Standard console startup message output
913     if (from == 0) { // Constructor
914
915       cout << "\n    Engine Name: "         << Name << endl;
916       cout << "      MinManifoldPressure: " << MinManifoldPressure_inHg << endl;
917       cout << "      MaxManifoldPressure: " << MaxManifoldPressure_inHg << endl;
918       cout << "      MinMaP (Pa):         " << minMAP << endl;
919       cout << "      MaxMaP (Pa):         " << maxMAP << endl;
920       cout << "      Displacement: "        << Displacement             << endl;
921       cout << "      Bore: "                << Bore                     << endl;
922       cout << "      Stroke: "              << Stroke                   << endl;
923       cout << "      Cylinders: "           << Cylinders                << endl;
924       cout << "      Compression Ratio: "   << CompressionRatio         << endl;
925       cout << "      MaxHP: "               << MaxHP                    << endl;
926       cout << "      Cycles: "              << Cycles                   << endl;
927       cout << "      IdleRPM: "             << IdleRPM                  << endl;
928       cout << "      MaxRPM: "              << MaxRPM                   << endl;
929       cout << "      Throttle Constant: "   << Z_throttle               << endl;
930       cout << "      ISFC: "                << ISFC                     << endl;
931       cout << "      Volumetric Efficiency: " << volumetric_efficiency    << endl;
932       cout << "      PeakMeanPistonSpeed_fps: " << PeakMeanPistonSpeed_fps << endl;
933       cout << "      Intake Impedance Factor: " << Z_airbox << endl;
934       cout << "      Dynamic FMEP Factor: " << FMEPDynamic << endl;
935       cout << "      Static FMEP Factor: " << FMEPStatic << endl;
936
937       cout << endl;
938       cout << "      Combustion Efficiency table:" << endl;
939       Lookup_Combustion_Efficiency->Print();
940       cout << endl;
941
942       cout << endl;
943       cout << "      Mixture Efficiency Correlation table:" << endl;
944       Mixture_Efficiency_Correlation->Print();
945       cout << endl;
946
947     }
948   }
949   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
950     if (from == 0) cout << "Instantiated: FGPiston" << endl;
951     if (from == 1) cout << "Destroyed:    FGPiston" << endl;
952   }
953   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
954   }
955   if (debug_lvl & 8 ) { // Runtime state variables
956   }
957   if (debug_lvl & 16) { // Sanity checking
958   }
959   if (debug_lvl & 64) {
960     if (from == 0) { // Constructor
961       cout << IdSrc << endl;
962       cout << IdHdr << endl;
963     }
964   }
965 }
966 } // namespace JSBSim