Ejemplo n.º 1
0
        private static Task PlayMoneyValue(Step step, ICall call, PlayValueStepSettings stepSettings)
        {
            var numbersToPromptsConverter = new MoneyValueToPrompts(call.Logger);
            var valueToPlay = (decimal?)DynamicState.GetProperty(call.CallState, stepSettings.Value);

            if (valueToPlay == null)
            {
                throw new ArgumentException("Value specified does not exist on CallState: " + stepSettings.Value);
            }

            var prompts = numbersToPromptsConverter.GetPromptsForValue(valueToPlay.Value);

            var promptSettings = new PlayerPromptSettings()
            {
                IsInterruptible = stepSettings.IsInterruptible,
                NextStep        = step.GetStepFromConnector(NextStep),
                Prompts         = prompts,
                Direction       = stepSettings.Direction
            };

            call.PromptPlayer.DoStepAsync(promptSettings);
            if (stepSettings.Direction != Direction.Outgoing)
            {
                call.CallState.AddStepToIncomingQueue(step.GetStepFromConnector(NextStep));
            }
            else
            {
                call.CallState.AddStepToOutgoingQueue(step.GetStepFromConnector(NextStep));
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 2
0
    private void recordDynamicState()
    {
        DynamicState ds = new DynamicState();

        foreach (MoveableScript m in moveables)
        {
            switch (m.type)
            {
            case BoardCodes.PLAYER:
                ds.playerPosition = m.GetCoords();
                break;

            case BoardCodes.MIMIC:
                ds.mimicPositions.Add(m.GetCoords());
                break;

            case BoardCodes.MIRROR:
                ds.mirrorPositions.Add(m.GetCoords());
                break;
            }
        }

        foreach (coord b in buttonCoords.Keys)
        {
            if (buttonCoords[b].laser.data.isActive)
            {
                ds.activeButtons.Add(b);
            }
        }

        dynamicStateStack.Push(ds);
        //Debug.Log (ds.toJson ());
        LoggingManager.instance.RecordEvent(LoggingManager.EventCodes.DYNAMIC_STATE, ds.toJson());
    }
Ejemplo n.º 3
0
        private static async Task PlayNumberValue(Step step, ICall call, PlayValueStepSettings stepSettings)
        {
            var promptSettings = new PlayerPromptSettings()
            {
                IsInterruptible = stepSettings.IsInterruptible,
                NextStep        = step.GetStepFromConnector(NextStep),
                Direction       = stepSettings.Direction
            };

            await call.PromptPlayer.DoStepAsync(promptSettings);

            var valueToPlay = DynamicState.GetProperty(call.CallState, stepSettings.Value);

            if (valueToPlay == null)
            {
                throw new ArgumentException("Value specified does not exist on CallState: " + stepSettings.Value);
            }

            await call.PromptPlayer.PlayNumberToLineAsync(valueToPlay.ToString(),
                                                          stepSettings.Direction == Direction.Incoming
                                                          ?call.CallState.GetIncomingLineId()
                                                              : call.CallState.GetOutgoingLineId());

            if (stepSettings.Direction != Direction.Outgoing)
            {
                call.CallState.AddStepToIncomingQueue(step.GetStepFromConnector(NextStep));
            }
            else
            {
                call.CallState.AddStepToOutgoingQueue(step.GetStepFromConnector(NextStep));
            }
        }
Ejemplo n.º 4
0
        public void TestInitialisation()
        {
            DynamicState state = new DynamicState();

            Assert.IsInstanceOfType(state, typeof(IState));
            Assert.AreEqual(DynamicState.TYPE, state.DescribeType());
        }
Ejemplo n.º 5
0
 public Target(String name, TargetType type, DynamicState dynamicState, int value)
 {
     Name         = name;
     Type         = type;
     DynamicState = dynamicState;
     Value        = value;
 }
 public Target(String name, TargetType type, DynamicState dynamicState, int value)
 {
     this.Name         = name;
     this.TargetType   = type;
     this.DynamicState = dynamicState;
     this.Value        = value;
 }
        public void DynamicState_CreateEmpty_DoesNotThrowUponReadCalls()
        {
            DynamicState empty = DynamicState.CreateEmpty(10);  // Arbitrary number

            Assert.DoesNotThrow(() => empty.GetEdge(2, 5));
            Assert.DoesNotThrow(() => empty.GetEdge(1, 2));
            Assert.DoesNotThrow(() => empty.GetEdge(7, 3));

            DynamicState.AreaEdge e1 = empty.GetEdge(2, 5);
            DynamicState.AreaEdge e2 = empty.GetEdge(1, 2);
            DynamicState.AreaEdge e3 = empty.GetEdge(7, 3);

            Assert.DoesNotThrow(() => { bool b = e1.IsCausingClearEffect; });
            Assert.DoesNotThrow(() => { bool b = e2.IsCausingPotentialEnemiesEffect; });
            Assert.DoesNotThrow(() => { int i = e1.ToNodeId; });

            for (int i = 0; i < 10; i++)
            {
                Assert.DoesNotThrow(() => empty.IsEnemyAreaReader()(i));
                Assert.DoesNotThrow(() => empty.IsControlledByTeamReader()(i));
                Assert.DoesNotThrow(() => empty.IsContestedAreaReader()(i));
                Assert.DoesNotThrow(() => empty.TakingFireMagnitudeLevelReader()(i));

                DynamicState.AreaNode n;
                Assert.DoesNotThrow(() => empty.GetNodeData(i));
                n = empty.GetNodeData(i);
                Assert.DoesNotThrow(() => { int d = n.TakingFireMagnitudeLevel; });
                Assert.DoesNotThrow(() => { bool b = n.IsControlledByTeam; });

                Assert.DoesNotThrow(() => { Dictionary <FactType, Fact> f = DynamicStateInternalReader.GetNodeFact(i, empty); });
                Assert.DoesNotThrow(() => { Dictionary <EffectType, EffectSum> f = DynamicStateInternalReader.GetNodeEffectSum(i, empty); });
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// An override of the Subsystem CanPerform method
        /// </summary>
        /// <param name="proposedEvent"></param>
        /// <param name="environment"></param>
        /// <returns></returns>
        public override bool CanPerform(Event proposedEvent, Universe environment)
        {
            if (base.CanPerform(proposedEvent, environment) == false)
            {
                return(false);
            }
            //double timetoslew = (rand()%5)+8;
            double timetoslew = _timetoslew;

            double es = proposedEvent.GetEventStart(Asset);
            double ts = proposedEvent.GetTaskStart(Asset);
            double te = proposedEvent.GetTaskEnd(Asset);

            if (es + timetoslew > ts)
            {
                if (es + timetoslew > te)
                {
                    // TODO: Change this to Logger
                    //Console.WriteLine("Antenna: Not enough time to slew event start: "+ es + "task end" + te);
                    return(false);
                }
                else
                {
                    ts = es + timetoslew;
                }
            }

            // set task end based upon time to capture
            te = ts + timetocapture;
            proposedEvent.SetTaskEnd(Asset, te);
            // from Brown, Pp. 99
            DynamicState    position               = Asset.AssetDynamicState;
            double          timage                 = ts + timetocapture / 2;
            Matrix <double> m_SC_pos_at_ts_ECI     = position.PositionECI(ts);
            Matrix <double> m_target_pos_at_ts_ECI = _task.Target.DynamicState.PositionECI(ts);
            Matrix <double> m_pv     = m_target_pos_at_ts_ECI - m_SC_pos_at_ts_ECI;
            Matrix <double> pos_norm = -m_SC_pos_at_ts_ECI / Matrix <double> .Norm(-m_SC_pos_at_ts_ECI);

            Matrix <double> pv_norm = m_pv / Matrix <double> .Norm(m_pv);


            double I               = (arc - Math.Sin(arc)) * (Math.Pow(r2, 4) - Math.Pow(r1, 4)) / 8;
            double area            = (Math.Pow(r2, 2) - Math.Pow(r1, 2)) * (Math.PI);
            double volume          = area * L;
            double deltaangle      = Math.Acos(Matrix <double> .Dot(position.PositionECI(te), position.PositionECI(ts))) / (Matrix[System.Double].Norm(position.PositionECI(te)) * Matrix[System.Double].Norm(position.PositionECI(ts)));
            double a               = deltaangle / (Math.Pow(te - ts, 2));
            double M               = density * volume;
            double force           = a * M;
            double finaldeflection = force * Math.Pow(L / 2, 2) * ((5 * (L / 2)) / (6 * E * I));
            double antstress       = (M * L / 2) / I;
            double incidenceang    = 90 - 180 / Math.PI * Math.Acos(Matrix <double> .Dot(pos_norm, pv_norm));

            // set state data
            _newState.AddValue(ANTDATA_KEY, new KeyValuePair <double, double>(timage, incidenceang));
            _newState.AddValue(ANTINCIDENCE_KEY, new KeyValuePair <double, double>(timage, incidenceang));
            _newState.AddValue(ANTSTRESS_KEY, new KeyValuePair <double, double>(timage, incidenceang));

            return(true);
        }
Ejemplo n.º 9
0
        public static void LiquidStateAwaitableSyncTest()
        {
            var config = StateMachineFactory.CreateAwaitableConfiguration <State, Trigger>();

            config.ForState(State.Off)
            .OnEntry(async() => await AsyncConsoleWriteLine("OnEntry of Off"))
            .OnExit(async() => await AsyncConsoleWriteLine("OnExit of Off"))
            .PermitReentry(Trigger.TurnOff)
            .Permit(Trigger.Ring, State.Ringing, async() => { await AsyncConsoleWriteLine("Attempting to ring"); })
            .Permit(Trigger.Connect, State.Connected, async() => { await AsyncConsoleWriteLine("Connecting"); });

            var connectTriggerWithParameter = config.SetTriggerParameter <string>(Trigger.Connect);

            config.ForState(State.Ringing)
            .OnEntry(async() => await AsyncConsoleWriteLine("OnEntry of Ringing"))
            .OnExit(async() => await AsyncConsoleWriteLine("OnExit of Ringing"))
            .PermitDynamic(connectTriggerWithParameter,
                           async name =>
            {
                await Task.Yield();
                return(DynamicState.Create(name == "Alice" ? State.Connected : State.Off));
            },
                           async(trigger, name) =>
            {
                if (trigger.Destination == State.Connected)
                {
                    await AsyncConsoleWriteLine("Attempting to connect to " + name);
                }
                else
                {
                    await AsyncConsoleWriteLine("Hanging up on " + name);
                }
            })
            .Permit(Trigger.Talk, State.Talking, async() => { await AsyncConsoleWriteLine("Attempting to talk"); });

            config.ForState(State.Connected)
            .OnEntry(async() => await AsyncConsoleWriteLine("AOnEntry of Connected"))
            .OnExit(async() => await AsyncConsoleWriteLine("AOnExit of Connected"))
            .PermitReentry(Trigger.Connect)
            .Permit(Trigger.Talk, State.Talking, async() => { await AsyncConsoleWriteLine("Attempting to talk"); })
            .Permit(Trigger.TurnOff, State.Off, async() => { await AsyncConsoleWriteLine("Turning off"); });


            config.ForState(State.Talking)
            .OnEntry(async() => await AsyncConsoleWriteLine("OnEntry of Talking"))
            .OnExit(async() => await AsyncConsoleWriteLine("OnExit of Talking"))
            .Permit(Trigger.TurnOff, State.Off, async() => { await AsyncConsoleWriteLine("Turning off"); })
            .PermitDynamic(Trigger.Ring, () => DynamicState.Create(State.Ringing),
                           async() => { await AsyncConsoleWriteLine("Attempting to ring"); });

            var machine = StateMachineFactory.Create(State.Ringing, config, queued: false);

            machine.FireAsync(Trigger.Talk).Wait();
            machine.FireAsync(Trigger.Ring).Wait();
            machine.FireAsync(connectTriggerWithParameter, "Alice").Wait();
            machine.FireAsync(Trigger.TurnOff).Wait();
            machine.FireAsync(Trigger.Ring).Wait();
            machine.FireAsync(connectTriggerWithParameter, "Bob").Wait();
        }
Ejemplo n.º 10
0
    /// <summary>
    /// 添加设置动态unit到关联子unit列表
    /// </summary>
    /// <param name="position"></param>
    /// <param name="orient"></param>
    /// <param name="unit"></param>
    public void SetDynamicLink(Vector3 position, float orient, DynamicUnit unit)
    {
        if (unit == null)
        {
            return;
        }
        if (this.destroyed || unit.destroyed || this.scene.mapPath == null)
        {
            return;
        }
        if (this.mDynState == DynamicState.LINK_CHILD)
        {
            this.mDynState = DynamicState.LINK_PARENT_CHILD;
        }
        else if (this.mDynState == DynamicState.NULL)
        {
            this.mDynState = DynamicState.LINK_PARENT;
        }
        if (this.linkUnits == null)
        {
            this.linkUnits = new List <DynamicLinkUnit>();
        }
        int             count           = this.linkUnits.Count;
        DynamicLinkUnit dynamicLinkUnit = null;

        for (int i = 0; i < count; i++)
        {
            if (this.linkUnits[i] != null && this.linkUnits[i].mDynamic != null && this.linkUnits[i].mDynamic == unit)
            {
                dynamicLinkUnit = this.linkUnits[i];
                break;
            }
        }
        if (dynamicLinkUnit == null)
        {
            dynamicLinkUnit = new DynamicLinkUnit(unit);
            this.linkUnits.Add(dynamicLinkUnit);
        }
        else
        {
            dynamicLinkUnit.Init();
        }
        if (unit.mDynState == DynamicState.LINK_PARENT)
        {
            unit.mDynState = DynamicState.LINK_PARENT_CHILD;
        }
        else
        {
            unit.mDynState = DynamicState.LINK_CHILD;
        }
        Vector3 eulerAngles = this.rotation.eulerAngles;

        dynamicLinkUnit.SetPositionAndOrient(position, orient);
        Vector3 vector  = this.position + dynamicLinkUnit.GetPosition(eulerAngles.y);
        float   orient2 = eulerAngles.y * 0.0174532924f + orient;

        unit.OnLinkLocation(vector, orient2);          //子Unit放置到位置
    }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates a new target from the xmlNode data
        /// </summary>
        /// <param name="targetXmlNode"></param>
        public Target(XmlNode targetXmlNode)
        {
            Name = targetXmlNode.Attributes["TargetName"].Value;
            string typeString = targetXmlNode.Attributes["TargetType"].Value.ToString();

            Type         = (TargetType)Enum.Parse(typeof(TargetType), typeString);
            DynamicState = new DynamicState(targetXmlNode.ChildNodes.Item(0));
            Value        = Convert.ToInt32(targetXmlNode.Attributes["Value"].Value);
        }
        // function MODEL-BASED-REFLEX-AGENT(percept) returns an action
        public IAction Execute(IPercept percept)
        {
            this.state = this.UpdateState(this.state, this.action, percept, this.model);

            var rule = this.RuleMatch(this.state, this.rules);

            this.action = this.RuleAction(rule);

            return(this.action);
        }
Ejemplo n.º 13
0
        public static void LiquidStateSyncTest()
        {
            var config = StateMachineFactory.CreateConfiguration <State, Trigger>();

            config.ForState(State.Off)
            .OnEntry(() => Console.WriteLine("OnEntry of Off"))
            .OnExit(() => Console.WriteLine("OnExit of Off"))
            .PermitReentry(Trigger.TurnOff)
            .Permit(Trigger.Ring, State.Ringing, () => { Console.WriteLine("Attempting to ring"); })
            .Permit(Trigger.Connect, State.Connected, () => { Console.WriteLine("Connecting"); });

            var connectTriggerWithParameter = config.SetTriggerParameter <string>(Trigger.Connect);

            config.ForState(State.Ringing)
            .OnEntry(() => Console.WriteLine("OnEntry of Ringing"))
            .OnExit(() => Console.WriteLine("OnExit of Ringing"))
            .PermitDynamic(connectTriggerWithParameter,
                           name => DynamicState.Create(name == "Alice" ? State.Connected : State.Off),
                           (trigger, name) =>
            {
                if (trigger.Destination == State.Connected)
                {
                    Console.WriteLine("Attempting to connect to " + name);
                }
                else
                {
                    Console.WriteLine("Hanging up on " + name);
                }
            })
            .Permit(Trigger.Talk, State.Talking, () => { Console.WriteLine("Attempting to talk"); });

            config.ForState(State.Connected)
            .OnEntry(() => Console.WriteLine("AOnEntry of Connected"))
            .OnExit(() => Console.WriteLine("AOnExit of Connected"))
            .PermitReentry(Trigger.Connect)
            .Permit(Trigger.Talk, State.Talking, () => { Console.WriteLine("Attempting to talk"); })
            .Permit(Trigger.TurnOff, State.Off, () => { Console.WriteLine("Turning off"); });


            config.ForState(State.Talking)
            .OnEntry(() => Console.WriteLine("OnEntry of Talking"))
            .OnExit(() => Console.WriteLine("OnExit of Talking"))
            .Permit(Trigger.TurnOff, State.Off, () => { Console.WriteLine("Turning off"); })
            .PermitDynamic(Trigger.Ring, () => DynamicState.Create(State.Ringing),
                           () => { Console.WriteLine("Attempting to ring"); });

            var machine = StateMachineFactory.Create(State.Ringing, config);

            machine.Fire(Trigger.Talk);
            machine.Fire(Trigger.Ring);
            machine.Fire(connectTriggerWithParameter, "Alice");
            machine.Fire(Trigger.TurnOff);
            machine.Fire(Trigger.Ring);
            machine.Fire(connectTriggerWithParameter, "Bob");
        }
 // Constructors
 public WorldRepresentation(StaticState staticState, DynamicState dynamicState = null, Interpretation interpretation = null)
 {
     StaticState = staticState ?? throw new ArgumentNullException("staticState", "ERROR: Tried to instantiate a new WorldRepresentation with no Static State. This is illegal because Dynamic-State information and Interpretation information both depend on Static State information");
     if (dynamicState == null && interpretation != null)
     {
         throw new ArgumentNullException("dynamicState", "ERROR: Tried to instantiate a new WorldRepresentation with Interpretation but no Dynamic State. This is illegal because Interpretation information depends on Dynamic State information");
     }
     DynamicState   = dynamicState ?? DynamicState.CreateEmpty(staticState.NumberOfNodes);
     Interpretation = interpretation ?? Interpretation.CreateEmpty(staticState.NumberOfNodes);
     NumberOfNodes  = staticState.NumberOfNodes;
 }
Ejemplo n.º 15
0
 private void undo()
 {
     // TODO: Record an undo with logging as an event
     if (dynamicStateStack.Count <= 1)
     {
         return;
     }
     try {
         dynamicStateStack.Pop();
         DynamicState ds = dynamicStateStack.Peek();
         LoggingManager.instance.RecordEvent(LoggingManager.EventCodes.UNDO, ds.toJson());
         //int mimicIdx = 0;
         //int mirrorIdx = 0;
         List <coord> mimicCoords  = ds.mimicPositions.ToList();
         List <coord> mirrorCoords = ds.mirrorPositions.ToList();
         while (moveables.Count > 0)
         {
             MoveableScript ms = moveables[0];
             moveables.RemoveAt(0);
             if (ms is PlayerScript)
             {
                 continue;
             }
             Destroy(ms.gameObject);
         }
         player.SetCoords(ds.playerPosition.col, ds.playerPosition.row);
         player.transform.position = new Vector3(player.GetCoords().col + mapOrigin.x, player.GetCoords().row + mapOrigin.y + player.yOffset);
         moveables.Add(player);
         foreach (coord c in mimicCoords)
         {
             MimicScript m = GameObject.Instantiate(mimic);
             m.SetCoords(c.col, c.row);
             m.transform.position = new Vector3(c.col + mapOrigin.x, c.row + mapOrigin.y + m.yOffset, -0.2f);
             moveables.Add(m);
         }
         foreach (coord c in mirrorCoords)
         {
             MirrorScript m = GameObject.Instantiate(mirror);
             m.SetCoords(c.col, c.row);
             m.transform.position = new Vector3(c.col + mapOrigin.x, c.row + mapOrigin.y + m.yOffset, -0.2f);
             moveables.Add(m);
         }
         foreach (coord c in buttonCoords.Keys)
         {
             if (buttonCoords[c].laser.data.isActive != ds.activeButtons.Contains(c))
             {
                 buttonCoords[c].TogglePressed();
             }
         }
     } catch (InvalidOperationException) {
         //TODO: Actually display this to the user
         Debug.Log("Empty stack, no previous move to undo.");
     }
 }
Ejemplo n.º 16
0
 protected Rule ruleMatch(DynamicState state, ISet <Rule> rules)
 {
     foreach (Rule r in rules)
     {
         if (r.evaluate(state))
         {
             return(r);
         }
     }
     return(null);
 }
 //START-AgentProgram
 // function MODEL-BASED-REFLEX-AGENT(percept) returns an action
 public Action execute(Percept percept)
 {
     // state <- UPDATE-STATE(state, action, percept, model)
     state = updateState(state, action, percept, model);
     // rule <- RULE-MATCH(state, rules)
     Rule rule = ruleMatch(state, rules);
     // action <- rule.ACTION
     action = ruleAction(rule);
     // return action
     return action;
 }
Ejemplo n.º 18
0
        public override bool canPerform(Event proposedEvent, Universe environment)
        {
            if (!base.canPerform(proposedEvent, environment))
            {
                return(false);
            }
            DynamicState    position     = Asset.AssetDynamicState;
            Matrix <double> assetPosECI  = position.PositionECI(proposedEvent.GetTaskStart(Asset));
            Matrix <double> targetPosECI = _task.Target.DynamicState.PositionECI(proposedEvent.GetTaskStart(Asset));

            return(GeometryUtilities.hasLOS(assetPosECI, targetPosECI));
        }
Ejemplo n.º 19
0
        public override bool CanPerform(Event proposedEvent, Domain environment)
        {
            if (!base.CanPerform(proposedEvent, environment))
            {
                return(false);
            }
            DynamicState position     = Asset.AssetDynamicState;
            Vector       assetPosECI  = position.PositionECI(proposedEvent.GetTaskStart(Asset));
            Vector       targetPosECI = _task.Target.DynamicState.PositionECI(proposedEvent.GetTaskStart(Asset));

            return(GeometryUtilities.hasLOS(assetPosECI, targetPosECI));
        }
Ejemplo n.º 20
0
        // function MODEL-BASED-REFLEX-AGENT(percept) returns an action
        public IAction Execute(IPercept percept)
        {
            // state <- UPDATE-STATE(state, action, percept, model)
            state = updateState(state, action, percept, model);
            // rule <- RULE-MATCH(state, rules)
            Rule rule = ruleMatch(state, rules);

            // action <- rule.ACTION
            action = ruleAction(rule);
            // return action
            return(action);
        }
        public void DynamicState_ReadNodeData_ReturnsCorrectInformation()
        {
            DynamicState d = null;

            for (int i = 0; i < 1; i++)
            {
                d = HardCodedStateCreator.CreateTestDynamicState();
            }
            for (int i = 0; i < 1; i++)
            {
                HardCodedStateCreator.CheckTestDynamicState(d);
            }
        }
Ejemplo n.º 22
0
    public static Tilt GetTilt(JSONNode data)
    {
        Tilt newTilt = new Tilt();

        foreach (JSONNode baseStation in data.Children)
        {
            if (Config.VerifySerialNumber(baseStation ["config"]))
            {
                newTilt = DynamicState.GetTiltOfLastDynamicState(baseStation["dynamic_states"]);
            }
        }

        return(newTilt);
    }
Ejemplo n.º 23
0
    /// <summary>
    /// 移除关联的所有子unit
    /// </summary>
    public void RemoveAllLinkDynamic()
    {
        this.mDynState = DynamicState.NULL;
        int count = this.linkUnits.Count;

        for (int i = count - 1; i >= 0; i--)
        {
            if (this.linkUnits[i] != null)
            {
                this.linkUnits[i].Remove();
            }
            this.linkUnits.RemoveAt(i);
        }
    }
        static void Main(string[] args)
        {
            SortedList <double, Matrix> state = new SortedList <double, Matrix>();
            DynamicState myState   = new DynamicState(state, DynamicStateType.DYNAMIC_ECI);
            Target       newTarget = new Target("newTarget", TargetType.FACILITY, myState, 5);
            Task         newTask   = new Task(taskType.COMM, newTarget, 5);

            Console.WriteLine(state);
            Console.WriteLine(myState);
            Console.WriteLine(newTarget);
            Console.WriteLine(newTask);

            Console.ReadLine();
        }
Ejemplo n.º 25
0
 public void Update(int dt)
 {
     ddt += dt;
     if (ddt >= gc.ADTime)
     {
         ddt = 0;
         AnimationStep++;
         if (AnimationStep >= 7)
         {
             AnimationStep = 7;
             State         = DynamicState.END;
         }
     }
 }
Ejemplo n.º 26
0
        /// <summary>
        /// An override of the Subsystem CanPerform method
        /// </summary>
        /// <param name="proposedEvent"></param>
        /// <param name="environment"></param>
        /// <returns></returns>
        public override bool CanPerform(Event proposedEvent, Domain environment)
        {
            if (base.CanPerform(proposedEvent, environment) == false)
            {
                return(false);
            }

            double es = proposedEvent.GetEventStart(Asset);
            double ts = proposedEvent.GetTaskStart(Asset);
            double te = proposedEvent.GetTaskEnd(Asset);

            // from Brown, Pp. 99
            DynamicState    position               = Asset.AssetDynamicState;
            Matrix <double> m_SC_pos_at_ts_ECI     = position.PositionECI(ts);
            Matrix <double> m_target_pos_at_ts_ECI = _task.Target.DynamicState.PositionECI(ts);
            Matrix <double> m_pv = m_target_pos_at_ts_ECI - m_SC_pos_at_ts_ECI;

            Matrix <double> sc_n = m_SC_pos_at_ts_ECI / Matrix <double> .Norm(m_SC_pos_at_ts_ECI);

            Matrix <double> pv_n = m_pv / Matrix <double> .Norm(m_pv);


            double slewAngle = Math.Acos(Matrix <double> .Dot(pv_n, -sc_n)) * 180 / Math.PI;

            //double timetoslew = (rand()%5)+8;
            double timetoslew = slewAngle / _slewRate;

            if (es + timetoslew > ts)
            {
                if (es + timetoslew > te)
                {
                    // TODO: Change this to Logger
                    //Console.WriteLine("ADCS: Not enough time to slew event start: "+ es + "task end" + te);
                    return(false);
                }
                else
                {
                    ts = es + timetoslew;
                }
            }



            // set state data
            _newState.SetProfile(POINTVEC_KEY, new HSFProfile <Matrix <double> >(ts, m_pv));
            proposedEvent.SetTaskStart(Asset, ts);
            return(true);
        }
Ejemplo n.º 27
0
        public ValidatorPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
            : base(metadata, controllerContext, rule, validator)
        {
            ShouldValidate = false;

            var model = controllerContext.Controller.ViewData.Model;
            if (validator is PropertyValidatorWithDynamicState)
            {
                
                DynamicState = new DynamicState(model, ((PropertyValidatorWithDynamicState)validator).Properties);
            }
            else
            {
                DynamicState = new DynamicState(model);
            }
        }
Ejemplo n.º 28
0
        public ValidatorPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
            : base(metadata, controllerContext, rule, validator)
        {
            ShouldValidate = false;

            var model = controllerContext.Controller.ViewData.Model;

            if (validator is PropertyValidatorWithDynamicState)
            {
                DynamicState = new DynamicState(model, ((PropertyValidatorWithDynamicState)validator).Properties);
            }
            else
            {
                DynamicState = new DynamicState(model);
            }
        }
Ejemplo n.º 29
0
 public Asset(XmlNode assetXMLNode)
 {
     if (assetXMLNode.Attributes["assetName"] != null)
     {
         Name = assetXMLNode.Attributes["assetName"].Value.ToString().ToLower();
     }
     else
     {
         throw new MissingMemberException("Missing name for Asset!");
     }
     if (assetXMLNode["DynamicState"] != null)
     {
         AssetDynamicState = new DynamicState(assetXMLNode["DynamicState"]);
     }
     IsTaskable = false;
 }
Ejemplo n.º 30
0
        public void ScanState()
        {
            Collection devCollection = (Collection)Application.Current.Properties["MonitorCollection"];
            while (true)
            {
                using (Bus.DataBusServiceClient client = new Bus.DataBusServiceClient())
                {
                    DeviceSign[] devArr = devCollection.GetDeviceIDList();

                    DeviceDynamic device;

                    foreach (var item in devArr)
                    {
                        device = devCollection.GetDevice(item.dev_id,item.mon_id);

                        string []  statelist=device.GetStateName();

                        DynamicState state;
                        Bus.AttributeValue attVal;

                        foreach(var stateitem in statelist)
                        {

                        Bus.DeviceState busquerystate = new Bus.DeviceState();
                        busquerystate.AgentID = device.Monitor_ID;
                        busquerystate.DevType = device.Dev_Type;
                        busquerystate.DevID = device.Device_ID;
                        busquerystate.Name = stateitem;
                        attVal = client.QueryStateTest(busquerystate);

                        if (attVal != null)
                        {
                            AttributeValue stateVal = new AttributeValue(attVal.Type, attVal.Value);

                            state = new DynamicState(stateitem, device.Device_ID,device.Monitor_ID, device.Dev_Type);
                            state.StateValue = stateVal;
                            device.ChangeStateValue(state);
                        }

                        }/////单个设备所以状态扫描

                    }///所有设备集合扫描
                } ///服务端口开

                Thread.Sleep(scantime);
            }////线程循环
        }
        public void DynamicState_UpdateConstructor_SuccessfullyUpdates()
        {
            // Set up the initial Dynamic State.
            DynamicState original = HardCodedStateCreator.CreateTestDynamicState();

            // Assert that the default test passes to begin with.. (just in case..)
            HardCodedStateCreator.CheckTestDynamicState(original);

            // Create the 'change' data, and create a new DynamicState object which contains those changes.
            DynamicState modified = new DynamicState(original, GenerateFactChangeData());

            // Assert that the original state object is unchanged.
            HardCodedStateCreator.CheckTestDynamicState(original);

            // Assert that the new state object is set up correctly, containing the changes and the copied-state from the original.
            TestModifiedDynamicState(modified);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Override of the canExtend method for the power subsystem
        /// </summary>
        /// <param name="newState"></param>
        /// <param name="universe"></param>
        /// <param name="evalToTime"></param>
        /// <returns></returns>
        public override bool CanExtend(Event proposedEvent, Universe universe, double evalToTime)
        {
            double ee = proposedEvent.GetEventEnd(Asset);

            if (ee > SimParameters.SimEndSeconds)
            {
                return(false);
            }

            Sun    sun = universe.Sun;
            double te  = proposedEvent.State.GetLastValue(DOD_KEY).Key;

            if (proposedEvent.GetEventEnd(Asset) < evalToTime)
            {
                proposedEvent.SetEventEnd(Asset, evalToTime);
            }

            // get the dod initial conditions
            double olddod = proposedEvent.State.GetValueAtTime(DOD_KEY, te).Value;

            // collect power profile out
            Delegate DepCollector;

            SubsystemDependencyFunctions.TryGetValue("DepCollector", out DepCollector);
            HSFProfile <double> powerOut = (HSFProfile <double>)DepCollector.DynamicInvoke(proposedEvent); // deps->callDoubleDependency("POWERSUB_getPowerProfile");
            // collect power profile in
            DynamicState        position = Asset.AssetDynamicState;
            HSFProfile <double> powerIn  = CalcSolarPanelPowerProfile(te, ee, proposedEvent.State, position, universe);
            // calculate dod rate
            HSFProfile <double> dodrateofchange = ((powerOut - powerIn) / _batterySize);

            bool   exceeded_lower = false, exceeded_upper = false;
            double freq                 = 1.0;
            HSFProfile <double> dodProf = dodrateofchange.limitIntegrateToProf(te, ee, freq, 0.0, 1.0, ref exceeded_lower, ref exceeded_upper, 0, olddod);

            if (exceeded_upper)
            {
                return(false);
            }
            if (dodProf.LastTime() != ee && ee == SimParameters.SimEndSeconds)
            {
                dodProf[ee] = dodProf.LastValue();
            }
            proposedEvent.State.AddValue(DOD_KEY, dodProf);
            return(true);
        }
Ejemplo n.º 33
0
    /// <summary>
    /// 移除指定的子unit
    /// </summary>
    /// <param name="unit"></param>
    public void RemoveLinkDynamic(DynamicUnit unit)
    {
        int count = this.linkUnits.Count;

        for (int i = 0; i < count; i++)
        {
            if (this.linkUnits[i] != null && this.linkUnits[i].mDynamic != null && this.linkUnits[i].mDynamic == unit)
            {
                this.linkUnits[i].Remove();
                this.linkUnits.RemoveAt(i);
                break;
            }
        }
        if (this.linkUnits.Count == 0)
        {
            this.mDynState = DynamicState.NULL;
        }
    }
Ejemplo n.º 34
0
        public static ChangeStateBackInfo ChangeDeviceDynamicState(DynamicState dyState, string strValue)
        {
            ChangeStateBackInfo backinfo;
            #region////暂用版本
            try
            {
            double val = Double.Parse(strValue);
            Bus.AttributeValue staval = new Bus.AttributeValue();

            staval.Type = "double";
            staval.Value = val;

            Bus.DeviceState deviceState = new Bus.DeviceState();

            deviceState.AgentID = dyState.AgentName;
            deviceState.DevID = dyState.DevID;
            deviceState.DevType = "XBPQ";
            deviceState.Name = dyState.StateName;
            deviceState.Value = staval;

                using (Bus.DataBusServiceClient client = new WpfDataBingding.TaskServiceReference.DataBusServiceClient())
                {
                    bool issucess = client.SetStates(new Bus.DeviceState[] { deviceState });
                    if (issucess == true)
                    {
                        backinfo = new ChangeStateBackInfo { isSucess=true, info=string.Empty};
                    }
                    else
                    {
                        backinfo = new ChangeStateBackInfo {  isSucess=false, info = string.Empty };
                    }
                    client.Close();
                }
            }
            catch(Exception e)
            {
                backinfo = new ChangeStateBackInfo { isSucess=false, info=e.Message.ToString() };
                return backinfo;
            }

            return backinfo;
            #endregion
        }
 /**
  * Set the agent's current conception of the world state.
  *
  * @param state
  *            the agent's current conception of the world state.
  */
 public void setState(DynamicState dstate)
 {
     state = dstate;
 }
Ejemplo n.º 36
0
        /*********************************************
        初始化监控状态
        *********************************************/
        public void GenerateSate(Bus.UserMonTask usertask, Bus.DataBusServiceClient client)
        {
            var state_list = usertask.MonTaskList.GroupBy(c => new { c.DevID, c.AgentName });
               {
               Collection monCollection = (Collection)Application.Current.Properties["MonitorCollection"];
               DeviceDynamic device;

               foreach (var item in state_list)
               {

                   device = monCollection.GetDevice(item.Key.DevID,item.Key.AgentName);
                   DynamicState state;
                   Bus.AttributeValue attVal;

                   foreach(var deviceitem in item)
                   {

                       {
                           Bus.DeviceState busquerystate = new Bus.DeviceState();

                           busquerystate.AgentID = deviceitem.AgentName;
                           busquerystate.DevType = deviceitem.DevType;
                           busquerystate.DevID = deviceitem.DevID;
                           busquerystate.Name = deviceitem.StateName;

                           attVal=client.QueryStateTest(busquerystate);
                       }
                       if (attVal != null)
                       {
                           AttributeValue stateVal = new AttributeValue(attVal.Type, attVal.Value);

                           state = new DynamicState(deviceitem.StateName, deviceitem.DevID, deviceitem.AgentName, deviceitem.DevType, deviceitem.ViewType, deviceitem.DomainName, deviceitem.ChangeThreshold, deviceitem.TimeInterval);

                           int timeinterval = deviceitem.TimeInterval;

                           if (timeinterval < device.Scan_Time)
                           {
                               device.Scan_Time = timeinterval;
                           }
                           state.StateValue = stateVal;
                           device.AddMonitorState(state);
                       }
                   }/////查询单个状态值

               }////根据设备归类状态查询
               }
        }
 protected Rule ruleMatch(DynamicState state, HashSet<Rule> rules)
 {
     foreach (Rule r in rules)
     {
         if (r.evaluate(state))
         {
             return r;
         }
     }
     return null;
 }
 protected abstract DynamicState updateState(DynamicState state, Action action, Percept percept, Model model);
Ejemplo n.º 39
0
        /// <summary>
        /// 将从数据总线获取的监控代理列表信息转化为对应的本地类型
        /// </summary>
        /// <param name="monAgentList">从数据总线获取的监控代理列表</param>
        public void initFromDataContractObj(bus.MonAgentInfo[] monAgentArray)
        {
            this.monitorAgentList = new ObservableCollection<MonitorAgent>();

            for (int i = 0; i < monAgentArray.Length; i++)
            {
                bus.MonAgentInfo monAgent = monAgentArray[i];//取出一个MonAgentInfo元素引用

                //新建一个MonitorAgent对象
                MonitorAgent monAgent_new = new MonitorAgent();
                monAgent_new.ID = monAgent.Id;
                monAgent_new.DeviceList = new ObservableCollection<Device>();
                //依次初始化monAgent_new的每个设备
                foreach (bus.MonDeviceInfo devInfo in monAgent.MonDevList)
                {
                    //新建一个Device对象
                    Device device_new = new Device();

                    device_new.MonAgentBelongTo = monAgent_new;//添加设备对其所属监控代理的引用
                    //利用数据契约对应对象初始化
                    device_new.DevID = devInfo.Id;
                    device_new.DevType = devInfo.Type;
                    device_new.Name = devInfo.Name;

                    //初始化静态属性集合
                    device_new.StaticStateList = new ObservableCollection<StaticState>();
                    foreach (bus.StaticAttribute staticAttribute in devInfo.StaticAttrList)
                    {
                        //新建一个StaticState对象
                        StaticState sState_new = new StaticState();
                        sState_new.DeviceBelongTo = device_new;//添加状态对其所属设备的引用
                        sState_new.Name = staticAttribute.AttrName;
                        AttributeValue attrVal_new = new AttributeValue();
                        try
                        {
                            attrVal_new.setDataValue(AttributeValue.mapType(staticAttribute.AttrValueType),
                                                     staticAttribute.AttrValue);
                            sState_new.AttributeValue = attrVal_new;
                        }
                        catch (Exception e)
                        {
                            throw new ApplicationException("数据契约静态属性'" + staticAttribute.AttrName + "'转化为本地类型中,值转化出错:" + e.Message, e);
                        }
                        device_new.StaticStateList.Add(sState_new);//将新静态属性添加到新静态属性列表
                    }

                    //初始化动态属性集合
                    device_new.DynamicStateList = new ObservableCollection<DynamicState>();
                    foreach (bus.State dState in devInfo.StateList)
                    {
                        //新建一个StaticState对象
                        DynamicState dState_new = new DynamicState();
                        dState_new.DeviceBelongTo = device_new;//添加状态对其所属设备的引用
                        dState_new.Name = dState.DsName;
                        dState_new.Title = dState.DsTitle;
                        dState_new.Unit = dState.DsUnit;
                        dState_new.ViewType = dState.DsViewType;
                        dState_new.AttributeValue = new AttributeValue();
                        try
                        {
                            dState_new.AttributeValue.setDataValue(AttributeValue.mapType(dState.DsValueType),
                                                     dState.DsDefaultValue);
                        }
                        catch (Exception e)
                        {
                            throw new ApplicationException("数据契约动态属性'" + dState.DsName + "'转化为本地类型中,值转化出错:" + e.Message, e);
                        }

                        device_new.DynamicStateList.Add(dState_new);//将新静态属性添加到新静态属性列表
                    }

                    monAgent_new.DeviceList.Add(device_new);//将新设备添加到设备列表
                }//devInfo

                this.monitorAgentList.Add(monAgent_new);//将新监控代理添加到代理列表
            }//monAgent
        }