Ejemplo n.º 1
0
            public bool parse(IMyTerminalBlock block, out List <Data> cfg)
            {
                cfg = new List <Data>();

                MyIni ini = new MyIni();

                if (ini.TryParse(block.CustomData))
                {
                    // read system config
                    if (ini.ContainsSection("system"))
                    {
                        Program.DefaultAirlockTag       = getIniString(ini, "system", "tag", "Airlock");
                        Program.DefaultAirlockInnerTag  = getIniString(ini, "system", "innertag", "In");
                        Program.DefaultAirlockOuterTag  = getIniString(ini, "system", "outertag", "Out");
                        Program.DefaultAirlockDelayTime = TimeSpan.FromSeconds(getIniDouble(ini, "system", "delay", 1.0));
                        Program.DefaultAutomaticMode    = getIniAutomatic(ini, "system", "mode", Automatic.Full);

                        switch (getIniString(ini, "system", "interval", "10"))
                        {
                        case "1":
                            Program.DefualtUpdateFrequency = UpdateFrequency.Update1;
                            break;

                        case "100":
                            Program.DefualtUpdateFrequency = UpdateFrequency.Update100;
                            break;

                        default:
                            Program.DefualtUpdateFrequency = UpdateFrequency.Update10;
                            break;
                        }
                    }

                    // read airlock config
                    List <string> sections = new List <string>();
                    ini.GetSections(sections);

                    foreach (var section in sections)
                    {
                        if (section != "system")
                        {
                            Data data = new Data();
                            data.name_      = section;
                            data.delay_     = TimeSpan.FromSeconds(getIniDouble(ini, section, "delay", Program.DefaultAirlockDelayTime.Seconds));
                            data.automatic_ = getIniAutomatic(ini, section, "automatic", Program.DefaultAutomaticMode);

                            cfg.Add(data);
                        }
                    }

                    return(true);
                }

                return(false);
            }
Ejemplo n.º 2
0
        void ExtractBlueprints()
        {
            _blueprints = new Dictionary <string, BlueprintInfo>();
            var sections = new List <string>();

            _ini.GetSections(sections);
            sections.ForEach(section => {
                if (section.ToLower() == "general")
                {
                    return;
                }

                _blueprints.Add(section, BlueprintInfo.FromIni(_ini, section, Echo));
            });
        }
            public AutoConnectionDispatcher(MyGridProgram program, CommandLine command, MyIni ini, Action <string> logger, IProcessManager manager)
            {
                this.logger  = logger;
                this.manager = manager;
                // Station level initialization
                this.stationName   = ini.GetThrow(INI_GENERAL_SECTION, INI_NAME_KEY).ToString();
                this.referenceName = ini.GetThrow(INI_GENERAL_SECTION, INI_REFERENCE_KEY).ToString();
                IMyTerminalBlock reference = program.GridTerminalSystem.GetBlockWithName(this.referenceName);

                if (reference == null)
                {
                    throw new ArgumentException($"Could not find reference block '{this.referenceName}'");
                }
                this.igc         = program.IGC;
                this.transformer = new CoordinatesTransformer(reference, manager);
                this.log("initializing");
                // Connectors initialization
                var sections = new List <string>();

                ini.GetSections(sections);
                foreach (string sectionName in sections.Where(s => s.StartsWith(AutoConnector.IniConnectorPrefix)))
                {
                    var connector = new AutoConnector(this.stationName, sectionName, program, this.logger, this.transformer, ini);
                    this.autoConnectors.Add(new AutoConnectionServer(ini, this.igc, connector, manager, this.logger));
                }
                this.log($"has {this.autoConnectors.Count} auto connectors");
                this.registerCommands(command, program);

                IMyBroadcastListener listener = this.igc.RegisterBroadcastListener("StationConnectionRequests");

                this.manager.Spawn(p => {
                    if (listener.HasPendingMessage)
                    {
                        MyIGCMessage msg = listener.AcceptMessage();
                        command.StartCmd($"{msg.As<string>()} {msg.Source}", CommandTrigger.Antenna);
                    }
                }, "ac-dispatcher");

                this.manager.AddOnSave(save);
            }
Ejemplo n.º 4
0
            void updateData()
            {
                bool changed = false;

                if (!ReferenceEquals(this.prevData, this.remote.CustomData))
                {
                    this.prevData = this.remote.CustomData;
                    var ini = new MyIni();
                    ini.Parse(this.remote.CustomData);
                    ini.GetSections(this.tmpSections);
                    this.waypoints.Clear();
                    this.tmpSections.ForEach(s => this.waypoints.Add(s, new APWaypoint(ini, s)));
                    changed = true;
                }
                this.remote.GetWaypointInfo(this.tmpWps);
                if (this.tmpWps.Count > 0)
                {
                    foreach (MyWaypointInfo wp in this.tmpWps)
                    {
                        APWaypoint curWP;
                        if (this.waypoints.TryGetValue(wp.Name, out curWP))
                        {
                            curWP.WP = wp;
                        }
                        else
                        {
                            this.waypoints.Add(wp.Name, new APWaypoint(wp));
                        }
                    }
                    this.save();
                    this.remote.ClearWaypoints();
                }
                if (changed)
                {
                    foreach (APWaypoint wp in this.waypoints.Values)
                    {
                        wp.Update(this, this.logger);
                    }
                }
            }
Ejemplo n.º 5
0
        public Program()
        {
            MyIni         config   = ParseIni();
            List <string> sections = new List <string>();

            config.GetSections(sections);

            List <Role> roles = new List <Role>();

            foreach (string section in sections)
            {
                Echo($"Adding Role: {section}");
                //TODO: I'm so sorry...
                if (section.StartsWith("deposit"))
                {
                    continue;
                }
                roles.Add(RoleFactory.Build(section, config, this));
            }

            this.drone = new Drone(this, roles);
        }
Ejemplo n.º 6
0
            public Tunnel(MyIni asteroidCatalogue)
            {
                //go into the asteroid catalogue, look at available deposits and assign StartingPoint, EndPoint and TunnelIndex
                List <string> sections = new List <string>();

                asteroidCatalogue.GetSections(sections);
                IEnumerable <string> deposits = sections.Where(record => record.StartsWith("deposit"));

                //Assume one entry for now
                string rawValue, deposit;
                double depth;
                int    index;

                if (deposits != null && deposits.Count() != 0)
                {
                    deposit = deposits.First();
                }
                else
                {
                    throw new Exception("No deposit data found!");
                }

                if (!asteroidCatalogue.Get(deposit, "deposit_depth").TryGetDouble(out depth))
                {
                    throw new Exception("deposit_depth is missing");
                }
                if (!asteroidCatalogue.Get(deposit, "index").TryGetInt32(out index))
                {
                    throw new Exception("index is missing");
                }

                //Convert config data into usable vectors
                Vector3D TopLeftCorner;

                if (asteroidCatalogue.Get(deposits.First(), "top_left_corner").TryGetString(out rawValue))
                {
                    Vector3D.TryParse(rawValue, out TopLeftCorner);
                }
                else
                {
                    throw new Exception("top_left_corner is missing");
                }

                Vector3D TopRightCorner;

                if (asteroidCatalogue.Get(deposits.First(), "top_right_corner").TryGetString(out rawValue))
                {
                    Vector3D.TryParse(rawValue, out TopRightCorner);
                }
                else
                {
                    throw new Exception("top_right_corner is missing");
                }

                Vector3D BottomLeftCorner;

                if (asteroidCatalogue.Get(deposits.First(), "bottom_left_corner").TryGetString(out rawValue))
                {
                    Vector3D.TryParse(rawValue, out BottomLeftCorner);
                }
                else
                {
                    throw new Exception("bottom_left_corner is missing");
                }

                SetPointsFromDeposit(index, TopLeftCorner, TopRightCorner, BottomLeftCorner, depth);
            }
Ejemplo n.º 7
0
            public override void HandleCallback(string callback)
            {
                switch (callback)
                {
                case "unicast":
                    MyIGCMessage message = Drone.NetworkService.GetUnicastListener().AcceptMessage();

                    if (message.Data == null)
                    {
                        Drone.LogToLcd($"\nNo Message");
                    }

                    if (message.Tag == DockingRequestChannel)
                    {
                        Drone.LogToLcd("\nReceived Docking Request");
                        IMyShipConnector dockingPort = GetFreeDockingPort();

                        if (dockingPort == null)
                        {
                            Drone.LogToLcd("\nNo Free Docking Port");
                        }
                        else
                        {
                            MyTuple <Vector3D, Vector3D, Vector3D> payload = new MyTuple <Vector3D, Vector3D, Vector3D>();
                            payload.Item1 = dockingPort.GetPosition() + dockingPort.WorldMatrix.Forward * 40;
                            payload.Item2 = dockingPort.GetPosition() + 1.5 * dockingPort.WorldMatrix.Forward;

                            Drone.LogToLcd($"\nClearance granted: {message.Source}");
                            Drone.LogToLcd($"\nApproach: {payload.Item1.ToString()}");
                            Drone.LogToLcd($"\nDocking Port: { payload.Item2.ToString()}");

                            Drone.Program.IGC.SendUnicastMessage(message.Source, DockingRequestChannel, payload);
                        }
                    }
                    else if (message.Tag == "Notifications")
                    {
                        Drone.LogToLcd($"Received notification:{message.Data.ToString()}");
                        DroneKlaxon.LoopPeriod = 2f;
                        DroneKlaxon.Play();
                    }
                    else if (message.Tag == "survey_reports")
                    {
                        MyTuple <long, string, double, Vector3D, Vector3D, Vector3D> report = (MyTuple <long, string, double, Vector3D, Vector3D, Vector3D>)message.Data;
                        Drone.LogToLcd($"Received survey_report: {report.ToString()}");

                        //TODO: This needs to be in a persistence layer, not the CustomData
                        MyIni            ini = new MyIni();
                        MyIniParseResult config;
                        if (!ini.TryParse(Drone.Program.Me.CustomData, out config))
                        {
                            throw new Exception($"Error parsing config: {config.ToString()}");
                        }

                        //TODO: what about multiple deposits?
                        ini.Set($"deposit {report.Item1.ToString()}", "deposit_type", report.Item2.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "deposit_depth", report.Item3.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "top_left_corner", report.Item4.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "top_right_corner", report.Item5.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "bottom_left_corner", report.Item6.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "index", 0);

                        Drone.Program.Me.CustomData = ini.ToString();
                    }
                    else if (message.Tag == "tunnel_complete")
                    {
                        MyIni ini = new MyIni();

                        MyIniParseResult config;
                        if (!ini.TryParse(Drone.Program.Me.CustomData, out config))
                        {
                            throw new Exception($"Error parsing config: {config.ToString()}");
                        }

                        int completedIndex = (int)message.Data;

                        List <string> sections = new List <string>();
                        ini.GetSections(sections);
                        IEnumerable <string> deposits = sections.Where(record => record.StartsWith("deposit"));
                        string deposit;

                        if (deposits != null && deposits.Count() != 0)
                        {
                            deposit = deposits.First();
                        }
                        else
                        {
                            throw new Exception("No deposit data found!");
                        }

                        ini.Set(deposit, "index", completedIndex + 1);
                        Drone.Program.Me.CustomData = ini.ToString();
                    }

                    break;

                case "docking_request_pending":
                    ProcessDockingRequest();
                    break;

                case "recall_miner":
                    Drone.LogToLcd("Recalling miner");
                    Drone.Program.IGC.SendUnicastMessage(MinerAddress, "recall", "recall");
                    break;

                case "recall_surveyor":
                    Drone.LogToLcd("Recalling surveyor");
                    Drone.Program.IGC.SendUnicastMessage(SurveyorAddress, "recall", "recall");
                    break;

                case "deploy_miner":
                    Drone.LogToLcd("Launching miner");

                    List <IMyProgrammableBlock> miners = new List <IMyProgrammableBlock>();
                    Drone.Grid().GetBlocksOfType(miners, pb => MyIni.HasSection(pb.CustomData, "miner"));

                    //We only support one miner for now
                    // Set the deposit details in the miners config
                    IMyProgrammableBlock miner   = miners.First();
                    MyIni            minerConfig = new MyIni();
                    MyIniParseResult result;
                    if (!minerConfig.TryParse(miner.CustomData, out result))
                    {
                        Drone.LogToLcd(miner.CustomData);
                        throw new Exception($"Error parsing config: {result.ToString()}");
                    }

                    //Vector3D MiningSite = DepositCentre + 10 * Vector3D.Normalize(DepositNormal);
                    //Vector3D TunnelEnd = DepositCentre - DepositDepth * Vector3D.Normalize(DepositNormal);

                    //get deposit data from catalogue
                    //calculate mining_site for next tunnel
                    //calculate tunnel_end from mining_site and depth
                    MyIni asteroidCatalogue = new MyIni();
                    asteroidCatalogue.TryParse(Drone.Program.Me.CustomData);
                    Tunnel tunnel = new Tunnel(asteroidCatalogue);

                    minerConfig.Set("miner", "mining_site", tunnel.StartingPoint.ToString());
                    minerConfig.Set("miner", "tunnel_end", tunnel.EndPoint.ToString());
                    minerConfig.Set("miner", "index", tunnel.TunnelIndex);
                    miner.CustomData = minerConfig.ToString();

                    miner.TryRun("launch");
                    break;

                case "deploy_surveyor":
                    Drone.LogToLcd("Launching surveyor");

                    List <IMyProgrammableBlock> surveyors = new List <IMyProgrammableBlock>();
                    Drone.Grid().GetBlocksOfType(surveyors, pb => MyIni.HasSection(pb.CustomData, "surveyor"));
                    IMyProgrammableBlock surveyor = surveyors.First();

                    surveyor.TryRun("launch");
                    break;

                case "echo":
                    Drone.LogToLcd("Echo");
                    DroneKlaxon.Play();
                    break;

                case "":
                    // Just Ignore empty arguments
                    break;

                default:
                    Drone.LogToLcd($"\nDrone received unrecognized callback: {callback}");
                    break;
                }
            }
Ejemplo n.º 8
0
        public void Main(string argumentString)
        {
            _output.Clear();
            var arguments = argumentString.ToUpper().Split(';');

            _output.Add($"Mode: {(_isFast ? "Fast" : "Slow")}");

            switch (arguments[0])
            {
            case "":
                foreach (var entry in _spinners)
                {
                    var spinner         = entry.Value;
                    var cycleStatus     = spinner.CalculateCycleStatus();
                    var maxPosition     = spinner.Pistons.Sum(piston => piston.HighestPosition);
                    var currentPosition = spinner.Pistons.Sum(piston => piston.CurrentPosition);

                    _output.Add($"{entry.Key}:");
                    _output.Add($"  {Math.Round(currentPosition, 2)} m/{Math.Round(maxPosition, 2)} m");
                    _output.Add($"  Change in angle: {Math.Round(cycleStatus.ChangeInAngle)}°");

                    if (!cycleStatus.CycleFinished)
                    {
                        continue;
                    }

                    if (spinner.Pistons.All(piston => piston.CurrentPosition == piston.HighestPosition))
                    {
                        spinner.Rotor.Enabled = false;
                        spinner.Drills.ForEach(drill => drill.Enabled = false);
                    }

                    var extendTotalBy = _isFast ? _pistonExtendFast : _pistonExtendSlow;

                    foreach (var piston in spinner.Pistons)
                    {
                        var extendBy = Math.Min(piston.HighestPosition - piston.CurrentPosition, extendTotalBy);
                        extendTotalBy  -= extendBy;
                        piston.MaxLimit = piston.CurrentPosition + extendBy;
                    }
                }
                ;
                break;

            case "LOWER":
                foreach (var spinner in _spinners.Values)
                {
                    spinner.Rotor.RotorLock = true;
                    spinner.Pistons.ForEach(piston => {
                        piston.MaxLimit = piston.HighestPosition;
                        piston.Velocity = _pistonLowerSpeed / spinner.Pistons.Count();
                    });
                }

                break;

            case "PARSE":
                MyIniParseResult result;
                if (!_ini.TryParse(Me.CustomData, out result))
                {
                    _output.Add($"CustomData parsing error: \nLine {result.LineNo}\nError: {result.Error}");
                    return;
                }

                var lookup = new LookupHelper {
                    GridTerminalSystem = GridTerminalSystem,
                };

                _pistonLowerSpeed = (float)_ini
                                    .Get("general", "PistonLowerSpeed")
                                    .ToDouble(_pistonLowerSpeed);
                _drillSpeedMetersPerSecond = (float)_ini
                                             .Get("general", "DrillSpeedMeterPerSecond")
                                             .ToDouble(_drillSpeedMetersPerSecond);

                var lcdInfoName = _ini.Get("general", "LcdInfo").ToString(_lcdInfoName);
                _lcdInfo = lookup.GetBlockWithName <IMyTextPanel>(lcdInfoName);

                _spinners = new Dictionary <string, SpinnerInfo>();
                var sections = new List <string>();
                _ini.GetSections(sections);
                sections.ForEach(section => {
                    if (section.ToLower() == "general")
                    {
                        return;
                    }

                    var spinnerInfo = SpinnerInfo.FromIni(_ini, section, lookup);
                    _spinners.Add(section, spinnerInfo);
                });

                break;

            case "PERSIST_PISTON_POSITION":
                foreach (var entry in _spinners)
                {
                    entry.Value.Pistons.ForEach(piston => piston.MaxLimit = piston.CurrentPosition);
                }

                break;

            case "RETRACT":
                foreach (var spinner in _spinners.Values)
                {
                    var velocity = -3f / spinner.Pistons.Count;
                    spinner.Pistons.ForEach(piston => piston.Velocity = velocity);
                }

                break;

            case "START":
                foreach (var spinner in _spinners.Values)
                {
                    spinner.Drills.ForEach(drill => drill.Enabled = true);
                    spinner.Pistons.ForEach(piston => {
                        piston.MaxLimit = piston.CurrentPosition;
                        piston.Enabled  = true;
                        piston.Velocity = 0.5f;
                    });
                    spinner.Rotor.RotorLock         = false;
                    spinner.Rotor.Enabled           = true;
                    spinner.Rotor.TargetVelocityRad = spinner.GetTargetVelocityRotorRad(_isFast, _drillSpeedMetersPerSecond);
                }

                Runtime.UpdateFrequency = UpdateFrequency.Update100;

                break;

            case "STOP":
                foreach (var spinner in _spinners.Values)
                {
                    spinner.Rotor.Enabled = false;
                    spinner.Drills.ForEach(drill => drill.Enabled = false);
                }

                Runtime.UpdateFrequency = UpdateFrequency.None;

                break;

            case "STOP_EMERGENCY":
                foreach (var spinner in _spinners.Values)
                {
                    spinner.Rotor.Enabled = false;
                    spinner.Drills.ForEach(drill => drill.Enabled    = false);
                    spinner.Pistons.ForEach(piston => piston.Enabled = false);
                }

                Runtime.UpdateFrequency = UpdateFrequency.None;

                break;

            case "TOGGLE_SPEED":
                _isFast = !_isFast;

                foreach (var spinner in _spinners.Values)
                {
                    spinner.Drills.ForEach(drill => drill.Enabled = !_isFast);
                    spinner.Rotor.TargetVelocityRad = spinner.GetTargetVelocityRotorRad(_isFast, _drillSpeedMetersPerSecond);
                }

                break;
            }

            _output.ForEach(line => Echo(line));
            _lcdInfo?.WriteText(String.Join("\n", _output.ToArray()));
        }