//populates some form values, gets scenario timeframe
        private void InitConnection()
        {
            if (!_stkconnected)
            {
                // Get reference to running STK instance
                _uiApp = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application") as AgUiApplication;

                // Get our IAgStkObjectRoot interface
                _stkRoot      = _uiApp.Personality2 as AgStkObjectRoot;
                _zscen        = _stkRoot.CurrentScenario as IAgScenario;
                _stkconnected = true;

                dtp_start.Value = DateTime.ParseExact(_zscen.StartTime, ParsingFormats, null, System.Globalization.DateTimeStyles.None);
                dtp_end.Value   = DateTime.ParseExact(_zscen.StopTime, ParsingFormats, null, System.Globalization.DateTimeStyles.None);

                //btn_refresh.BackColor = Color.LimeGreen;
            }
            else
            {
                //refresh scenario times
                dtp_start.Value = DateTime.ParseExact(_zscen.StartTime, ParsingFormats, null, System.Globalization.DateTimeStyles.None);
                dtp_end.Value   = DateTime.ParseExact(_zscen.StopTime, ParsingFormats, null, System.Globalization.DateTimeStyles.None);
            }


            if (string.IsNullOrEmpty(_workingUserDirectory))
            {
                //get user directory for working purposes
                IAgExecCmdResult conRes = _stkRoot.ExecuteCommand(@"GetDirectory / UserData");
                _workingUserDirectory = conRes[0];
            }

            SafelyUpdateLabel("Connected and using: " + Environment.NewLine + _workingUserDirectory);
        }
        private void ButtonConnect_Click(object sender, EventArgs e)
        {
            try
            {
                // Connect to open STK
                AgUiApplication app = System.Runtime.InteropServices.Marshal.GetActiveObject("STK12.Application") as AgUiApplication;
                m_root = app.Personality2 as AgStkObjectRoot;

                if (m_root.Children.Count == 0)
                {
                    throw new Exception("No scenario open.");
                }

                PopulateComboBoxes();

                //IMPORTANT - set default units to epoch seconds
                m_root.UnitPreferences.SetCurrentUnit("DateFormat", "EpSec");

                // Add event handlers to update combo boxes when object is added/removed/modified
                m_root.OnStkObjectAdded   += new IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(Root_OnStkObjectAdded);
                m_root.OnStkObjectDeleted += new IAgStkObjectRootEvents_OnStkObjectDeletedEventHandler(Root_OnStkObjectDeleted);
                m_root.OnStkObjectChanged += new IAgStkObjectRootEvents_OnStkObjectChangedEventHandler(Root_OnStkObjectChanged);

                buttonConnect.Enabled    = false;
                radioButtonOpen.Enabled  = true;
                radioButtonClose.Enabled = true;
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error connecting to STK: " + exception.Message, "Error");
            }
        }
Exemple #3
0
        //#####################################################################
        /// <summary>
        /// 初始化STK 10 桌面程序
        /// <para>1 启动STK桌面程序(若已有场景,则关联当前场景)</para>
        /// <para>2 为uiApp,stkRoot赋值</para>
        /// </summary>
        public static void InitialSTK10Desktop()
        {
            try
            {
                try
                {
                    //  关联已打开的STK桌面程序
                    uiApp = Marshal.GetActiveObject("STK10.Application") as AgUiApplication;
                }
                catch
                {
                    //  创建新的STK桌面程序
                    uiApp = new AgUiApplication();
                    uiApp.LoadPersonality("STK");
                    uiApp.Visible     = true;
                    uiApp.UserControl = true;
                }

                // Retrieve the root of the StkEngine Automation Object Model.
                _stkRoot = uiApp.Personality2 as AGI.STKObjects.AgStkObjectRoot;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "初始化STK 10出错!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Exemple #4
0
        //#####################################################################
        /// <summary>
        /// 初始化STK 11 桌面程序
        /// <para>1 启动STK桌面程序(若已有场景,则关联当前场景)</para>
        /// <para>2 为uiApp,stkRoot赋值</para>
        /// </summary>
        public static void InitialSTK11Desktop()
        {
            try
            {
                try
                {
                    //  关联已打开的STK桌面程序
                    uiApp = Marshal.GetActiveObject("STK11.Application") as AgUiApplication;
                }
                catch
                {
                    //  创建新的STK桌面程序
                    //Guid clsID = typeof(AgUiApplicationClass).GUID;
                    //Type t = Type.GetTypeFromCLSID(clsID);
                    //uiApp = Activator.CreateInstance(t) as AGI.Ui.Application.AgUiApplication;
                    uiApp = new AgUiApplication();
                    uiApp.LoadPersonality("STK");
                    uiApp.Visible     = true;
                    uiApp.UserControl = true;
                }

                // Retrieve the root of the StkEngine Automation Object Model.
                _stkRoot = uiApp.Personality2 as AGI.STKObjects.AgStkObjectRoot;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "初始化STK 11出错!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void createScenarioTleDoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            app = new AgUiApplication();
            app.LoadPersonality("STK");
            root      = (AgStkObjectRoot)app.Personality2;
            initState = new InitialState();
            satData   = new Data(Convert.ToDouble(tbMass.Text), Convert.ToDouble(tbDragArea.Text), Convert.ToDouble(tbCd.Text), Convert.ToDouble(tbSolarArea.Text), Convert.ToDouble(tbCr.Text));
            STK.CreateScenarioFromTle(ref root, Convert.ToDouble(this.nudDuration.Value), ref initState, currentTle);
            STK.ConfigurePropagator(root);
            root.Rewind();
        }
        private void createScenarioSatcatDoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            app = new AgUiApplication();
            app.LoadPersonality("STK");
            root      = (AgStkObjectRoot)app.Personality2;
            initState = new InitialState();
            satData   = new Data(Convert.ToDouble(tbMass.Text), Convert.ToDouble(tbDragArea.Text), Convert.ToDouble(tbCd.Text), Convert.ToDouble(tbSolarArea.Text), Convert.ToDouble(tbCr.Text));
            string satelliteID = this.dgvSatList.SelectedRows[0].Cells[1].Value.ToString();

            currentTle = STK.CreateScenarioFromSatcat(ref root, Convert.ToDouble(this.nudDuration.Value), ref initState, satelliteID);

            STK.ConfigurePropagator(root);
            root.Rewind();
        }
        private void ConnectToSTK()
        {
            // Try to connect to existing STK instance, otherwise open a new one
            try
            {
                m_stkApplication = Marshal.GetActiveObject("STK12.Application") as AgUiApplication;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                m_stkApplication = new AgUiApplication();

                m_stkApplication.LoadPersonality("STK");
                m_stkApplication.Visible = true;
            }

            m_stkRoot = (AgStkObjectRoot)m_stkApplication.Personality2;
        }
Exemple #8
0
        public NPAS_To_STK()
        {
            missionindex = new string[200];

            try
            {
                m_oSTK = Marshal.GetActiveObject("STK11.Application") as AGI.Ui.Application.AgUiApplication;
                Console.Write("Looking for an instance of STK... ");
            }
            catch
            {
                Console.Write("Creating a new STK 11 instance... ");
                Guid clsID = typeof(AgUiApplicationClass).GUID;
                Type oType = Type.GetTypeFromCLSID(clsID);
                m_oSTK = Activator.CreateInstance(oType) as AGI.Ui.Application.AgUiApplication;
                try
                {
                    m_oSTK.LoadPersonality("STK");
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    Console.WriteLine("Error");
                    Console.WriteLine(ex.Message);
                    //  Console.WriteLine("Press any key to continue . . .");
                    //  Console.ReadKey();
                    Environment.Exit(0);
                }
            }
            try
            {
                m_oApplication = (IAgStkObjectRoot)m_oSTK.Personality2;
                Console.WriteLine("done.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadKey();
                Environment.Exit(0);
            }
        }
Exemple #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            AgUiApplication uiApplication = new AgUiApplication();

            uiApplication.LoadPersonality("STK");
            uiApplication.Visible = false;
            IAgStkObjectRoot root = uiApplication.Personality2 as IAgStkObjectRoot;

            root.NewScenario("scenario");
            IAgStar star = root.CurrentScenario.Children.New(AgESTKObjectType.eStar, "MyStar") as IAgStar;

            //wait();

            run();

            //wait();

            AgFacility facility = root.CurrentScenario.Children.New(AgESTKObjectType.eFacility, "MyFacility") as AgFacility;

            button1.Text = root.CurrentScenario.Children.Count.ToString();
            uiApplication.Quit();
        }
Exemple #10
0
        public static PropagationResults PropagateAstrogatorSatellite(AgStkObjectRoot root, AgUiApplication app, InitialState state, TLE tle, Data satData, Uncertainty uncertainty, int runId, int nRuns, string propName)
        {
            PropagationResults propResults = new PropagationResults();

            propResults.RunNumber = runId.ToString().PadLeft(3, '0');
            IAgSatellite sat = root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, tle.GetSatNumber() + "Astrogator") as IAgSatellite;

            //Set the propagator to Astrogator
            sat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
            //get the Driver for the Propagator
            IAgVADriverMCS driver = sat.Propagator as IAgVADriverMCS;

            //Clear all segments from the MCS
            driver.MainSequence.RemoveAll();

            //// Target Sequence ////
            IAgVAMCSTargetSequence ts = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeTargetSequence, "SetupState", "-") as IAgVAMCSTargetSequence;

            ts.Action = AgEVATargetSeqAction.eVATargetSeqActionRunActiveProfiles;

            // add the initial state segment in the target sequence
            IAgVAMCSInitialState initState = ts.Segments.Insert(AgEVASegmentType.eVASegmentTypeInitialState, "InitialState", "-") as IAgVAMCSInitialState;

            initState.OrbitEpoch = ((IAgScenario)root.CurrentScenario).StartTime;
            // define elements
            initState.SetElementType(AgEVAElementType.eVAElementTypeCartesian);
            IAgVAElementCartesian cart = initState.Element as IAgVAElementCartesian;

            cart.X  = Convert.ToDouble(state.CartesianPosX);
            cart.Y  = Convert.ToDouble(state.CartesianPosY);
            cart.Z  = Convert.ToDouble(state.CartesianPosZ);
            cart.Vx = Convert.ToDouble(state.CartesianVelX);
            cart.Vy = Convert.ToDouble(state.CartesianVelY);
            cart.Vz = Convert.ToDouble(state.CartesianVelZ);

            // spacecraft parameters
            IAgVASpacecraftParameters spacecraftParameters = (IAgVASpacecraftParameters)initState.SpacecraftParameters;

            spacecraftParameters.DryMass  = satData.Mass;
            spacecraftParameters.Cd       = satData.Cd;
            spacecraftParameters.DragArea = satData.DragArea;
            spacecraftParameters.Cr       = satData.Cr;
            spacecraftParameters.SolarRadiationPressureArea = satData.SunArea;
            spacecraftParameters.RadiationPressureArea      = 1e-10;
            IAgVAFuelTank fuelTank = (IAgVAFuelTank)initState.FuelTank;

            fuelTank.FuelMass = 0;

            // enable the control parameter for the state variables
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianX);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianY);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianZ);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVx);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVy);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVz);

            // add the results
            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/InTrack");
            IAgVAStateCalcRelMotion intrackRel = ((IAgVAMCSSegment)initState).Results[0] as IAgVAStateCalcRelMotion;

            intrackRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_1 = intrackRel.Reference as IAgLinkToObject;

            link_1.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/Radial");
            IAgVAStateCalcRelMotion radialRel = ((IAgVAMCSSegment)initState).Results[1] as IAgVAStateCalcRelMotion;

            radialRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_2 = radialRel.Reference as IAgLinkToObject;

            link_2.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/CrossTrack");
            IAgVAStateCalcRelMotion crosstrackRel = ((IAgVAMCSSegment)initState).Results[2] as IAgVAStateCalcRelMotion;

            crosstrackRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_3 = crosstrackRel.Reference as IAgLinkToObject;

            link_3.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/InTrackRate");
            IAgVAStateCalcRelMotion intrackrateRel = ((IAgVAMCSSegment)initState).Results[3] as IAgVAStateCalcRelMotion;

            intrackrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_4 = intrackrateRel.Reference as IAgLinkToObject;

            link_4.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/RadialRate");
            IAgVAStateCalcRelMotion radialrateRel = ((IAgVAMCSSegment)initState).Results[4] as IAgVAStateCalcRelMotion;

            radialrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_5 = radialrateRel.Reference as IAgLinkToObject;

            link_5.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/CrossTrackRate");
            IAgVAStateCalcRelMotion crosstrackrateRel = ((IAgVAMCSSegment)initState).Results[5] as IAgVAStateCalcRelMotion;

            crosstrackrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_6 = crosstrackrateRel.Reference as IAgLinkToObject;

            link_6.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            /// differential corrector setup ///
            IAgVAProfileDifferentialCorrector dc = ts.Profiles["Differential Corrector"] as IAgVAProfileDifferentialCorrector;

            // control parameters
            IAgVADCControl xControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.X");

            xControlParam.Enable       = true;
            xControlParam.MaxStep      = 1;
            xControlParam.Perturbation = 0.1;
            IAgVADCControl yControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Y");

            yControlParam.Enable       = true;
            yControlParam.MaxStep      = 1;
            yControlParam.Perturbation = 0.1;
            IAgVADCControl zControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Z");

            zControlParam.Enable       = true;
            zControlParam.MaxStep      = 1;
            zControlParam.Perturbation = 0.1;
            IAgVADCControl vxControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vx");

            vxControlParam.Enable       = true;
            vxControlParam.MaxStep      = 0.001;
            vxControlParam.Perturbation = 1e-04;
            IAgVADCControl vyControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vy");

            vyControlParam.Enable       = true;
            vyControlParam.MaxStep      = 0.001;
            vyControlParam.Perturbation = 1e-04;
            IAgVADCControl vzControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vz");

            vzControlParam.Enable       = true;
            vzControlParam.MaxStep      = 0.001;
            vzControlParam.Perturbation = 1e-04;

            // results
            double[] deviations = uncertainty.GetRandomDeviation();

            IAgVADCResult intrackResult = dc.Results.GetResultByPaths("InitialState", "InTrack");

            intrackResult.Enable       = true;
            intrackResult.DesiredValue = deviations[0];
            intrackResult.Tolerance    = 0.01;
            IAgVADCResult radialResult = dc.Results.GetResultByPaths("InitialState", "Radial");

            radialResult.Enable       = true;
            radialResult.DesiredValue = deviations[1];
            radialResult.Tolerance    = 0.01;
            IAgVADCResult crosstrackResult = dc.Results.GetResultByPaths("InitialState", "CrossTrack");

            crosstrackResult.Enable       = true;
            crosstrackResult.DesiredValue = deviations[2];
            crosstrackResult.Tolerance    = 0.01;
            IAgVADCResult intrackRateResult = dc.Results.GetResultByPaths("InitialState", "InTrackRate");

            intrackRateResult.Enable       = true;
            intrackRateResult.DesiredValue = deviations[3] / 1000;
            intrackRateResult.Tolerance    = 0.001;
            IAgVADCResult radialRateResult = dc.Results.GetResultByPaths("InitialState", "RadialRate");

            radialRateResult.Enable       = true;
            radialRateResult.DesiredValue = deviations[4] / 1000;
            radialRateResult.Tolerance    = 0.001;
            IAgVADCResult crosstrackRateResult = dc.Results.GetResultByPaths("InitialState", "CrossTrackRate");

            crosstrackRateResult.Enable       = true;
            crosstrackRateResult.DesiredValue = deviations[5] / 1000;
            crosstrackRateResult.Tolerance    = 0.001;

            /// Propagator ///
            IAgVAMCSPropagate propagate = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypePropagate, "ToGround", "-") as IAgVAMCSPropagate;

            ((IAgVAMCSSegment)propagate).Properties.Color = Color.Red;
            //propagate.PropagatorName = "CustomProp";
            propagate.PropagatorName = propName;

            // add an Epoch stopping condition
            IAgVAStoppingConditionCollection propStoppingConditions = propagate.StoppingConditions as IAgVAStoppingConditionCollection;
            IAgVAStoppingConditionElement    epochElement           = propStoppingConditions.Add("Epoch");
            IAgVAStoppingCondition           epoch = (IAgVAStoppingCondition)epochElement.Properties;

            epoch.Trip = ((IAgScenario)root.CurrentScenario).StopTime;
            // add an Altitude stopping condition
            IAgVAStoppingConditionElement altitudeElement = propStoppingConditions.Add("Altitude");
            IAgVAStoppingCondition        altitude        = (IAgVAStoppingCondition)altitudeElement.Properties;

            altitude.Trip = 0;
            // remove the original stopping condition
            propagate.StoppingConditions.Remove("Duration");

            // run the MCS
            driver.RunMCS();
            driver.ClearDWCGraphics();


            // get the stop time
            IAgDataPrvInterval dp          = ((IAgStkObject)sat).DataProviders.GetDataPrvIntervalFromPath("Astrogator MCS Ephemeris Segments") as IAgDataPrvInterval;
            IAgDrResult        result      = dp.Exec(((IAgScenario)root.CurrentScenario).StartTime, ((IAgScenario)root.CurrentScenario).StopTime);
            string             satStopTime = result.DataSets[3].GetValues().GetValue(1).ToString();

            if (satStopTime.Equals((Convert.ToString(((IAgScenario)root.CurrentScenario).StopTime))))
            {
                // the satellite does not decay (it is propagated until the scenario stop time)
                propResults.IsDecayed = false;
            }
            else
            {
                propResults.IsDecayed   = true;
                propResults.ImpactEpoch = satStopTime;
                // remove the millisecond part
                satStopTime = satStopTime.Split('.')[0];

                //ask for LLA data at stop time
                IAgDataPrvTimeVar dpInfo  = ((IAgStkObject)sat).DataProviders.GetDataPrvInfoFromPath("LLA State//Fixed") as IAgDataPrvTimeVar;
                IAgDrResult       resInfo = dpInfo.ExecSingle(satStopTime);
                string            lat     = resInfo.DataSets[1].GetValues().GetValue(0).ToString();
                string            lon     = resInfo.DataSets[2].GetValues().GetValue(0).ToString();
                string            alt     = resInfo.DataSets[3].GetValues().GetValue(0).ToString();
                propResults.ImpactLat = lat;
                propResults.ImpactLon = lon;
                propResults.ImpactAlt = alt;

                // create a target object
                IAgTarget target = root.CurrentScenario.Children.New(AgESTKObjectType.eTarget, "Target" + (runId).ToString().PadLeft(3, '0')) as IAgTarget;
                target.Graphics.Color        = Color.Red;
                target.Graphics.LabelVisible = false;
                IAgPosition pos = target.Position;
                pos.AssignGeodetic(lat, lon, 0);

                // create and display the time event
                IAgCrdnProvider   provider   = root.CurrentScenario.Children["Target" + (runId).ToString().PadLeft(3, '0')].Vgt;
                IAgCrdnEventEpoch eventEpoch = provider.Events.Factory.CreateEventEpoch(runId.ToString().PadLeft(3, '0') + "_Impact", "Impact Epoch") as IAgCrdnEventEpoch;
                eventEpoch.Epoch = satStopTime;
                try { root.ExecuteCommand("Timeline * TimeComponent Add ContentView \"Scenario Availability\" \"Target/Target" + (runId).ToString().PadLeft(3, '0') + " " + runId.ToString().PadLeft(3, '0') + "_Impact Time Instant\""); }
                catch (Exception) { }
                root.ExecuteCommand("Timeline * Refresh");

                // create a unique ephemeris file for each Astrogator run
                DateTime now = DateTime.Now;
                string   satEphemerisPath = Directory.GetCurrentDirectory() + "\\Ephemeris\\Reentry_run_" + (runId).ToString().PadLeft(3, '0') + ".e";
                root.ExecuteCommand("ExportDataFile */Satellite/" + tle.GetSatNumber() + "Astrogator Ephemeris \"" + satEphemerisPath + "\" Type STK CoordSys ICRF CentralBody Earth InterpBoundaries Include");
                propResults.EphemerisFilePath = satEphemerisPath;
                // unload Astrogator satellite
                root.CurrentScenario.Children[tle.GetSatNumber() + "Astrogator"].Unload();

                if (runId == nRuns)
                {
                    // remove the TLE sat
                    // root.CurrentScenario.Children[tle.GetSatNumber()].Unload();
                }
            }

            try
            {
                AGI.Ui.Core.IAgUiWindowsCollection windows = app.Windows;
                foreach (dynamic window in app.Windows)
                {
                    string windowCaption = (string)window.Caption;
                    if (windowCaption.Contains("Setup"))
                    {
                        window.Close();
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(propResults);
        }