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