]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/models/propulsion/FGPiston.cpp
Sync with JSBSim CVS
[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.52 2010/06/05 12:12:34 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 double FGPiston::Calculate(void)
389 {
390   if (FuelFlow_gph > 0.0) ConsumeFuel();
391
392   Throttle = FCS->GetThrottlePos(EngineNumber);
393   Mixture = FCS->GetMixturePos(EngineNumber);
394
395   //
396   // Input values.
397   //
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 //  if (equivalence_ratio < 0.668)
420 //    Running = false;
421
422   doEnginePower();
423   if (IndicatedHorsePower < 0.1250) Running = false;
424
425   doEGT();
426   doCHT();
427   doOilTemperature();
428   doOilPressure();
429
430   if (Thruster->GetType() == FGThruster::ttPropeller) {
431     ((FGPropeller*)Thruster)->SetAdvance(FCS->GetPropAdvance(EngineNumber));
432     ((FGPropeller*)Thruster)->SetFeather(FCS->GetPropFeather(EngineNumber));
433   }
434
435   PowerAvailable = (HP * hptoftlbssec) - Thruster->GetPowerRequired();
436
437   return Thruster->Calculate(PowerAvailable);
438 }
439
440 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
441
442 double FGPiston::CalcFuelNeed(void)
443 {
444   double dT = FDMExec->GetDeltaT() * Propulsion->GetRate();
445   FuelExpended = FuelFlowRate * dT;
446   return FuelExpended;
447 }
448
449 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
450
451 int FGPiston::InitRunning(void) {
452   Magnetos=3;
453   p_amb = Atmosphere->GetPressure() * psftopa;
454   double mix= p_amb / (101325.0*1.3);
455   FCS->SetMixturePos(EngineNumber, mix);
456   Thruster->SetRPM( 2.*IdleRPM/Thruster->GetGearRatio() );
457   //Thruster->SetRPM( 1000 );
458   Running=true;
459 // cout <<"Set Running in FGPiston. RPM:" << Thruster->GetRPM()*Thruster->GetGearRatio() <<" Pressure:"<<p_amb<<" Mixture:"<< mix <<endl;
460   return 1;
461 }
462
463 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
464 /**
465  * Start or stop the engine.
466  */
467
468 void FGPiston::doEngineStartup(void)
469 {
470   // Check parameters that may alter the operating state of the engine.
471   // (spark, fuel, starter motor etc)
472   bool spark;
473   bool fuel;
474   // Check for spark
475   Magneto_Left = false;
476   Magneto_Right = false;
477   // Magneto positions:
478   // 0 -> off
479   // 1 -> left only
480   // 2 -> right only
481   // 3 -> both
482   if (Magnetos != 0) {
483     spark = true;
484   } else {
485     spark = false;
486   }  // neglects battery voltage, master on switch, etc for now.
487
488   if ((Magnetos == 1) || (Magnetos > 2)) Magneto_Left = true;
489   if (Magnetos > 1)  Magneto_Right = true;
490
491   // Assume we have fuel for now
492   fuel = !Starved;
493
494   // Check if we are turning the starter motor
495   if (Cranking != Starter) {
496     // This check saves .../cranking from getting updated every loop - they
497     // only update when changed.
498     Cranking = Starter;
499     crank_counter = 0;
500   }
501
502   if (Cranking) crank_counter++;  //Check mode of engine operation
503
504   if (!Running && spark && fuel) {  // start the engine if revs high enough
505     if (Cranking) {
506       if ((RPM > IdleRPM*0.8) && (crank_counter > 175)) // Add a little delay to startup
507         Running = true;                         // on the starter
508     } else {
509       if (RPM > IdleRPM*0.8)                            // This allows us to in-air start
510         Running = true;                         // when windmilling
511     }
512   }
513
514   // Cut the engine *power* - Note: the engine may continue to
515   // spin if the prop is in a moving airstream
516
517   if ( Running && (!spark || !fuel) ) Running = false;
518
519   // Check for stalling (RPM = 0).
520   if (Running) {
521     if (RPM == 0) {
522       Running = false;
523     } else if ((RPM <= IdleRPM *0.8 ) && (Cranking)) {
524       Running = false;
525     }
526   }
527 }
528
529 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
530
531 /**
532  * Calculate the Current Boost Speed
533  *
534  * This function calculates the current turbo/supercharger boost speed
535  * based on altitude and the (automatic) boost-speed control valve configuration.
536  *
537  * Inputs: p_amb, BoostSwitchPressure, BoostSwitchHysteresis
538  *
539  * Outputs: BoostSpeed
540  */
541
542 void FGPiston::doBoostControl(void)
543 {
544   if(BoostManual) {
545     if(BoostSpeed > BoostSpeeds-1) BoostSpeed = BoostSpeeds-1;
546     if(BoostSpeed < 0) BoostSpeed = 0;
547   } else {
548     if(BoostSpeed < BoostSpeeds - 1) {
549       // Check if we need to change to a higher boost speed
550       if(p_amb < BoostSwitchPressure[BoostSpeed] - BoostSwitchHysteresis) {
551         BoostSpeed++;
552       }
553     } if(BoostSpeed > 0) {
554       // Check if we need to change to a lower boost speed
555       if(p_amb > BoostSwitchPressure[BoostSpeed - 1] + BoostSwitchHysteresis) {
556         BoostSpeed--;
557       }
558     }
559   }
560 }
561
562 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
563
564 /**
565  * Calculate the manifold absolute pressure (MAP) in inches hg
566  *
567  * This function calculates manifold absolute pressure (MAP)
568  * from the throttle position, turbo/supercharger boost control
569  * system, engine speed and local ambient air density.
570  *
571  * Inputs: p_amb, Throttle,
572  *         MeanPistonSpeed_fps, dt
573  *
574  * Outputs: MAP, ManifoldPressure_inHg, TMAP
575  */
576
577 void FGPiston::doMAP(void)
578 {
579   double Zt = (1-Throttle)*(1-Throttle)*Z_throttle; // throttle impedence
580   double Ze= MeanPistonSpeed_fps > 0 ? PeakMeanPistonSpeed_fps/MeanPistonSpeed_fps : 999999; // engine impedence
581
582   double map_coefficient = Ze/(Ze+Z_airbox+Zt);
583
584   // Add a one second lag to manifold pressure changes
585   double dMAP = (TMAP - p_ram * map_coefficient) * dt;
586   TMAP -=dMAP;
587
588   // Find the mean effective pressure required to achieve this manifold pressure
589   // Fixme: determine the HP consumed by the supercharger
590
591   PMEP = (TMAP - p_amb) * volumetric_efficiency; // Fixme: p_amb should be exhaust manifold pressure
592
593   if (Boosted) {
594     // If takeoff boost is fitted, we currently assume the following throttle map:
595     // (In throttle % - actual input is 0 -> 1)
596     // 99 / 100 - Takeoff boost
597     // In real life, most planes would be fitted with a mechanical 'gate' between
598     // the rated boost and takeoff boost positions.
599
600     bool bTakeoffPos = false;
601     if (bTakeoffBoost) {
602       if (Throttle > 0.98) {
603         bTakeoffPos = true;
604       }
605     }
606     // Boost the manifold pressure.
607     double boost_factor = (( BoostMul[BoostSpeed] - 1 ) / RatedRPM[BoostSpeed] ) * RPM + 1;
608     MAP = TMAP * boost_factor;
609     // Now clip the manifold pressure to BCV or Wastegate setting.
610     if (bTakeoffPos) {
611       if (MAP > TakeoffMAP[BoostSpeed]) MAP = TakeoffMAP[BoostSpeed];
612     } else {
613       if (MAP > RatedMAP[BoostSpeed]) MAP = RatedMAP[BoostSpeed];
614     }
615   } else {
616       MAP = TMAP;
617   }
618
619   // And set the value in American units as well
620   ManifoldPressure_inHg = MAP / inhgtopa;
621 }
622
623 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
624 /**
625  * Calculate the air flow through the engine.
626  * Also calculates ambient air density
627  * (used in CHT calculation for air-cooled engines).
628  *
629  * Inputs: p_amb, R_air, T_amb, MAP, Displacement,
630  *   RPM, volumetric_efficiency,
631  *
632  * TODO: Model inlet manifold air temperature.
633  *
634  * Outputs: rho_air, m_dot_air
635  */
636
637 void FGPiston::doAirFlow(void)
638 {
639   double gamma = 1.3; // specific heat constants
640 // loss of volumentric efficiency due to difference between MAP and exhaust pressure
641 // Eq 6-10 from The Internal Combustion Engine - Charles Taylor Vol 1
642   double ve =((gamma-1)/gamma) +( CompressionRatio -(p_amb/MAP))/(gamma*( CompressionRatio - 1));
643
644   rho_air = p_amb / (R_air * T_amb);
645   double swept_volume = (displacement_SI * (RPM/60)) / 2;
646   double v_dot_air = swept_volume * volumetric_efficiency *ve;
647
648   double rho_air_manifold = MAP / (R_air * T_amb);
649   m_dot_air = v_dot_air * rho_air_manifold;
650
651 }
652
653 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
654 /**
655  * Calculate the fuel flow into the engine.
656  *
657  * Inputs: Mixture, thi_sea_level, p_amb, m_dot_air
658  *
659  * Outputs: equivalence_ratio, m_dot_fuel
660  */
661
662 void FGPiston::doFuelFlow(void)
663 {
664   double thi_sea_level = 1.3 * Mixture; // Allows an AFR of infinity:1 to 11.3075:1
665   equivalence_ratio = thi_sea_level * 101325.0 / p_amb;
666 //  double AFR = 10+(12*(1-Mixture));// mixture 10:1 to 22:1
667 //  m_dot_fuel = m_dot_air / AFR;
668   m_dot_fuel = (m_dot_air * equivalence_ratio) / 14.7;
669   FuelFlowRate =  m_dot_fuel * 2.2046;  // kg to lb
670   FuelFlow_pph = FuelFlowRate  * 3600;  // seconds to hours
671   FuelFlow_gph = FuelFlow_pph / 6.0;    // Assumes 6 lbs / gallon
672 }
673
674 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
675 /**
676  * Calculate the power produced by the engine.
677  *
678  * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb, ISFC,
679  *   Mixture_Efficiency_Correlation, Cycles, MaxHP, PMEP,
680  *   MeanPistonSpeed_fps
681  *
682  * Outputs: PctPower, HP, FMEP, IndicatedHorsePower
683  */
684
685 void FGPiston::doEnginePower(void)
686 {
687   IndicatedHorsePower = 0;
688   FMEP = 0;
689   if (Running) {
690     // FIXME: this needs to be generalized
691     double ME, percent_RPM, power;  // Convienience term for use in the calculations
692     ME = Mixture_Efficiency_Correlation->GetValue(m_dot_fuel/m_dot_air);
693
694     percent_RPM = RPM/MaxRPM;
695 // Guestimate engine friction losses from Figure 4.4 of "Engines: An Introduction", John Lumley
696     FMEP = (-FMEPDynamic * MeanPistonSpeed_fps * fttom - FMEPStatic);
697
698     power = 1;
699
700     if ( Magnetos != 3 ) power *= SparkFailDrop;
701
702
703     IndicatedHorsePower = (FuelFlow_pph / ISFC )* ME * power;
704
705   } else {
706     // Power output when the engine is not running
707     if (Cranking) {
708       if (RPM < 10) {
709         IndicatedHorsePower = StarterHP;
710       } else if (RPM < IdleRPM*0.8) {
711         IndicatedHorsePower = StarterHP + ((IdleRPM*0.8 - RPM) / 8.0);
712         // This is a guess - would be nice to find a proper starter moter torque curve
713       } else {
714         IndicatedHorsePower = StarterHP;
715       }
716     }
717   }
718
719   // Constant is (1/2) * 60 * 745.7
720   // (1/2) convert cycles, 60 minutes to seconds, 745.7 watts to hp.
721   double pumping_hp = ((PMEP + FMEP) * displacement_SI * RPM)/(Cycles*22371);
722
723   HP = IndicatedHorsePower + pumping_hp - 1.5; //FIXME 1.5 static friction should depend on oil temp and configuration
724 //  cout << "pumping_hp " <<pumping_hp << FMEP << PMEP <<endl;
725   PctPower = HP / MaxHP ;
726 //  cout << "Power = " << HP << "  RPM = " << RPM << "  Running = " << Running << "  Cranking = " << Cranking << endl;
727 }
728
729 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
730 /**
731  * Calculate the exhaust gas temperature.
732  *
733  * Inputs: equivalence_ratio, m_dot_fuel, calorific_value_fuel,
734  *   Cp_air, m_dot_air, Cp_fuel, m_dot_fuel, T_amb, PctPower
735  *
736  * Outputs: combustion_efficiency, ExhaustGasTemp_degK
737  */
738
739 void FGPiston::doEGT(void)
740 {
741   double delta_T_exhaust;
742   double enthalpy_exhaust;
743   double heat_capacity_exhaust;
744   double dEGTdt;
745
746   if ((Running) && (m_dot_air > 0.0)) {  // do the energy balance
747     combustion_efficiency = Lookup_Combustion_Efficiency->GetValue(equivalence_ratio);
748     enthalpy_exhaust = m_dot_fuel * calorific_value_fuel *
749                               combustion_efficiency * 0.33;
750     heat_capacity_exhaust = (Cp_air * m_dot_air) + (Cp_fuel * m_dot_fuel);
751     delta_T_exhaust = enthalpy_exhaust / heat_capacity_exhaust;
752     ExhaustGasTemp_degK = T_amb + delta_T_exhaust;
753     ExhaustGasTemp_degK *= 0.444 + ((0.544 - 0.444) * PctPower);
754   } else {  // Drop towards ambient - guess an appropriate time constant for now
755     combustion_efficiency = 0;
756     dEGTdt = (RankineToKelvin(Atmosphere->GetTemperature()) - ExhaustGasTemp_degK) / 100.0;
757     delta_T_exhaust = dEGTdt * dt;
758     ExhaustGasTemp_degK += delta_T_exhaust;
759   }
760 }
761
762 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
763 /**
764  * Calculate the cylinder head temperature.
765  *
766  * Inputs: T_amb, IAS, rho_air, m_dot_fuel, calorific_value_fuel,
767  *   combustion_efficiency, RPM, MaxRPM, Displacement
768  *
769  * Outputs: CylinderHeadTemp_degK
770  */
771
772 void FGPiston::doCHT(void)
773 {
774   double h1 = -95.0;
775   double h2 = -3.95;
776   double h3 = -140.0; // -0.05 * 2800 (default maxrpm)
777
778   double arbitary_area = Displacement/360.0;
779   double CpCylinderHead = 800.0;
780   double MassCylinderHead = 8.0;
781
782   double temperature_difference = CylinderHeadTemp_degK - T_amb;
783   double v_apparent = IAS * 0.5144444;
784   double v_dot_cooling_air = arbitary_area * v_apparent;
785   double m_dot_cooling_air = v_dot_cooling_air * rho_air;
786   double dqdt_from_combustion =
787     m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
788   double dqdt_forced = (h2 * m_dot_cooling_air * temperature_difference) +
789     (h3 * RPM * temperature_difference / MaxRPM);
790   double dqdt_free = h1 * temperature_difference;
791   double dqdt_cylinder_head = dqdt_from_combustion + dqdt_forced + dqdt_free;
792
793   double HeatCapacityCylinderHead = CpCylinderHead * MassCylinderHead;
794
795   CylinderHeadTemp_degK +=
796     (dqdt_cylinder_head / HeatCapacityCylinderHead) * dt;
797 }
798
799 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
800 /**
801  * Calculate the oil temperature.
802  *
803  * Inputs: CylinderHeadTemp_degK, T_amb, OilPressure_psi.
804  *
805  * Outputs: OilTemp_degK
806  */
807
808 void FGPiston::doOilTemperature(void)
809 {
810   double target_oil_temp;        // Steady state oil temp at the current engine conditions
811   double time_constant;          // The time constant for the differential equation
812   double efficiency = 0.667;     // The aproximate oil cooling system efficiency // FIXME: may vary by engine
813
814 //  Target oil temp is interpolated between ambient temperature and Cylinder Head Tempurature
815 //  target_oil_temp = ( T_amb * efficiency ) + (CylinderHeadTemp_degK *(1-efficiency)) ;
816   target_oil_temp = CylinderHeadTemp_degK + efficiency * (T_amb - CylinderHeadTemp_degK) ;
817
818   if (OilPressure_psi > 5.0 ) {
819     time_constant = 5000 / OilPressure_psi; // Guess at a time constant for circulated oil.
820                                             // The higher the pressure the faster it reaches
821                                             // target temperature.  Oil pressure should be about
822                                             // 60 PSI yielding a TC of about 80.
823   } else {
824     time_constant = 1000;  // Time constant for engine-off; reflects the fact
825                            // that oil is no longer getting circulated
826   }
827
828   double dOilTempdt = (target_oil_temp - OilTemp_degK) / time_constant;
829
830   OilTemp_degK += (dOilTempdt * dt);
831 }
832
833 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
834 /**
835  * Calculate the oil pressure.
836  *
837  * Inputs: RPM, MaxRPM, OilTemp_degK
838  *
839  * Outputs: OilPressure_psi
840  */
841
842 void FGPiston::doOilPressure(void)
843 {
844   double Oil_Press_Relief_Valve = 60; // FIXME: may vary by engine
845   double Oil_Press_RPM_Max = MaxRPM * 0.75;    // 75% of max rpm FIXME: may vary by engine
846   double Design_Oil_Temp = 358;          // degK; FIXME: may vary by engine
847   double Oil_Viscosity_Index = 0.25;
848
849   OilPressure_psi = (Oil_Press_Relief_Valve / Oil_Press_RPM_Max) * RPM;
850
851   if (OilPressure_psi >= Oil_Press_Relief_Valve) {
852     OilPressure_psi = Oil_Press_Relief_Valve;
853   }
854
855   OilPressure_psi += (Design_Oil_Temp - OilTemp_degK) * Oil_Viscosity_Index * OilPressure_psi / Oil_Press_Relief_Valve;
856 }
857
858 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
859
860 string FGPiston::GetEngineLabels(const string& delimiter)
861 {
862   std::ostringstream buf;
863
864   buf << Name << " Power Available (engine " << EngineNumber << " in HP)" << delimiter
865       << Name << " HP (engine " << EngineNumber << ")" << delimiter
866       << Name << " equivalent ratio (engine " << EngineNumber << ")" << delimiter
867       << Name << " MAP (engine " << EngineNumber << " in inHg)" << delimiter
868       << Thruster->GetThrusterLabels(EngineNumber, delimiter);
869
870   return buf.str();
871 }
872
873 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
874
875 string FGPiston::GetEngineValues(const string& delimiter)
876 {
877   std::ostringstream buf;
878
879   buf << PowerAvailable << delimiter << HP << delimiter
880       << equivalence_ratio << delimiter << ManifoldPressure_inHg << delimiter
881       << Thruster->GetThrusterValues(EngineNumber, delimiter);
882
883   return buf.str();
884 }
885
886 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
887 //
888 //    The bitmasked value choices are as follows:
889 //    unset: In this case (the default) JSBSim would only print
890 //       out the normally expected messages, essentially echoing
891 //       the config files as they are read. If the environment
892 //       variable is not set, debug_lvl is set to 1 internally
893 //    0: This requests JSBSim not to output any messages
894 //       whatsoever.
895 //    1: This value explicity requests the normal JSBSim
896 //       startup messages
897 //    2: This value asks for a message to be printed out when
898 //       a class is instantiated
899 //    4: When this value is set, a message is displayed when a
900 //       FGModel object executes its Run() method
901 //    8: When this value is set, various runtime state variables
902 //       are printed out periodically
903 //    16: When set various parameters are sanity checked and
904 //       a message is printed out when they go out of bounds
905
906 void FGPiston::Debug(int from)
907 {
908   if (debug_lvl <= 0) return;
909
910   if (debug_lvl & 1) { // Standard console startup message output
911     if (from == 0) { // Constructor
912
913       cout << "\n    Engine Name: "         << Name << endl;
914       cout << "      MinManifoldPressure: " << MinManifoldPressure_inHg << endl;
915       cout << "      MaxManifoldPressure: " << MaxManifoldPressure_inHg << endl;
916       cout << "      MinMaP (Pa):         " << minMAP << endl;
917       cout << "      MaxMaP (Pa):         " << maxMAP << endl;
918       cout << "      Displacement: "        << Displacement             << endl;
919       cout << "      Bore: "                << Bore                     << endl;
920       cout << "      Stroke: "              << Stroke                   << endl;
921       cout << "      Cylinders: "           << Cylinders                << endl;
922       cout << "      Compression Ratio: "   << CompressionRatio         << endl;
923       cout << "      MaxHP: "               << MaxHP                    << endl;
924       cout << "      Cycles: "              << Cycles                   << endl;
925       cout << "      IdleRPM: "             << IdleRPM                  << endl;
926       cout << "      MaxRPM: "              << MaxRPM                   << endl;
927       cout << "      Throttle Constant: "   << Z_throttle               << endl;
928       cout << "      ISFC: "                << ISFC                     << endl;
929       cout << "      Volumetric Efficiency: " << volumetric_efficiency    << endl;
930       cout << "      PeakMeanPistonSpeed_fps: " << PeakMeanPistonSpeed_fps << endl;
931       cout << "      Intake Impedance Factor: " << Z_airbox << endl;
932       cout << "      Dynamic FMEP Factor: " << FMEPDynamic << endl;
933       cout << "      Static FMEP Factor: " << FMEPStatic << endl;
934
935       cout << endl;
936       cout << "      Combustion Efficiency table:" << endl;
937       Lookup_Combustion_Efficiency->Print();
938       cout << endl;
939
940       cout << endl;
941       cout << "      Mixture Efficiency Correlation table:" << endl;
942       Mixture_Efficiency_Correlation->Print();
943       cout << endl;
944
945     }
946   }
947   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
948     if (from == 0) cout << "Instantiated: FGPiston" << endl;
949     if (from == 1) cout << "Destroyed:    FGPiston" << endl;
950   }
951   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
952   }
953   if (debug_lvl & 8 ) { // Runtime state variables
954   }
955   if (debug_lvl & 16) { // Sanity checking
956   }
957   if (debug_lvl & 64) {
958     if (from == 0) { // Constructor
959       cout << IdSrc << endl;
960       cout << IdHdr << endl;
961     }
962   }
963 }
964 } // namespace JSBSim