C: Battery Discharge Rate

From FSDeveloper Wiki
Jump to navigationJump to search

Updated 16/05/2025 to fix another edge-case bug :-{

//----------------------

There's a long-standing bug in all versions of FS that causes the battery to discharge in under twenty minutes from the time you start to draw power. This is not related to load. Doug Dawson built an XML add-on that fixes the problem; this is the C equivalent that can be dropped into your code. SET_BATTERY_VOLTS is the enumeration name and I call the function from the CLIENT_1SEC event. By habit I prefix all SimConnect functions with 'sc_'.

hr = SimConnect_AddToDataDefinition(hSimConnect, SET_BATTERY_VOLTS, "ELECTRICAL BATTERY VOLTAGE", "Volts", SIMCONNECT_DATATYPE_FLOAT64, 0);
case CLIENT_1SEC:
{
  // Battery charger.
  // - dis_charge_rate = charge or drain rate in percentage of system_voltage per hour e.g. 2.4 will give a 10% charge, -3.6 will give a 15% drain
  // - battery_voltage should contain the current battery voltage obtained from the sim
  // - system_voltage is the battery max value e.g. 24 (volts)
  sc_battery_charger(dis_charge_rate, battery_voltage, system_voltage);
}
break;
// *******************************************************
// Called from the CLIENT_1SEC event.
// Set the battery voltage to avoid a long-standing bug with a sub-twenty minute drain time
// Setting charge_discharge_rate to one hundred percent prevents any battery drain at all
// Setting charge_discharge_rate to zero will discharge at the default rate
// Setting between zero and 99 will charge/discharge at that percentage per hour
// *******************************************************
void sc_battery_charger(double charge_discharge_rate, double current_volts, double target_volts)
{
  double volts_out = 0;
  double rate = 0; 

   // Sanity checks
   if (charge_discharge_rate >= 100.0)
   {
     volts_out = target_volts;		// No discharge
   }
   else if(charge_discharge_rate == 0.0)
   {
     volts_out = current_volts;		// No change
   }
   else if (charge_discharge_rate)
   {
     rate = charge_discharge_rate / 3600; // 3600 = 1 hour
     // Add or subtract the percentage charge to the current voltage
     // Current volts can be negative for a discharge
     volts_out = current_volts + rate;
     // Sanity check
     if (volts_out > target_volts) volts_out = target_volts;
   }

   // Set the voltage on the sim
   if (rate)hres = SimConnect_SetDataOnSimObject(hSimConnect, SET_BATTERY_VOLTS, SIMCONNECT_OBJECT_ID_USER, 0, 1, sizeof(volts_out), &volts_out);

 return;
}