public bool exec(BaconArgs Args, Environment Environment, out StringBuilder Response) { Environment.Debug.newScope("BaconShell.Command.exec"); Environment.Debug.add("exec command '" + name + "'", BaconDebug.DEBUG); Response = new StringBuilder(); bool succeed = false; try { Environment.Debug.newScope("dynamic command '" + name + "'"); Response = this.func(Args, Environment); Environment.Debug.leaveScope(); succeed = true; } catch (Exception e) { succeed = false; Response.Clear(); Response.AppendLine(e.ToString()); } Environment.Debug.add("response length: " + Response.Length.ToString(), BaconDebug.DEBUG); Environment.Debug.leaveScope(); return(succeed); }
public void Main(string argument) { List <IMyTextPanel> TTYs = new List <IMyTextPanel>(); GridTerminalSystem.GetBlocksOfType <IMyTextPanel>(TTYs, (IMyTextPanel x) => x.CustomName.Contains("TTY") && x.CubeGrid.Equals(Me.CubeGrid)); BaconShell.Environment env = new BaconShell.Environment(this, GridTerminalSystem, new BaconDebug("debug", GridTerminalSystem, this, 99)); BaconShell bs = new BaconShell(env); for (int i_TTY = 0; i_TTY < TTYs.Count; i_TTY++) { IMyTextPanel TTY = TTYs[i_TTY]; string stdin = TTY.GetPrivateText(); if (!stdin.Equals("")) { StringBuilder stdout = new StringBuilder(); string[] command = stdin.Split(new Char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < command.Length; i++) { BaconArgs Args = BaconArgs.parse(command[i]); stdout.Append(bs.runCommand(Args, env).ToString()); } TTY.WritePrivateText(""); TTY.WritePublicText(stdout.ToString()); } } }
static public BMyLog4PB getLogger(BaconArgs ArgBag, Program Assembly) { byte filter = getVerbosityFilter(ArgBag); if (filter == 0) { return(null); } string tag = ArgBag.hasOption(BMyArgParams.LOG_TAG) ? ArgBag.getOption(BMyArgParams.LOG_TAG)[0] : BMyArgParams.LOG_TAG_DEFAULT; BMyLog4PB Logger = new BMyLog4PB( Assembly, filter, new BMyLog4PB.BMyEchoAppender(Assembly), new BMyLog4PB.BMyKryptDebugSrvAppender(Assembly), new BMyLog4PB.BMyTextPanelAppender( tag, Assembly ) ); if (ArgBag.hasOption(BMyArgParams.LOG_FORMAT)) { Logger.Format = ArgBag.getOption(BMyArgParams.LOG_FORMAT)[0]; } Logger.AutoFlush = false; Logger.If(BMyLog4PB.E_DEBUG)?.Debug("Log initialized. Tag: {0}, Format: {1}", tag, Logger.Format); return(Logger); }
private void Run(BaconArgs Args) { Log?.PushStack("private void Run()"); if (Args.hasOption("reactors")) { INCLUDE_REACTORS = true; Log?.Info("Include reactors in sorting."); } if (Args.hasOption("weapons")) { INCLUDE_WEAPONS = true; Log?.Info("Include weapons in sorting."); } if (Args.hasOption("docked")) { INCLUDE_DOCKED = true; Log?.Info("Include docked in sorting."); } if (Args.hasOption("ignore") && Args.getOption("ignore")[0] != null) { TAG_IGNORE = Args.getOption("ignore")[0]; Log?.Info("Use Tag \"{0}\" instead of \"#!BaconSort\" to exclude containers.", TAG_IGNORE); } List <IMyTerminalBlock> SourceBlocks = findAllBlocks(); Dictionary <string, List <IMyTerminalBlock> > DestinationBlockMap = getDestinationMap(SourceBlocks); foreach (IMyTerminalBlock SourceBlock in SourceBlocks) { DoSortContainer(SourceBlock, DestinationBlockMap); } Log?.PopStack(); }
private bool isAllowedToExecute(BaconArgs Args) { if (LastRun == null) { return(true); } int buff = 0; if (Args.hasOption("sleep") && int.TryParse(Args.getOption("sleep")[0], out buff)) { sleepTimeS = buff; } Log?.Debug("execution limit once every {0} seconds", sleepTimeS); TimeSpan TimeSinceLastRun = DateTime.Now.Subtract(LastRun); if (sleepTimeS <= TimeSinceLastRun.TotalSeconds) { LastRun = DateTime.Now; return(true); } Log?.Info("Sorting in {0} seconds.", sleepTimeS - TimeSinceLastRun.TotalSeconds); return(false); }
public void Main(string argument) { if (RCs == null) { RCs = new List <IMyRemoteControl>(); } Args = BaconArgs.parse(argument); EchoF("START - Remotes: {0}", RCs.Count); if (Args.getOption("reset").Count > 0) { Echo("RESET"); reset(); } List <IMyShipController> ShipCon = new List <IMyShipController>(); GridTerminalSystem.GetBlocksOfType <IMyShipController>(ShipCon, (s => s.CustomName.Contains("[BWDA]"))); if (ShipCon.Count > 0) { EchoF("Using {0} as Anchor", ShipCon[0].CustomName); foreach (IMyRemoteControl Remote in RCs) { updateDrone(Remote, ShipCon[0]); } } Echo("END"); }
public StringBuilder runCommand(BaconArgs Args, Environment Env) { Env.Debug.newScope("runCommand"); StringBuilder response = new StringBuilder(); if (Args.getArguments().Count > 0) { string cmd = Args.getArguments()[0]; if (availableCommands.ContainsKey(cmd)) { Args.getArguments().RemoveAt(0); StringBuilder _tmp = new StringBuilder(); if (!availableCommands[cmd].exec(Args, Env, out _tmp)) { response.AppendLine("an error occured during executing of '" + cmd + "'"); } response.Append(_tmp.ToString()); } else { Env.Debug.add("unknown command: " + cmd, BaconDebug.DEBUG); response.AppendLine("unknown command: " + cmd); } } else { Env.Debug.add("no command given", BaconDebug.DEBUG); } Env.Debug.leaveScope(); return(response); }
static private byte getVerbosityFilter(BaconArgs ArgBag) { byte slug = 0; int verbosity = ArgBag.getFlag(BMyArgParams.LOG_VERBOSITY); if (verbosity >= 1) { slug |= BMyLog4PB.E_FATAL; } if (verbosity >= 2) { slug |= BMyLog4PB.E_ERROR; } if (verbosity >= 3) { slug |= BMyLog4PB.E_WARN; } if (verbosity >= 4) { slug |= BMyLog4PB.E_INFO; } if (verbosity >= 5 && ArgBag.hasOption(BMyArgParams.LOG_ENABLEDEBUG)) { slug |= BMyLog4PB.E_DEBUG; } if (verbosity >= 6 && ArgBag.hasOption(BMyArgParams.LOG_ENABLEDEBUG)) { slug |= BMyLog4PB.E_TRACE; } return(slug); }
public Environment(Program App, string argument, UpdateType updateSource) { this.App = App; this.argumentRaw = argument; this.GlobalArgs = BaconArgs.parse(argument); this.updateSource = updateSource; this.Log = NewLog(); }
public BaconArgs parseArgs(string args) { if (!cache.ContainsKey(args)) { BaconArgs Result = new BaconArgs(); Result.Raw = args; bool isEscape = false; bool isEncapsulatedString = false; StringBuilder slug = new StringBuilder(); for (int i = 0; i < args.Length; i++) { char glyp = args[i]; if (isEscape) { slug.Append(glyp); isEscape = false; } else if (glyp.Equals('\\')) { isEscape = true; } else if (isEncapsulatedString && !glyp.Equals('"')) { slug.Append(glyp); } else if (glyp.Equals('"')) { isEncapsulatedString = !isEncapsulatedString; } else if (glyp.Equals(' ')) { if (slug.ToString().Equals("--")) { Result.add(args.Substring(i).TrimStart()); slug.Clear(); break; } else { Result.add(slug.ToString()); slug.Clear(); } } else { slug.Append(glyp); } } if (slug.Length > 0) { Result.add(slug.ToString()); } cache.Add(args, Result); } return(cache[args]); }
public override string ToString() { List <string> slug = new List <string>(); slug.Add(@"--" + OPT_TIMETOLIVE + "=" + BaconArgs.Escape(TimeToLive.ToString())); slug.Add(@"--" + OPT_TIMECREATED + "=" + BaconArgs.Escape(DateTimeToTimestamp(TimeCreated).ToString())); slug.Add(@"--" + OPT_TYPE + "=" + BaconArgs.Escape(Type)); slug.Add(@"--" + OPT_SENDER + "=" + BaconArgs.Escape(Sender)); slug.Add(@"--"); slug.Add(Content); return(string.Join(" ", slug)); }
public class Parser { static Dictionary <string, BaconArgs> h = new Dictionary <string, BaconArgs>(); public BaconArgs parseArgs(string a) { if (!h.ContainsKey(a)) { var b = new BaconArgs(); var c = false; var d = false; e = new StringBuilder(); for (int f = 0; f < a.Length; f++) { var g = a[f]; if (c) { e.Append(g); c = false; } else if (g.Equals('\\')) { c = true; } else if (d && !g.Equals('"')) { e.Append(g); } else if (g.Equals('"')) { d = !d; } else if (g.Equals(' ')) { if (e.ToString().Equals("--")) { b.add(a.Substring(f).TrimStart()); e.Clear(); break; } else { b.add(e.ToString()); e.Clear(); } } else { e.Append(g); } } if (e.Length > 0) { b.add(e.ToString()); } h.Add(a, b); } return(h[a]); }
/** * BaconSort * ============== * Copyright 2016 Thomas Klose <*****@*****.**> * License: https://github.com/BaconFist/SpaceEngineersIngameScript/blob/master/LICENSE * Source: https://github.com/BaconFist/SpaceEngineersIngameScript/blob/master/SpaceEngineersIngameScript/Scripts/BaconSort.cs * * Inventory Sorting * - Sort Items by tags in the Blockname * Tags: #ammo, #component, #bottle, #ingot, #ore, #handtool * - Ignore all Reactors by default (can be changed by arguments) * - Ignore all Weapons by default (can be changed by arguments) * - Ignore all containers with "#!BaconSort" in their Name (can be changed by arguments) * - Ignore docked Ships & Stations (can be changed by arguments) * - Sorts only once every 5 minutes (can be changed by arguments) * * How it works: * Add any tag to a Container with an Inventory to pull items of this type in it. * Script is lazy, it will sort a item only if it is not in a Container with a matching tag. (Example: It will not pull an SteelPlate from an container called "Large Cargo Container #component") * Source & Target Block must match some requirements: 1. Same Grid as PB, 2. Must be connected throug Conveyor-System * * * * * Arguments for Storting: * ==================================== * --reactors * Also sort Inventories of reactors * --weapons * Also sort Inventories of Weapons * --docked * Also sort inventories from docked Ships and Stations * --ignore="TAG" * ignore all Blocks with TAG in its name where TAG defaults to "#!BaconSort" * * * Arguments for Logging: * ==================================== * --log-noecho * Disable log messages in Detailed Info * * --log-lcd="TAG" * Print Log Messages on TextPanels/LCDs where TAG is in its Name * * --log-filter="F" (Default: fatal,error,warn,info) * Only log messages if type "F" wehre F can be any of TRACE,DEBUG,INFO,WARN,ERROR,FATAL,ALL. * Can be defined more than once (like --log-filter="info" --log-filter="warn") * Can also be defined like --log-filter="debug,WARN,Fatal". * "ALL" is equal to a combination of all other filters. * * Arguments for other stuff: * ================================== * --sleep="N" * scipt waits N seconfs before executing sorting loop where N defaults to 300 (5 minutes) * //this is a workaround for flashing timer bug on Dedicated Servers. * **/ public void Main(string argument) { BaconArgs Args = BaconArgs.parse(argument); BootstrapLog(Args); try { Log?.Debug("Stat Script at {0}", DateTime.Now); if (isAllowedToExecute(Args)) { Run(Args); } } catch (Exception e) { Log?.Fatal("Exception of Type {0} occured. Script Execution Terminated. => {1}", e.GetType().Name, e.Message); } finally { Log?.Flush(); } }
public void Main(string argument) { BaconArgs Args = BaconArgs.parse(argument); List <IMyUserControllableGun> Guns = new List <IMyUserControllableGun>(); GridTerminalSystem.GetBlocksOfType <IMyUserControllableGun>(Guns, (b => ((Args.getOption("allGrids").Count > 0) || b.CubeGrid.Equals(Me.CubeGrid)))); if (Args.getOption("enable").Count > 0) { for (int i = 0; i < Guns.Count; i++) { Guns[i].ApplyAction("OnOff_On"); } } else { for (int i = 0; i < Guns.Count; i++) { Guns[i].ApplyAction("OnOff_Off"); } } }
/* * example implementation for BaconArgs: * run the PB with * --source="TextPanel 1" --destination="TextPanel 2" * to copy PublicText from TextPanel 1 to TextPanel 2 */ public void Main(string argument) { // parse PB arguments with Baconargs BaconArgs Args = BaconArgs.parse(argument); // validate if there is one --source and one --destination option given // as you can see the options are accessed without the leading -- if (Args.getOption("source").Count == 1 && Args.getOption("destination").Count == 1) { // get the TextPanels using --source and --destination options // as options saved as a List<string> they are accessed like getOption("the option name")[zero-based-index] IMyTextPanel SourcePanel = GridTerminalSystem.GetBlockWithName(Args.getOption("source")[0]) as IMyTextPanel; IMyTextPanel DestinationPanel = GridTerminalSystem.GetBlockWithName(Args.getOption("destination")[0]) as IMyTextPanel; //copy private text from source to destination if both block could be found if (SourcePanel != null && DestinationPanel != null) { DestinationPanel.WritePublicText(SourcePanel.GetPublicText()); } } }
public BaconMessages(IMyTextPanel StorageDevice) { this.StorageDevice = StorageDevice; string[] data = (this.StorageDevice.GetPublicText() + this.StorageDevice.GetPrivateText()).Split(new Char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < data.Length; i++) { BaconArgs R = BaconArgs.parse(data[0]); if ((R.getOption(Message.OPT_SENDER).Count > 0) && (R.getOption(Message.OPT_TIMECREATED).Count > 0) && (R.getOption(Message.OPT_TIMETOLIVE).Count > 0) && (R.getOption(Message.OPT_TYPE).Count > 0) && (R.getArguments().Count > 0)) { int TimeToLive = 0; double TimeCreated = 0; string Content = R.getArguments()[0]; string Type = R.getOption(Message.OPT_TYPE)[0]; string Sender = R.getOption(Message.OPT_SENDER)[0]; if (int.TryParse(R.getOption(Message.OPT_TIMETOLIVE)[0], out TimeToLive) && double.TryParse(R.getOption(Message.OPT_TIMECREATED)[0], out TimeCreated)) { Message msg = new Message(Content, Sender, Type, TimeToLive, TimeCreated); Add(msg); } } } }
public BaconArgs parseArgs(string a) { if (!h.ContainsKey(a)) { var b = new BaconArgs(); var c = false; var d = false; var e = new StringBuilder(); for (int f = 0; f < a.Length; f++) { var g = a[f]; if (c) { e.Append(g); c = false; } else if (g.Equals('\\')) c = true; else if (d && !g.Equals('"')) e.Append(g); else if (g.Equals('"')) d = !d; else if (g.Equals(' ')) { b.add(e.ToString()); e.Clear(); } else e.Append(g); } if (e.Length > 0) b.add(e.ToString()); h.Add(a, b); } return h[a]; }
private void BootstrapLog(BaconArgs Args) { Log = new BMyLog4PB(this, 0); if (!Args.hasOption("log-noecho")) { Log?.AddAppender(new BMyLog4PB.BMyEchoAppender(this)); } if (Args.hasOption("log-lcd")) { string logLcdTag = Args.getOption("log-lcd")[0]; if (logLcdTag != null) { Log?.AddAppender(new BMyLog4PB.BMyTextPanelAppender(logLcdTag, this)); } } if (Args.hasOption("log-filter") && Args.getOption("log-filter").Count > 0) { log_Filter = 0; foreach (string filterArgValue in Args.getOption("log-filter")) { string[] filterList = filterArgValue.ToLowerInvariant().Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string filter in filterList) { switch (filter) { case "trace": log_Filter |= BMyLog4PB.E_TRACE; break; case "debug": log_Filter |= BMyLog4PB.E_DEBUG; break; case "info": log_Filter |= BMyLog4PB.E_INFO; break; case "warn": log_Filter |= BMyLog4PB.E_WARN; break; case "error": log_Filter |= BMyLog4PB.E_ERROR; break; case "fatal": log_Filter |= BMyLog4PB.E_FATAL; break; case "all": log_Filter |= BMyLog4PB.E_ALL; break; } } } } if (Log != null) { Log.Filter = log_Filter; } }
private void init() { #region initialization oldPBName = Me.CustomName; unique_id = (new Random()).Next(); all_blocks_found = true; autopilot_en = true; location_name = "UNKNOWN"; // For spinner counter = 0; string parse = Me.CustomName.Replace(BLOCK_PREFIX, ""); int id1 = Me.CustomName.IndexOf('['); int id2 = Me.CustomName.IndexOf(']'); if (id1 >= 0 && id2 >= 0) { parse = parse.Substring(id1 + 1, id2 - id1 - 1); } else { parse = ""; } BaconArgs Args = BaconArgs.parse(parse); IS_BASE = (Args.getFlag('b') > 0); DOCK_LEFT = (Args.getFlag('l') > 0); IS_PLANET = (Args.getFlag('p') > 0); if (IS_PLANET) { IS_BASE = true; } List <string> nameArg = Args.getOption("name"); if (nameArg.Count > 0 && nameArg[0] != null) { location_name = nameArg[0]; } // Set all known blocks to null or clear lists lcdPanel = null; messageReceiver = null; WANProgram = null; connector = null; remoteControl = null; door = null; timer = null; landLight = null; mainGear = 0; gyros.Clear(); destinations.Clear(); gears.Clear(); // Get all blocks List <IMyTerminalBlock> blks = new List <IMyTerminalBlock>(); GridTerminalSystem.SearchBlocksOfName(BLOCK_PREFIX, blks, hasPrefix); num_blocks_found = blks.Count; // Assign blocks to variables as appropriate foreach (var blk in blks) { // LCD panel for printing if (blk is IMyTextPanel) { lcdPanel = blk as IMyTextPanel; lcdPanel.ShowPublicTextOnScreen(); lcdPanel.SetValueFloat("FontSize", 1.2f); } // Wico Area Network programmable block else if (blk is IMyProgrammableBlock && !blk.Equals(Me)) { WANProgram = blk as IMyProgrammableBlock; } // Autopilot else if (!IS_BASE && blk is IMyRemoteControl) { remoteControl = blk as IMyRemoteControl; } /* Ship or station connector for docking * Used to connect to station and for orientation info */ else if (!IS_PLANET && blk is IMyShipConnector) { connector = blk as IMyShipConnector; } /* Door used for docking; used for orientation information * since it's more obvious which way a door faces than a connector */ else if (!IS_PLANET && blk is IMyDoor) { door = blk as IMyDoor; } // Gyros for ship orientation else if (!IS_BASE && blk is IMyGyro) { IMyGyro g = blk as IMyGyro; gyros.Add(g); } // Timer block so that we can orient ship properly - requires multiple calls/sec else if (!IS_BASE && blk is IMyTimerBlock) { timer = blk as IMyTimerBlock; timer.SetValueFloat("TriggerDelay", 1.0f); } // Light (interior or spotlight) determines where we will land else if (IS_BASE && IS_PLANET && blk is IMyInteriorLight) { landLight = blk as IMyInteriorLight; } // Landing gear.... else if (!IS_BASE && blk is IMyLandingGear) { IMyLandingGear gear = blk as IMyLandingGear; gears.Add(gear); if (gear.CustomName.ToLower().Contains("main")) { mainGear = gears.Count - 1; } } } // Make sure all gyros reset resetGyros(); // Clear block list blks.Clear(); // Get text panel blocks used by Wico Area Network for communication GridTerminalSystem.GetBlocksOfType <IMyTextPanel>(blks, hasWANRPrefix); if (blks.Count == 0) { Echo("Error: Can't find message received text panel for Wico Area Network"); all_blocks_found = false; } else { messageReceiver = blks[0] as IMyTextPanel; messageReceiver.WritePublicTitle(""); messageReceiver.WritePrivateTitle("NAV"); } if (WANProgram == null) { Echo("Error: Can't find programming block for Wico Area Network"); all_blocks_found = false; } if (lcdPanel == null) { Echo("Error: Expect 1 LCD"); all_blocks_found = false; } if (!IS_PLANET && connector == null) { Echo("Error: Can't find any connectors to use for docking"); all_blocks_found = false; } if (!IS_BASE && remoteControl == null) { Echo("Error: Can't find any remote control blocks"); all_blocks_found = false; } if (!IS_PLANET && door == null) { Echo("Error: Can't find door"); all_blocks_found = false; } if (!IS_BASE && gyros.Count == 0) { Echo("Error: No gyros detected"); all_blocks_found = false; } if (!IS_BASE && timer == null) { Echo("Error: No timer found"); all_blocks_found = false; } if (IS_PLANET && landLight == null) { Echo("Error: No light for landing ship destination found"); all_blocks_found = false; } if (!IS_BASE && gears.Count == 0) { Echo("Warning: no landing gear found. You will not be able to land on planets"); } // Init communicator state machine comm = communicate().GetEnumerator(); // Clear autopilot state machine fly = null; #endregion }
public BMyEnvironment(Program Assembly, string arguments) { this.Assembly = Assembly; ArgBag = BaconArgs.parse(arguments); Log = BMyLoggerFactory.getLogger(ArgBag, Assembly); }