Guest User

SE Ship/Station AI Core v1.2.25 (fixes power values)

a guest
Mar 4th, 2015
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 62.45 KB | None | 0 0
  1. #region CodeEditor
  2.  
  3.  
  4.         /*
  5.  * Full ship/station AI system by Anthropy in February 2015
  6.  * Parts of battery management code originally written by Stiggan and Malakeh in January 2015.
  7.  * There are lots of comments throughout the code to help you along.
  8.  * 100K is a lot of bytes so I'm not afraid to run out of them any time soon.
  9.  * Note however that it's still in heavy development and may radically change with updates.
  10.  */
  11.         //You can change some basic behavior here with these variables.
  12.         //If you want to toggle modules, see the Main() method at the bottom of the file.
  13.  
  14.         //Due to execution limits, we can not enumerate more than about 120 devices per catagory, or the script will simply be halted.
  15.         const int executionCap = 120;
  16.         const string shipName = "ShipAI Core v1.3-WIP";
  17.         const bool ignoreDevicesThatAreTooMuch = true; //Enforces execution cap
  18.         const bool maintenanceMode = false; //Set this to disable alarms on broken blocks
  19.         const string healingProjectorName = "Projector_healing";
  20.  
  21.         #region Variables
  22.         //Cached variables, attempting to only fetch everything a single time throughout program life.
  23.         List<IMyAssembler> assemblers = new List<IMyAssembler>();
  24.         List<IMyRefinery> refineries = new List<IMyRefinery>();
  25.  
  26.         List<IMyTerminalBlock> batteries = new List<IMyTerminalBlock>();
  27.         List<IMyTerminalBlock> solarpanels = new List<IMyTerminalBlock>();
  28.         List<IMyTerminalBlock> reactors = new List<IMyTerminalBlock>();
  29.         List<IMyTerminalBlock> antennas = new List<IMyTerminalBlock>();
  30.         List<IMyTerminalBlock> beacons = new List<IMyTerminalBlock>();
  31.         List<IMyTerminalBlock> turrets = new List<IMyTerminalBlock>();
  32.  
  33.         List<IMyTextPanel> statusPanels = new List<IMyTextPanel>();
  34.         List<IMyTextPanel> iconPanels = new List<IMyTextPanel>();
  35.         IMyTextPanel debugPanel;
  36.         IMyTextPanel storagePanel;
  37.  
  38.         IMyProjector healingProjector;
  39.         Dictionary<string, int> missingBlocks = new Dictionary<string, int>();
  40.  
  41.  
  42.         List<IMySoundBlock> speakersBlue = new List<IMySoundBlock>();
  43.         List<IMySoundBlock> speakersOrange = new List<IMySoundBlock>();
  44.         List<IMySoundBlock> speakersRed = new List<IMySoundBlock>();
  45.         List<IMySoundBlock> speakersPowerlow = new List<IMySoundBlock>();
  46.        
  47.  
  48.  
  49.         public double wattHourInBatteries = 0;
  50.         public double maxWattHourInBatteries = 0;
  51.  
  52.         public double solarpanelWatts = 0;
  53.         public double reactorWatts = 0;
  54.         public double batteryWatts = 0;
  55.         public double batteryInputWatts = 0;
  56.  
  57.         public double maxPower = 0;  
  58.         public double powerUsage = 0;
  59.  
  60.         public int dischargingBatteries = 0;
  61.         public int brokenBlockCount = 0;
  62.         public int offlineBlockCount = 0;
  63.         public int missingBlockCount = 0;
  64.         int activeAssemblers = 0;
  65.         int activeRefineries = 0;
  66.         int currentInternalIteration; //This is used to trigger things like purging old modules and such, and distribute load across iterations. Should never go higher than 10.
  67.  
  68.         public bool tooManyBatteries = false;
  69.         public bool tooManyReactors = false;
  70.         public bool tooManySolarpanels = false;
  71.         public bool tooManyAntennas = false;
  72.         public bool tooManyBeacons = false;
  73.         public bool isScreenModulePresent = false;
  74.         public bool isProjectorPresent = false;
  75.  
  76.         public string alertState = "";
  77.         public string powerState = ""; //This is NOT the message, this is the internal powerstate of the AI!
  78.         public string antennaString = "";
  79.         public string beaconString = "";
  80.         public string StatusString = "";
  81.         public string shortStatus = "";
  82.         public string damageReport = "";
  83.         public string offlineReport = "";
  84.         //public string missingReport; //I implemented everything, only to realize I don't even have the data :v..
  85.         public string powerReport = ""; //This is the message, NOT the internal powerstate!
  86.         public string shortCommsStatus = "";
  87.  
  88.         //Below here are technically variables, but they mask a var from ai_storage. don't use them more than needed.
  89.         public bool codeBlue
  90.         {
  91.             get { return alertState.Equals("blue"); }
  92.             set
  93.             {
  94.                 if (value)
  95.                 {
  96.                     alertState = "blue";
  97.                 }
  98.                 else
  99.                 {
  100.                     alertState = "none";
  101.                 }
  102.             }
  103.         }
  104.         public bool codeOrange
  105.         {
  106.             get { return alertState.Equals("orange"); }
  107.             set
  108.             {
  109.                 if (value)
  110.                 {
  111.                     alertState = "orange";
  112.                 }
  113.                 else
  114.                 {
  115.                     alertState = "none";
  116.                 }
  117.             }
  118.         }
  119.         public bool codeRed
  120.         {
  121.             //the easteregg here has been removed due to potential issues with the screen module template engine.
  122.             get { return getVariable("alertState").Equals("red"); }
  123.             set
  124.             {
  125.                 if (value)
  126.                 {
  127.                     storeVariable("alertState", "red");
  128.                 }
  129.                 else
  130.                 {
  131.                     storeVariable("alertState", "none");
  132.                 }
  133.             }
  134.         }
  135.  
  136.         #endregion
  137.  
  138.  
  139.         #region variableUpdaters
  140.         void updateSpeakers()
  141.         {
  142.             debugOutput("Updating speakers..");
  143.             List<IMyTerminalBlock> templist = new List<IMyTerminalBlock>();
  144.             GridTerminalSystem.GetBlocksOfType<IMySoundBlock>(templist);
  145.             speakersRed.Clear();
  146.             speakersOrange.Clear();
  147.             speakersBlue.Clear();
  148.             for (int i = 0; i < templist.Count; i++)
  149.             {
  150.                 if (!templist[i].DisplayNameText.EndsWith("_unmanaged"))
  151.                 {
  152.                     if (templist[i].DisplayNameText.EndsWith("_blue"))
  153.                     {
  154.                         speakersBlue.Add((IMySoundBlock)templist[i]);
  155.                     }
  156.                     else if (templist[i].DisplayNameText.EndsWith("_orange"))
  157.                     {
  158.                         speakersOrange.Add((IMySoundBlock)templist[i]);
  159.                     }
  160.                     else if (templist[i].DisplayNameText.EndsWith("_red"))
  161.                     {
  162.                         speakersRed.Add((IMySoundBlock)templist[i]);
  163.                     }
  164.                 }
  165.             }
  166.  
  167.  
  168.             debugOutput(string.Format("Found {0} blue, {1} orange, {2} red speakers.", speakersBlue.Count, speakersOrange.Count, speakersRed.Count));
  169.         }
  170.  
  171.         /// <summary>
  172.         /// All external modules must check in every 10 iterations to make sure they're still OK
  173.         /// </summary>
  174.         void updateModules()
  175.         {
  176.  
  177.             var screenModuleMessage = getVariable("screenModuleStatus") ;
  178.             if (screenModuleMessage == "Red one standing by.")
  179.             {
  180.                 isScreenModulePresent = screenModuleMessage == "Red one standing by.";
  181.             }
  182.             else
  183.             {
  184.                 debugOutput("No screen module found");
  185.             }
  186.             //storeVariable("", "screenModuleStatus"); //Reset the var so the Screen module has to check in again.
  187.         }
  188.  
  189.         void updateLCDPanels()
  190.         {
  191.             debugPanel = (IMyTextPanel)GridTerminalSystem.GetBlockWithName("debugpanel");
  192.             storagePanel = (IMyTextPanel)GridTerminalSystem.GetBlockWithName("ai_storage");
  193.             if (storagePanel == null)
  194.             {
  195.                 debugOutput("ERROR: NO STORAGE FOUND. Throwing exception..");
  196.                 debugOutput("Please create an LCD panel named 'ai_storage'.");
  197.                 debugOutput("Storage is required for proper functioning of the AI.");
  198.                 throw new Exception("No storage found!\nPlease create an LCD panel named 'ai_storage', edit the script and Remember and Exit again.\nCreate a panel named 'debugpanel' for more info.");
  199.             }
  200.             if (debugPanel != null) { debugPanel.WritePublicText(""); }
  201.  
  202.             debugOutput("Updating LCD Panels..");
  203.             List<IMyTerminalBlock> templist = new List<IMyTerminalBlock>();
  204.             GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(templist);
  205.  
  206.             statusPanels.Clear();
  207.             iconPanels.Clear();
  208.  
  209.  
  210.             for (int i = 0; i < templist.Count; i++)
  211.             {
  212.                 if (!templist[i].DisplayNameText.EndsWith("_unmanaged"))
  213.                 {
  214.                     if (templist[i].DisplayNameText.EndsWith("_status"))
  215.                     {
  216.                         statusPanels.Add((IMyTextPanel)templist[i]);
  217.                     }
  218.                     else if (templist[i].DisplayNameText.EndsWith("_icons") || templist[i].DisplayNameText.EndsWith("_icon"))
  219.                     {
  220.                         iconPanels.Add((IMyTextPanel)templist[i]);
  221.                     }
  222.                 }
  223.             }
  224.         }
  225.  
  226.         void updateRefineries()
  227.         {
  228.            
  229.             activeRefineries = 0;
  230.             if (debugPanel != null)
  231.             {
  232.                 debugPanel.WritePublicText("Updating refineries..", true);
  233.             }
  234.             refineries = getRefineries();
  235.             for (int i = 0; i < refineries.Count; i++)
  236.             {
  237.                 if (!refineries[i].DisplayNameText.EndsWith("_unmanaged"))
  238.                 {
  239.                     if (refineries[i].IsProducing) { activeRefineries++; }
  240.                 }
  241.             }
  242.             if (debugPanel != null)
  243.             {
  244.                 debugPanel.WritePublicText(refineries.Count + " found.\n", true);
  245.             }
  246.         }
  247.  
  248.         void updateAssemblers()
  249.         {
  250.             activeAssemblers = 0;
  251.             if (debugPanel != null)
  252.             {
  253.                 debugPanel.WritePublicText("Updating assemblers..", true);
  254.             }
  255.  
  256.             assemblers = getAssemblers();
  257.             for (int i = 0; i < assemblers.Count; i++)
  258.             {
  259.                 if (!assemblers[i].DisplayNameText.EndsWith("_unmanaged"))
  260.                 {
  261.                     if (assemblers[i].IsProducing) { activeAssemblers++; }
  262.                 }
  263.             }
  264.             if (debugPanel != null)
  265.             {
  266.                 debugPanel.WritePublicText(assemblers.Count + " found.\n", true);
  267.             }
  268.         }
  269.  
  270.         void updateBrokenBlocks()
  271.         {
  272.             if (healingProjector == null)
  273.             {
  274.                 debugOutput("No projector found, cannot update broken blocks!");
  275.                 return;
  276.             }
  277.             missingBlocks = new Dictionary<string, int>();
  278.             missingBlockCount = 0;
  279.  
  280.             string[] tempLines = ((IMyTerminalBlock)healingProjector).DetailedInfo.Split('\n');
  281.             bool a = false;
  282.             for (int i = 0; i < tempLines.Length; i++)
  283.             {
  284.                 if (tempLines[i] == "Blocks remaining:") { a = true; continue; }
  285.  
  286.                 if (a)
  287.                 {
  288.                     string[] tempParts = tempLines[i].Split(':');
  289.                     int parsedCount = 0;
  290.                     if (tempParts[1].Length > 0)
  291.                     {
  292.                         int.TryParse(tempParts[1].Trim(), out parsedCount);
  293.                     }
  294.                     missingBlocks.Add(tempParts[0], parsedCount);
  295.                     missingBlockCount += parsedCount;
  296.                 }
  297.             }
  298.         }
  299.  
  300.         void updateMiscWithBlacklist()
  301.         {
  302.             debugOutput("Updating Misc items..");
  303.             if (alertState == null)
  304.             {
  305.                 storeVariable("none", "alertState");
  306.                 debugOutput("alertstate persistent variable created");
  307.             }
  308.             if (powerState == null)
  309.             {
  310.                 storeVariable("none", "powerState");
  311.                 debugOutput("powerstate persistent variable created");
  312.             }
  313.  
  314.             healingProjector = (IMyProjector)GridTerminalSystem.GetBlockWithName(healingProjectorName);
  315.             if (healingProjector == null)
  316.             {
  317.                 debugOutput("No projector found! " + healingProjectorName);
  318.             }
  319.             else
  320.             {
  321.                 debugOutput("Found projector: " + ((IMyTerminalBlock)healingProjector).DisplayNameText);
  322.                 isProjectorPresent = true;
  323.             }
  324.  
  325.  
  326.             batteries.Clear();
  327.             solarpanels.Clear();
  328.             reactors.Clear();
  329.             beacons.Clear();
  330.             antennas.Clear();
  331.  
  332.             List<IMyTerminalBlock> newlist = new List<IMyTerminalBlock>();
  333.             GridTerminalSystem.GetBlocksOfType<IMyBatteryBlock>(batteries);
  334.             for (int i = 0; i < batteries.Count; i++)
  335.             { if (!batteries[i].DisplayNameText.EndsWith("_unmanaged"))
  336.             { newlist.Add(batteries[i]); } if (i > executionCap) { tooManyBatteries = true; if (ignoreDevicesThatAreTooMuch) { debugOutput("Ignoring batteries out of processing range."); break; } }
  337.             } debugOutput(newlist.Count + " batteries found.");
  338.             batteries.Clear(); batteries = newlist; newlist = new List<IMyTerminalBlock>();
  339.             GridTerminalSystem.GetBlocksOfType<IMySolarPanel>(solarpanels);
  340.             for (int i = 0; i < solarpanels.Count; i++)
  341.             { if (!solarpanels[i].DisplayNameText.EndsWith("_unmanaged"))
  342.             { newlist.Add(solarpanels[i]); if (i > executionCap) { tooManySolarpanels = true; if (ignoreDevicesThatAreTooMuch) { debugOutput("Ignoring solarpanels out of processing range."); break; } } }
  343.             }
  344.             solarpanels.Clear(); solarpanels = newlist; newlist = new List<IMyTerminalBlock>();
  345.             GridTerminalSystem.GetBlocksOfType<IMyReactor>(reactors);
  346.             for (int i = 0; i < reactors.Count; i++)
  347.             { if (!reactors[i].DisplayNameText.EndsWith("_unmanaged"))
  348.             { newlist.Add(reactors[i]); if (i > executionCap) { tooManyReactors = true; if (ignoreDevicesThatAreTooMuch) { debugOutput("Ignoring reactors out of processing range."); break; } } }
  349.             }
  350.             reactors.Clear(); reactors = newlist; newlist = new List<IMyTerminalBlock>();
  351.             GridTerminalSystem.GetBlocksOfType<IMyBeacon>(beacons);
  352.             for (int i = 0; i < beacons.Count; i++)
  353.             { if (!beacons[i].DisplayNameText.EndsWith("_unmanaged"))
  354.             { newlist.Add(beacons[i]); if (i > executionCap) { tooManyBeacons = true; if (ignoreDevicesThatAreTooMuch) { debugOutput("Ignoring beacons out of processing range."); break; } } }
  355.             }
  356.             beacons.Clear(); beacons = newlist; newlist = new List<IMyTerminalBlock>();
  357.             GridTerminalSystem.GetBlocksOfType<IMyRadioAntenna>(antennas);
  358.             for (int i = 0; i < antennas.Count; i++)
  359.             { if (!antennas[i].DisplayNameText.EndsWith("_unmanaged"))
  360.             { newlist.Add(antennas[i]); if (i > executionCap) { tooManyAntennas = true; if (ignoreDevicesThatAreTooMuch) { debugOutput("Ignoring beacons out of processing range."); break; } } }
  361.             }
  362.             antennas.Clear(); antennas = newlist; newlist = new List<IMyTerminalBlock>();
  363.  
  364.             wattHourInBatteries = getWattHourInBatteries();
  365.             maxWattHourInBatteries = getMaxWattHourInBatteries();
  366.             solarpanelWatts = solarPower(true);
  367.             reactorWatts = reactorPower(true);
  368.             batteryWatts = batteryPower();
  369.             batteryInputWatts = batteryPowerInput();
  370.             maxPower = reactorWatts + solarpanelWatts;
  371.             powerUsage = reactorPower(false) + solarPower(false) + batteryWatts;
  372.             dischargingBatteries = getDischargingBatteryCount();
  373.             debugOutput("Done.");
  374.         }
  375.  
  376.         void updateScreenModuleValues()
  377.         {
  378.             //Layout below should be EXACTLY that of the above Variables region!
  379.             //This is to make sure discrependancies are easily spotted.
  380.             debugOutput("Writing missing blockcounts");
  381.             storeVariable(serializeDictionary(missingBlocks), "missingBlocks");
  382.            
  383.             debugOutput("Writing power values");
  384.             storeVariable(wattHourInBatteries.ToString(), "wattHourInBatteries");
  385.             storeVariable(maxWattHourInBatteries.ToString(), "maxWattHourInBatteries");
  386.  
  387.             storeVariable(solarpanelWatts.ToString(), "solarpanelWatts");
  388.             storeVariable(solarPower(true).ToString(), "solarpanelMaxWatts");
  389.             storeVariable(reactorWatts.ToString(), "reactorWatts");
  390.             storeVariable(reactorPower(true).ToString(), "reactorMaxWatts");
  391.             storeVariable(batteryWatts.ToString(), "batteryWatts");
  392.             storeVariable(batteryPower(true).ToString(), "batteryMaxWatts");
  393.             storeVariable(batteryInputWatts.ToString(), "batteryInputWatts");
  394.             storeVariable(batteryPower(true).ToString(), "batteryInputMaxWatts");
  395.  
  396.             storeVariable(maxPower.ToString(), "maxPower");
  397.             storeVariable(powerUsage.ToString(), "powerUsage");
  398.            
  399.             debugOutput("Writing block counts");
  400.             storeVariable(reactors.Count.ToString(), "reactorCount");
  401.             storeVariable(solarpanels.Count.ToString(), "solarpanelCount");
  402.             storeVariable(batteries.Count.ToString(), "batteryCount");
  403.             storeVariable(refineries.Count.ToString(), "refineryCount");
  404.             storeVariable(assemblers.Count.ToString(), "assemblerCount");
  405.             storeVariable(antennas.Count.ToString(), "antennaCount");
  406.             storeVariable(beacons.Count.ToString(), "beaconCount");
  407.  
  408.  
  409.             debugOutput("Writing meta blockcounts");
  410.             storeVariable(dischargingBatteries.ToString(), "dischargingBatteries");
  411.             storeVariable(wattHourInBatteries.ToString(), "brokenBlockCount");
  412.             storeVariable(offlineBlockCount.ToString(), "offlineBlockCount");
  413.             storeVariable(missingBlockCount.ToString(), "missingBlockCount");
  414.             storeVariable(activeAssemblers.ToString(), "activeAssemblers");
  415.             storeVariable(activeRefineries.ToString(), "activeRefineries");
  416.             storeVariable(currentInternalIteration.ToString(), "currentInternalIteration");
  417.  
  418.             debugOutput("Writing booleans");
  419.             storeVariable(tooManyBatteries.ToString(), "tooManyBatteries");
  420.             storeVariable(tooManyReactors.ToString(), "tooManyReactors");
  421.             storeVariable(tooManySolarpanels.ToString(), "tooManySolarpanels");
  422.             storeVariable(tooManyAntennas.ToString(), "tooManyAntennas");
  423.             storeVariable(tooManyBeacons.ToString(), "tooManyBeacons");
  424.  
  425.             debugOutput("Writing strings");
  426.             storeVariable(shipName, "shipName");
  427.  
  428.             storeVariable(alertState, "alertState");
  429.             storeVariable(powerState, "powerState");
  430.             storeVariable(antennaString, "antennaString");
  431.             storeVariable(beaconString, "beaconString");
  432.             storeVariable(StatusString, "StatusString");
  433.             storeVariable(shortStatus, "shortStatus");
  434.             storeVariable(damageReport, "damageReport");
  435.             storeVariable(offlineReport, "offlineReport");
  436.             //storeVariable(missingReport, "missingReport");
  437.             storeVariable(powerReport, "powerReport");
  438.             storeVariable(shortCommsStatus, "shortCommsStatus");
  439.  
  440.  
  441.             debugOutput("Done writing values to disk");
  442.         }
  443.  
  444.  
  445.         #endregion
  446.  
  447.  
  448.         #region internalFunctions
  449.         /// <summary>
  450.         /// Original function written by Stiggan/Malekeh, took from the Battery management script.
  451.         /// Splits down the DetailedInfo field of a block and retrieves the value corresponding to the given name of a field.
  452.         /// </summary>
  453.         /// <param name="block"></param>
  454.         /// <param name="name"></param>
  455.         /// <returns></returns>
  456.         public string getDetailedInfoValue(IMyTerminalBlock block, string name)
  457.         {
  458.             string value = "";
  459.             string[] lines = block.DetailedInfo.Split('\n');
  460.             for (int i = 0; i < lines.Length; i++)
  461.             {
  462.                 string[] line = lines[i].Split(':');
  463.                 if (line[0].Equals(name))
  464.                 {
  465.                     value = line[1].Trim();
  466.                     break;
  467.                 }
  468.             }
  469.             return value;
  470.         }
  471.  
  472.         public string generateReportFromDictionary(Dictionary<string, int> dict)
  473.         {
  474.             string toReturn = "";
  475.             string[] keys = new string[dict.Keys.Count];
  476.             int[] values = new int[dict.Values.Count];
  477.             dict.Keys.CopyTo(keys, 0);
  478.             dict.Values.CopyTo(values, 0);
  479.             for (int i = 0; i < dict.Count; i++)
  480.             {
  481.                 toReturn += string.Format("\n  >Missing {0}: {1}", keys[i], values[i]);
  482.             }
  483.             return toReturn;
  484.         }
  485.  
  486.         public bool detailExist(IMyTerminalBlock block, string name)
  487.         {
  488.             return !String.IsNullOrEmpty(getDetailedInfoValue(block, name));
  489.         }
  490.  
  491.         /// <summary>
  492.         /// Internal function to convert a string like "2.00 MWh" or "536 W" to a normalized double value in watts.
  493.         /// </summary>
  494.         /// <param name="text"></param>
  495.         /// <param name="hour">Whether or not you're retrieving a battery value, e.g 203.12 KWh. </param>
  496.         /// <returns>A normalized double value in watt(hour)s</returns>
  497.         public double getPowerAsDouble(string text, bool hour = false)
  498.         {
  499.             string h = "";
  500.             if (hour) { h = "h"; }
  501.             double totalPowerWatts = 0;
  502.             if (String.IsNullOrWhiteSpace(text))
  503.             {
  504.                 return 0;
  505.             }
  506.             var splittedStoredPower = text.ToLower().Split(' ');
  507.             if (splittedStoredPower[1] == "mw" + h)
  508.             {
  509.                 totalPowerWatts += double.Parse(splittedStoredPower[0]) * 1000000;
  510.             }
  511.             else if (splittedStoredPower[1] == "gw" + h)
  512.             {
  513.                 totalPowerWatts += double.Parse(splittedStoredPower[0]) * 1000000000;
  514.             }
  515.             else if (splittedStoredPower[1] == "kw" + h)
  516.             {
  517.                 totalPowerWatts += double.Parse(splittedStoredPower[0]) * 1000;
  518.  
  519.             }
  520.             else if (splittedStoredPower[1] == "w" + h)
  521.             {
  522.                 totalPowerWatts += double.Parse(splittedStoredPower[0]);
  523.  
  524.             }
  525.             return totalPowerWatts;
  526.         }
  527.  
  528.         public bool isHealthy(IMyTerminalBlock block)
  529.         {
  530.             return (block.IsFunctional && block.IsWorking);
  531.         }
  532.  
  533.         /// <summary>
  534.         /// Gets the current power drawn from the batteries.
  535.         /// </summary>
  536.         /// <returns></returns>
  537.         public double batteryPower(bool max = false)
  538.         {
  539.             double output = 0;
  540.             for (int i = 0; i < batteries.Count; i++)
  541.             {
  542.                 if (isHealthy(batteries[i]) && ((IMyFunctionalBlock)batteries[i]).Enabled && !max)
  543.                 {
  544.                     output += getPowerAsDouble(getDetailedInfoValue(batteries[i], "Current Output"));
  545.                     output -= getPowerAsDouble(getDetailedInfoValue(batteries[i], "Current Input"));
  546.                 }
  547.                 else if (max){
  548.                     output += getPowerAsDouble(getDetailedInfoValue(batteries[i], "Max Output"));
  549.                 }
  550.             }
  551.             return output;
  552.         }
  553.  
  554.         public double batteryPowerInput(bool max = false)
  555.         {
  556.             double output = 0;
  557.             if (!max)
  558.             {
  559.                 for (int i = 0; i < batteries.Count; i++)
  560.                 {
  561.                     output += getPowerAsDouble(getDetailedInfoValue(batteries[i], "Current Input"));
  562.                 }
  563.             }
  564.             else
  565.             {
  566.                 for (int i = 0; i < batteries.Count; i++)
  567.                 {
  568.                     output += getPowerAsDouble(getDetailedInfoValue(batteries[i], "Max Required Input"));
  569.                 }
  570.             }
  571.             return output;
  572.         }
  573.  
  574.         public bool healthyReactor(IMyTerminalBlock b)
  575.         {
  576.             // Abusing unfinished reactors not displaying Current Output field.
  577.             return isHealthy(b) && detailExist(b, "Current Output");
  578.         }
  579.  
  580.         /// <summary>
  581.         /// Prints a line to the debugpanel, if there is one (doesn't throw exceptions)
  582.         /// </summary>
  583.         /// <param name="output"></param>
  584.         void debugOutput(string output)
  585.         {
  586.             if (debugPanel != null)
  587.             {
  588.                 debugPanel.WritePublicText(output + "\n", true);
  589.                 if (debugPanel.GetPublicText().Length > 1000)
  590.                 {
  591.                     debugPanel.WritePublicText("WARNING: Debug log truncated due to size!\n");
  592.                 }
  593.             }
  594.  
  595.         }
  596.  
  597.         public double getPower(IMyTerminalBlock block, bool max)
  598.         {
  599.             if (max)
  600.             {
  601.                 if (!block.IsBeingHacked)
  602.                 {
  603.                     return getPowerAsDouble(getDetailedInfoValue(block, "Max Output"));
  604.                 }
  605.             }
  606.             else
  607.             {
  608.                 return getPowerAsDouble(getDetailedInfoValue(block, "Current Output"));
  609.             }
  610.             return 0;
  611.         }
  612.  
  613.         public int getDischargingBatteryCount()
  614.         {
  615.             int dischargingBats = 0;
  616.             for (int i = 0; i < batteries.Count; i++)
  617.             {
  618.                 var bat = (IMyBatteryBlock)batteries[i];
  619.                 if (!isRecharging(bat))
  620.                 {
  621.                     dischargingBats++;
  622.                 }
  623.             }
  624.             return dischargingBats;
  625.         }
  626.  
  627.         public double reactorPower(bool max)
  628.         {
  629.             double power = 0;
  630.             for (int i = 0; i < reactors.Count; i++)
  631.             {
  632.                 if (healthyReactor(reactors[i]) && ((IMyFunctionalBlock)reactors[i]).Enabled)
  633.                 {
  634.                     power += getPower(reactors[i], max);
  635.                 }
  636.             }
  637.             return power;
  638.         }
  639.  
  640.         public double solarPower(bool max)
  641.         {
  642.             double power = 0;
  643.             for (int i = 0; i < solarpanels.Count; i++)
  644.             {
  645.                 if (isHealthy(solarpanels[i]))
  646.                 {
  647.                     power += getPower(solarpanels[i], max);
  648.                 }
  649.             }
  650.             return power;
  651.         }
  652.  
  653.         public bool isRecharging(IMyTerminalBlock block)
  654.         {
  655.             return detailExist(block, "Fully recharged in");
  656.         }
  657.  
  658.         public void chargeAllBatteries()
  659.         {
  660.             debugOutput("Setting all but one battery to charge.");
  661.             dischargingBatteries = 0;
  662.             for (int i = 0; i < batteries.Count; i++)
  663.             {
  664.                 if (dischargingBatteries > 0) //Make sure there's at least one battery always on to prevent blackouts.
  665.                 {
  666.                     batteries[i].GetActionWithName("Recharge").Apply(batteries[i]);
  667.                 }
  668.                 else { dischargingBatteries++; }
  669.             }
  670.         }
  671.  
  672.         public void toggleRandomBattery()
  673.         {
  674.             Random rnd = new Random();
  675.             int i = rnd.Next(0, batteries.Count);
  676.             if (i < batteries.Count)
  677.             {
  678.                 if (!isRecharging(batteries[i]) && dischargingBatteries < 2) //If we're requested to toggle the only currently online battery
  679.                 {
  680.                     if (batteries.Count < 2) //And there's no other batteries available
  681.                     {
  682.                         debugOutput("There are no secondary batteries available. This means there's no protection against blackouts. Toggling anyway.");
  683.                         batteries[i].GetActionWithName("Recharge").Apply(batteries[i]);
  684.                     }
  685.                     else
  686.                     {
  687.                         //First enable a different battery to make sure there are no blackouts.
  688.                         int tryingBat = 0;
  689.                         bool success = false;
  690.                         int retries = 0;
  691.                         while (!success)
  692.                         {
  693.                             tryingBat = rnd.Next(0, batteries.Count);
  694.                             if (isRecharging(batteries[tryingBat]) && tryingBat != i)
  695.                             {
  696.                                 debugOutput("Turning on secondary battery to prevent blackouts");
  697.                                 batteries[tryingBat].GetActionWithName("Recharge").Apply(batteries[tryingBat]);
  698.                                 success = true;
  699.                                 //We can't check if this has worked within the same cycle, the status updates too slow.
  700.                                 //So we can't do anything else here.
  701.                             }
  702.                             retries++;
  703.                             if (retries > 10) { debugOutput("FIXME: Loop detected"); break; } //Against infinity and beyond..
  704.                         }
  705.                     }
  706.                 }
  707.                 else
  708.                 {
  709.                     debugOutput(string.Format("Toggling random {0}", batteries[i].DisplayNameText));
  710.                     batteries[i].GetActionWithName("Recharge").Apply(batteries[i]);
  711.                    
  712.                 }
  713.             }
  714.         }
  715.  
  716.         /// <summary>
  717.         /// Get normalized power string, in watts, kilowatts, megawatts, or gigawatts.
  718.         /// </summary>
  719.         /// <param name="watts">Raw value in watts</param>
  720.         /// <param name="hour">Whether or not to add an h to the end of the string</param>
  721.         /// <returns></returns>
  722.         public string getNormalizedPowerString(double watts, bool hour)
  723.         {
  724.             string h = "";
  725.             if(hour){ h = "h";}
  726.             if (watts > 1000000000)
  727.             {
  728.                 return string.Format("{0}Gw{1}", watts / 1000000000, h);
  729.             }
  730.             else if (watts > 1000000)
  731.             {
  732.                 return string.Format("{0}Mw{1}", watts / 1000000, h);
  733.             }
  734.             else if (watts > 1000)
  735.             {
  736.                 return string.Format("{0}Kw{1}", watts / 1000, h);
  737.             }
  738.             else
  739.             {
  740.                 return string.Format("{0}w{1}", watts, h);
  741.             }
  742.         }
  743.  
  744.         string getDamageReport(bool listOfflineBlocks)
  745.         {
  746.             StringBuilder report = new StringBuilder();
  747.             brokenBlockCount = 0;
  748.             offlineBlockCount = 0;
  749.             for (int i = 0; i < GridTerminalSystem.Blocks.Count; i++)
  750.             {
  751.                 if (!GridTerminalSystem.Blocks[i].IsFunctional)
  752.                 {
  753.                     report.AppendFormat("\n  >{0} is not functional.", GridTerminalSystem.Blocks[i].DisplayNameText);
  754.                     brokenBlockCount++;
  755.                     codeBlue = true; //Alert for damaged blocks
  756.                     debugOutput("set codeOrange to " + codeOrange.ToString());
  757.                 }
  758.                 if (!GridTerminalSystem.Blocks[i].IsWorking && GridTerminalSystem.Blocks[i].IsFunctional)
  759.                 {
  760.                     if (listOfflineBlocks)
  761.                     {
  762.                         report.AppendFormat("\n  -{0} is offline.", GridTerminalSystem.Blocks[i].DisplayNameText);
  763.                     }
  764.                     offlineBlockCount++;
  765.                 }
  766.             }
  767.             if (brokenBlockCount < 1 && codeBlue)
  768.             {
  769.                 codeBlue = false; //Turn off alarm again
  770.             }
  771.  
  772.             return report.ToString();
  773.         }
  774.  
  775.  
  776.  
  777.         /// <summary>
  778.         /// As proud as I am of this function I really hope it becomes legacy fast, KeenSWH. :L
  779.         /// </summary>
  780.         /// <returns>Amount of KWh in all the batteries</returns>
  781.         public double getWattHourInBatteries()
  782.         {
  783.             var screen = (IMyTextPanel)GridTerminalSystem.GetBlockWithName("debugpanel");
  784.  
  785.             if (batteries.Count < 1) { return 0; }
  786.             //Note: Function does not support ranges in terawatts. Add support if necessary.
  787.             double totalPowerWatts = 0;
  788.             for (int y = 0; y < batteries.Count; y++)
  789.             {
  790.                 var storedPower = getDetailedInfoValue(batteries[y], "Stored power");
  791.                 //screen.WritePublicText(storedPower.Replace("kWh", "").Trim(), false); //Debugging line.
  792.                 totalPowerWatts += getPowerAsDouble(storedPower, true);
  793.             }
  794.  
  795.  
  796.             return totalPowerWatts;
  797.         }
  798.  
  799.         /// <summary>
  800.         /// Gets the maximum amount of energy stored in all batteries (i.e full capacity)
  801.         /// </summary>
  802.         /// <returns></returns>
  803.         public double getMaxWattHourInBatteries()
  804.         {
  805.             var screen = (IMyTextPanel)GridTerminalSystem.GetBlockWithName("debugpanel");
  806.  
  807.             if (batteries.Count < 1) { return 0; }
  808.             double totalPowerWatts = 0;
  809.             for (int y = 0; y < batteries.Count; y++)
  810.             {
  811.                 var storedPower = getDetailedInfoValue(batteries[y], "Max Stored Power");
  812.                 //screen.WritePublicText(storedPower.Replace("kWh", "").Trim(), false); //Debugging line.
  813.                 totalPowerWatts += getPowerAsDouble(storedPower, true);
  814.             }
  815.  
  816.  
  817.             return totalPowerWatts;
  818.         }
  819.  
  820.  
  821.         public List<IMyRefinery> getRefineries()
  822.         {
  823.             List<IMyTerminalBlock> a = new List<IMyTerminalBlock>();
  824.             GridTerminalSystem.GetBlocksOfType<IMyRefinery>(a);
  825.             List<IMyRefinery> refineries = new List<IMyRefinery>();
  826.             for (int i = 0; i < a.Count; i++)
  827.             {
  828.                 refineries.Add((IMyRefinery)a[i]);
  829.             }
  830.             return refineries;
  831.         }
  832.  
  833.         public List<IMyAssembler> getAssemblers()
  834.         {
  835.             List<IMyTerminalBlock> a = new List<IMyTerminalBlock>();
  836.             GridTerminalSystem.GetBlocksOfType<IMyAssembler>(a);
  837.             List<IMyAssembler> assemblers = new List<IMyAssembler>();
  838.             for (int i = 0; i < a.Count; i++)
  839.             {
  840.                 assemblers.Add((IMyAssembler)a[i]);
  841.             }
  842.             return assemblers;
  843.         }
  844.  
  845.         public string serializeDictionary(Dictionary<string, int> dict)
  846.         {
  847.             string output = "";
  848.             string[] keys = new string[dict.Keys.Count];
  849.             int[] values = new int[dict.Values.Count];
  850.             dict.Keys.CopyTo(keys, 0);
  851.             dict.Values.CopyTo(values, 0);
  852.             for (int i = 0; i < dict.Count; i++)
  853.             {
  854.                 output += "\n" + keys[i] + ":" + values[i].ToString();
  855.             }
  856.             return output;
  857.         }
  858.  
  859.         public Dictionary<string, int> deserializeDictionary(string input)
  860.         {
  861.             Dictionary<string, int> returndict = new Dictionary<string, int>();
  862.             string[] inputLines = input.Split('\n');
  863.             for (int i = 0; i < inputLines.Length - 1; i++)
  864.             {
  865.                 if (inputLines[i].Length < 1) { continue; }
  866.                 string[] inputLineParts = inputLines[i].Split(':');
  867.                 if (inputLineParts.Length > 0)
  868.                 {
  869.                     returndict.Add(inputLineParts[0], int.Parse(inputLineParts[1]));
  870.                 }
  871.             }
  872.  
  873.             return returndict;
  874.         }
  875.  
  876.  
  877.  
  878.         //Stores a variable using a LCD panel named 'ai_storage'.
  879.         //Colons and newlines can now be used, as I'm substituting them internally.
  880.         void storeVariable(string variable, string name)
  881.         {
  882.             variable = variable.Replace(":", "[COLON]").Replace("\n", "[NEWLINE]");
  883.             List<string> c = new List<string>();
  884.             string b = storagePanel.GetPublicText();
  885.             string oldvar;
  886.             if (b.Contains(name + ":"))
  887.             {
  888.                 oldvar = getVariable(name).Replace(":", "[COLON]").Replace("\n", "[NEWLINE]");
  889.                 b = b.Replace(name + ":" + oldvar, name + ":" + variable);
  890.             }
  891.             else
  892.             {
  893.                 b += "\n"+ name + ":" + variable;
  894.             }
  895.  
  896.             storagePanel.WritePublicText(b);
  897.             //storeVariable is called too much to always log on AI core.
  898.             //debugOutput(string.Format("storeVariable(): {0} '{1}'", name, variable));
  899.         }
  900.  
  901.         //Retrieves a variables from the ai_storage LCD panel.
  902.         string getVariable(string name)
  903.         {
  904.             List<string> b = new List<string>();
  905.             b.AddRange(storagePanel.GetPublicText().Split('\n'));
  906.             string toReturn = null;
  907.             for (int i = 0; i < b.Count; i++)
  908.             {
  909.                 if (b[i].StartsWith(name))
  910.                 {
  911.                     toReturn = b[i].Split(':')[1].Replace("[NEWLINE]", "\n").Replace("[COLON]", ":");
  912.                     break;
  913.                 }
  914.             }
  915.             if (toReturn == null)
  916.             {
  917.                 debugOutput(string.Format("No variable '{0}' found.", name));
  918.             }
  919.             else
  920.             {
  921.                
  922.                 //This is too heavily used to always debug. Turn on if necessary.
  923.                 //debugOutput(string.Format("getVariable(): {0} '{1}'", name, toReturn));
  924.             }
  925.  
  926.             return toReturn;
  927.         }
  928.  
  929.         #endregion
  930.  
  931.  
  932.         #region AI_Modules
  933.         //Below here are the modules of the script you can enable in the Main() void.
  934.  
  935.         void soundAlerts()
  936.         {
  937.             if (codeBlue) {
  938.                 for (int i = 0; i < speakersBlue.Count; i++)
  939.                 {
  940.                     debugOutput("Playing sound on " + speakersBlue[i].DefinitionDisplayNameText);
  941.                     speakersBlue[i].ApplyAction("PlaySound");
  942.                     if (!speakersBlue[i].IsSoundSelected)
  943.                     {
  944.                         debugOutput("No sound selected on " + speakersBlue[i].DefinitionDisplayNameText);
  945.                     }
  946.                 }
  947.             }
  948.             else if (codeOrange) {
  949.                 for (int i = 0; i < speakersOrange.Count; i++)
  950.                 {
  951.                     debugOutput("Playing sound on " + speakersOrange[i].DefinitionDisplayNameText);
  952.                     speakersOrange[i].ApplyAction("PlaySound");
  953.                     if (!speakersOrange[i].IsSoundSelected)
  954.                     {
  955.                         debugOutput("No sound selected on " + speakersOrange[i].DefinitionDisplayNameText);
  956.                     }
  957.                 }
  958.             }
  959.             else if (codeRed) {
  960.                 for (int i = 0; i < speakersRed.Count; i++)
  961.                 {
  962.                     debugOutput("Playing sound on " + speakersRed[i].DefinitionDisplayNameText);
  963.                     speakersRed[i].ApplyAction("PlaySound");
  964.                     if (!speakersRed[i].IsSoundSelected)
  965.                     {
  966.                         debugOutput("No sound selected on " + speakersRed[i].DefinitionDisplayNameText);
  967.                     }
  968.                 }
  969.             }
  970.         }
  971.  
  972.         //This is needed both for the core as well as the screen module.
  973.         void updateStatusString(bool doDamageReport = true)
  974.         {
  975.             debugOutput("Updating information messages..");
  976.             StatusString = ""; //used by status panels
  977.             shortStatus = "All systems functional."; //Override if necessary
  978.             damageReport = "";
  979.             shortCommsStatus = " OFFLINE"; //Overridden if there's antennas found.
  980.  
  981.             if (doDamageReport)
  982.             {
  983.                 damageReport = getDamageReport(false);
  984.             }
  985.  
  986.             if (offlineBlockCount > 0)
  987.             {
  988.                 shortStatus = string.Format("All systems functional. {0} systems offline.", offlineBlockCount);
  989.             }
  990.            
  991.             if (brokenBlockCount > 0)
  992.             {
  993.                 shortStatus = string.Format("Warning: {0} systems unavailable.", brokenBlockCount);
  994.             }
  995.            
  996.             if (isProjectorPresent)
  997.             {
  998.                 if (missingBlockCount > 0)
  999.                 {
  1000.                     shortStatus = string.Format("Warning: {0} missing blocks detected.", missingBlockCount);
  1001.                 }
  1002.                 if (missingBlockCount > 0 && brokenBlockCount > 0)
  1003.                 {
  1004.                     shortStatus = "Warning: Ship has sustained damage to various systems.";
  1005.                 }
  1006.                 if (missingBlockCount > 10 && brokenBlockCount > 1)
  1007.                 {
  1008.                     shortStatus = "Error: Ship has sustained extensive damage to various systems. Exit strategy advised.";
  1009.                 }
  1010.  
  1011.                 debugOutput("Adding missing block report");
  1012.                 StatusString += generateReportFromDictionary(missingBlocks);
  1013.  
  1014.             }
  1015.             else
  1016.             {
  1017.                 StatusString += "\n  -No projector detected. Missing block detection offline.";
  1018.             }
  1019.  
  1020.        
  1021.  
  1022.             //Update stuff for the Screens module
  1023.             if (isScreenModulePresent)
  1024.             {
  1025.                 offlineReport = getDamageReport(true);
  1026.             }
  1027.  
  1028.  
  1029.  
  1030.             // Generate Status messages
  1031.             if (refineries.Count > 0)
  1032.             {
  1033.                 for (int i = 0; i < refineries.Count; i++)
  1034.                 {
  1035.                     if (refineries[i].IsProducing)
  1036.                     { StatusString += string.Format("\n  -{0} is processing ore.", refineries[i].DisplayNameText); }
  1037.                 }
  1038.             }
  1039.             if (assemblers.Count > 0)
  1040.             {
  1041.                 for (int i = 0; i < assemblers.Count; i++)
  1042.                 {
  1043.                     if (assemblers[i].IsProducing)
  1044.                     { StatusString += string.Format("\n  -{0} is assembling parts.", assemblers[i].DisplayNameText); }
  1045.                 }
  1046.             }
  1047.             if (maxPower < powerUsage) { StatusString += "\n  -Warning: Draining batteries."; }
  1048.             if ((maxPower > powerUsage) && (wattHourInBatteries < maxWattHourInBatteries)) { StatusString += "\n  -Batteries charging."; }
  1049.             if (wattHourInBatteries == maxWattHourInBatteries) { StatusString += "\n  -Batteries fully charged."; }
  1050.             else if (wattHourInBatteries > (maxWattHourInBatteries) / 4) { StatusString += "\n  -Batteries OK."; }
  1051.             else if (wattHourInBatteries < (maxWattHourInBatteries / 4)) { StatusString += "\n  -Batteries low."; shortStatus = "Low power."; }
  1052.             bool tooManyMessage = false;
  1053.             if (tooManyAntennas) { StatusString += "\n >Too many antennas to handle."; tooManyMessage = true; }
  1054.             if (tooManyBatteries) { StatusString += "\n >Too many batteries to handle."; tooManyMessage = true; }
  1055.             if (tooManyBeacons) { StatusString += "\n >Too many beacons to handle."; tooManyMessage = true; }
  1056.             if (tooManyReactors) { StatusString += "\n >Too many reactors to handle."; tooManyMessage = true; }
  1057.             if (tooManySolarpanels) { StatusString += "\n >Too many solar panels to handle."; tooManyMessage = true; }
  1058.             if (tooManyMessage) { StatusString += "\n >Remove devices or alter execution cap at own risk. (see top of script)"; }
  1059.             if (!ignoreDevicesThatAreTooMuch) { StatusString += "\n >Execution cap disabled."; }
  1060.  
  1061.             if (batteryInputWatts > powerUsage)
  1062.             {
  1063.                 StatusString += "\n >Unknown power source detected."; //What the hell are we charging the batteries with?
  1064.             }
  1065.  
  1066.             // Generate Power Overview
  1067.             powerReport = string.Format(
  1068.                 " {0}/{1} currently used.",
  1069.                 new string[] {
  1070.                     getNormalizedPowerString(powerUsage, false) ,
  1071.                     getNormalizedPowerString(maxPower, false)
  1072.                 }); ;
  1073.             if (batteries.Count > 0)
  1074.             {
  1075.                 powerReport += string.Format(
  1076.                     "\n *Batteries: {0}/{1} in {2} batteries ({3} in use)",
  1077.                     new string[] {
  1078.                         getNormalizedPowerString(wattHourInBatteries,true),
  1079.                         getNormalizedPowerString(maxWattHourInBatteries,true),
  1080.                         batteries.Count.ToString(),
  1081.                         getDischargingBatteryCount().ToString()
  1082.                     });
  1083.             }
  1084.             if (solarpanels.Count > 0)
  1085.             {
  1086.                 powerReport += string.Format(
  1087.                    "\n *Solar: {2} panels | {0}/{1}",
  1088.                    new string[] {
  1089.                         getNormalizedPowerString(solarPower(false),false),
  1090.                         getNormalizedPowerString(solarpanelWatts,false),
  1091.                         solarpanels.Count.ToString()
  1092.                     });
  1093.             }
  1094.             if (reactors.Count > 0)
  1095.             {
  1096.                 powerReport += string.Format(
  1097.                     "\n *Reactors: {2} reactors | {0}/{1}",
  1098.                     new string[] {
  1099.                         getNormalizedPowerString(reactorPower(false),false),
  1100.                         getNormalizedPowerString(reactorWatts,false),
  1101.                         reactors.Count.ToString()
  1102.                     });
  1103.             }
  1104.             debugOutput("status: " + StatusString);
  1105.  
  1106.  
  1107.             //Check comms status    
  1108.             antennaString = "\n *No antennas found.";
  1109.             beaconString = "\n *No beacons found.";
  1110.             string tempshortCommsStatus = " OFFLINE.";
  1111.             float tempmaxAntennaRange = 0;
  1112.             if (antennas.Count > 0)
  1113.             {
  1114.                 string antString = "";
  1115.                 int workingAnts = 0;
  1116.                 for (int i = 0; i < antennas.Count; i++)
  1117.                 {
  1118.                     var ant = (IMyRadioAntenna)antennas[i];
  1119.                     antString += "\n *" + ant.DisplayNameText + " (" + ant.Radius + "m)";
  1120.                     if (!ant.IsFunctional) { antString += " - Damaged"; }
  1121.                     if (!ant.IsWorking) { antString += " - Offline"; }
  1122.                     if (isHealthy(ant))
  1123.                     {
  1124.                         workingAnts++;
  1125.                         if (ant.Radius > tempmaxAntennaRange) { tempmaxAntennaRange = ant.Radius; }
  1126.                         tempshortCommsStatus = string.Format(" Comms Online ({0}m range, {1}/{2} antennas in use)", tempmaxAntennaRange, workingAnts, antennas.Count);
  1127.                         debugOutput("Healthy antenna found. " + ant.DisplayNameText);
  1128.                     }
  1129.                 }
  1130.                 antennaString = string.Format(
  1131.                     "{1}",
  1132.                     new string[] {
  1133.                         antennas.Count.ToString(),
  1134.                         antString
  1135.                     });
  1136.                 shortCommsStatus = tempshortCommsStatus;
  1137.             }
  1138.  
  1139.             if (shortCommsStatus.Contains("OFFLINE"))
  1140.             {
  1141.                 StatusString += "\n >Communications offline.";
  1142.                 shortStatus = "Core systems functional. Comms offline.";
  1143.             }
  1144.  
  1145.  
  1146.             if (beacons.Count > 0)
  1147.             {
  1148.                 string beacString = "";
  1149.                 for (int i = 0; i < beacons.Count; i++)
  1150.                 {
  1151.                     var beac = (IMyBeacon)beacons[i];
  1152.                     beacString += "\n *" + beac.DisplayNameText + " (Beacon, " + beac.Radius + "m range)";
  1153.                     if (!beac.IsFunctional) { beacString += " - Damaged"; }
  1154.                     if (!beac.IsWorking) { beacString += " - Offline"; }
  1155.                 }
  1156.                 beaconString = string.Format(
  1157.                     "{1}",
  1158.                     new string[] {
  1159.                         beacons.Count.ToString(),
  1160.                         beacString
  1161.                     });
  1162.             }
  1163.             debugOutput("Done.");
  1164.         }
  1165.  
  1166.         /// <summary>
  1167.         /// Updates all LCD panels with _Status suffix with useful information and messages.
  1168.         /// This is by far the heaviest function, but turning it off will also cripple the AI's functionality heavily.
  1169.         /// </summary>
  1170.         void updateStatusPanels()
  1171.         {
  1172.             //Fetch and prepare variables for use
  1173.  
  1174.            
  1175.  
  1176.             //Format information for displaying
  1177.             StringBuilder updateScreenBuilder = new StringBuilder();
  1178.  
  1179.             updateScreenBuilder.AppendFormat( //Status screen parts
  1180.                 "{0} - {1}\nStatus: {2}{3}{4}",
  1181.                 shipName,
  1182.                 DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString(),
  1183.                     shortStatus,
  1184.                     damageReport,
  1185.                     StatusString
  1186.                 );
  1187.             //Show Assembler information if there are assemblers
  1188.             if (assemblers.Count > 0)
  1189.             {
  1190.                 updateScreenBuilder.AppendFormat(
  1191.                     "\nAssembly: {0}",
  1192.                     string.Format(
  1193.                     "{0} assemblers, {1} active.",
  1194.                     new string[] {
  1195.                         assemblers.Count.ToString(),
  1196.                         activeAssemblers.ToString()
  1197.                         })
  1198.                     );
  1199.             }
  1200.  
  1201.             //Show Ore processing information if there are refineries
  1202.             if (refineries.Count > 0)
  1203.             {
  1204.                 updateScreenBuilder.AppendFormat(
  1205.                     "\nOre processing: {0}",
  1206.                     string.Format(
  1207.                     "{0} refineries, {1} active.",
  1208.                     new string[] {
  1209.                         refineries.Count.ToString(),
  1210.                         activeRefineries.ToString()
  1211.                         })
  1212.                     );
  1213.             }
  1214.  
  1215.             //Show power information
  1216.             updateScreenBuilder.AppendFormat("\nPower: {0}", powerReport);
  1217.             //Show Comms information
  1218.             updateScreenBuilder.AppendFormat(
  1219.                 "\nComms: {0}{1}{2}",
  1220.                 shortCommsStatus,
  1221.                 antennaString,
  1222.                 beaconString
  1223.                 );
  1224.  
  1225.  
  1226.  
  1227.  
  1228.             //Apply text to all screens with _status suffix
  1229.             for (int i = 0; i <  statusPanels.Count; i++)
  1230.             {
  1231.                 if (statusPanels[i].DisplayNameText.EndsWith("_status"))
  1232.                 {
  1233.                     IMyTextPanel screen = (IMyTextPanel)statusPanels[i];
  1234.                     screen.WritePublicText(updateScreenBuilder.ToString());
  1235.                 }
  1236.             }
  1237.  
  1238.  
  1239.         }
  1240.  
  1241.         void updateIconPanels()
  1242.         {
  1243.             if (codeBlue)
  1244.             {
  1245.                 for (int i = 0; i < iconPanels.Count; i++)
  1246.                 {
  1247.                     debugOutput("Setting texture on " + iconPanels[i].DisplayNameText);
  1248.                     iconPanels[i].ShowPublicTextOnScreen();
  1249.                     iconPanels[i].ShowTextureOnScreen();
  1250.                     iconPanels[i].AddImageToSelection("Construction");
  1251.                     //THIS IS BROKEN UNTIL WE CAN REMOVE IMAGES. For fuck sake Keen Dx
  1252.                 }
  1253.             }
  1254.         }
  1255.  
  1256.  
  1257.         /// <summary>
  1258.         /// Automatically increases/decreases antenna range to available power
  1259.         /// Attempting to not drain any battery
  1260.         /// </summary>
  1261.         /// <param name="minimumRangeMeters">Minimum amount of meters Antenna must be visible</param>
  1262.         void manageAnntenas(long minimumRangeMeters, long maximumRangeMeters)
  1263.         {
  1264.             if (antennas.Count < 1) { return; }
  1265.             if (maxPower < powerUsage) //If there's power being drained from the batteries
  1266.             {
  1267.                 for (int i = 0; i < antennas.Count; i++)
  1268.                 {
  1269.                     var ant = (IMyRadioAntenna)antennas[i];
  1270.                     if (ant.Radius > minimumRangeMeters && isHealthy(ant))
  1271.                     {
  1272.                         ant.ApplyAction("DecreaseRadius");
  1273.                     }
  1274.                 }
  1275.             }
  1276.             else if(maxPower -100 > powerUsage) //Only up the range if there's enough power overhead
  1277.             {
  1278.                 for (int i = 0; i < antennas.Count; i++)
  1279.                 {
  1280.                     var ant = (IMyRadioAntenna)antennas[i];
  1281.                     if (ant.Radius < maximumRangeMeters && isHealthy(ant))
  1282.                     {
  1283.                         ant.ApplyAction("IncreaseRadius");
  1284.                     }
  1285.                 }
  1286.             }
  1287.         }
  1288.  
  1289.         /// <summary>
  1290.         /// Automatically increases/decreases antenna range to available power
  1291.         /// Attempting to not drain any battery
  1292.         /// </summary>
  1293.         /// <param name="minimumRangeMeters">Minimum amount of meters Antenna must be visible</param>
  1294.         void manageBeacons(long minimumRangeMeters, long maximumRangeMeters)
  1295.         {
  1296.             if (antennas.Count < 1) { return; }
  1297.             if (maxPower < powerUsage) //If there's power being drained from the batteries
  1298.             {
  1299.                 for (int i = 0; i < beacons.Count; i++)
  1300.                 {
  1301.                     var beacon = (IMyBeacon)beacons[i];
  1302.                     if (beacon.Radius > minimumRangeMeters && isHealthy(beacon))
  1303.                     {
  1304.                         beacon.ApplyAction("DecreaseRadius");
  1305.                     }
  1306.                 }
  1307.             }
  1308.             else if (maxPower - 100 > powerUsage) //Only up the range if there's enough power overhead
  1309.             {
  1310.                 for (int i = 0; i < beacons.Count; i++)
  1311.                 {
  1312.                     var beacon = (IMyBeacon)beacons[i];
  1313.                     if (beacon.Radius < maximumRangeMeters && isHealthy(beacon))
  1314.                     {
  1315.                         beacon.ApplyAction("IncreaseRadius");
  1316.                     }
  1317.                 }
  1318.             }
  1319.         }
  1320.  
  1321.  
  1322.         /// <summary>
  1323.         /// Toggles refineries to make sure at least the given amount of energy in KWh is left in the batteries (default is 25%)
  1324.         /// Note: any value for mininmumKWh must be an ABSOLUTE value, e.g 500KWh, not in percentages. If you want percentages, edit the method.
  1325.         /// </summary>
  1326.         /// <param name="toggleOffset">Offset before refineries are turned on again to prevent togglestorm</param>
  1327.         /// <param name="minimumKWh">Least amount of KWh (e.g 500KWh) that must be left in batttery</param>
  1328.         void manageRefineries(int toggleOffset = 350, int minimumKWh = 0)
  1329.         {
  1330.             var power = getWattHourInBatteries();
  1331.             bool toggleRefineries = true;
  1332.             for (int i = 0; i < refineries.Count; i++)
  1333.             {
  1334.                 if (minimumKWh <= 0)
  1335.                 {
  1336.                     if (power <= (getMaxWattHourInBatteries() / 4)) { refineries[i].ApplyAction("OnOff_Off"); }
  1337.                     else if (power >= ((getMaxWattHourInBatteries() / 4) + toggleOffset)) { refineries[i].ApplyAction("OnOff_On"); }
  1338.                 }
  1339.                 else
  1340.                 {
  1341.                     if (power <= minimumKWh) { refineries[i].ApplyAction("OnOff_Off"); }
  1342.                     else if (power >= (minimumKWh + toggleOffset)) { refineries[i].ApplyAction("OnOff_On"); }
  1343.                 }
  1344.             }
  1345.  
  1346.             if (toggleRefineries)
  1347.             { refineries.ForEach(s => s.RequestEnable(true)); }
  1348.             else { refineries.ForEach(s => s.RequestEnable(false)); }
  1349.         }
  1350.  
  1351.         /// <summary>
  1352.         /// Works just like manageRefineries, except with Assemblers. Literally I used the same code with a quick case-sensitive replace.
  1353.         /// </summary>
  1354.         /// <param name="toggleOffset"></param>
  1355.         /// <param name="minimumKWh"></param>
  1356.         void manageAssemblers(int toggleOffset = 350, int minimumKWh = 0)
  1357.         {
  1358.             var power = getWattHourInBatteries();
  1359.             bool toggleAssemblers = true;
  1360.             for (int i = 0; i < assemblers.Count; i++)
  1361.             {
  1362.                 if (minimumKWh <= 0)
  1363.                 {
  1364.                     if (power <= (getMaxWattHourInBatteries() / 4)) { assemblers[i].ApplyAction("OnOff_Off"); }
  1365.                     else if (power >= ((getMaxWattHourInBatteries() / 4) + toggleOffset)) { assemblers[i].ApplyAction("OnOff_On"); }
  1366.                 }
  1367.                 else
  1368.                 {
  1369.                     if (power <= minimumKWh) { assemblers[i].ApplyAction("OnOff_Off"); }
  1370.                     else if (power >= (minimumKWh + toggleOffset)) { assemblers[i].ApplyAction("OnOff_On"); }
  1371.                 }
  1372.             }
  1373.  
  1374.             if (toggleAssemblers)
  1375.             { assemblers.ForEach(s => s.RequestEnable(true)); }
  1376.             else { assemblers.ForEach(s => s.RequestEnable(false)); }
  1377.         }
  1378.  
  1379.         /// <summary>
  1380.         /// Reactor management is really a matter of personal taste,
  1381.         /// but I personally want solar and battery power to be used before reactors become active.
  1382.         /// I also don't want reactors to charge batteries. which is the only thing you can toggle in this scheme
  1383.         /// If you don't like the reactor scheme, build your own.
  1384.         /// </summary>
  1385.         /// <param name="chargeBatteries">Whether or not to charge batteries using reactor power</param>
  1386.         void manageReactors(bool chargeBatteries = false)
  1387.         {
  1388.             //updateMisc(); //Might not be needed, if updateStatusPanel() is called first.
  1389.             if (batteries.Count < 1 && solarpanels.Count < 1)
  1390.             { return; } //It would be unwise to turn off our only known energy source.
  1391.  
  1392.  
  1393.             if (maxPower < powerUsage || solarpanels.Count < 1) //If Solar power doesn't cut it
  1394.             {
  1395.                 if (wattHourInBatteries < (maxWattHourInBatteries / 4)) //If battery is low
  1396.                 {
  1397.                     debugOutput("Turning on reactors (maxpower<usage, watthoursinbats<maxwatthours/4)" );
  1398.                     for (int i = 0; i < reactors.Count; i++)
  1399.                     {
  1400.                         reactors[i].ApplyAction("OnOff_On"); //Turn on all reactors
  1401.                        
  1402.                     }
  1403.                     if (!chargeBatteries) //And if we don't wanna charge the batteries with reactor power
  1404.                     {
  1405.                         debugOutput("Turning off batteries (!chargebatteries)");
  1406.                         for (int i = 0; i < batteries.Count; i++)
  1407.                         {
  1408.                             batteries[i].ApplyAction("OnOff_Off"); //Turn off all batteries
  1409.                             debugOutput("Turning off batteries");
  1410.                         }
  1411.                     }
  1412.                 }
  1413.             }
  1414.             else if (solarpanels.Count > 0)//If solar power is enough to charge the batteries and there are solar panels
  1415.             {
  1416.                 debugOutput("Solar output high enough to charge batteries.");
  1417.                 debugOutput("Turning off all reactors, and setting all batteries to charge");
  1418.                 for (int i = 0; i < batteries.Count; i++)
  1419.                 {
  1420.                     batteries[i].ApplyAction("OnOff_On"); //Turn on all batteries
  1421.                 }
  1422.                 for (int i = 0; i < reactors.Count; i++)
  1423.                 {
  1424.                     reactors[i].ApplyAction("OnOff_Off"); //Turn off all reactors
  1425.                 }
  1426.             }
  1427.  
  1428.         }
  1429.  
  1430.         /// <summary>
  1431.         /// Original battery management code written and tested by Stiggan and Malakeh in January 2015.
  1432.         /// </summary>
  1433.         void manageBatteries()
  1434.         {
  1435.             // Raise the usage by this much in kW to make batteries kick in earlier.  
  1436.             int offset = 0;
  1437.  
  1438.             // Modify total on the reactors maximum to make batteries kick in earlier.  
  1439.             float margin = 1.00f;
  1440.  
  1441.  
  1442.             maxPower = (int)(margin * ((float)maxPower));
  1443.             powerUsage += offset * 1000;
  1444.  
  1445.             if (maxPower > powerUsage)
  1446.             {
  1447.                 toggleRandomBattery(); // Toggle on a battery to see if power is needed.
  1448.                 chargeAllBatteries(); // Sets batteries to charge.
  1449.             }
  1450.             else
  1451.             {
  1452.                 chargeAllBatteries(); // Sets batteries to discharge.
  1453.             }
  1454.         }
  1455.  
  1456.         /// <summary>
  1457.         /// This function automatically toggles turrets when the alertState goes to Red.
  1458.         /// </summary>
  1459.         void manageTurrets()
  1460.         {
  1461.             if (codeRed)
  1462.             {
  1463.                 for (int i = 0; i < turrets.Count; i++)
  1464.                 {
  1465.                     turrets[i].ApplyAction("OnOff_On");
  1466.                 }
  1467.             }
  1468.             else
  1469.             {
  1470.                 for (int i = 0; i < turrets.Count; i++)
  1471.                 {
  1472.                     turrets[i].ApplyAction("OnOff_Off");
  1473.                 }
  1474.             }
  1475.         }
  1476.  
  1477.         #endregion
  1478.  
  1479.         void Main()
  1480.         {
  1481.             currentInternalIteration++;
  1482.             updateLCDPanels(); //Must be first to execute, otherwise ai_storage and debugpanel are unavailable.
  1483.  
  1484.             debugOutput("Running internal Update Modules");
  1485.             updateModules();
  1486.             updateMiscWithBlacklist();
  1487.             updateBrokenBlocks();
  1488.  
  1489.             updateAssemblers();
  1490.             updateRefineries();
  1491.             updateSpeakers();
  1492.             updateStatusString();
  1493.             updateScreenModuleValues(); //This is optional if you don't have the Screen module.
  1494.             //updateIconPanels(); //A fix is underway: http://forums.keenswh.com/post/01071008-lcd-panel-image-api-unsuable-in-scripts-7318058?pid=1286386079
  1495.  
  1496.             debugOutput(string.Format("blue: {0} orange: {1} red: {2}", codeBlue, codeOrange, codeRed));
  1497.  
  1498.  
  1499.             debugOutput("Running External Modules");
  1500.             //Add and remove members from the script to activate their functionality. The void members right above Main() are available for use.
  1501.             if (!isScreenModulePresent)
  1502.             {
  1503.                 debugOutput("No Screen module found, printing to status panels from core..");
  1504.                 updateStatusPanels(); //Turn this off if you have the AI Screen Module.
  1505.             }
  1506.  
  1507.  
  1508.             debugOutput("Running Ship Management Modules");
  1509.             soundAlerts();
  1510.             manageAssemblers();
  1511.             manageRefineries();
  1512.             //manageBatteries(); //Powermanagement is broken and to be replaced.
  1513.             manageTurrets(); //Toggles turrets; Red means on, no alerts means off.
  1514.             manageAnntenas(500, 35000);
  1515.             manageBeacons(500, 35000);
  1516.  
  1517.             if (currentInternalIteration > 9) { currentInternalIteration = 0; }
  1518.             debugOutput("AI Iteration " + currentInternalIteration.ToString() + " finished.");
  1519.         }
  1520.  
  1521.         #endregion
Advertisement
Add Comment
Please, Sign In to add comment